Compare commits

..
Author SHA1 Message Date
Meta Vens
20bbe616ca Lodur tests: the dead-flow Actor test gets an airway so its zero checks bite
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-28 01:08:12 +01:00
Meta Vens
f3d7dd34ff Lodur tests: the allocation test measures in an AggressiveOptimization helper; TieredPGO is back on for the core tests
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-28 01:04:54 +01:00
Meta Vens
c324570dbd Actor.Tick steps a dead physiology so its flows read zero; allocation tests run with TieredPGO off; Nose comment
A dead physiology's Step zeroes Bleed, AirwayBleed, Coughed, Drained, DrawnLive and
DrawnPooled, but the Actor skipped it, so the flows stood at the dying step's values
for every tick after. The Actor now steps it; the drive is still written only on
ticks the physiology was alive at entry. Folds vessel-sites-s2-lows: the Core tests
run with TieredPGO off (the instrumented tier allocates when the background tier-up
lands), and the Nose pin comment reads 20.8 degrees plus 1.11 per mm.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-27 23:12:45 +01:00
Meta Vens
192fc1582c Soul s1 fixes: Coughed is capped at removed so Drained is never negative; Reach has one gate; the vessel fixture is the spec's clutch; bounds at the rule's midpoints
Drained read -5e-23 at a cough of 0.3 (removed x cough / total can exceed removed by an ulp), which BDS refuses: cap Coughed at removed, with a sweep over cough rates and drains pinning every airway flow at or above 0. Reach gates every tissue by the shells listed before it (the unsited total pre-loop was a dead second authority). The vessel fixture clutches at hold 0.8, priority 3 (the probe's), blood-loss bound re-derived 0.5443; the cough test now fails cough 2.0 (quarter-time bound); death, occlusion and coughed bounds at their geometric midpoints; the Nose pin says why its separation is 1.20.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-27 20:13:58 +01:00
Meta Vens
5a43458689 Major vessels are sited tissues among the shells: carotids at the side of the neck, femoral at the inner thigh
Reach gates a sited tissue by the shells listed before it (stack order is depth order); an unsited core keeps the total, and the validator refuses a shell only after an unsited core. Every shipped sited core follows all its shells, so its reach is unchanged (831,060-case sweep: only the Femoral differs).
Content: VesselV 3.5, CarotidLeft/Right on the head, Femoral on each thigh; LarynxV 1.0 -> 0.7 and the airway's cough 2.0 -> 0.3 so the front of the throat drowns him before it bleeds him out.
Pins: the vessel and throat bands on a real Actor at severity 20 and gain 10, the cough bound re-derived, and LowestHysteresis pinned by its own margin (1 mm and 10 mm fail).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-27 19:05:27 +01:00
Meta Vens
15c955bda7 LowestOpening holds its answer through a 5 mm margin (face down it no longer swaps nose and mouth at -5.8 degrees of pitch); pin TakeDrawn's guard and LowestOpening's first-on-a-tie rule
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-27 06:42:42 +01:00
Meta Vens
a1028222d3 Ragdoll keeps its airway sensor handles: TakeDrawn splits a breath's pooled draw by each opening's reading and LowestOpening names where liquid leaves
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-27 06:31:41 +01:00
Meta Vens
ab6e07cd90 Pin the dry-sample guard, DrawnLive zeroed after death, and the dying step into a full airway
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-27 04:52:17 +01:00
Meta Vens
5a91ad60b9 Physiology reports what each breath drew into the airway, live and pooled, in world m^3
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-27 04:43:20 +01:00
Meta Vens
a0c46a0011 Pin the site surface's strictness, the point check on every axis, and the Trachea and KidneyLeft sites
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-27 04:16:09 +01:00
Meta Vens
22e753617c A wound reaches the tissues under its point: PartTissuesDef.Reach by shell depth and core sites
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-27 04:00:58 +01:00
Meta Vens
5eb97dc5d0 Pin the gain applied once and the exact-zero spill of a draw into a full airway
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-27 03:42:44 +01:00
Meta Vens
1fe6606fa8 Airway tissue bleeds into the airway at the caller's blood gain; a full airway spills through the mouth
TissueDef.AirwayShare splits each wound's bleed into Bleed (surface) and AirwayBleed (airway). Physiology takes bloodGain (default 1). Bleeding runs before the airway; a breath draws only into the room left; the dying step reports its flows and the next step zeroes them. Larynx and Trachea tissues added; lungs share 0.5.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-27 03:28:04 +01:00
Meta Vens
47605e1e68 bds-mvp-map: airway internal bleed (gain owner, conservation, drown-vs-bleed-out timing)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 03:20:29 +01:00
Meta Vens
cb20b37717 bds-mvp-map: wound blood probe facts (bleed rate, settle cost, slot reuse)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 00:52:32 +01:00
Meta Vens
23591429e2 Only a touch outside a joint's subtree supports it: each body's weight is carried from the common ancestor of it and what it touches
Ragdoll.Drive deposits each body's weight at the lowest common ancestor of it and every
body it touches in this ragdoll (a touch outside the ragdoll deposits nowhere), reading
Facts.Touching, and throws when the world dropped touching pairs. The ContactCount gate
is deleted (ruling gravity-support-subtree-external). Hold pose -0.68, -0.25, box half
0.155, bounds re-derived by the margin rule, replay golden re-recorded.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-26 17:43:32 +01:00
Meta Vens
002f6f6165 Every muscle carries its unsupported subtree's weight times its strength; the pain-box hold is re-solved into the box
Drive adds a gravity feedforward to the PD term (ruling gravity-feedforward-all-muscles):
per joint, minus the gravity torque of the child's subtree about the joint origin, times
the strength, kept to the joint-frame axes the muscle has gains for. Mass, ContactCount,
JointOrigin and Gravity are read from Ymir; a body in contact carries no load (ruling
gravity-feedforward-count-gate); a zero-gravity world skips it. Core is untouched.

Re-derived by their rules, with base values kept in the comments: the hold pose (-0.70,
-0.36), BoxHalf 0.145, the replay golden, the wrist cone overshoot bound, the gravity reach
and ward bounds (now claimed), the hinge test. New pins: zero-gravity hashes, half-strength
sag, the feedforward about a hinge's axis only, the settled palm on the box centre.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-26 17:15:54 +01:00
Meta Vens
93e85a5a33 Record the zero-gravity readings before the gravity feedforward: the 2 s ragdoll hashes and the reach hashes
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-26 17:15:54 +01:00
Meta Vens
f959226bb3 Map: subtree-external gravity support (facts 32-34, cut-order row 3d)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 07:35:41 +01:00
Meta Vens
e47e3d30ce Map: the frustration bar does not lift on changed facts (ruling frustration-lifts-without-fact-changes)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 05:27:23 +01:00
Meta Vens
a1564bbb55 Frustration bar: a changed fact no longer lifts it; it ends on target forgotten or RetrySeconds, or the pair planning (ruling lodur:ruling:frustration-lifts-without-fact-changes)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-26 05:27:14 +01:00
Meta Vens
2081373fa7 Brain.Validate: RetrySeconds must be positive; a bar that lifts the next tick is no bar
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-26 05:27:14 +01:00
Meta Vens
425fbd285e Planner frustration: a futile direct try is barred after FrustrationSeconds, reported as Frustrated, and decided again past the dwell; the bar lifts on a change or after RetrySeconds
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-26 05:27:14 +01:00
Meta Vens
52c89b4e81 Airway tests: the drain ramp is pinned, the side and upright bounds are re-derived by measurement
The_drain_is_linear_in_drop_up_to_DrainDrop reads the drained share at drop 0, 0.0125, 0.025, 0.05, 0.1 (0, 1/4, 1/2, 1, 1); the binary-drain and
doubled-slope mutants now die. SideDropBound 0.0036 -> 0.0110 m (shipped worst 0.01323, least claimed mutant 0.00914) and UprightBound -0.0206 -> -0.0408 m
(shipped 0.04615, least claimed 0.03615) from the measured readings of Soul's 19 mutants, geometric midpoints, separation 1.45 and 1.28.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-26 05:22:54 +01:00
Meta Vens
b725a975a3 Physiology: Afflict over a span of layers is all or none; the single-layer call is its one-layer case
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-26 05:08:52 +01:00
Meta Vens
1986520bec Planner select: the commit tick checks the plan, an exhausted replan keeps the plan in force, one buffer for the pending plan, a Self goal's plan shared after the budget is gone, carried paths pinned, crowd rate as a margin
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-26 04:43:53 +01:00
Meta Vens
e94fc96680 Tests: the pending plan is the plan in force on the commit tick
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-26 04:25:59 +01:00
Meta Vens
7be39b2b41 Docs: deepening and the decision's plan (fact 31 measured, target shape, rationale); a crowded-room allocation test
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-26 04:22:58 +01:00
Meta Vens
8cfd4d743d The plan is the decision's: made by the Select that chose or re-chose the pair, carried with it, checked on carried ticks; the per-tick Derive is deleted
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-26 04:22:06 +01:00
Meta Vens
f2669847fe Select: pass 2 deepens across the want pairs (round k asks for exactly k steps, a bound per pair), so short plans are found first and one dead end cannot starve the budget
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-26 04:21:57 +01:00
Meta Vens
237f3346aa Planner.Plan: a first depth, so a call can search for a plan of exactly k steps
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-26 04:21:57 +01:00
Meta Vens
861b4cb270 Docs: the planner gate as built, cut order row 2c, fact 28 (crowded room and cost measured)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-26 04:21:57 +01:00
Meta Vens
f073350e6d Tests: Soul's planner-move probes as tests (wide and deep fuzz against a forward oracle, budget boundary, reach radii, non-moves, determinism and allocation)
Folds lodur:follow_up:planner-moves-s1-lows: the deep generator makes plans of 3 to 5 steps through several movers, with asserted counts; a gives-then-move oracle is told apart from the move-then-gives one.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-26 04:21:57 +01:00
Meta Vens
dedd232d7b Select: wants on goals, the planner gate (satisfied not offered, planned scored by length, unplanned tried direct), one think budget per Select, the plan on the Actor
A GoalSpec.Want and a PlanSteps consideration; Brain.PlanDepth, DirectDiscount, ThinkBudget, ReachMeters; a Deliberation per Actor owning the planner, the want-pair heap and the budget; Select with no pair lets go of the target (stale-target-without-pair); Actor.PlanLength and PlanStep derived each tick.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-26 04:21:57 +01:00
Meta Vens
412aa50b05 SeatedOrientTests: NearWardBound at the geometric midpoint its comment states, sqrt(4.34 x 7.65) = 5.76 cm
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 04:18:45 +01:00
Meta Vens
5657766f2e Map: the hand-off slew bounds the arm layer's contribution under a constant base, not a goal switch
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-26 04:17:21 +01:00
Meta Vens
c846e216ed Seated ward bounds at the geometric midpoint of shipped and the least claimed mutant
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-26 04:17:21 +01:00
Meta Vens
f46f0a5b13 Pin the hand path's shape and state: segment hand-off, re-engage from releasing, Restart keeping the swivel, the quintic, the blocked radius
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-26 04:17:20 +01:00
Meta Vens
811bac5d8f Arms reach across the body through a clearance via point, and the arm hand-off is slewed both ways
ArmChain owns the arm's whole motion across ticks. Drive and Release replace
the Toward blends in OrientRig.Drive: an engaging arm slews from the base pose,
a released arm slews back and then writes the base untouched, and Compose runs
on every tick of an Actor with a rig. A reach the trunk blocks (decided once per
path start) follows a minimum-jerk hand path through a via point ahead of the
trunk; any other reach solves directly, slewed. Actor commits restart the path.
FarArmWedgedFloor is retired for FarArmBound; the ward bounds are re-derived.
Slew renormalisation and sign-flip are pinned.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-26 04:15:02 +01:00
Meta Vens
2cc6099570 Airway drain follows the drop of each opening's rim below the deepest airway sump; the facing cosine and DrainFacingStart are deleted
ReadAirway writes per opening how far its lowest rim point lies below the deepest BodyPlan.AirwaySumps point along gravity; AirwaySample.Drop and
AirwayDef.DrainDrop replace Facing and DrainFacingStart. A side-lying body now drains and an upright one does not; the humanoid pose path is pinned by
creation-pose, rotated-head, side-lying fall, welded-stool and seated-fall tests.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-26 03:58:30 +01:00
Meta Vens
66d96ac3eb ReadAirway also writes each opening's facing against the caller's down, from the body's pose; the two-span form is deleted
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-26 03:58:30 +01:00
Meta Vens
ba35236726 Map: gravity feedforward on supported bodies, pain-box hold re-solved, what moves (facts 28-30)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 03:39:25 +01:00
Meta Vens
fa3c50b9d2 Map: the planner move rule replaces the reach-optimism sentence
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-26 03:38:05 +01:00
Meta Vens
df92dce668 Planner: a step that gives its This reach is a move; other things are in reach after it only if near it
Regress refuses a move that leaves a needed reach literal wrong and meets the ones it makes right; Meets broadens a reach literal to every This near its thing. The forward oracle applies the same rule from three x positions; reach literals are drawn more often so the rule changes 69 of 4000 worlds. A verb that also gives reach to a Tool keeps that give: gives stand over the derived reach.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-26 03:38:05 +01:00
Meta Vens
6f6bfe91a9 Planner: a budget per Plan call and LastExhausted
Plan takes the most groundings the call may regress (default NodeBudget, at least 1); Search, Try and the depth loop compare against it, and LastExhausted says a -1 was a spent budget, not an absent plan.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-26 03:38:05 +01:00
Meta Vens
06d20596a7 Map: reach path and gravity feedforward facts 23-27 (cited as 19-23 in their records), half-turn line
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 03:09:58 +01:00
Meta Vens
33a01ec9bb Map: planner moves and select (body facts 19-22, per-decision think budget)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 03:07:58 +01:00
Meta Vens
77d00d326f Arm IK targets slew at MaxAngularRate; the singular-band clamp rule is deleted
Per ruling lodur:ruling:ik-output-slew-limit (superseding
lodur:ruling:ik-clamp-singular-uses-previous): each solve moves the returned
shoulder target (by rotation angle) and elbow flex toward the solved ones by
at most MaxAngularRate * tick (placeholder 10 rad/s, near human peak arm
speed). SingularBand, the held swing direction, Split and SwingDirection are
gone; the clamp is the stateless swing-twist clamp again. Swivel temporal
coherence (held swivel, BasinMargin, SwivelRate) is unchanged. Reset, and
Actor.ResetArms through it, also snaps the slew: the next solve returns the
solution unslewed.

Tests: per-tick bound StepBound = rate * Dt + 1e-5 on both targets over the
tie lines, the 81 random jumps, 20 cm walks through the half-turn band, edge
crossings, full circles about the shoulder, and leaps; leaps settle on a
fresh chain's solution (by tick 38 of 200) and two chains agree bit for bit.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 02:34:40 +01:00
Meta Vens
c05710c752 Arm IK clamp holds the previous swing direction near a half-turn swing; Actor.ResetArms
The swing-twist split in the clamp is singular at a half-turn swing, where the
swing direction turns up to a half turn for a small change in the target. Within
SingularBand (placeholder 0.25 rad) of it the clamp keeps the previous tick's
swing direction, blended from the fresh one across the band's width again, and
reads the twist against that direction (ruling
lodur:ruling:ik-clamp-singular-uses-previous). The first solve after
construction or Reset clamps along the fresh direction.

The random-jump test no longer excludes the 20 half-turn cases: all 81 stay
under the 0.129 rad per-tick bound; a tripwire keeps at least 5 in the band.

Actor.ResetArms (through OrientRig.ResetArms) resets both arm chains; tested
for both arms on each side's feasible tie.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 02:26:42 +01:00
Meta Vens
4bc9627354 Arm IK holds each arm's swivel across ticks, changing basin with hysteresis
Ruling lodur:ruling:ik-swivel-temporal-coherence. ArmChain is now one arm's
solver across ticks: it keeps the previous unclamped shoulder target, projects
it onto the new goal's swivel circle, stays in that swivel's basin, takes the
stateless choice only when it beats the basin by BasinMargin (less violation,
or less twist when both are feasible), and turns the swivel at most
SwivelRate * tick per solve. The first solve after construction or Reset is the
stateless rule. Both constants are placeholders. OrientRig takes the Actor's
tick and owns one chain per arm; the Actor has no reset path, so a chain resets
only at construction.

Tests: Soul's six sagittal tie lines walked as goal paths, both arms mirrored;
the random-segment stateless jumps walked across their micron gaps (jumps at a
half-turn swing, where the clamp's swing-twist split is singular, are counted
and excluded); a basin switch on the feasible tie; Reset restores the stateless
rule bit for bit. Independent-goal tests reset per goal.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 02:14:21 +01:00
Meta Vens
788ebd2389 Seated test: the far-arm exclusion names its owner and trips when the far arm reaches
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 01:43:49 +01:00
Meta Vens
e8c6d7e5fb Arm solve: least-violating swivel, clamped, when none is feasible; continuity test across the feasible edge
The zero-twist clamp fallback jumped the shoulder target up to 1.4 rad as a goal
left the feasible set. Now the swivel minimises swing past the cone plus twist
past its range (in double, golden section over a 36-step grid), and swing and
twist clamp to the limits: at the edge that is the last feasible swivel.
The target is linear in the swivel half-angle, so the scan reads
cos(phi/2) A + sin(phi/2) B, and the least swing over the swivel is a 2x2
eigenvalue that skips the feasible scan when nothing fits the cone.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 01:43:49 +01:00
Meta Vens
c9b2345eba Docs and Core comments: fetal and stare-at-hands are data; phantom target test; no binding named in Core
goal-ai-map row 4 lists look, reach, ward off and recoil as this cut's layers,
fetal and stare-at-hands as data. A test runs the layers on a phantom target
and a real one at one place and reads identical targets. BodyPlan and the Core
project comment no longer name the Ymir binding.

Finding: lodur:finding:cut-lodur-orient-goals.s1.doc-drift-and-phantom-unproven

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 01:01:59 +01:00
Meta Vens
880cc8d61e Orient test: recoil composes before look and arms
A look and a reach at half weight blend from the recoiled neck and shoulder;
recoil applied after them fails the test.

Finding: lodur:finding:cut-lodur-orient-goals.s1.layer-order-unpinned

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 01:01:58 +01:00
Meta Vens
4e056c24f8 Arm solve: nearest feasible swivel when zero twist leaves the cone; seated ward test per wrist, gravity off and on
The seated ward-off wrists fell short with gravity off as well: the zero-twist
swivel saturated the shoulder cone 20 to 23 cm short of head-height ward goals
that a swivel with 0.27 to 0.52 rad twist reaches inside the limits. The solver
now takes the swivel nearest zero twist that is inside the cone and the twist
limits (Tolani, Goswami and Badler 2000), clamping only when none is.

The seated test measures each wrist against its own ward goal: gravity off at
the head-height sounds (both arms, 7.0 cm worst) and the near arm at a low
sound, and gravity on separately. Bounds by deterministic-bound-margin; the
sideways, no-spread, half-spread, half-weight and zero-twist mutants are killed.
The far arm at the low sound wedges against the trunk (goal-ai-map fact 8).

Finding: lodur:finding:cut-lodur-orient-goals.s1.seated-ward-bound-vacuous

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 01:01:58 +01:00
Meta Vens
d7cb5ffa83 Seated ragdoll looks and wards off: Ragdoll.ReadPartPoses test, bounds by deterministic-bound-margin, docs
The seated scenario reads the part poses off the ragdoll and drives it through the Actor's orient layers; the head error and wrist-to-line bounds sit at the geometric midpoint of the shipped worst and the least claimed mutant. docs/lodur-target.md gains the Orient row and the tick order.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-26 00:36:37 +01:00
Meta Vens
5547312624 Orient layers: Look, Arms (Reach, WardOff, Present) and Recoil on a goal's PoseBehaviour, solved from the committed target and the caller's part poses
Layers record data on the behaviour; OrientRig resolves the look and arm chains once at Actor construction (bent or straddling arms refused there, naming goal and side); PoseBehaviour.Write composes recoil, look and arms between the key pose and the flinch blend and never writes strength. No layers: the key loop's arithmetic as before. The Actor takes an optional BodyPlan and per-tick part poses and holds the Nearer arm per committed pair.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-26 00:31:49 +01:00
Meta Vens
51755968ce Airway tests: no-will bound at the geometric midpoint, four unpinned branches pinned, Draw read from content, placeholders named at their outcomes
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-26 00:20:17 +01:00
Meta Vens
bd5ba7fecd Airway physiology and air hunger: CO2 and a ventilation deficit drive the urge, the urge drives arousal and a struggle goal; a will-held breath ends in a gasp; cough and drainage
Physiology gains the airway (liquid, occlusion), carbon dioxide and BreathUrge; DriveState.AirHunger (written only by the Actor) raises arousal under max(load, AirHunger) and DriveQuantity.AirHunger lets a goal read it. The Actor holds the breath on will while liquid is at the airway, in contest with the urge through WithdrawalReflex, and reports TickEvents.Gasp. The struggle is content, a goal under When AirHunger, so a broken will cannot stop it. Oxygen constants are unchanged; new constants are marked placeholders.

Pins the fading-effort window on the real Actor at slow scale 1 and 20: out 81.6 s, dead 154.3 s, mean awake effort 0.72.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-26 00:17:56 +01:00
Meta Vens
a02ab2d424 Planner: verb-level relevance before grounding, a grounding budget, pinned orders
Search asks which groundings of a verb give a literal still open before grounding any, so a tool verb no longer costs capacity squared per
level; Regress no longer decides relevance (one owner). A counter of regressed groundings (NodeBudget 4096) ends a runaway search as no plan.
The 4000-world forward-search equivalence, the n-1 side for n=1..4 and a multi-step tie order are pinned.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-25 23:59:40 +01:00
Meta Vens
87a35da7d5 Docs: facts on percepts, bit 63 reach, the Planner row
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-25 23:59:40 +01:00
Meta Vens
32ead47c03 Add the bounded regressive Planner: facts, verbs with needs and gives, shallowest plan within a caller depth
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-25 23:59:40 +01:00
Meta Vens
df2bea039b Carry facts on emitters and percepts; refuse the reach bit and fact disagreement
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-25 23:59:40 +01:00
Meta Vens
ce5a0997ab Pin the Actor's oxygen wiring: arousal and post-ceiling effort reach Physiology (lockstep twin); PhysiologyInput doc says applied, not asked
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-25 23:33:48 +01:00
Meta Vens
cc26fa39ef Bruise heals on real seconds: wounds are Acute, Slow is for toxins, radiation and osmosis; one-lung test pins Breathing 0.5 at scale 1 and 20 and the blood store both sides (uptake)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-25 23:33:48 +01:00
Meta Vens
fdbfd2cf19 Physiology oxygen: Breathing capacity, blood and brain oxygen stores, hypoxia curve; Heart no longer Vital
The bloodLoss argument threaded through Capacity and Fold becomes one driver array (BloodLoss, BrainOxygen); organism effects may target any capacity and use any non-affliction driver. Gases run on the Acute clock from PhysiologyInput(Arousal, Effort), which the Actor reports from its drive and last tick's strengths. Constants are literature-shaped placeholders (rulings bds-asphyxia-real-time, bds-heart-stop-stagger).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-25 23:11:54 +01:00
Meta Vens
fec539a569 Pin shell fit across every shell and box axis, capsule and sphere radius, and +Infinity refusal on thickness and sheet fields
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-25 23:05:13 +01:00
Meta Vens
e2a2fa4703 Docs: PhysiologyPlan owns the tissue stack material; Resolve is the one join
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-25 23:05:13 +01:00
Meta Vens
76995717a0 Humanoid: skin and muscle sheet material, fat as stack thickness
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-25 23:05:13 +01:00
Meta Vens
03524676c4 Resolve is the one (label, side) join; Physiology calls it; shells must fit
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-25 23:05:13 +01:00
Meta Vens
56a58bc975 Add SheetDef and TissueDef Thickness and Sheet with validation
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-25 23:05:13 +01:00
Meta Vens
3a73c985ee Pin goal-target Distance axes, the sense-region observer, the age input, multiplied considerations, the Id 0 skip, multi-kind filters, the untargeted reset of TargetId and a retarget within the dwell
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-25 22:57:28 +01:00
Meta Vens
88f6e753f0 Goals name a kind of thing as target; Select scores (goal, percept) pairs by priority times response curves, with commitment to the current pair
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-25 22:57:28 +01:00
Meta Vens
0dbdf97d83 Map: goal planner split (2b verbs and planner, 2c planner select)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 22:48:59 +01:00
Meta Vens
aac6079369 Pin motor fold order and weights, vascularity and the bleed clamp, slot reuse age, dead Bleed, and a refused Tick leaving the physiology untouched
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-25 22:00:47 +01:00
Meta Vens
7d1eae37a4 Cut is Acute: bleeding, clotting and healing run on real seconds whatever the slow scale (bds-physiology-clock); pinned on the Humanoid plan
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-25 22:00:46 +01:00
Meta Vens
336c4da837 Actor steps its Physiology: consciousness slot, motor ceiling, Died; SetWillSlots narrowed to SetAttention
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-25 22:00:46 +01:00
Meta Vens
bbaf8af493 PhysiologyPlans.Humanoid: tissue stacks, blood, blood-loss stages, Cut and Bruise for the 19-part body
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-25 22:00:46 +01:00
Meta Vens
c99eaad8ae Physiology: integrity from injuries, capacities, blood, motor ceiling, bds-death; bounded affliction table
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-25 22:00:46 +01:00
Meta Vens
3c1067da4b Physiology content: tissue stacks, afflictions with data effects, blood; validated at construction
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-25 22:00:46 +01:00
Meta Vens
a501bd7383 Map: flesh cut order (no-particle-contact, attach batch ABI 17, dormant ABI 18); probe P7 grid mask
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 21:50:06 +01:00
Meta Vens
8a948aa8c5 Map: bounded regressive goal planner (depth is intelligence), four mind stats; planner cost probe
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 21:43:58 +01:00
Meta Vens
997b1fe67e IkReachTests: reach bound at the geometric mean of shipped worst and least claimed mutant (3.77 cm)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-25 21:28:40 +01:00
Meta Vens
fb30ed52ee IkReachTests: Ymir joint frames pinned to Ik.JointFrame; zero-gravity reach bound, gravity error reported, determinism
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-25 21:05:34 +01:00
Meta Vens
23925d4552 IkTests: forward kinematics, zero twist, limits, mirror, look, allocation
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-25 21:05:33 +01:00
Meta Vens
388a572828 Ik: zero-twist two-bone arm and clamped look as a Core producer of joint targets
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-25 21:05:32 +01:00
Meta Vens
c4cc3b0a78 Map: goal targets and IK (body facts, cut order 3b, rationale)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 20:56:30 +01:00
Meta Vens
13248b7f22 Ragdoll binding: one liquid sensor per airway opening at build; ReadAirway reads live and pooled volume
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-25 20:50:43 +01:00
Meta Vens
bbeed80af6 Body plan: airway openings as data (Mouth and Nose on the humanoid head), validated to reach outside their part
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-25 20:50:43 +01:00
Meta Vens
ae49a7de8c Map: flesh on the bones (tissue stack, dormant pinning, live budget) and the cost probes behind it
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 20:46:12 +01:00
Meta Vens
4118b4792d Percepts: Touch updates the slot's Kind; a freed slot is zeroed fully; tests for both and for the anonymous-emitter hole
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-25 20:36:56 +01:00
Meta Vens
ee23c32898 Percepts: emitters carry an id and kind; Perception remembers sensed things in a bounded slot table; phantom id bit reserved
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-25 20:19:38 +01:00
Meta Vens
e3811644c3 Map: Fella's goal AI (percepts, goal targets, seated motion, locomotion chain, interactions)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 20:16:33 +01:00
Meta Vens
fbc3501d71 Map: BodyPlan authority, derived tree, consumers, verification; drop stale 12-muscle and Region lines
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-25 01:12:11 +01:00
Meta Vens
28c6a0dfae Sense tolerance comment: weakest mutant reads 0.5
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-25 00:26:45 +01:00
Meta Vens
30aefa8da7 BodyPlan: refuse fields a shape cannot carry, drop the unreachable root clause; pin sense-point offset, box depth, rotation finiteness; docs name BodyPlan and Ragdoll
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-25 00:22:51 +01:00
Meta Vens
d9a721611b Ragdoll builds a BodyPlan; Limb, Muscle, Region and the hard-coded Build are deleted
ReadRegions becomes ReadSensePoints; strength and target arrays index by plan joint ordinal.
Ymir limb lane is now the plan part ordinal, so HandTests.BaseHash is re-pinned (the only pin moved).
Proof, BaseCreationHash with the Limb term removed, seed 1, Ymir cdf79b1:
  Lodur d7a626b: 0x65216f91ffc63d24   this cut: 0x65216f91ffc63d24   (equal)
Full function: d7a626b 0xccf5cedb0df1b2e8 (old pin) -> this cut 0xbbcc7aff6c088398 (new pin).
Tests: Core 182/182, Lodur.Tests 46/46; the connected pain box replay is unchanged.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-25 00:03:21 +01:00
Meta Vens
f04ad22371 BodyPlan: parts, joints that are the tree, sense points by label and side; Humanoid() carries the old numbers; HumanoidRagdoll.cs renamed Ragdoll.cs (content unchanged)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-25 00:03:21 +01:00
Meta Vens
d7a626b20a Flail test: seeds 1-20 x three cadences, measured bars (hands 60 mm, body joints 45 mm), ruling flail-bar-honest-multiseed
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-20 22:38:27 +01:00
Meta Vens
bf9ea69457 Hand geometry pinned by behaviour: rest curl, finger limit window, wrist and thumb cones each fail a named test, not only the replay
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-20 22:31:32 +01:00
Meta Vens
be7102dcaa StrainShake 0.03 -> 0.08 (3-7 cm shake at the palm), pain-box half 0.12 -> 0.125 (hand in the box until the break), measured numbers and the recorded replay re-pinned
Core golden tsv byte-identical.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-20 21:25:17 +01:00
Meta Vens
5d269eccb9 Ragdoll hands: palm, thumb and fingers per arm (19 bodies, 18 joints, appended); hand region at the palm; shoulder and elbow damping carry the hand mass
Hand gains are bounded by each body's own inertia and every hand joint keeps
passive damping. The pain-box hold point is re-measured at the palm. Three
ConnectedPainBox tests (strain shake bar, hand-in-box until the break, the
recorded replay) are red here and move with the next commit.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-20 21:13:45 +01:00
Meta Vens
e3fb0a8582 PdMuscle: Passive damping floor (tissue viscosity); Drive no longer skips limp muscles, PdMuscle decides
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-20 21:02:00 +01:00
Meta Vens
dedf391699 Docs: who writes what per tick; the MVP map's state columns, cut order and landed state refreshed (will-mix landed before startle-attention)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-20 09:26:10 +01:00
Meta Vens
f9e302ef96 Perception: Sense refuses a gain outside [0, 1]
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-20 06:54:42 +01:00
Meta Vens
378febf354 Actor: the ramp's last tick assigns the declared target; the Load lag is documented
A lerp need not land on a nonzero target (0.8 + (0.15 - 0.8) is not 0.15), so the last tick,
which is also the takeover tick of a zero-length ramp, assigns the target itself. Brain, Actor and
lodur-target.md say a gain change reaches Load one tick after the Actor sets it. A huge finite
EntrySeconds is pinned as an unending ramp.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-20 06:53:37 +01:00
Meta Vens
a9136cbcdd Tests: the entry ramp's length is rounded, not floored
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-20 06:18:14 +01:00
Meta Vens
1e00157dfe Actor: a goal's entry arousal and sensory gain are reached over EntrySeconds
GoalSpec.EntryArousal (double?, in [0,1]) and GoalSpec.EntrySeconds (finite, not negative, default 0,
rounded to ticks once like the onset). On takeover the Actor records the arousal and gain, and for
the ramp's ticks, after the drive steps, sets them to start + (target - start) x k / ticks (1 when
ticks is 0), so calm's stress bar and flinch drive tail off rather than cut; after it the drive owns
arousal again. EntryResolve stays a snap; the Start goal's targets apply at construction.
lodur:ruling:flinch-tail-after-stimulus

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-20 06:14:50 +01:00
Meta Vens
f2f5a10226 Perception: a goal's sensory gain gates the sense channels' afferents
GoalSpec.SensoryGain (default 1, in [0,1]) is held in DriveState.SensoryGain, written only by the
Actor at takeover (at construction for the Start goal) and handed to Perception.Sense. The gain
multiplies each channel's afferent as it leaves the conduction ring, so sensitisation still follows
the world; Load is built from the gated afferents; ChannelStimulus stays the world's; the
nociceptive region afferents, the withdrawal reflex and its flinch are not gated.
lodur:ruling:stress-bar-shows-arousal-calm-silences

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-20 06:11:38 +01:00
Meta Vens
e5a66bbc54 Actor: pin the onset's rounding; clamp an out-of-range onset instead of casting it
A case whose quotient sits just under an integer (0.29 s at dt 0.01 is
28.999999999999996 ticks) kills Round -> Floor. An onset whose tick count is
past the long range, +infinity included, is now one guard (>= long.MaxValue)
rather than a cast that is undefined across runtimes and could go negative on
one that wraps; huge finite onsets (1e300, 1e19) are tested.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-20 05:21:45 +01:00
Meta Vens
72fc3425ac Tests: an entry effect fires once per entry; the mend is inclusive in Step and Enter
A rage with EntryResolve 1 and Effort drains the will it was given (resolve
below 0.3 after the onset), and a calm/rage pair entered twice sets resolve to
the entry value twice and not again inside the goal. Mutants: Enter applied
every tick instead of on the takeover (2 tests fail); mend made strict in
Enter and in Step (1 test fails each). A goal with EntryResolve equal to
WillMendsAt mends; recovery landing exactly on WillMendsAt mends on that tick.
Addresses findings entry-once-unpinned and mend-boundary-unpinned.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-20 05:04:48 +01:00
Meta Vens
f8f88f53c0 Will: a test seam lowers the Attention and Consciousness slots; tests pin every reader of Will
Attention and Consciousness get internal setters, Actor.SetWillSlots and an
InternalsVisibleTo for Lodur.Core.Tests; nothing public changes and the slots
still start at 1. Tests assert Will = min(resolve x attention, consciousness)
and that reflex suppression, the flinch gate and the voluntary weight each
move when a slot drops with resolve full. Each of six mutants (reflex, weight
or gate reading Resolve; Will as Resolve, without Attention, without the
Consciousness cap) fails the suite. Addresses finding will-slots-unpinned.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-20 05:02:18 +01:00
Meta Vens
9c26a5509a Actor: the Start goal's entry resolve applies at construction
A puppet started in rage (Start = a goal with EntryResolve) began at resolve
1.0 because only goal changes applied the entry effect. The pain-box golden
and the seed-1 body hashes are unchanged (no fixture Start goal carries an
entry resolve). Addresses finding start-goal-entry-ignored.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-20 04:59:15 +01:00
Meta Vens
91a3c6ffd0 Actor: the involuntary onset is rounded to whole ticks once
Compared as (tick - goalSince) x dt >= seconds in floating point, an onset of
1.85 s at dt 1/120 lasted 223 ticks, not 222. It is now precomputed per goal
beside the dwell and compared as integers (+infinity stays involuntary
throughout); effort and weight read the same count. Addresses finding
onset-boundary-float.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-20 04:58:19 +01:00
Meta Vens
c7d5fc9917 Drive: every DriveParameters value is validated at construction
A NaN or negative rate (a NaN DrainTrait made Resolve NaN and Tick threw from
PoseBehaviour.Write after the drive had half-stepped) is now a construction
error. DriveParameters.Validate owns the checks, WillMendsAt and WillCurve
included. Addresses finding nan-drive-throws-after-step.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-20 04:56:59 +01:00
Meta Vens
7ec8d42465 Docs: the will breaks and mends, goals carry entry effects, the will mix
Layer 3 (Breaks, WillMendsAt, Will with its Attention and Consciousness
slots) and layer 4 (EntryResolve, Effort, InvoluntarySeconds, the strength
rule) in docs/lodur-target.md, and the README's one sentence.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-20 04:19:12 +01:00
Meta Vens
afb8df397a Will mix: every voluntary pose is weighted by the available will
A goal that is voluntary (past its InvoluntarySeconds) writes each muscle at
HoldStrength x min(1, Will^WillCurve + leak x FlinchGain); an involuntary one
writes HoldStrength. PoseBehaviour.Write takes the weight first and throws
outside [0, 1]; targets (Blend) are unchanged. DriveParameters.WillCurve
(default 0.25) is validated in the Actor constructor.

Body tests re-pinned, with the reason:
- seed-1 replay: break tick 1770, switch tick 1782 and 16 flinches are
  unchanged; the arm's track and world hash moved (hand e283e3615b6b2cbc ->
  a0fafe85c80e98f7, world cd1902f3dd65af64 -> 83155f2abf0e7e91) because the
  hold now weakens as resolve falls. Renamed from "pre_brain_base".
- "the movement is the leak": a leak-free arm now also sags as the will
  fails, and loses the last flinch (1750 ms) because it leaves the box sooner.
  The leak is isolated with WillCurve 0.001 (weight ~1), the claim unchanged;
  a new test pins the sag itself.
The golden table is untouched.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-20 04:18:55 +01:00
Meta Vens
c93bdb7e1f Brain: goals carry an entry effect, an effort and an involuntary onset
GoalSpec.EntryResolve sets resolve on the tick the goal takes over (then the
mend check runs); Effort is resolve drained per second to sustain the goal,
paid only once it is voluntary and scaled by (1 - Pull); InvoluntarySeconds
is the onset that runs without will (+infinity throughout). Brain.Validate
refuses out-of-range values naming the goal. The pain-box fixtures mark their
release goal involuntary throughout. The behaviour weight arrives next.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-20 04:13:27 +01:00
Meta Vens
74883f85e5 Drive: the will breaks and mends as a recurring event; reflex and flinch read Will
Resolve keeps evolving through a break. A break fires on each tick resolve
reaches zero while the will is not broken (counted in Breaks); a broken will
mends when resolve climbs back to DriveParameters.WillMendsAt (default 0.25).
WillBroken is now "broken now"; DriveQuantity.Breaks is the one-way "has
broken". Will = Resolve x Attention capped by Consciousness, the two being
slots that read 1.0 until lodur-startle-attention and lodur-physiology.
Reflex suppression and the flinch gate read Will, not a WillBroken special
case. The pain-box fixtures gate their release on Breaks >= 1. The golden
table is untouched and still byte-identical.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-20 04:11:51 +01:00
Meta Vens
fe8d2b3781 Docs: commitment is soft; a built Brain owns its data
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-20 03:48:04 +01:00
Meta Vens
6305bd843c Brain: soft commitment (a higher priority preempts the dwell), read-only getters, pinned dwell edges
A goal's minimum dwell now gates only decisions whose target does not strictly outrank it; a strictly
higher-priority goal preempts after the latency. GoalSpec.When, PoseBehaviour.Keys and FlinchPose read back as
read-only views (the Actor's path keeps its own arrays). Infinite dwell is refused. Tests pin the exact
boundary tick, the dwell index, the rounding rule, time-in-goal from takeover, preemption both ways and that
writing through a getter is impossible.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-20 03:48:04 +01:00
Meta Vens
d19fbc0794 Docs: name PoseBehaviour and GoalChanged; state that goal pull defaults to 0
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-20 03:48:04 +01:00
Meta Vens
4f421f42cc Brain: optional minimum dwell per goal; a built Brain owns copies; pin condition reads, latency and phase
GoalSpec.MinDwellSeconds (default 0) holds a goal until it has been active that many ticks, so a condition
hovering at its threshold no longer chatters. Brain, GoalSpec and PoseBehaviour copy the lists and arrays
they are given. New tests pin every drive quantity a condition reads, Below's strictness, the one-tick latency
floor and negative refusal, that the pending goal's behaviour is not written during the latency, that a
behaviour's phase restarts from the time in the goal, and the dwell and copy rules. Defaults leave the
golden table and the connected world hash unchanged.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-20 03:48:04 +01:00
Meta Vens
29f7a158b6 Docs: layer 4 is the Brain; pull and latency follow the goal
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-20 03:48:03 +01:00
Meta Vens
c26c15c11c The Brain: authored goals selected by conditions over drive state, one pose behaviour
The Actor takes a Brain (goals with id, priority, pull, conditions and a behaviour) and switches to the
highest-priority eligible goal after the Brain's deliberate latency, firing GoalChanged. Lodur no longer
has a hold/withdraw rule: Goal, Actor.Goal, TickEvents.Withdrew, ObjectivePull and
WithdrawalParameters.LatencySeconds are deleted; resolve drain takes the active goal's pull.
HoldAgainstReflex becomes PoseBehaviour (a pose held or a loop of keys). The pain box is a two-goal
Brain whose golden table (420 rows) and connected world hash are unchanged.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-20 03:48:03 +01:00
Meta Vens
978202009c Body regions: Head, the head body's centre
Office emitters are sensed at the head. RegionCount is 3; the connected pain box still replays the base world hash, break tick and hand track.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-20 03:48:03 +01:00
Meta Vens
2026b7cb63 Pin the connected pain box seed 1 timeline at the pre-Brain base
Break tick, deliberate switch tick, flinch count, hand track hash and world hash recorded at 5d0fec8, so the Brain cut can show it drives the body with the same bits.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-20 03:48:03 +01:00
Meta Vens
58c2201a1c Target r5: narrow the SIMBICON exclusion to the upright path; stepping strategies that re-plan targets are in scope
Operator, 2026-11-20 (lodur:ruling:lodur-locomotion-rosen-style).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 03:15:58 +01:00
Meta Vens
5d0fec8c94 Target r4: one severance owner, will is the budget, sandbox is content; topology scope narrowed to the authored part tree; MVP map
Operator rulings lodur:ruling:bds-mvp-scope and bds-sandbox-arenas-will-economy (2026-11-20).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 00:52:02 +01:00
Meta Vens
a0488275c6 Pin that arousal updates before it drains resolve on the same tick
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-20 00:45:30 +01:00
Meta Vens
9842cec85f Perception: refuse an emitter with an unknown channel before any state steps
Pins the sense point as the sense region's own, on every axis, with three regions.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-20 00:45:29 +01:00
Meta Vens
3579521d56 lodur-target: layers 1 and 3 name the emitters, the load and arousal
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-20 00:18:42 +01:00
Meta Vens
c6a1208aa2 Drive: arousal from sensory load drains resolve; Actor takes senses and emitters
Arousal rises under load and decays when quiet, drains resolve beside pain and strain
(scaled by pull and trait), and resolve recovers only when pain and arousal are both low.
Actor.Tick gains a trailing emitter span; the pain box's expressions keep their operand order
and the 420-row golden table passes unchanged.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-20 00:18:33 +01:00
Meta Vens
f052a36f2c Perception: point emitters on audio, visual and interrupt channels, combined into one load
Per channel the largest emitter intensity at the sense region's point goes through the same
threshold, sensitisation and conduction delay as noxious input; the channels saturate as
1 - prod(1 - afferent). Without senses the loop does nothing and the pain box is untouched.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-20 00:16:45 +01:00
Meta Vens
981b941e49 NerveParameters: NociceptorThreshold becomes Threshold
The record is the one transduction for every channel from the sensory-load cut on, noxious or not.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-20 00:15:32 +01:00
Meta Vens
1491bed18d Pin the shake's upper bound, the golden table's line endings, and a clean BDS tree for regeneration
Soul lows on cut-nervous-layers.s2: shake-test-has-no-upper-bound (0.06 and
0.15 now fail at 7.7 and 14 cm), golden-tsv-eol-unpinned,
golden-generator-trusts-head.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 22:06:34 +01:00
Meta Vens
05b74e864e Lodur.Body.Ymir: HumanoidRagdoll, Muscle and Limb public; friend grant and native-world collection gone
Ymir 0b0321a makes the SoA world public and locks world create/destroy. The ragdoll's
Build takes the caller's Box3DSoaWorld and Lodur still never creates one. Deleted
AssemblyInfo.cs (InternalsVisibleTo), NativeWorld.cs and the collection attributes; first-slice.md
now records that no DLL rename is needed under MinGW.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-19 21:51:28 +01:00
Meta Vens
7a82ce1fcf gitattributes: shell scripts keep LF on Windows checkouts
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-19 21:12:21 +01:00
Meta Vens
ca2c02e67f Lodur.Tests: pin the strain shake on the body; name the Ymir defect on the native-world collection
At the shipped StrainShake 0.03 the hand's height moves over 3 cm peak to peak per second
in seconds 8-13; at StrainShake 0 it moves under 1.5 cm. NativeWorld.cs now names
lodur:finding:cut-nervous-layers.s1.ymir-concurrent-world-create and says to remove it
once Ymir's lock lands.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-19 21:12:14 +01:00
Meta Vens
c52d67bcfd Lodur.Core.Tests: pain-box golden table (420 runs), resolve recovery, flinch gate; generator committed
pain-box-golden.tsv holds BadDaySimulator 9f59764's PainBoxSimulation for 7 intensity/pull
settings x seeds 1-60: outcome, break and end ms, flinch count and a hash of the per-tick
stimulus/pain/strain/resolve/goal stream. The Actor reproduces it exactly.
tools/pain-box-golden regenerates it from that commit. New tests kill 'resolve recovery
off' and 'flinch reported after the break'.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-19 21:12:14 +01:00
Meta Vens
9c07f42545 Actor: a flinch is a suppressed-reflex leak, so none after the will breaks
Corrects the stated reason: the gate is the intended semantics, not seed 1 parity.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-19 21:12:14 +01:00
Meta Vens
af83eee8a5 Lodur.Core.Tests: csproj comment names no engine
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-19 20:49:20 +01:00
Meta Vens
4dc827083b docs: connect-rungs map (body facts, model page, rationale, Ymir cut draft)
Imagination's map for the nervous-layers cut, committed from the scratchpad so it is
durable.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-19 20:49:13 +01:00
Meta Vens
fc34388ef9 docs: target r3 text, README status and entry points, Windows MinGW result
lodur-target.md becomes the r3 text: body on Ymir, layer type names and tick order,
one-physics-world restated with the game as owner, core tests build without Ymir.
README status drops 'layers 1-4 not coded'. first-slice.md records the MinGW Windows
build (DLL prefix workaround) instead of 'unrun'.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-19 20:49:12 +01:00
Meta Vens
83eb5afdca Lodur.Tests: connected pain box on the ragdoll, region readout, native worlds serialised
The Actor drives the ragdoll (pelvis welded to a static stool) through strengths and
targets only: the hand stays in the stimulus box until the will breaks, flinches pull it
away from a leak-free control, the broken will takes it out within 300 ms, same seed gives
the same events and world hash. Classes that build native worlds share one xunit
collection: two live Box3D worlds on different threads crashed the host (0xC000001D).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-19 20:48:36 +01:00
Meta Vens
0e6bec1dfc Lodur.Body.Ymir: Region and HumanoidRagdoll.ReadRegions, the hand points perception senses at
A hand is the tip of its lower-arm capsule (centre + rotation * (0, -0.14, 0)); the
ragdoll has no hand body. Allocates nothing. The visibility change (HumanoidRagdoll,
Muscle, Limb public; InternalsVisibleTo deleted) waits on Ymir's public SoA world.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-19 20:48:35 +01:00
Meta Vens
5e0e8c4866 Lodur.Core.Tests: behaviour tests for the nervous layers, core-engine-free
References only Lodur.Core. Covers conduction delay, sensitisation, containment,
reflex gain set from the previous tick's resolve, suppression cost, broken will,
ordered break times, stand-in output, zero allocation, no shared state, and parity
with the pain box (seed 1: will breaks at 14730 ms, withdraws at 14830 ms, 16 flinches).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-19 20:42:37 +01:00
Meta Vens
fd7afc1174 Lodur.Core: perception, withdrawal reflex, drive and a hold-against-reflex stand-in, run by Actor
Layers 1-3 and a layer-4 stand-in move in from the pain box (BadDaySimulator
PainBoxSimulation.cs at 9f59764), keeping its double arithmetic and in-tick order.
Actor owns one character's nervous state and runs perception, reflex, drive, behaviour
once per tick from caller-owned spans into caller-owned spans; it allocates only in its
constructor and never touches physics. Quat gains Nlerp.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-19 20:42:36 +01:00
18c4ffd0d5 Merge pull request 'docs: MotionBricks fit survey (verdict: optional tier)' (#1) from nibu/motionbricks-fit-note into main 2026-11-10 17:17:03 +00:00
0764cfc909 Merge pull request 'First slice: PD-muscle humanoid ragdoll on Ymir's SoA world' (#2) from nibu/first-slice into main 2026-11-10 17:16:57 +00:00
Nibu
d2ad276e53 Point the Ymir dependency at main now that the SoA joints merged
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-10 17:16:55 +00:00
Nibu
ef7386a35d First slice: PD-muscle humanoid ragdoll on Ymir's SoA world
Lodur.Core: engine-free PD law with per-muscle strength. Lodur.Body.Ymir: 13-body, 12-joint ragdoll
driven through the world's torque lanes from caller-owned strength and target arrays. Tests: stand, fall,
rest, per-muscle strength, torque conservation, no allocation, same seed gives the same state hash.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-07 04:07:37 +00:00
92 changed files with 23715 additions and 107 deletions

2
.gitattributes vendored Normal file
View file

@ -0,0 +1,2 @@
*.sh text eol=lf
tests/Lodur.Core.Tests/pain-box-golden.tsv text eol=lf

2
.gitignore vendored Normal file
View file

@ -0,0 +1,2 @@
bin/
obj/

9
Directory.Build.props Normal file
View file

@ -0,0 +1,9 @@
<Project>
<PropertyGroup>
<!-- Sibling Ymir checkout (Ymir main, from the SoA-joints merge on): the body layer binds to its SoA world. -->
<YmirRoot Condition="'$(YmirRoot)' == '' and '$(YMIR_ROOT)' != ''">$(YMIR_ROOT)</YmirRoot>
<YmirRoot Condition="'$(YmirRoot)' == ''">$(MSBuildThisFileDirectory)..\Ymir</YmirRoot>
<Nullable>enable</Nullable>
<ImplicitUsings>disable</ImplicitUsings>
</PropertyGroup>
</Project>

6
Lodur.slnx Normal file
View file

@ -0,0 +1,6 @@
<Solution>
<Project Path="src/Lodur.Core/Lodur.Core.csproj" />
<Project Path="src/Lodur.Body.Ymir/Lodur.Body.Ymir.csproj" />
<Project Path="tests/Lodur.Core.Tests/Lodur.Core.Tests.csproj" />
<Project Path="tests/Lodur.Tests/Lodur.Tests.csproj" />
</Solution>

View file

@ -4,8 +4,24 @@ A physics character middleware for characters that **feel and react**: they
pull back from something hot, jump when poked, and, if they want their
objective badly enough, crawl toward it after losing a leg.
**Status: design only. No code exists yet.** The design is
[`docs/lodur-target.md`](docs/lodur-target.md); read it first.
**Status: layers 1-3 and a layer-4 stand-in run on a PD-muscle ragdoll on Ymir.** The
design is [`docs/lodur-target.md`](docs/lodur-target.md); read it first. `Lodur.Core`
holds perception, the withdrawal reflex, the drive state and a hold-against-reflex
stand-in, run per character by `Actor`; `Lodur.Body.Ymir` is the PD-muscle active ragdoll
on Ymir's Box3D SoA world ([`docs/first-slice.md`](docs/first-slice.md), measured and
unmeasured). Behaviour selection beyond the stand-in, impairment and the learned tracker
are not coded.
Entry points: `src/Lodur.Core/Actor.cs` (one character's nervous state, one tick per
physics step), `src/Lodur.Core/PdMuscle.cs` (engine-free PD law, strength per muscle),
`src/Lodur.Core/BodyPlan.cs` (a body as data: parts, joints that are the tree, sense points, airway openings),
`src/Lodur.Body.Ymir/Ragdoll.cs` (builds a `BodyPlan` into a Ymir world; `Drive`, `ReadSensePoints`, and `ReadAirway`, which reads the liquid sensors it places at the airway openings (live and pooled volume) and each opening's drop below the airway sumps against the caller's down),
`tests/Lodur.Core.Tests` (the layers and parity with the pain box; builds without Ymir),
`tests/Lodur.Tests` (stand, fall, rest, same-seed-same-hash, and the connected pain box:
`ConnectedPainBoxTests`). The map this was cut from is
[`docs/connect-rungs-map.md`](docs/connect-rungs-map.md). Needs a sibling Ymir checkout at
`main` (the SoA joints merge, 2026-11-10, or later); `dotnet test tests/Lodur.Tests` builds
its native library with cmake.
## The problem
@ -19,10 +35,12 @@ time. Lodur is that layer.
## Shape (planned)
- **Core** (C#, no engine references): perception, reflexes, a drive state of
pain, shock, adrenaline and resolve that evolves every tick, and behaviour
selection that turns the drive into targets plus muscle strength.
pain, shock, adrenaline and resolve that evolves every tick (the will breaks
at zero resolve and mends as it recovers, and can break again), and behaviour
selection that turns the drive into targets plus muscle strength, weighted by
the will available to each voluntary pose.
- **Body** (per engine): follows those targets on the engine's own articulated
physics. v1 is a PD-tracking active ragdoll in Unity; v2 adds a small learned
physics. v1 is a PD-tracking active ragdoll on Ymir; v2 adds a small learned
tracker for upright balance behind the same interface.
## First consumer

368
docs/bds-mvp-map.md Normal file
View file

@ -0,0 +1,368 @@
# Bad Day Simulator MVP on Lodur and Ymir (map)
Imagination pass `bds-mvp-map`, nibu-imagination, session nibu-self-2026-11-17, 2026-11-20.
Serves `lodur:ruling:bds-mvp-scope` and `lodur:ruling:bds-sandbox-arenas-will-economy`, under target
`lodur:target:r3`. Committed as `Lodur/docs/bds-mvp-map.md`; the bases, probes and body facts below are as of the pass (Modeling refreshed the state columns and the cut table on 2026-11-20, see "Landed since the pass"); the target r4 text below went to
`docs/lodur-target.md` when Self admits r4.
## Bases
| Repo | Base | Note |
|---|---|---|
| GameCult/Ymir | `0b0321a` (main) | Box3D v0.1.0 at `extern/box3d` 8441b4a |
| GameCult/Lodur | `1491bed` (read), main now `a048827` | rung 3 sensory load merged to main during this pass (a048827); Lodur anchors below are at 1491bed and move with it |
| GameCult/BadDaySimulator | `a218c55` (main) | |
| Godot client | none | a parallel Imagination maps `client-ready-sim`, `godot-client-v1`; not admitted at 5566 |
In-flight specs this map sequences around (no report unless noted): `rung3-sensory-load` (merged), `rung3-office-stress`, `rung4-goal-flip`, `rung4-office-flip`.
## Landed since the pass (Modeling, 2026-11-20; mains: Ymir `5104b17`, Lodur `f9e302e`, BDS `bd01101`)
Body facts 1 and 8-10 below describe the bases, not today. What the cuts changed; the owners' inputs, outputs, derived
state and forbidden writers are in `docs/lodur-target.md` ("Who writes what, per tick") and BDS's README ("Who owns
what"); rulings and specs are cited by id, not restated.
- **Ymir** (ABI 8): contact and hit facts with materials, exact per-step contact impulse, grab anchor, motor joint,
point impulse, ray, joint handles with generations, tombstoned joint lanes, and joint origin lanes (the joint
frame's origin in the world, on body A). Not landed: thresholds, overload facts, removal of bodies and joints
(`ymir-break-and-remove`, still refused by the API).
- **Lodur**: the drive's will breaks and mends as a recurring event (`Breaks`, `WillMendsAt`); `Will` = min(resolve x
attention, consciousness) is derived; every voluntary pose is written at `Will^WillCurve` (the will mix), an
involuntary goal onset at full weight; goals carry `EntryResolve`, `Effort`, `InvoluntarySeconds`, and `SensoryGain`,
`EntryArousal`, `EntrySeconds` (the Actor ramps gain and arousal over the entry, Perception gates the sense channels
with the gain and refuses one outside [0, 1]). Startle (the Attention writer) and physiology (the Consciousness
writer) are not built.
- **BDS**: the chamber and the office are scenarios on one stepping session each; the office arc is snap, rage, calm
(the stress column is arousal), and each scenario's release goal is declared by id. The Godot client draws the
body run as one skinned SDF puppet: `PuppetField` meshes, `PuppetModel` owns bind, signature and rebuild,
`PuppetSkin` skins every frame and derives the surface, `Puppet` owns the Godot mesh and the build counter, the
shader only draws the bevel, `RenderCheck` is the windowed oracle. Not landed: a sandbox session, commands,
levels, runtime bodies.
## Body facts (probes)
All probes 2026-11-20, read-only on `F:\Projects`; the C probe is
`scratchpad/imag-mvp/probe/probe.c`, built with StrawberryPerl gcc 13.2
(`gcc -O1 -std=c17 -mavx2 -I extern/box3d/include -I extern/box3d/src probe.c extern/box3d/src/*.c`)
against Ymir's pinned Box3D, sphere r 0.1 m, density 1000, 1/120 s, 4 substeps, sleep off, one worker.
1. **Ymir SoA has none of what the MVP needs from physics.** `native/Ymir.Box3D/ymir_box3d_soa.c`: body kinds
sphere/static box/capsule/box only (42-48, check at 365); joint kinds revolute/spherical/weld only (50-55,
C# `Box3DSoaWorld.cs:13-18`); no remove, no kinematic body, no motor joint, no impulse, no raycast, no events;
`add_body` builds every shape with `b3DefaultShapeDef()` (453) whose `enableContactEvents` is **false** in
v0.1.0 (`extern/box3d/src/types.c:66-80`, the field is zero-initialised). Lanes are dense, append-only
(`count++` at 485), capacity fixed at create (289-333), views are zero-copy pointers fixed for the world's life
(`Box3DSoaWorld.cs:150-155`). Duplicate stable ids are refused by a linear scan (419-425). Shape `userData`
already carries the stable id (454).
2. **Box3D v0.1.0 has every API the MVP needs.** Headers: `b3World_GetContactEvents` (box3d.h:69),
`b3World_GetJointEvents` (72), `b3DestroyBody` (490), `b3Body_SetTargetTransform` (557),
`b3Body_ApplyLinearImpulse` (598), `b3DestroyJoint` (1014), `b3Joint_GetConstraintForce/Torque` (1059/1062),
`b3Joint_SetForceThreshold/TorqueThreshold` (1080/1086), `b3CreateMotorJoint` (1219), `b3_kinematicBody`
(types.h:230), `b3JointDef.forceThreshold/torqueThreshold` (types.h:622/625, default `FLT_MAX`,
joint.c:28-29), `b3MotorJointDef` with linear/angular spring hertz, damping and max force (types.h:696-730),
manifold points with `normalImpulse` and `totalNormalImpulse` (types.h:2573/2577). This corrects
`lodur:research:mvp-prior-art.contact-events` ("no normal-impulse accessor found in the docs"): the
accessor is `b3Body_GetContactData` / `b3Contact_GetData` manifolds.
3. **Contact events, run.** With `enableContactEvents` and `enableHitEvents` on both shapes, a sphere dropped
1.4 m gave 1 begin, 1 hit (approach 5.25 m/s), 0 ends over 120 steps. At rest, the manifold's
`normalImpulse` summed to 0.0873 per step against m g dt = 0.349: it is the **last substep's** impulse
(0.349 / 4). Force from a contact is `totalNormalImpulse / dt`, or `normalImpulse * substeps / dt`.
4. **End events after removal, run.** Destroying a resting body gives **no** end event in the destroy call's
buffer and **one** after the next step, carrying the destroyed shape's id (invalid by then).
`b3Body_Disable` behaves the same. So a consumer must resolve a dead shape id to the stable id it had. Ymir's
planar session already does this: `ymir_box3d.c:694-712` (`ymir_session_resolve_event_shape`, a
retired-shape table filled at removal, 1420-1437) and drains begin/hit/end with manifold details at 773-830.
The SoA world should reuse that pattern, not invent one.
5. **Joint over threshold, run.** A spherical joint with `forceThreshold` 200 N under a ramped pull reported one
`b3JointEvent` on the step the force crossed it; `b3Joint_GetConstraintForce` read 1241.9 N on that step; the
joint is **not** destroyed by Box3D (event only); `b3DestroyJoint` from the event left the child falling free.
Joint events are only for awake joints; Ymir disables sleep (soa.c:337, 447), so every joint reports.
6. **Grab, run.** A shapeless kinematic body moved by `b3Body_SetTargetTransform` each step, joined to a 4.19 kg
sphere by a motor joint (linear spring 5 Hz, damping 0.7, max spring force 50 N, angular spring off), held
the sphere at (0.72, 1.02) against a target of (1.0, 1.5): the max force (50 N against 41 N of weight) bounds
the pull, as the Box2D v3 drag sample states (`lodur:research:mvp-prior-art.grab-drag`). Destroying the
grabbed body destroyed the motor joint with it (`b3Joint_IsValid` 0).
7. **Impulse at a point, run.** `b3Body_ApplyLinearImpulse` of 1 N s, 0.1 m above the centre, gave v 0.28 m/s and
spin -5.0 rad/s: an off-centre poke turns the part, which the force lanes (centre of mass only, soa.c:593-626)
cannot do.
8. **Lodur today.** Perception senses named box volumes at points only (`Perception.cs:82-113`); regions are two
sense points read by `Ragdoll.ReadSensePoints`; one reflex kind (`WithdrawalReflex.cs`); drive is pain,
strain, resolve, `WillBroken` (`DriveState.cs`); behaviour blends two poses by leak and shake
(`PoseBehaviour.cs:87-115`); the body takes one strength and one joint-space target per plan joint
(`Ragdoll.Drive`). No IK, no clips, no physiology, no grip; the part tree is `BodyPlan` (parts, joints that are the tree,
sense points), without HP, coverage or vital flags. Rung 3 adds emitters and arousal; rung 4 the goal flip and `PoseBehaviour`.
9. **BDS today.** Headless and body pain box only (`src/BadDay.Ymir/BodyPainBox.cs`); the world is built per run
with capacity 15 (58); the puppet is welded to a stool because the PD ragdoll cannot balance for 15 s (59-62).
No session type survives beyond a run, no commands, no level content.
10. **Godot today.** Nothing; no repo under `F:\Projects` matches.
## The systems, by owner
`exists` cites base code; `new` is MVP work and names the cut that builds it (cut order below).
### Ymir (physics facts and actuators; decides nothing about bodies' meaning)
| System | State | Cut |
|---|---|---|
| Contact facts: begin/end/hit per step with stable ids, lanes, point, normal, approach speed, material ids; per-body contact force lane | landed (ABI 5-7; `docs/soa-world.md`: facts per step, exact per-step contact impulse per body and per hit); planar session precedent `ymir_box3d.c:694-830` | `ymir-contact-facts` |
| Material id per body (u64, the game's), carried on hit facts | landed (the body's `material_id`, on the hit facts) | `ymir-contact-facts` |
| Raycast (closest hit: lane, stable id, point, normal, fraction) for picking and hitscan | landed (ABI 5) | `ymir-grab-anchor` |
| Grab anchor: shapeless kinematic body moved by target transform; motor joint (linear/angular spring, max force) | landed (ABI 5-6: grab release, joint handles with generations; probe 6) | `ymir-grab-anchor` |
| Point impulse command | landed (ABI 5; probe 7) | `ymir-grab-anchor` |
| Joint stress: per-joint force/torque thresholds (create and set), overload facts with measured force/torque | new; probe 5 | `ymir-break-and-remove` |
| Runtime removal of bodies and joints; tombstoned lanes; reuse after a step; removal facts (incl. joints that die with a body); end-touch attribution for dead shapes | new; probe 4 | `ymir-break-and-remove` |
| Placeable joint kinds for building (motor-driven revolute, prismatic, distance/rope, spring) | new | follow-up `ymir-joint-kinds` |
| More shapes (hulls, compounds) for authored props | new | follow-up `ymir-shapes` |
### Lodur (general character middleware; no gore)
| System | Layer | State | Cut |
|---|---|---|---|
| Part tree: the body plan as content (parts, parent, side, max HP, coverage, vital flags, muscles, Ymir lane binding) | 3 data + 5 binding | `BodyPlan` holds parts, joints as the tree and sense points; HP, coverage and vital flags are new | `lodur-physiology` |
| Touch perception per part: pressure (contact force), impact (hit speed, material), external-joint pull (grab, strap) | 1 (+5 reads Ymir) | new | `lodur-touch` |
| Reflexes: withdrawal (exists), startle on sensory and touch onsets, flinch-from-touch, brace on impact | 2 | withdrawal exists `WithdrawalReflex.cs` and reads `Will`; rest new | `lodur-startle-attention`, `lodur-reflex-set` |
| Physiology as drive state: per-part HP and injuries, body blood fraction, bleeding, pain sum, shock, consciousness, capacities scaling muscle strength, death | 3 | new | `lodur-physiology` |
| Will economy: resolve (exists) times attention (new, startle drains it) is the budget every voluntary layer draws on; reflexes act against it | 3/4 | landed except attention: `Will` = min(resolve x attention, consciousness) in `DriveState`, read by the reflex and the will mix; the Attention and Consciousness slots read 1 until startle and physiology write them | `lodur-startle-attention` (open), `lodur-will-mix` (landed `afb8df3`) |
| Voluntary motor layers: hold pose (exists as `PoseBehaviour`), clip player, IK goals (reach, look, aim), grip; mixed by will | 4 | hold exists, weighted by `Will^WillCurve` (`PoseBehaviour.Write`; an involuntary goal onset writes at weight 1); rest new | `lodur-will-mix`, `lodur-ik-goals`, `lodur-clips` |
| Body interface: strengths + joint targets (exists) + IK goals with weights | 5 | partial `Ragdoll.Drive` | `lodur-ik-goals` |
| Severing: physiology decides; binding removes the joint in Ymir; impairment states derived per part, mirror-symmetric | 3 decides, 5 executes | new | `lodur-sever-impair` |
| Grip: hand holds an object by a breakable weld whose threshold follows grip strength; drop on pain, overload, unconsciousness; the tool frame is an IK end effector | 4/5 | new | `lodur-grip` |
### Bad Day Simulator (content, rules, sandbox; owns the gore)
| System | State | Cut |
|---|---|---|
| Sandbox session: one deterministic world with puppets and objects; command queue (spawn, remove, grab begin/move/end, poke, cut, place joint, wire) | new; today per-run `BodyPainBox.Run` | follow-up `bds-sandbox-session` (after `client-ready-sim`) |
| Damage content: material ids to insult kinds and gains (blade Cut, bat Blunt, spike Pierce), tear from joint overload | new | follow-up `bds-damage-content` |
| Gore presentation data: blood colour, bleed particle rates by wound, decal sets, stump caps, gibs | new; waits on `bds-gore-look` | follow-up `bds-gore-content` |
| Levels and arenas as CultCache: objects, joints, stimulus volumes, emitters, triggers, signal wires; arenas are levels built with the player's commands | new | follow-up `bds-level-content` |
| Contraption logic: signals between objects (switch, timer, sensor volume, motor, emitter) ticked in the session | new | follow-up `bds-contraption-signals` |
| Guns and ballistics: hitscan by Ymir raycast, recoil impulse, damage content | new | follow-up `bds-guns` |
### Godot client
| System | State | Cut |
|---|---|---|
| Render bodies from Ymir lanes by stable id | landed: `BodyRenderer` draws static boxes and `Puppet` the dynamic bodies as one skinned SDF mesh (BDS README, "Who owns what") | `godot-client-v1` |
| Bodies added and removed at runtime from Ymir lifecycle facts | new | follow-up `godot-runtime-bodies` |
| Input to commands: ray pick, grab drag, poke, cut, place, wire | new | follow-up `godot-interaction` |
| Blood visuals from BDS gore events (particles at wounds, decals at hits, stump caps) | new | follow-up `godot-blood` |
| Building tools UI over the level commands | new | follow-up `godot-build-tools` |
## Authority map (MVP)
**Owner of each decision, one each.**
- **Whether a body or joint exists in the world:** Ymir, on command only. Ymir never removes anything on its
own; a joint over threshold is a fact, not a removal (probe 5: Box3D itself does the same).
- **What touched what this step, how hard:** Ymir's contact facts and contact-force lane. Nothing else derives
touch from geometry; the box-volume stimuli stay named game stimuli (a heat source is not a contact).
- **What damage an insult does to a part, and whether a part is severed, disabled or dead:** Lodur physiology,
from insults (part, kind, magnitude) the binding builds out of Ymir facts and the game's material table.
**The joint break threshold is no longer an owner; it is a stress sensor** whose facts become Tear insults.
- **What the body tries to do:** Lodur's will mix: voluntary layers weighted by available will, reflexes against
it (ruling `bds-sandbox-arenas-will-economy`). `PoseBehaviour`'s blend (`PoseBehaviour.cs:87-115`) is
no longer an owner; it becomes one voluntary layer (hold pose) inside the mix.
- **Muscle strength ceiling:** physiology capacities times consciousness; the will mix may only scale down from
it. Content gains are parameters, not owners.
- **Where the player's hand is and what it holds:** BDS sandbox session (grab handle); Ymir executes the anchor.
- **What a material means (sharp, blunt, hot) and how gore looks:** BDS content. Lodur sees only insult kinds.
- **What is drawn:** Godot, from Ymir lanes and lifecycle facts, BDS presentation events. Godot owns no
simulation state and never writes a lane.
**Inputs/outputs per tick (one order, the body run's order today, `BodyPainBox.cs:106-110`, extended):**
BDS applies queued commands (spawn/remove/grab target/impulse) → Ymir step → Ymir facts (contacts, hits,
overloads, removals) → binding turns facts into per-part touch samples and insults → Actor tick: perception,
reflex (gain from last tick's drive), drive and physiology, will mix → binding writes strengths, targets, IK
solve onto torque lanes, executes severing and grip changes as commands for the next step → BDS emits
presentation events (wound opened, part severed, death) → Godot draws.
**Derived state:** impairment state per part (from HP, severed, nerve flags); capacities; consciousness;
"dead"; blood visuals; Godot node set (from lifecycle facts); joint overload (a sensor reading).
**Forbidden writers:** Godot writing any lane or calling Ymir directly; BDS setting muscle strengths or targets
(body-one-interface); Ymir destroying a joint on threshold; any per-wound lookup choosing behaviour
(drive-is-state); a voluntary layer writing targets outside the will weighting; the binding deciding damage.
**Shared paths:** player grab, a scripted grab in an arena, and a level load all go through the session's
command queue; arenas are levels; a player cut and a falling blade go through the same contact-to-insult path;
a torn limb and a cut limb go through the same physiology severing decision; reload of a level replays the
same commands as building it.
**Deletion lines:** `PoseBehaviour.Blend` as the motor owner (in `lodur-will-mix`, landed: `Blend` now only mixes the hold layer's flinch pose, the strength is the will mix); hand-only `Region`
enum and `ReadRegions` as perception's body model (landed: deleted with `Limb` and `Muscle` in `lodur:cut_spec:cut-body-plan-data.r2`; `lodur-touch` reads parts and sense points by plan label); the per-run world in
`BodyPainBox.Run` as BDS's only world (in `bds-sandbox-session`, scenario runs become sessions,
follow-up `scenario-session-unify`).
## Model page: identity, lifecycle, authority
| Kind | Named by | Lifecycle | Decides | Persisted |
|---|---|---|---|---|
| Ymir body lane | caller's `stable_id` (u64, unique among live bodies of a world) and its lane while alive | add → live → removed (tombstoned) → lane reusable after the next completed step | Ymir on command | no (the level persists what spawned it) |
| Ymir joint lane | lane while alive; caller may tag | add → live → removed by command or with its body | Ymir on command | no |
| Body part (def) | (body plan content id, part label) | authored content, immutable at runtime | content (game), schema Lodur | CultCache content |
| Body part (state) | (actor, part label) | spawned with the actor → intact → impaired/disabled → severed or dead; never resurrected in MVP (`bds-reattach`) | Lodur physiology | no in MVP (`bds-gore-look` option persist) |
| Wound (injury) | (actor, part, ordinal) | opened by an insult → bleeding → clotting (content rate) → closed; no tending in MVP | Lodur physiology | no |
| Blood (body) | (actor) scalar fraction | 1.0 at spawn, falls by bleeding, recovers only while nothing bleeds (RimWorld, `rw-blood-bleeding`) | Lodur physiology | no |
| Blood visual (pool, decal, spray) | presentation instance | emitted from wound/hit events, fades or stays per `bds-gore-look` | BDS presentation data, Godot draws | no (question) |
| Severed part | the stable ids of its bodies (they survive; only the joint goes) | severed → loose physics prop owned by the session, grabbable, removable by the player | physiology severs; session owns the prop after | no |
| Grab | (session, pointer) handle; anchor's stable id | begin on ray pick → target moved per tick → end on release, or ends when its body is removed (Ymir removal fact) | BDS session | no |
| Impairment state | (actor, limb slot, side) | derived each tick from part states; closed set `Intact, Impaired, Disabled, Severed` per limb slot, mirror-symmetric | derived (physiology) | no |
| Animation clip | content id | authored, immutable | content (BDS), schema Lodur | CultCache content |
| IK goal | (actor, chain) for chain in the closed set `ArmL, ArmR, LegL, LegR, Look, Aim` | written every tick by a voluntary layer, weighted by will, consumed by the binding's solver | Lodur will mix | no |
| Held object (grip) | (actor, hand side) → object stable id | grip begins on behaviour or level content → weld joint with threshold = grip strength → released by behaviour, reflex, unconsciousness or overload | Lodur grip state; Ymir weld executes | level may author "starts holding X" (content) |
| Level / arena | content id | authored with player tools, saved, loaded by replaying commands | BDS | CultCache |
| Contact / hit / overload / removal fact | (step, ordinal) | one step | Ymir | no |
| Attention | (actor) scalar | 1.0, and nothing writes it yet but the test seam `Actor.SetAttention`; startle will drop it, recovering in under a second | Lodur drive | no |
## Questions for the operator and Deru (one batch; admitted as `question`s)
1. `bds-gore-look`: what gore looks like and whether it stays. Options: stylised (bright blood, decals and
spurts, capped stumps, no viscera), realistic (wound textures, exposed bone, gibs), stylised with a content
slider. Recommend stylised default with presentation data shaped to take a realism slider later; blood
visuals fade per session and are never saved in levels. Grounds: People Playground reads clearly with
stylised blood (`mvp-prior-art.pp-physiology`); the sim (wounds, blood fraction) is the same for every
option, so only BDS content and Godot change.
2. `bds-death`: what kills a puppet and what death looks like. Options: RimWorld rules (consciousness 0,
blood loss 100%, lethal part destroyed: head, neck, torso, heart), then limp and permanent until reset;
People Playground rules (no hard line; integrity and oxygen fade, revivable by an item); no death in the
MVP (unconscious only). Recommend RimWorld rules with a session reset, revival items later
(`rw-consciousness`, `rw-body-tree`, `pp-physiology`).
3. `bds-reattach`: can parts be put back. Options: no; prop-only (the player may weld a severed arm back with
the joint tool, it hangs limp and stays Severed to physiology); full heal. Recommend prop-only: it costs
nothing (it is the joint tool) and keeps physiology one-way.
4. `bds-dismember-trigger`: what takes a part off. Options: blades and extreme force both (Cut insults past a
part's HP, and Tear from joint overload while grabbed or hit); blades only; an explicit sever tool. Recommend
both through one severing rule (DF: severed limbs common; Box3D thresholds as sensors, `joint-break-apis`).
5. `bds-upright`: how the puppet stays up in the MVP. Options: seated or strapped (today's stool weld); an
assist pin on pelvis and torso whose strength is consciousness times will, so a fainting puppet collapses
(PuppetMaster pin weights, euphoria doc 10.1); hung or suspended; learned balance (v2, out of MVP per
`euphoria-body-layer-order`). Recommend the assist pin: it is a voluntary layer in the will mix, reads as
standing, and its failure is the collapse People Playground shows.
6. `bds-mvp-clips`: which animations exist. Options: poses only (idle, guard, cower, protect-head, brace, reach,
aim); poses plus a few looping clips (idle sway, struggle, writhe); generated clips from Vili. Recommend poses
plus three loops, authored as pose keys (rung 4's `PoseBehaviour` generalised); Vili clips when its retarget to
this ragdoll exists.
7. `bds-will-visible`: what failing will looks like. Options: tremor and sag (strain shake exists,
`PoseBehaviour.cs:89`), slower and shorter reaches, aim wander; plus an on-screen will bar; plus vocal or
facial cues (presentation). Recommend tremor, sag, slower reach and aim wander from the will mix, plus a
debug bar; voice later.
## Target r4 (landed: `5d0fec8` and r5 `58c2201`; `docs/lodur-target.md` is now the text)
Keep r3's invariants and add:
- `one-severance-owner`: A part is damaged, disabled or severed only by Lodur's physiology; Ymir reports
contacts and joint stress and removes a joint only on command; no physics threshold removes anything by itself.
- `will-is-the-budget`: Every voluntary motor layer (hold, clip, IK reach, look, aim, grip) is weighted by
available will (resolve times attention, capped by consciousness); reflexes act against it with their own
gains; nothing writes targets outside that mix.
- `sandbox-is-content`: An arena is a level built from the commands the player has; no engine path exists only
for an arena; levels are CultCache.
Replace r3's first not-in-scope line with: "Adapting to body topology outside the authored part tree (new
limbs, re-rooted trees, morphology-agnostic learned control). Losing a subtree of the authored tree is in
scope as a closed set of impairment states per limb slot, mirror-symmetric." Add to not in scope: "Weapons,
ballistics, gore and wound presentation (Bad Day Simulator content)."
This resolves the tension the MVP ruling names: severing changes topology only inside the authored tree, so
the behaviour set compensates through a closed set of states (intact, impaired, disabled, severed per limb
slot), as the r3 doc's open item proposed and `euphoria-stimulus-and-impairment` asks (hopping after losing a
leg is a behaviour keyed on the state, not a re-learned controller).
## Rationale
- **Facts, not callbacks.** Ymir fills fixed-capacity fact buffers per step and the caller reads spans, like
lanes; no managed callback crosses the ABI, overflow is counted, never silent (bounded-tick).
- **Tombstones, not compaction.** Lodur and the client cache lane indices (`Ragdoll._bodyLane`,
`Ragdoll.cs:16`). Swap-remove, as the planar session does (`ymir_box3d.c:1435-1436`), would move a
live body's lane under them. A removed lane keeps its last state and a `Removed` kind; reuse waits for a
completed step so end facts still name the old id.
- **Grab is felt.** A motor joint is not a contact, so a grab produces no contact fact. The binding treats every
joint on a ragdoll body that the ragdoll does not own (grab, strap, grip, a player's weld) as a touch at its
anchor with the joint's constraint force: one rule for grabs, restraints and held tools.
- **Poke is a body.** The poke and cut tools are small kinematic bodies on the grab anchor, so their touch
arrives through contacts and their damage through the material table, like a falling blade. The impulse
command stays for explosions, recoil and bullets.
- **Physiology is drive state.** RimWorld's model (part tree, HP, pain sum, blood fraction, consciousness,
capacities; `rw-*` notes) is per-tick state with no per-wound behaviour lookup, which drive-is-state asks.
Numbers start from RimWorld and ATLS bands (`df-and-atls`) as content defaults.
- **Grip and aim follow PuppetMaster's prop and IK split.** A held prop becomes part of the puppet through its
own joint, pick-up and drop are one assignment, and props drop when the puppet loses balance
(`mvp-prior-art-2.puppetmaster-prop-attachment`); aiming IK runs before the physics read so the muscles chase
the aimed pose and physics, pain and will degrade it (`mvp-prior-art-2.ik-after-physics-aiming`). Lodur's
grip is that model with the drop rule moved into drive state (pain in the hand, unconsciousness, overload
of the weld's threshold). Aim error is not a parameter: it is the gap between the aim IK goal and where the
will-weighted, tremoring, startled arm lands. Arma's suppression and fatigue sway
(`mvp-prior-art-2.suppression-aim-degradation`, `aim-physiology-numbers`) are the games that fake that gap
with a sway multiplier; here it emerges, which is what the ruling asks for.
- **Building is props plus constraints plus signals.** Garry's Mod composes from props and a fixed set of
constraint tools and saves entities then constraints (`mvp-prior-art-2.gmod-constraint-duplicator`);
People Playground, Besiege and Algodoo add activation signals, sensors, timers and logic
(`mvp-prior-art-2.algodoo-ppg-besiege-signals`). BDS levels are that triple as CultCache: objects (with
behaviours as content), joints (Ymir kinds, `ymir-joint-kinds`), wires; load creates objects before
joints, as the duplicator's paste does. No source reached says how those games' shipped levels were built;
the ruling's "arenas with the player's tools" is ours.
- **Startle moves up.** The new ruling makes distraction a will drain, so `lodur:follow_up:startle-reflex`
becomes cut `lodur-startle-attention`. It did not land right after rung 4: `lodur-will-mix` landed first (it needs only the `Will` slots, which read 1), so startle now depends on it.
## Cut order
Agent pace: S is one Hands session plus Soul, about 1-2 h; M about 3-4 h; L about 6 h. Ymir runs in parallel
with the Lodur rungs (different repo); Lodur cuts serialise on `Actor.cs`; BDS waits on the client pass.
| # | Cut | Repo | One line | Depends on | Size |
|---|---|---|---|---|---|
| 1 | `ymir-contact-facts` | Ymir | contact/hit facts, contact-force lane, material ids | ymir-shape-lanes (parallel client pass, ABI 3) | M | landed |
| 1' | `ymir-grab-anchor` | Ymir | kinematic anchor, motor joint, impulse, raycast | ymir-shape-lanes (sibling of 1) | S-M | landed |
| 2 | `ymir-break-and-remove` | Ymir | thresholds, overload facts, remove body/joint, tombstones, removal facts | 1 | M | open |
| - | `rung3-sensory-load` Soul, `rung4-goal-flip`, `rung3-office-stress`, `rung4-office-flip` | Lodur/BDS | landed (rung 3 `a048827`, rung 4 the Brain `c26c15c`; the office arc and the chamber release in BDS) | as admitted | - |
| - | `client-ready-sim`, `godot-client-v1` | BDS/Godot | landed (`BodyPainBoxSession`; the Godot client at `client/`) | its own | - |
| 3 | `lodur-will-mix` | Lodur | voluntary layers weighted by will; PoseBehaviour demoted | rung4-goal-flip | M, landed (`afb8df3`, with the recurring break `74883f8`; goal entry effects `c93bdb7`) |
| 4 | `lodur-physiology` | Lodur | part tree content, HP, wounds, blood, pain, shock, consciousness, capacities, death | 3 (landed) | L (split core/binding if over budget) |
| 5 | `lodur-touch` | Lodur | per-part touch from contact facts, external-joint pull; insults from material table | 1, 2, 4 | M |
| 6 | `lodur-startle-attention` | Lodur | startle reflex on onsets; attention scales will | 3 (it writes the Attention slot the will mix already reads) | M, open |
| 7 | `lodur-ik-goals` | Lodur | IK goals in body interface; two-bone arm/leg, look, aim | 3 | M |
| 8 | `lodur-reflex-set` | Lodur | flinch-from-touch, brace | 3, 5 | M |
| 9 | `lodur-sever-impair` | Lodur | severing via binding, impairment states | 2, 4, 5; Q `bds-dismember-trigger`, `bds-reattach` | M |
| 10 | `lodur-clips` | Lodur | pose-key clips as a voluntary layer | 3; Q `bds-mvp-clips` | S |
| 11 | `lodur-assist-pin` | Lodur | upright assist as a voluntary layer | 3; Q `bds-upright` | S |
| 12 | `lodur-grip` | Lodur | grip weld, drop rules, tool frame for aim | 2, 7 | M |
| 13 | `bds-sandbox-session` | BDS | session + command queue, grab/poke/cut | client-ready-sim, 1' | M |
| 14 | `bds-damage-content` + `bds-gore-content` | BDS | materials to insults; gore data | 5, 9; Q `bds-gore-look`, `bds-death` | M |
| 15 | `godot-runtime-bodies`, `godot-interaction`, `godot-blood` | Godot | lifecycle, input, blood | godot-client-v1, 2, 13, 14 | M each |
| 16 | `ymir-joint-kinds`, `bds-level-content`, `bds-contraption-signals`, `godot-build-tools` | mixed | building and arenas | 13 | M-L each |
| 17 | `bds-guns` | BDS | gun content aimed by IK | 7, 12, 1' | M |
Rough total: about 26 cuts, roughly 70-90 agent-hours; with Ymir and BDS/Godot running beside the Lodur chain,
the critical path is the Lodur chain 3 → 4 → 5 → 9 (and 3 → 7 → 12; startle, 6, is off it), about 30 agent-hours after rung 4 lands.
The playable MVP (grab, poke, cut, bleed, sever, reflexes, will) is cuts 1-9, 13-15.
Admitted 2026-11-20 (pass `bds-mvp-map`): specs `lodur:cut_spec:cut-ymir-contact-facts.r2`,
`cut-ymir-grab-anchor.r2` (siblings, after the parallel pass's `ymir-shape-lanes`), `cut-ymir-break-and-remove.r2` (after contact facts); every
later cut above is a `lodur:follow_up:<label>` of the same name (22), owner nibu; questions
`lodur:question:bds-*` (7); ideas `lodur:idea:bds-mvp-map.*` (22, seven rejected and resolved Recorded).
## Wound blood slice (pass `bds-slice-map`, 2026-11-27; mains Lodur `2359142`, Ymir `1d27114`, BDS `f26ec57`)
Probe: `<scratchpad>/nibu-imagination/probe/Program.cs` (Release, net10 roll-forward, paired interleaved medians of 9 against a no-fluid control).
- **B, bleed.** One Knife cut (Skin, Fat, Muscle at 60) bleeds 78.0 mL/s at peak and kills by BloodLoss at 38.1 s; 3 cuts 234 mL/s and 11.2 s; 6 cuts 468 mL/s and 5.5 s. Every bleed-out spills 2.50 L real, 25.0 L visible at gain 10, 1600 drops of 15.625 mL.
- **A, cost on the seated world.** Drops at three body points, settled when supported and under 0.05 m/s for 30 ticks: +0.076 ms a tick at 50 drops/s (live 42), +0.250 at 150/s (live 126), +0.562 at 300/s (live 256), at caps 512 to 2048 alike; wets 37-39, overflow 0. Cap-bound (only the cap settles): 512 live +1.49 ms, 1024 +3.9, 2048 +7.2. Settling carries the gain; the cap stays 512.
- **A, lane reuse.** A lane freed by Settle is free only after the next Step: settling only when emission finds the cap full refuses 795 of about 2,600 drops at cap 512. Settle after the Step, down to LiveCap - MaxDropsPerTick.
- **I, identity.** A SeatedPuppet world with particle capacities and no fluid steps byte-identically over 1200 driven ticks (hash `B3ACA960FE3B41E7` both); Ragdoll.Build places 2 airway sensors.
Order: `cut-bds-wound-blood.r1`, then `cut-bds-client-office.r1`, then follow-up `bds-drown-own-blood-slice` (its Lodur part, `lodur-airway-internal-bleed`, can run beside the client cut). Idea `bds-slice-map.gain-at-circulation-boundary` holds the aspirate-cough amplification hazard for that slice.
## Airway internal bleed (pass `internal-bleed-map`, 2026-11-27; mains Lodur `cb20b37`, Ymir `c635c17`, BDS `407319b`)
Probe: `<scratchpad>/imag-airway/probe` (a scratch copy of Lodur.Core at `cb20b37` with spec `cut-lodur-airway-internal-bleed.r1`'s rule; `Program.cs`, Release, net10).
- **P1, conservation.** Over every run (knife on Skin, Fat, Muscle plus a Larynx core of share 1; gains 1 and 10; vascularity 0.2 and 1), blood lost = skin bleed + airway bleed exactly (2500.2 = 2166.9 + 333.4 mL), and Coughed + Drained + AirwayLiquid = gain x airway bleed exactly (3183.6 + 150.0 = 3333.6 mL at gain 10), the overflow spill included.
- **P2, timing.** Larynx-only Cut 60 (vascularity 1): airway full (occlusion 0.99) at 0.3 s at gain 10, 31.1 s at gain 1; dies of BloodLoss at 53.7 s either way. Larynx-only Cut 20: full at 129 s (gain 10) and 147 s (gain 1), unconscious at 127.7 s both, dead 275-290 s by Consciousness: blood-loss stages, not hypoxia, take him first. With the knife's skin, fat and muscle also cut he is unconscious at 11-18 s and dead at 20-32 s, before the ruled 75 s asphyxia: a cut throat cannot drown him with today's knife (question `bds-throat-cut-bleed-band`).
- **P3, cost.** Physiology.Step on the humanoid with two knife wounds: 2.563 us base, 2.687 us with the rule and Larynx and Trachea added (paired interleaved medians of 7, +0.17 us).
- **Source reads.** Breathing in takes nothing from the world: `Ragdoll.ReadAirway` and `SeatedBody.ReadAirway` only read sensor lanes (idea `internal-bleed-map.drawn-liquid-stays-in-world`). Ymir creates and removes sensors at runtime (`Box3DSoaWorld.CreateSensors`, `Remove`) and destroys particles (`DestroyParticles`), but has no partial take from a wet patch. BDS's knife names Skin, Fat, Muscle and no airway tissue; the Humanoid has no larynx or trachea at `cb20b37`.
Gain owner: the caller (BDS `BloodParameters.Gain`), passed to `Physiology` at construction like `slowScale`; Lodur content holds none. The airway is in world units, so bled blood enters at the gain and leaves at 1x.
Order: `cut-lodur-airway-internal-bleed.r1` (beside `cut-bds-client-office.r1`), then follow-up `lodur-wound-reach` (Lodur), then `bds-throat-cut` (BDS, after client-office and question `bds-throat-cut-bleed-band`), then `bds-airway-expulsion`, then `bds-fella-air-hunger` (question `bds-air-hunger-struggle-look`). `lodur-airway-wound-openings` is off the slice's path.

280
docs/connect-rungs-map.md Normal file
View file

@ -0,0 +1,280 @@
# Lodur: connect the rungs (map)
Campaign `lodur` (Nibu's mind). Imagination pass `connect-rungs-map`, session `nibu-self-2026-11-17`,
2026-11-19. Operator order: "A, connect the rungs" (`lodur:ruling:lodur-body-on-ymir`). This file is the prose
map: body facts, the model page, rationale, the proposed target r3 text (committed as docs/lodur-target.md), and the
Ymir cut draft. Committed here from the Imagination scratchpad so it is durable; the bases below are the pins it was probed at.
## Bases
| Repo | Base | Note |
|---|---|---|
| GameCult/Lodur | `18c4ffd0d598c34fc00f96c7f5d23aafdc003706` | main = origin/main |
| GameCult/BadDaySimulator | `9f597647a608a6c6e44473cc9f1399983de14616` | main = origin/main |
| GameCult/Ymir | `7ba31c30fc3329b84cc638646310259c663c1051` | origin/main. **`F:\Projects\Ymir` local `main` is 11 behind** (its last fetch was 2026-10-29; it has no SoA world at all). I ran `git fetch origin` only (refs, no checkout). Lodur's sibling default `..\Ymir` therefore builds against a tree without `Box3DSoaWorld` until that checkout is fast-forwarded; that is Self's call, not done. |
## Body facts (probes)
All probes in detached worktrees `F:\aeth-wt\connect\{Ymir,Lodur,BadDaySimulator}` at the bases above
(Ymir submodule `extern/box3d` at pin `8441b4a`), Windows 11 workstation, 2026-11-19. Worktrees removed after.
1. **Windows build of Ymir native works with MinGW, with one defect.** No MSVC/VS on the workstation
(`vswhere` finds nothing). `CMAKE_GENERATOR="Ninja Multi-Config" CC=gcc dotnet test tests/Lodur.Tests`
(gcc and ninja from StrawberryPerl, CMake 3.x in Program Files) configures "Box3D on MinGW", builds 53
objects, and links `bin\Debug\libymir_box3d.dll`. The build then fails MSB3030: `Ymir.Box3D.csproj`
expects `bin\$(Configuration)\ymir_box3d.dll` (MSVC naming; MinGW adds the `lib` prefix). After copying the
DLL to the unprefixed name: **Lodur.Tests 21/21 pass on Windows** (6 s), including same-seed-same-hash
within one process. The CultLib pin guard in Ymir's `Directory.Build.targets` did not fire for this graph.
Without `CMAKE_GENERATOR` set: not tried.
2. **What Ymir's SoA world exposes for a hand in a box** (`src/Ymir.Box3D/Box3DSoaWorld.cs`, origin/main;
`docs/soa-world.md` "Not done"): body lanes (stable id, kind, parent, limb, position, rotation quaternion,
linear and angular velocity), write lanes (force, torque), joint lanes. **No contact facts, no sensor shapes,
no overlap or ray queries, no body removal.** Box3D compiles `sensor.c` but Ymir's SoA ABI does not
surface sensors. So the hand-in-box test is geometry over the body lanes: the hand point is the
palm body's centre (the ragdoll has palm, thumb and fingers bodies per arm).
The box is a game stimulus volume (layer 1 "named game stimuli"), not a physics body.
3. **The SoA world is internal.** `Box3DSoaWorld`, `Box3DSoaView` and the kind enums are `internal`, visible to
`Ymir.Core`, `Ymir.Box3D.Soa.Tests`, `Lodur.Body.Ymir` and `Lodur.Tests` by `InternalsVisibleTo`
(`src/Ymir.Box3D/Properties/AssemblyInfo.cs:3-6`, commit 0227636 "until Ymir.Core has a public surface").
`Ragdoll` (Lodur.Body.Ymir) builds a `BodyPlan` into a caller-owned `Box3DSoaWorld`. **Bad Day Simulator cannot name the
world today**, so it cannot own its one physics world without a Ymir change.
4. **A pelvis weld to a static body holds the ragdoll upright for 20 s.** `AddJoint(Weld, staticBox, pelvis)`
is accepted (native refuses only out-of-range or equal indices). Full-strength ragdoll, pelvis welded to a
5 cm static box behind it: head 1.739 m and pelvis 1.110 m at every 2 s checkpoint to 20 s. Unwelded it
topples at about 2 s (first-slice.md), and the pain box breaks at about 15 s.
5. **Arm reach into a box, at strength 1.** Right shoulder target `FromAxisAngle(1,0,0,-1.0)` (joint frame),
elbow `FromAxisAngle(0,0,1,-0.6)`: hand tip settles at about (-0.21, 1.19, 0.46). Over 2-4 s of hold its
range is x [-0.233, -0.191], y [1.175, 1.220], z [0.448, 0.469] (natural wobble, no tremor). Shoulder
`-1.2`, elbow 0.3 gives (-0.21, 1.20, 0.48). Positive shoulder angles swing the arm back (+1.0 puts the hand
at z -0.25). Strength 0 leaves it hanging at y 0.96.
6. **Strength above 1 is not safe on the arm.** Strength 3 with the same targets sagged the hand to y 1.03 and
let it drift in x to -0.35 (explicit PD past its stable damping). Keep strength in [0, 1].
7. **Withdrawal is fast.** Switching the arm target to shoulder +0.3, elbow 2.0 (strength 1) takes the hand out
of a 0.12 m half-extent box centred at (-0.21, 1.19, 0.46) in 5-6 ticks at 120 Hz (about 50 ms).
Shoulder -0.3 / elbow 1.5 takes 18 ticks.
8. **Visible strain needs low frequency.** A 9 Hz shoulder-target tremor of 0.08 rad leaves the hold range
unchanged to the millimetre (the PD at swing gains 20/1 filters it). 3 Hz at 0.15 rad widens y to
[1.162, 1.230]; 4 Hz at 0.3 rad to [1.161, 1.233] and z to [0.437, 0.477]. So strain shows as a shake of a
few Hz, not physiological tremor frequency.
9. **Pain-box baseline at the BDS base** (Windows, git-bash, `dotnet run --project src/BadDay.Cli -- run
--seed N > file`; Summary uses `WriteLine`, so CRLF on Windows and the hashes are platform-bound):
13/13 tests pass; seed 1 "will broke at 14730 ms, hand out at 14830 ms, 16 flinches". sha256 run-1
`973603f9…dd4cc`, run-2 `cf1a6060…a4af95`, run-3 `bafc5967…20e1`. PainSweep table (scratch csproj compiling
`tools/PainSweep/Program.cs` against BadDay.Core; stdout) sha256 `13424cd1…7bf`; cells e.g. 0.80 x 0.95 =
14.9 s, 0.20 x 0.50 = 95.4(8/9), every suppression-0 cell "never". Hands recaptures at base with one method.
10. **Where the model's arithmetic sits** (`src/BadDay.Core/PainBoxSimulation.cs` at base): traits 22-23; box
stimulus 59-61; nociceptor threshold, sensitisation, conduction ring 64-69; pain 72-73; reflex suppression,
leak, flinch, strain 77-86; resolve drain, recovery, break 89-101; sample 104; withdrawal 106-112. Order
inside a tick matters: suppression reads last tick's resolve (gain set ahead of time); the Flinch row is
logged after pain but before strain and resolve update (lines 83, 85, 94).
## Body plan authority (cut `lodur:cut_spec:cut-body-plan-data.r2`, `cut-bds-body-plan-labels.r1`)
The body's structure is data in one place; the hard-coded `HumanoidRagdoll`, `Limb`, `Muscle` and `Region` enums are deleted.
- **Owner:** `BodyPlan` (`src/Lodur.Core/BodyPlan.cs`), built by a plan factory (`BodyPlans.Humanoid()`, a quadruped in `QuadrupedPlanTests`). Immutable after construction.
- **Inputs:** `PartDef` (label, side, shape, size, creation pose, density, friction), `JointDef` (label, side, kind, parent and child part ordinals, anchor, axis, limits, `MuscleGains`), `SensePointDef` (label, side, part, offset).
- **The tree is the joint list.** No part carries a parent field. `ParentOf(part)` is derived at construction from the one joint that has the part as child; part 0 is the root. A part is the child of exactly one joint and a parent precedes its child, so the tree is acyclic and creation order is part order.
- **Names are `(label, side)`**, unique per list (parts, joints, sense points), resolved by `PartIndex`, `JointIndex`, `SenseIndex`; an unknown name throws. Ordinals are plan order and are not a contract between repos; labels are.
- **Validate** (in the constructor, refuses): rule 1 unique non-empty labels; 2 joint ends are parts and parent precedes child; 3 a root exists and every other part has exactly one attaching joint; 4 sense points sit on parts; 5 finite numbers, positive sizes and density, and no field the shape cannot carry (sphere rotation, box rolling resistance, unused size components), limits ordered, cone non-negative.
- **Derived state:** `ParentOf`, the three label indexes, and in `Ragdoll` the part-to-lane and joint-to-lane maps (`BodyLane`, `JointLane`; the parent lane comes from `ParentOf`, the limb lane is the part ordinal). Nothing derived is persisted.
- **Output:** `Ragdoll.Build(world, plan, origin, firstStableId)` adds bodies in part order, then joints in joint order, to the caller's world; `Drive` takes one strength and one target per plan joint; `ReadSensePoints` writes one point per plan sense point. The binding holds no body numbers.
- **Forbidden writers:** the binding, perception, reflex and BDS never add, reorder or alter parts, joints or labels after construction; no code outside `BodyPlan` derives a part's parent; no consumer hard-codes a part or joint ordinal (resolve by label at build).
- **Consumers:** `Ragdoll` (Lodur.Body.Ymir); BDS `SeatedPuppet.Plan` is the one plan instance, passed to `Ragdoll.Build` and therefore the same object as `ragdoll.Plan`; `OfficeBody` and `BodyPainBox` resolve joint, part and sense-point labels against it once at build and index arrays by the resulting ordinals thereafter.
- **Verification layer:** `tests/Lodur.Core.Tests/BodyPlanTests.cs` (each Validate rule, label resolution, derived tree), `tests/Lodur.Tests/QuadrupedPlanTests.cs` (a second morphology builds through the same binding), `RagdollTests.cs` (stand, fall, per-joint strength, torque equal and opposite), BDS tests against the label-resolved humanoid.
## The model page (step 0b)
No persistent content is introduced by these cuts: every parameter stays a code default or a CLI argument,
so `content-is-cultcache` is not engaged yet (follow-up `lodur:follow_up:drive-profiles-as-content`).
| Kind | What names it | Lifecycle | Who decides |
|---|---|---|---|
| Nerve, reflex and drive parameters (`NerveParameters`, `WithdrawalParameters`, `DriveParameters`) | Nothing persistent: C# records with defaults in Lodur.Core; a per-actor instance is a value | Built once when the consumer creates an actor (per-seed traits folded in as `Gain`, `DrainTrait`), immutable for the actor's life | Lodur owns the schema and defaults; the consumer (BDS scenario) owns per-actor values and the trait draw |
| Actor (nervous state: afferent rings, drive state, goal) | The consumer's handle; no id inside Lodur | Created with the scenario, ticked once per physics step, never persisted, dies with the scenario | Lodur.Core alone writes it; nothing else writes drive state |
| Puppet definition (the 19-body humanoid: shapes, joints, gains, sense points) | `BodyPlan` data in Lodur.Core (`BodyPlans.Humanoid()`), built by `Ragdoll` in Lodur.Body.Ymir; world stable ids `firstStableId + part ordinal` passed by the caller | Built into the caller's world once; no removal (Ymir has none) | `BodyPlan` owns geometry, joints, gains and labels, `Ragdoll` builds them; BDS owns placement and stable-id allocation (see "Body plan authority") |
| Stimulus source (the pain box) | BDS object, scenario-local; not a world body | Placed by the scenario; intensity written every tick from its schedule (ramp, noise, disable time) | BDS writes intensity and on/off; Lodur perception only reads it and decides containment and transduction |
| Restraint (stool weld) | BDS scene object: one static box + one weld joint in the world | Created with the scenario | BDS (a game object acting on the body through the world, like a grab; not a layer above Lodur) |
| Scenario run | (seed, parameters) | One run, headless or on the body | BDS; the timeline is output, not content |
## Rationale
- **Wrong owner, now.** The pain box is perception, reflex and drive flattened into the consumer. Lodur.Core
holds only the PD law. The cut moves layers 1-3 and a layer-4 stand-in into Lodur.Core and leaves BDS with
the things a game owns: the box schedule, the seed and trait draw, the restraint, the world, the recorder.
- **Move first, retune never in the same cut.** The layers keep the pain box's double arithmetic and the order
of operations, so seed 1 still breaks at 14730 ms and the sweep table is byte-identical. The only planned
difference: every timeline row becomes end-of-tick state, which changes the strain and resolve columns of
Flinch rows (they were logged mid-tick). Any retune (latencies, `[M]` figures) is a later, separately
falsifiable cut.
- **The game owns the world** (`one-physics-world`, `lodur-body-on-ymir`): BDS creates the Ymir world and Lodur
adds its bodies to it. That needs Ymir's SoA world to be nameable outside Ymir, hence the Ymir cut. A Lodur
facade that creates and hides the world would make Lodur the world's owner, which is the split this invariant
forbids.
- **Headless stays engine-free.** BadDay.Core references only Lodur.Core, so the sweep and the headless tests
build with `dotnet` alone; the body scenario lives in a new BadDay.Ymir project. One more csproj buys a
measure that does not need cmake.
- **Posture.** The PD ragdoll cannot balance for 15 s; the puppet sits strapped at the pelvis (body fact 4).
The learned tracker (v2) is what lets it stand later.
- **Visible strain** is a 3-4 Hz shake along the withdraw direction, scaled by strain (body fact 8), plus the
flinch blend. Sweat is a render concern; there is no renderer.
## Cut order
1. `ymir-soa-public` (GameCult/Ymir): **not admitted**, because Ymir is not in the lodur repo set (target r2:
Lodur, BadDaySimulator). Recommended: target r3 adds GameCult/Ymir; then admit the draft below. Tracked as
`lodur:follow_up:ymir-soa-public-surface`. Ymir is Nibu's stewardship (`nibu:stewardship:gamecult_-ymir.n1`).
2. `nervous-layers` (GameCult/Lodur), `lodur:cut_spec:cut-nervous-layers.r1`. Its Core commits need nothing
from Ymir; its body-binding commit needs cut 1 on Ymir main.
3. `pain-box-on-lodur` (GameCult/BadDaySimulator), `lodur:cut_spec:cut-pain-box-on-lodur.r1`, depends on 2;
blocked on `lodur:question:bds-consumes-lodur`.
### Draft cut spec: ymir-soa-public (admit after target r3 names GameCult/Ymir)
- repo GameCult/Ymir, branch `nibu/soa-public`, base `7ba31c30fc3329b84cc638646310259c663c1051`.
- deletes: `src/Ymir.Box3D/Properties/AssemblyInfo.cs:5-6` (2 lines, the Lodur friend grants).
- file_changes: `src/Ymir.Box3D/Box3DSoaWorld.cs:5` `Box3DSoaKind`, `:13` `Box3DSoaJointKind`, `:151`
`Box3DSoaView`, `:223` `Box3DSoaWorld` become `public`; the native desc/view structs and
`Box3DSoaNative` stay internal; the `Box3DSoaView` constructor stays internal. `native/Ymir.Box3D/CMakeLists.txt`
`:22` `set_target_properties(ymir_box3d ...)` gains `PREFIX ""` so MinGW emits `ymir_box3d.dll` (body fact 1).
`docs/soa-world.md` "Managed (... internal)" and "Not done ... public typed surface" lines: say the SoA world
is public in Ymir.Box3D. Ymir.Core keeps its own surface.
- verification: `dotnet test tests/Ymir.Box3D.Soa.Tests` green; Lodur at 18c4ffd with `YMIR_ROOT` at the head
builds and its 21 tests pass with the friend grants gone; on Windows,
`CMAKE_GENERATOR="Ninja Multi-Config" CC=gcc` builds with no DLL rename. Negative: `InternalsVisibleTo\("Lodur`
in `src/` finds nothing.
- estimate: about +10 / -4 lines, no targets.
## Proposed target r3 text for `Lodur/docs/lodur-target.md`
Hands commits this in `nervous-layers`; Self admits the typed `lodur:target:r3` (invariants as below, repos
GameCult/Lodur, GameCult/BadDaySimulator, GameCult/Ymir; doc at that commit) with the superseding resolution
of r2.
```markdown
# Lodur: target
Campaign `lodur`. The operator's rulings live in Nibu's mind under roots `lodur` and `motion-pipeline` (the
workshop ran under `motion-pipeline`; some of those show as moved in Eureka's mind, and Nibu's copies are the
ones in force). This document holds the rationale and the design truths the campaign produces. Where it and a
ruling disagree, the ruling wins and this file is stale.
## What it is for
A character that reacts to forces and stimuli, and compensates for injury, the way a person would: it pulls
back from something hot, jumps when poked, and crawls toward its objective on one leg if it wants that
objective badly enough. (`motion-pipeline:ruling:euphoria-stimulus-and-impairment`.)
The field has the physics and the balance. NaturalMotion's Euphoria shipped active, physically simulated
characters in GTA IV through Red Dead Redemption 2, and learned trackers (DReCon, ProtoMotions, MaskedMimic)
follow arbitrary motion while keeping their feet. What the field does not have, per the prior-art pass, is the
nervous system on top: senses that are not forces, reflexes layered under deliberate behaviour with their own
latencies, and a character whose will competes with its pain. That layer is Lodur. Evidence:
`gamecult-ops/docs/research/euphoria-at-home-prior-art.md` (sections 1-9 at `8320c18`, section 10 at
`15d9a4e`).
Named after the god in Voluspa who gives the first humans blood, warmth and good colour
(`motion-pipeline:ruling:euphoria-middleware-named-lodur`).
## Layers
Signal flows one way per tick, in this order; each layer has one owner. Layers 1-4 are `Lodur.Core`
(`netstandard2.1`, no references); layer 5 is a body binding.
1. **Perception** (`Perception`, `NerveParameters`, `BoxStimulus`). Contacts, impulses, temperature,
proximity and named game stimuli become typed signals on body regions. Input: one point per body region
(from the body binding, read-only) and the game's stimulus sources. Today one channel (noxious) and one
source kind: a box volume with an intensity the game writes each tick. Output per region: the stimulus, and
the afferent signal after threshold, sensitisation and conduction delay. A poke that barely moves the body
is still a stimulus.
2. **Reflex** (`WithdrawalReflex`, `WithdrawalParameters`). Fast, local responses to afferent signals
(withdrawal now; startle and bracing later), each with a latency, overlaid on whatever the body is doing.
Each reflex's gain is set ahead of time by the drive, the way descending pathways modulate spinal reflexes
(the Gom Jabbar case): a reflex reads the drive state of the previous tick, never waits for behaviour.
Output: the reflex command that leaks past suppression, the strain load of holding the rest down, and
flinch events. Physiology sets the scale: withdrawal roughly 60-150 ms, voluntary reaction about 200 ms
(figures `[M]` in the research doc; verify before they become constants).
3. **Drive** (`DriveState`, `DriveParameters`). Per-character state that evolves every tick: pain from
afferent input, strain from suppressed reflexes, resolve drained by both and scaled by the objective's pull;
later shock on a clock that blood loss speeds and adrenaline that spikes on threat. Resolve reaching zero
breaks the will, which releases every suppression. Static per-character values are this state with its
dynamics frozen. (`motion-pipeline:ruling:euphoria-drive-is-dynamic-state`.)
4. **Behaviour.** The drive selects and weights behaviours (hold against a reflex, withdraw, writhe, crawl to
the objective, pass out, get up) that emit targets and per-muscle strength into caller-owned arrays, and
nothing else. Today one stand-in: hold a pose against the withdrawal reflex, blended toward a withdraw pose
by the reflex leak, shaking with strain, and withdrawing once the will breaks.
5. **Body.** Follows targets with per-muscle strength in the game's physics world. v1 is GameCult's own
PD-tracking active ragdoll on **Ymir**, GameCult's boundary around a pinned Box3D, read and driven through
Ymir's structure-of-arrays world in place (`lodur:ruling:lodur-body-on-ymir`): `Lodur.Body.Ymir`. It owns
the puppet's shapes, joints and gains and reports body-region points upward to perception. v2 is a small
learned tracker for upright states (DReCon scale: 340 us per character per frame measured, 60 us of it the
policy) behind the same interface. (`motion-pipeline:ruling:euphoria-body-layer-order`.)
`Actor` runs layers 1-4 for one character in that order once per physics step, from caller-owned inputs into
caller-owned outputs, and reports its events (flinch, will broke, goal changed) as flags.
## Invariants
- `core-engine-free`: the core assemblies reference no engine and no physics. A Unity or Ymir type in the
core is a defect, not a convenience. The core's tests build without Ymir.
- `body-one-interface`: the body consumes only targets and per-muscle strength. Drive, behaviour and reflex
never set a joint, force or physics property directly; swapping the PD ragdoll for a learned tracker changes
no layer above.
- `one-physics-world`: the game creates and owns one physics world, Ymir's; Lodur adds its bodies to that
world and never creates one of its own. Game objects (a restraint, a box, a thrown chair) act on a puppet
through that world.
- `reflex-gain-from-drive`: a reflex fires on its own shorter latency and overlays the running behaviour; it
never waits for behaviour selection. Will acts on reflexes ahead of time, not after: drive state (resolve,
the pull of the objective) sets each reflex's gain, so a resolved character can hold its hand in the box.
Suppression is never free: the stimulus still feeds pain, and holding a reflex down shows as visible strain
until resolve breaks. Deliberate behaviour takes over a fired reflex only after its own, longer latency.
(`motion-pipeline:ruling:lodur-reflexes-suppressible-by-will`.)
- `drive-is-state`: what a hurt character does is decided by drive state evolving over time, never by a
per-wound lookup.
- `bounded-tick`: per-character work per tick is bounded and allocates nothing in steady state, and the same
inputs give the same outputs. A middleware that hitches is unusable in a game.
- `content-is-cultcache`: persistent content (puppet and object definitions, drive parameters, saved levels
in Bad Day Simulator) is CultCache, per the GameCult substrate doctrine. JSON is schema publication only.
Parameters that are only code defaults are not yet content.
## First consumer
Bad Day Simulator (`GameCult/BadDaySimulator`): a 3D sandbox in the spirit of how People Playground plays,
not its camera or UI. The player gets a level and places puppets of various sorts and objects with set
behaviours and interactions. (`motion-pipeline:ruling:euphoria-sandbox-shape`,
`motion-pipeline:ruling:euphoria-sandbox-named-bad-day-simulator`.) Its one physics world is Ymir's. It is a
separate repo so that Lodur's boundary has a real consumer from the first cut. Its first item is the pain box,
the Synaptic Induction Chamber (`lodur:ruling:bds-pain-box-item`,
`lodur:ruling:bds-pain-box-named-synaptic-induction-chamber`).
## Not in scope
- Adapting to arbitrary changes of body topology. The operator called it too ambitious; impairment is handled
through the drive and the behaviour set.
- A Rust port of the core.
- The StreamPixels overlay as a consumer before StreamPixels M1 ships.
- Depending on RootMotion PuppetMaster (paid, not redistributable, and no balance control: research
section 10.1).
- Hand-tuned balance controllers of the SIMBICON family as the upright path.
## Open
- **Impairment states.** Self's proposal, not ruled: a closed set of named body states (intact, missing a leg,
missing an arm, both legs), with mirror symmetry; crawling as the first locomotion after any leg loss.
- **How Bad Day Simulator consumes Lodur** (`lodur:question:bds-consumes-lodur`).
- **The pain measure** (`lodur:question:pain-sweep-measure`).
- **Ymir gaps Lodur needs next**: contact facts for pain from impacts, body removal, joint springs for stiff
ankles (`nibu-body:follow_up:ymir-soa-lodur-needs`).
- **Renderer and rig** for Bad Day Simulator: nothing draws the puppet yet.
- **Training host for v2.** Raven trains only when the household's GPU allows
(`motion-pipeline:ruling:raven-gpu-defers-to-household`).
- **Trademark search** on "Bad Day Simulator" before anything public is announced.
```
Changes against r2: header names Nibu's mind; layer 5 binds to Ymir (Unity ArticulationBody wording gone, it
was replaced by `lodur-body-on-ymir`); layers carry their first type names and the tick order; `one-physics-world`
restated with the game as the world's owner; `core-engine-free` adds "core tests build without Ymir";
`bounded-tick` adds same-inputs-same-outputs (it was implicit in every test); `content-is-cultcache` says code
defaults are not content; the Rust-port line drops "until a first consumer outside Unity exists" (Unity is no
longer the first host); Open drops the Unity version and UPM items (moot under Ymir) and the rig licence item
becomes renderer and rig.

43
docs/first-slice.md Normal file
View file

@ -0,0 +1,43 @@
# First slice: a PD-muscle ragdoll on Ymir
Bad Day Simulator ladder rung 1: a body that stands, falls and rests deterministically, read through
Ymir's structure-of-arrays world. Nothing above layer 5 exists yet.
## What is built
- `Lodur.Core` (`netstandard2.1`, no references): `Quat`, `MuscleGains`, `PdMuscle.Torque`. A PD law on one
joint: the child's rotation relative to the parent and their relative angular velocity in, a torque out.
Strength is a multiplier on every gain; zero is limp and returns exactly zero, except that a muscle with `Passive` keeps that fraction of its damping (tissue viscosity). Swing (joint frame x, y) and
twist (z) have separate gains.
- `Lodur.Body.Ymir` (`net8.0`, references Ymir.Box3D): `Ragdoll` builds a `BodyPlan` (here `BodyPlans.Humanoid`: 19 bodies, palm, thumb and fingers per arm, and 18 joints) in a
caller-owned `Box3DSoaWorld`: capsule limbs, box pelvis, torso and feet, a sphere head, ball joints at
spine, neck, shoulders and hips, hinges at elbows, knees and ankles. `Drive(strengths, targets)` writes
each muscle's torque onto the world's torque lanes (equal and opposite on child and parent). The strength
array and the target array belong to the caller; nothing is copied or retained, and a tick allocates
nothing (tested).
- Tests (`tests/Lodur.Tests`): the PD law's behaviour; stand, fall, rest; per-muscle strength; torque
conservation; fractional strength scaling; no allocation; same seed, same state hash.
## Measured (Linux x64, Debug native build, one machine)
- At 120 Hz, with full strength and a random one-step shove from the seed (up to 30 N m per axis on pelvis and
torso), the ragdoll holds head height 1.73 m (initial 1.74) through 1.5 s for seeds 1, 2, 3 (tested) and
through about 2 s in the exploratory runs. It then topples: there is no balance controller, so a
pose-holding PD ragdoll is an inverted pendulum with soft ankles.
- With zero strength it falls (head under 0.6 m within 1 s) and its trunk comes to rest within 6 s for seeds
1, 2, 3 (trunk under 0.05 m/s and 0.2 rad/s). Extremities can keep rocking: a head resting on an arm
chattered at up to about 3.5 rad/s for 10 s in one seed. The test bounds it (under 0.6 m/s, 6 rad/s); it
does not claim every body is still.
- Same seed gives the same FNV-1a hash of every body and joint lane at 14 checkpoints, in one process. A
different seed, or one strength element changed, gives a different hash.
## Not measured, or limits found
- Cross-platform bit-identity: unclaimed. Windows (2026-11-19, no MSVC): builds and passes with MinGW gcc, `CMAKE_GENERATOR="Ninja Multi-Config" CC=gcc`; Ymir 0b0321a emits `ymir_box3d.dll` under MinGW, so no rename is needed, and its world create/destroy lock makes test classes safe to run in parallel (before it, two live worlds crashed the host). Unity consumption: unrun. One machine, Debug
native build only; no Release run, no run in a second process.
- Explicit PD through torque lanes limits stiffness and damping: damping times the step must stay under the
inertia it acts on. Hips and spine went unstable at damping 15 and 20 and are set to 3 and 4; the gains
are tuned by running, not derived. Stiff ankles (what balance needs) need joint springs or motors inside
the solver, which Ymir's SoA world does not expose yet.
- A bare sphere rolls on forever, so the head takes a rolling resistance (0.1).
- Hands, a rig licence question, impairment, contact facts (pain input), body removal: not built.

136
docs/flesh-map.md Normal file
View file

@ -0,0 +1,136 @@
# Flesh on the bones: map
Pass `flesh-bones-map` (Imagination, 2026-11-25). Pinned to Lodur fbc3501, Ymir d82da6d, BadDaySimulator 3d6e735.
Rests on rulings bds-particle-tissues, bds-flesh-at-rest, bds-body-skeleton-particle-flesh-rough, bds-skeleton-19-for-mvp,
bds-cut-location, bds-gut-length, bds-gut-rope-tension, bend-limit-stiffness, ymir-sheet-sieve-at-budget-substeps,
particles-are-constraint-graphs, and on the ideas of pass bds-body-flesh-map (2026-11-23), which this map measures and corrects.
## Target shape
Fella is 19 Ymir rigid bones (the plan's parts). Each part's flesh is one skin sheet and, on the six muscled parts, one muscle
sheet: Ymir particles, distances and bends, each particle attached to its own bone at its rest point. Sheets of neighbouring
parts are stitched across each joint by distances. At rest a part's flesh is dormant: in no Ymir loop at all, drawn from the
bone pose. Lodur's binding wakes one part when that part is disturbed and pins it again when it settles. A wound removes the
sheet edges it crosses; a sever at a joint removes that joint's stitches with the joint. Fat and bone are thicknesses in the
part's tissue stack, not particles. Internal tubes and organs stay meshes until released (follow-ups lodur-organ-release-rope,
lodur-exposed-tube-chains).
### Tissue layers per part (plan data)
| Part (label, side) | Skin sheet | Muscle sheet | Stack only |
| --- | --- | --- | --- |
| Pelvis, Torso | yes | yes | fat, bone; organs contained |
| Head | yes | no (scalp over skull) | fat, bone; brain contained |
| UpperArm, LowerArm, Thigh, Shin (L, R) | yes | yes | fat, bone; vessels, tendons contained |
| Foot, Palm, Thumb, Fingers (L, R) | yes | no | bone, tendons contained |
Authority: `PhysiologyPlan.Parts` owns each part's tissue stack (`PartTissuesDef`: `TissueDef` Thickness and `SheetDef`: spacing,
edge and attachment compliance, tensile strength), joined to the `BodyPlan` only by `PhysiologyPlan.Resolve`, the one
(label, side) join. The sheet builder reads (`BodyPlan`, `PhysiologyPlan`). Lodur.Core derives the sheet geometry (rest points
in the part frame, edges, bends, joint stitches) from the part's shape and stack, deterministically, at build. Derived
geometry is never stored: a stored copy would be a cache that could disagree with the stack. The content lives in
`PhysiologyPlans.Humanoid` until lodur-body-plan-cultcache.
## Authority map
- Owner of flesh meaning (which part, which layer, awake or dormant, wound, sever): Lodur's binding (Lodur.Body.Ymir), from
plan data and physiology insults.
- Owner of flesh physics (positions, constraint solve, tension and attachment-force sensors, components): Ymir.
- Inputs to the binding's wake rule: contact impulse lanes on the part's bone, insults on the part, wounds, severs,
evisceration; for re-pinning, attachment force times compliance (the deviation; no new lane).
- Outputs: Ymir commands (create in batches, set pinned, remove distances, destroy particles); Tear insults from DistanceTension.
- Derived: sheet geometry (from the stack), render embedding weights (BDS client, at load), components and tethers (Ymir),
the active lists of the pin cut (Ymir, at command time), the per-particle held-body list and limb skip (Ymir, at command time).
- Forbidden writers: Ymir never wakes, pins, tears or splits on its own; BDS never commands flesh except through the session;
no per-tick writes of dormant particles.
- Demotions: "pinned = inverse mass 0 in every constraint" (follow-up ymir-particle-pinning as admitted) is no longer the
mechanism; dormant particles leave the loops. held_by's scan over every attachment is no longer an owner; the held list is
derived at command time.
## Body facts (probes)
Probe sources: `<scratchpad>/imag-flesh/fella.c`, `sieve.c`, and a copy of Ymir d82da6d `ymir_particles.c` with opt-in probe
patches (pinned skip flags, a body group filter in place of held_by, flesh out of the solid contact grid, phase timers; the
unpatched paths are byte-for-byte the shipped code). gcc 13.2 -O2 -ffp-contract=off, one core, 120 Hz x 4 substeps. Bones are
kinematic proxies driven by forward kinematics of BodyPlans.Humanoid (sways at 3 rad/s); Box3D's own step is not included.
P1 Counts per Fella, sampler at skin 10 cm / muscle 14 cm with a ring floor of 4: 397 skin + 264 muscle = 661 particles,
3,123 distances (383 joint stitches), 434 bends, 661 attachments. At 8 / 10 cm with a ring floor of 6: 619 + 414 = 1,033,
4,742 distances (527 stitches), 736 bends. Torso skin 110 and pelvis 54 at 8 cm; hands 76 together.
P2 Per-tick cost, median of 5 interleaved runs of 600 ticks (`matrix2.sh`, 10/14 cm config):
| Scene | Live particles | ms/tick |
| --- | --- | --- |
| A 1 Fella pinned as mass 0 in the solve (shipped code) | 0 | 4.918 |
| B 1 Fella pinned by skip flags | 0 | 0.255 |
| H 4 Fellas pinned by skip flags | 0 | 1.023 |
| D 1 live forearm, rest dormant (absent) | 40 | 0.204 |
| E 1 Fella live, flesh out of particle contact, limb skip | 661 | 1.036 |
| F E plus a released 8 m gut (300 particles, self-colliding) | 961 | 2.359 |
| G E with flesh in the solid contact walk | 661 | 5.441 |
| I E with held_by's attachment scan instead of the limb skip | 661 | 5.280 |
| J 4 Fellas' bones and capacity, 1 Fella live, rest absent | 661 | 2.271 |
| K J plus the gut | 961 | 4.262 |
Phase split (fella_prof): a live Fella in the contact walk spends 4.4 of 5.4 ms in particle_contacts walking pairs of its
own group that never collide. With nothing live, 0.6 ms of 4 Fellas' 1.2 ms is grid_sort clearing a bucket table sized 2x
particle capacity (32,768 buckets). body_contacts is live particles x every body: 0.49 ms for 232 particles x 77 bodies.
P3 Command cost (one call each, 4 Fellas + gut, 8/10 cm): remove 24 skin edges 0.59-0.65 ms, remove 32 elbow stitches
0.61-0.66 ms (one outlier 10.3 ms); 1 Fella + gut at 10/14 cm: 0.12-0.47 and 0.11-0.17 ms. Every remove, attach and
create_distances runs rederive_topology over the whole world. Waking a part (restoring inverse mass) 2-10 us.
P4 Spawn with one attach per call (the only attach Ymir has): 1 Fella 147 ms, 4 Fellas 2.3 s (quadratic in world size).
P5 Joint rings: with held_by, neighbouring bones of the same Fella push flesh at the joints: max live deviation from the
attachment point 0.064 m against 0.023 m with the limb skip (8/10 cm, all live).
P6 Sieve (`sieve.c`): a skin sheet at 8 cm (36 particles, r 0.036, 96 edges) attached along a static capsule (r 0.07,
half 0.18, horizontal) under a 7x7x7 fluid pour or a 4x4x4 solid block, 3 s at 4 substeps:
| Load, rate | Worst edge stretch | Deep tick x pairs | Load inside the bone | Skin mean axis distance |
| --- | --- | --- | --- | --- |
| fluid 60 Hz | 0.0204 | 35 | 0 | 0.0700 |
| fluid 120 Hz | 0.0221 | 2 | 0 | 0.0700 |
| solid 60 Hz | 0.0275 | 2 | 0 | 0.0700 |
| solid 120 Hz | 0.0321 | 0 | 0 | 0.0700 |
| mutant: attachments off (compliance 1e3), fluid 120 Hz | 0.0566 | 0 | 0 | 0.4016 |
The body-backed skin does not sieve: it holds its place within 0.1 mm and stretches 2-3%. 96 of 343 fluid particles reach the
bone surface between skin particles, which is where the drawn skin is; none enters the bone. The corner-pinned tarp's sieve
is a limit of loose cloth, not of BDS skin.
P7 Solid grid sized by its members (pass ymir-dormant-map; `probes/flesh/grid-mask.probe.patch` on top of the P2 probe,
`grid-mask.fella.patch` adds `MASKSIZED` and an FNV hash of the pos_x, pos_y and vel_z lanes; runs `grid-mask-h.out`,
`grid-mask-k.out`). grid_sort's solid pass uses a mask from the member count (16 or more buckets, at least twice the count,
capped at the table) and walk_half hashes with the same mask. The hash is equal with and without it on a live Fella plus
self-colliding gut (961 live) and on 4 skip-flag Fellas, because walk_half reads a cell's particles in lane order whatever
the bucket count. The fluid grid is left full size: fluid_density sums in bucket order. Paired interleaved medians, 5 runs of
600 ticks:
| Scene | Full table | Sized | Particle-free (bones only) |
| --- | --- | --- | --- |
| 4 Fellas pinned by skip flags | 0.988 | 0.486 | 0.096 |
| 1 live Fella out of contact + gut, 3 Fellas' bones (K) | 3.975 | 3.464 | |
Phase split of the sized 4-Fella run, ms per tick: grid 0.056, particle contacts 0.087, attachments 0.021, distances 0.123,
bends 0.028, bodies 0.014. Those are walks over dormant lanes that active lists remove.
## Cut order
1. cut-ymir-skin-sieve-test (Ymir, test and doc). Beside it: 2. cut-ymir-particle-limb-contact (Ymir: held list derived at
command time, LIMB attachment flag skips the attached body's limb tree) and 3. cut-ymir-flesh-no-particle-contact
(NO_PARTICLE_CONTACT phase bit, solid grid sized by its members; no ABI number).
4. cut-ymir-attach-batch (ABI 17): attach takes n descs and ends in one derivation; the ONE_WAY attachment flag. After
ymir-break-and-remove (ABI 16) and limb-contact.
5. cut-ymir-particle-pinning-dormant (ABI 18): set_pinned; dormant particles out of every substep walk through command-time
active lists and a derived solve inverse mass; pinned particles bordering live ones are kinematic per substep; wake writes
position and velocity from the anchor. After 2, 3 and 4.
6. lodur-tissue-sheet-material (stack material in PhysiologyPlan, Resolve), then lodur-sheet-builder (the deterministic sheet builder).
7. lodur-body-sheets-graph (binding: build dormant, wake per part, re-pin, wounds and severs as commands), after lodur-physiology and lodur-sheet-builder.
8. bds-flesh-render-embedding; then lodur-organ-release-rope and lodur-exposed-tube-chains.
Budget reading: at rest flesh must cost nothing per tick (P2 B, H); one hurt part costs about 0.2 ms; a whole live Fella about
1 ms alone and 2.3 ms in a 4-Fella world; an eviscerated gut adds 1.3 to 2 ms. The rope scene already takes about 2 ms, so a
whole-body event on top of it overruns: question bds-flesh-live-budget.

491
docs/goal-ai-map.md Normal file
View file

@ -0,0 +1,491 @@
# Fella's goal-following AI (map)
Campaign `lodur`, pass `goal-ai-map`, 2026-11-25. Serves `lodur:ruling:bds-fella-needs-goal-ai`: Fella follows
simple goals, moving towards or away from things and interacting with objects. Read with
`lodur:ruling:bds-hallucination-shown` (hallucinations alter his reality and drive behaviour by type),
`lodur:ruling:bds-graft-control-by-wiring`, `lodur:ruling:npc-brain-authors-goals`,
`lodur:ruling:lodur-locomotion-rosen-style` and `lodur:ruling:bds-mvp-clips`. Where this file and a ruling
disagree, the ruling wins.
## Bases
Lodur `fbc3501`, BDS `3d6e735`, Ymir `d82da6d` (origin mains, fetched 2026-11-25).
## Body facts (probes and reads at base)
1. `Brain` (`src/Lodur.Core/Brain.cs`) is goals selected by eligibility (conditions over `DriveState`) then
priority, committed by the Actor after the deliberate latency. A goal has exactly one behaviour, a
`PoseBehaviour`, and **no target**: nothing in a goal names a thing in the world.
2. `Perception` (`src/Lodur.Core/Perception.cs`) reduces the world to intensities: noxious boxes per region, and
point `Emitter`s (channel, position, radius, intensity) reduced to one stimulus per channel at the sense
region, then one `Load`. An emitter has **no identity**: the puppet cannot tell two sounds apart, or know
where anything is. There is no percept of an object.
3. No IK exists in the code (`grep -rniE "\bIK\b|reach|two-bone" src` finds nothing); `lodur-ik-goals` is a
follow-up. The body interface is per-joint strength plus target rotation (`Ragdoll.Drive`).
4. The puppet cannot stand: every BDS body run builds through `SeatedPuppet.Build`, which welds the pelvis to a
stool (`BDS src/BadDay.Ymir/SeatedPuppet.cs:24-30`). `lodur-assist-pin` (the will-scaled upright assist the
Rosen ruling names) is a follow-up, unbuilt.
5. BDS authors two Brains, `OfficeBrain` and `ChamberBrain`; neither has a target. Emitters are built in BDS
`Setting.cs` and `StressSession.cs` with no id.
6. `dotnet test tests/Lodur.Core.Tests` at base: 188 passed, 0 failed (2026-11-25).
Pass `goal-targets-ik-map`, Lodur `4118b47` (percepts landed), Ymir `d82da6d`, 2026-11-25. Probes in the
scratch project `imag-goals/probe` (not committed); humanoid, 120 Hz, 4 substeps.
7. **Joint target convention (probe).** Ymir's joint frame lane at build is the shortest arc from +z to the
plan's axis: Shoulder `(-0.707, 0, 0, 0.707)` (z to up), Elbow `(0, 0.707, 0, 0.707)` (z to across). A target
q makes the child's rotation relative to the parent, from the creation pose, `F q F^-1`: at gravity 0 the
measured upper-arm direction in the torso frame for shoulder `x -1.0` was `(0.14, -0.55, 0.83)` against
predicted `(0, -0.54, 0.84)`, the forearm for elbow `z -1.2` `(0.00, -0.36, 0.93)` against `(0, -0.36, 0.93)`.
Spherical Lower/Upper bound twist (about frame z, the bone axis) and Cone bounds swing (Ymir
`AddJoint` summary). Shoulder twist tracks weakly: a combined target `z +0.6` then `x -0.8` reached joint
rotation `(-0.385, -0.065, 0.157, 0.907)` against `(-0.372, -0.115, 0.272, 0.880)` (twist kp 1, swing kp 20).
Swinging the right arm toward +x hits the torso: the arm collides with its own trunk.
8. **Zero-twist two-bone solve (probe).** Choosing the elbow swivel so the shoulder target has no twist is
closed form: `R = Rot(v, phi) * Arc(p, v)`, `phi/2 = atan2(-Q.y, w v.y + (v x Q).y)` with `(Q, w) = Arc(p, v)`
and y the creation-pose bone axis; the result is unique. Arm lengths: L1 0.310 m, L2 0.265 m (anchors).
That swivel can push the swing past the shoulder cone where another swivel reaches: the seated ward-off goals at
head height (`(0.30, 1.74, 0.26)` left, `(0.00, 1.74, 0.26)` right) clamp 20.5 and 22.6 cm short at zero twist and
are reached at twist 0.27 and 0.52 inside the [-1, 1] limits. At gravity 0 the twist muscle holds those to 0.54
and 0.44 and the wrists land 7.0 and 2.8 cm off (probe, cut `lodur-orient-goals` s1 fix).
Across the body, a goal the zero-twist swivel reaches can still be missed: the right arm swinging toward
`(-0.04, 1.60, 0.24)` drives its forearm into the side of the trunk and wedges there, 45 cm short at gravity 0
(two forearm contacts, swing 0.20 against 1.50); a forward via point for 0.6 s first brings it to 9.8 cm.
9. **Reach on the ragdoll (probe).** Solving each step from the measured torso frame, wrist error after 4 s,
right arm, targets at shoulder plus an offset. Gravity 0, free-floating: `(0,-0.25,0.35)` 3.0 cm,
`(0.12,-0.1,0.4)` 11.1 cm (swing 1.22 near the 1.5 cone, across the body), `(-0.15,-0.3,0.25)` 2.3 cm,
`(0,0.05,0.45)` 1.0 cm. Gravity on, pelvis welded to a static box: 13.6, 17.9, 10.2 and 23.9 cm: PD sag
under gravity, not IK error. A naive task-space integrator on the target (2 and 4 per second, 0.3 m cap)
made it worse (2 to 38 cm, swing past the cone); see follow-up `lodur-reach-tracking`.
10. **Select's one caller** is `Actor.Tick` (`Actor.cs:173`); BDS never calls it (grep at BDS origin/main).
Every authored priority is >= 0 (BDS OfficeBrain 0, 1, 2; ChamberBrain 0, 1; PainBoxBrain 0).
11. **Percept slots are reused** by another id after eviction (`Perception.Admit`), so a target is tracked by
Id. Sense runs before Select within a tick (`Actor.cs:145`, `:173`).
12. **In-flight overlap.** `lodur-physiology-core.r1` changes `Actor.cs` 5-16, 46-90, 100-105, 131-140 and
207-213, `DriveState.cs`, `WillTests.cs`, `CalmSensesTests.cs`; `lodur-airway-openings` changes `BodyPlan.cs`,
`BodyPlans.cs`, `Ragdoll.cs`. `brain-goal-targets` touches `Actor.cs` only at 36-40, 126-129 and 169-194;
`lodur-ik-goals` touches none of these files.
Pass `goal-planner-map`, Lodur `997b1fe`, 2026-11-25, after `lodur:ruling:bds-intelligence-is-planning-depth`.
Probe: a scratch C# replica (not committed), net10 Release on the workstation, 41 rounds of 200 calls in shuffled
order per round, paired medians against a utility-only Select in the same round.
13. **Planner cost (probe).** World: 16 percept slots (the `Perception` default capacity), 48 grounded verbs (go to
each slot, grab and drop four portable things, unlock with either key on either door, open, cut the strap,
switch off, eat, two filler verbs on each of eight other things), facts as a 128-bit set; Fella starts strapped
down with a knife in reach. Six planned wants per Select (open either door, 8 steps; pain off, 4; fed, 6; hold
the knife, 1; a filler, 5). Iterative-deepening regression to the depth limit, plus the utility pass over six
goals by 16 slots. Paired median extra cost per Select over utility alone (3.75 us):
| Depth | Regressive (F.E.A.R.) | Forward | Wants planned | Regressive nodes |
|---|---|---|---|---|
| 1 | 0.47 us | 0.59 us | 1/6 | 18 |
| 2 | 1.33 us | 1.56 us | 1/6 | 41 |
| 3 | 3.30 us | 4.06 us | 1/6 | 97 |
| 4 | 8.52 us | 16.07 us | 2/6 | 244 |
Nodes, untimed, beyond 4: 516, 1118, 2744, 5860 at depths 5 to 8 (all six wants planned at 8); forward search
visits 15035 at depth 5. Regression grows about 2.2x a level, forward about 10x. At depth 4 the planner costs
about 1 ms of CPU per second per puppet at 120 Hz, so it can run every Select: no planning cadence, no plan cache.
14. **Where depth bites.** In the probe world a depth-3 Fella plans nothing but grabbing the knife; depth 4 finds
"grab knife, cut strap, go to switch, switch off"; the door needs 8. Depth is visible in play exactly as the
ruling wants: the same room, the same wants, a different number of things he can work out.
15. **What exists to plan over.** Percepts carry id, kind, position, salience and age (`Perception.cs:111-131`);
nothing carries a fact about the thing (open, locked, on). Interactions do not exist (follow-up
`lodur-interactions`); a verb today has neither preconditions nor effects.
Pass `goal-planner-cut`, Lodur `419d454` (`nibu/brain-goal-targets` head, in Soul review), 2026-11-25.
16. **Baseline.** `dotnet test tests/Lodur.Core.Tests -c Release` at `419d454`: 278 tests. The first run after a
fresh build failed one test in a reflection-invoked path; four reruns passed 278/278. The failing test was not
named in the output kept; a Hands pass that sees it names it.
17. **Facts have no home at base.** `Emitter` carries channel, position, radius, intensity, `Id`, `Kind`;
`Percept` carries id, kind, position, salience, seconds since sensed (`Perception.cs` `Emitter`, `Percept`).
A thing's kind may change between ticks (`PerceptTests` "takes the new kind"), so facts follow the same rule:
the slot takes what it was last sensed with, and `Sense` refuses two emitters of one id that disagree.
18. **Overlap.** Cut 2b is split. Part 1 (`lodur:cut_spec:cut-lodur-goal-planner.r1`) touches only
`Perception.cs`, a new `Planner.cs`, tests and `docs/lodur-target.md` (its row lands after line 115, not
adjacent to `lodur-tissue-sheet-material`'s edit at 112). Part 2 (follow-up `lodur-planner-select`) edits
`Brain.Select` and `Actor`, where `lodur-orient-goals` (ctor `BodyPlan?`, Tick `parts`, the commit block) and
the oxygen cut (`Physiology.Step` input, the ceiling loop) also edit; it runs after whichever of them is in
flight and adds only trailing optional parameters.
Pass `planner-select-cut`, Lodur `77d00d3` (main: goal targets, planner part 1, airway, orient goals), 2026-11-26.
Probes in the scratch project `nibu-imagination-select/probe` (not committed): `Lodur.Core` at `77d00d3` with
`NodeBudget` made settable and a `MoveRule` switch in `Regress` only; net10 Release on the workstation.
19. **Baseline.** `dotnet test tests/Lodur.Core.Tests -c Release` at `77d00d3`: 377 passed.
20. **Reach and the oracle.** `Planner.Plan` sets bit 63 once per call from distance to the observer
(`Planner.cs:177-181`) and no verb takes it away (finding `reach-is-monotone`). The forward oracle in
`PlannerEquivalenceTests` places things only at x 0.5 or 5 and its `Apply` has no reach rule, so it cannot see the
rule either way: with the Regress half of the move rule on, the 17 planner tests (equivalence included) passed.
21. **Crowded worlds (probe).** Rooms of 16, 48 and 64 things (a strap at 0.3 m; knives, keys, doors 70% locked,
switches, tools and four junk kinds within 12 m), verbs of the test catalogue plus `Pry` (strap with a tool) and
junk `Fiddle`/`Stack` decoys, wants on every door, switch, knife and the strap; 100 seeds. Plan calls exhausting the
4096 budget while an unbounded search finds a plan within depth: none at depth <= 5; at depth 6, 23 of 1200 calls
(48 things) and 96 of 1800 (64); at 7-8, 62/1200 and 127/1800. The move rule removed 2-3 plans per 600-1800 calls at
depth 4 (plans holding two far things in reach) and cut nodes slightly. **Decisions** (300 seeds, the best pair by
`raw x (1 - 0.08 len)`, direct `raw x 0.5 x (1 - 0.08 (d + 1))`): per-plan budget, exhaustive or best-first, chose
as unbounded search in every room; one 4096 budget per decision spent best-first differed in 0 rooms at depth 4,
11-20 of 300 at depths 5-8 for 48-64 things, and 16 of 300 at depth 8 for 16 things.
22. **Cost per Select (probe).** Paired interleaved medians, 31 rounds, us per Select (all want pairs):
| Things | Depth | Every pair | Best-first, budget per plan | Best-first, budget per decision |
|---|---|---|---|---|
| 16 | 4 | 25.8 | 10.9 | 11.1 |
| 16 | 8 | 937.6 | 578.7 | 233.0 |
| 48 | 4 | 239.0 | 59.3 | 65.5 |
| 48 | 6 | 1989.9 | 525.1 | 213.4 |
| 48 | 8 | 3169.1 | 1114.2 | 237.7 |
| 64 | 4 | 526.8 | 105.0 | 101.1 |
| 64 | 8 | 3539.3 | 905.2 | 172.6 |
A grounding costs about 0.2 us here, not the 35 ns fact 13's world implied, and pairs multiply it: the 8.5 us of
fact 13 was six wants, not a want per thing. At 120 Hz, 1.1 ms per Select is 13% of a core per Fella.
Pass `reach-tracking-map` (its records cite these facts as 19-23; here they are 23-27), Lodur `77d00d3`, Ymir `e51cf76`, 2026-11-26. Probes in a scratch test class (not committed)
in `F:\aeth-wt\imag-reach-lodur`, net8 Release; humanoid, 120 Hz, 4 substeps; errors after 2 s (seated) or 4 s (reach).
23. **Gravity sag is PD sag, and feedforward removes it (probe).** At base the seated head-height wards read 16.0-17.8
cm under gravity against 2.8-7.0 cm without; the welded reach targets 10.2-24.0 cm against 0.25-0.89 cm. Adding,
after `Ragdoll.Drive`, each joint's subtree gravity load times the muscle's strength (`-(sum m_b (x_b - a_j)) x g`,
masses from the plan's shape and density, which Box3D also uses) brings the reach targets to 0.88, 0.11, 0.55 cm and
the seated wards to 3.95-5.51 cm. At half strength it still sags (12.0-22.9 cm), as a weak will must: the torque
and the stiffness scale together. Cost, an O(parts) bottom-up form, 41 paired interleaved rounds: +0.79 us per
`Drive` (0.89 to 1.66 us) against 89.4 us per `world.Step`.
24. **Feedforward on every muscle moves 13 of 60 `Lodur.Tests` (probe, also projected onto each muscle's gain
axes).** ConnectedPainBoxTests (5): the held arm no longer sags into the box, the will never breaks, the replay
golden changes; HandTests (7): thumbs keep turning at rest (0.2-1.2 rad/s), the wrist overshoots its cone to
1.069, the finger rest reads 0.29 against 0.35; RagdollTests hinge-axis torque (1). Content and tuning were set
against sagging muscles. Question `gravity-feedforward-scope`.
25. **The far-arm wedge is cleared by a via point ahead of the wrist's own side (probe).** Seated low sound, right
wrist from (-0.21, 0.975, 0) to its ward goal (-0.04, 1.60, 0.24) in the torso's creation frame: the straight
wrist segment touches the trunk (distance 0.0 to the torso and pelvis boxes); for the head-height sound on the
right it clears by 6.6 cm, on the left it touches (0.0). Minimum-jerk path, two 0.3 s segments, via point
`(wrist x, mid y, trunk front + c)`, under gravity with feedforward: low far arm 9.9, 7.6, 6.0 cm at c = 0.15,
0.2, 0.3 (zero gravity, c 0.2: 7.8); the left head-height sound's right arm 2.2-3.2 cm. A via point at the
midpoint's x needs c 0.3 and fails at 0.15-0.2 (38-40 cm); at the goal's or shoulder's height 8.2-16.6 cm. A
straight path with no via: 47.5 cm.
26. **A hand path costs where nothing blocks (probe).** The straight minimum-jerk path on the unblocked right-side
ward ends 12.8 cm off (gravity, feedforward) against 5.5 cm for the direct solve; on the left-side ward without a
via, 9.7 against 3.95 (zero gravity 28.2 against 2.8). The final IK targets are the same; the shoulder twist is
not: 0.84 rad off its target after the path against 0.06 direct, no contacts at the end. The twist muscle (kp 1,
fact 7) cannot pull the twist back once the path leaves it elsewhere. Question `reach-path-unblocked`.
27. **The hand-off jump.** `OrientRig.Compose` runs only while the goal in force has layers (`Actor.Tick`,
`PoseBehaviour.Write`), and an arm not driven keeps its slewed output, so engaging slews from stale targets and
disengaging writes the base pose at once (Soul s4 on `lodur-orient-goals`: 0.65 rad in a tick).
28. **Feedforward on a supported body makes it weightless (probe, pass `gravity-cuts-map`).** The hand-rest bodies
that keep turning (fact 24) belong to a fallen body: `RagdollScenario` lies on the ground after 5 s (head at
0.11 m). Feedforward cancels the weight that gave the floor contact its friction, so palm, thumb and fingers
drift at 0.07-0.80, 0.21-1.20 and 0.12-0.94 rad/s (off: 0.000-0.012). Skipping feedforward on the hand joints
leaves them drifting (thumb 0.13-2.88): the load comes from the arms and trunk. Reading the anchor from Ymir's
`JointOrigin` lane instead of the plan changes nothing measurable. A gate that gives a body touching anything
(`ContactCount > 0`) no load settles every hand body (0.000-0.007 rad/s) and passes all five hand-rest tests.
A continuous gate (load minus `ContactImpulse / dt`) is worse than none (thumb 1.5-1.9 rad/s): the one-step
lag rings. The count gate also counts self-contact: thumb against fingers, a forearm on its own thigh.
29. **The pain-box hold re-solved, and its survival curve (probe).** At the base pose (shoulder -1.0, elbow -0.6)
feedforward lifts the palm from (-0.207, 1.121, 0.446) to (-0.174, 1.395, 0.572), out of the box, and no seed
of 20 breaks in 60 s. A grid fit of the two hold angles to put the settled palm (seed 1, 3-4 s, box at
intensity 0) at the box centre gives shoulder -0.66, elbow -0.28 (0.49 cm) without the gate and -0.70, -0.36
(0.34 cm) with it. Seeds 1-20, 60 s limit, break / first flinch in s: at base 14.12-19.23 / 6.86-9.34, median
break 15.9 s, every seed breaks by 19.3 s (no censoring); re-solved pose with gate within +0.03 s of base on
every seed's break and first flinch within 0.11 s (seed 13; the rest equal). Hand in the box after 2 s: 99-100% at
base, 94-98% gated.
30. **What moves with the gate and the re-solved pose (probe, gravity hard-coded so the two zero-gravity tests are
probe artefacts).** `Lodur.Tests`: 5 of 60 (13 ungated): the seed-1 replay golden; the leak test, whose hand
now leaves the box at tick 1756, 18 ticks before the break at 1774 (box half 0.125 was sized against sag); the
wrist cone, 1.0616 against the 1.06 bound both sides; the hinge-torque test (the wrist's feedforward reaches the
forearm). BDS `3d6e735` against it: 69 of 71 (70 of 71 ungated): the body hand-in-box test (one excursion
before the break) and, gated only, the flinch control (tracks 5.5 cm apart before the first flinch, 6.0 after).
Office body tests, the CLI goldens and `tools/PainSweep` (engine-free, no body) do not move. Probe:
`F:\aeth-wt\imag-gravity-probe\` (patch, harness, logs).
31. **The built gate in a crowded room (probe, `PlannerSelectTests`).** The first build planned pairs best raw first, a whole
depth each. Room of 48 things (a strap at 0.3 m, a knife at
0.5 m, then knives, keys, doors 70% locked, switches and four junk kinds within 12 m; the test catalogue plus `Pry`,
`Fiddle`, `Stack`; wants on every door, switch, knife and the strap; doors outrank the strap), 100 seeds, ThinkBudget
4096 against `int.MaxValue`: decisions that differ were 0 at depth 4, 37 at 5, 59 at 6 and 62 at 8 (at 64 things, 8
at depth 4). This is far above fact 21's 4-7%: the first pair in raw order is a locked door no plan within depth 6
reaches, it spends the whole budget searching, and the strap he could cut is starved to a direct try. The count is
a property of the world's priorities (a crowd of high-raw unplannable wants), not of the gate; fact 21's room did
not have it. Paired interleaved medians (20 seeds, 20 measured ticks each after 12 settling ticks, net10 Release,
workstation): `Brain.Select` alone, budget 4096, 406 us at depth 4 and 766 us at depth 6 (unbounded: 259 us and
13.3 ms); `Actor.Tick` over a utility-only Brain, extra 441 us at depth 4 and 924 us at depth 6, the difference
from Select being the committed pair's plan, a second Plan call with the full budget every tick. A grounding costs
about 0.1-0.2 us. Deepening across pairs, with the plan made by the Select that chooses the pair and carried with
it, as built: decisions that differ are a rate, about 0.5% at 48 things and 3% at 64, at every depth (400 seeds, 5000-5399: 1 and 11;
seeds 0-399: 1 and 13; seeds 9000-9399: 3 and 23; the first 100 seeds gave 0 and 2, a property of those seeds). Paired interleaved medians, 48 things, budget 4096, net10 Release: `Brain.Select` 206, 205 and 206 us at depths 4, 6 and 8
(unbounded 205, 208, 206; a Select spends 1592 groundings at the median, 4096 at most), `Actor.Tick` extra over a
utility-only Brain 68 us at depth 4 and 79 us at depth 6: a tick spends at most one `ThinkBudget`. At depth 4 the move rule's plan cost
is about 2x on movers and 1.0x elsewhere (Soul s1 on `lodur-planner-moves`, paired medians, 6 wants); the budget
bounds it, so no work on it here.
32. **Self-contact under the count gate, and the subtree-external gate (probe, pass `gravity2-map`).** At `63444f0` the
count gate's self-contact cost shows in tests: the gravity reach reads 3.01, 3.16, 3.97 cm (ungated 0.89, 0.13,
0.54) because the right thumb and fingers touch. Probed gate: each body's load is deposited at the lowest common
ancestor of it and every body it touches (a body touching nothing deposits at itself; a touch outside the ragdoll
deposits nowhere, as the count gate), then summed bottom-up as at `63444f0`, so a joint carries a body unless a
touch outside the joint's subtree supports it. Touching pairs were kept in the probe from Ymir's Begin/End facts
and equal `ContactCount` on every body every step (2,614,540 body-steps, 0 mismatches). Readings: gravity reach
0.77, 0.16, 0.72 cm; half strength 19.00, 13.85, 22.79 cm; seated ward under gravity 7.03 cm worst (count 6.00,
ungated 7.59, zero gravity 8.11: the ward is not gravity-limited); hand-rest tests pass (ungated: 5 fail). In
the chamber hold at 3 s, 5 of the 7 touching pairs are self-contacts. Cost per `Drive` from a per-step pair list
(lanes mapped by offset, LCA by depth walk), 20000 calls x 41 paired interleaved rounds, net10 Release: +0.227,
+0.230, +0.255 us over the count gate's 1.58-1.93 us. Probe: `F:\aeth-wt\imag-gravity2-probe-lodur.patch`
(scratch modes `LODUR_GATE=count|subtree|none`), logs `F:\aeth-wt\imag-gravity2-*.txt`.
33. **The pain-box hold under the subtree-external gate (probe).** The count-gate pose -0.70, -0.36 settles the palm
4.74 cm from Box (count 0.24). Grid 0.04 then 0.01: -0.68, -0.25 at 0.15 cm (count-gate refit -0.73, -0.30 at
0.15 cm: the fit is a ridge). Seeds 1-20, 60 s: median break 15.90 s (14.16-19.26), holding at 10/15/20 s
1.00/0.70/0.00, censored 0, median first flinch 7.55 s (`63444f0`: 15.88 s, 1.00/0.70/0.00, 7.55). Box half by
the shipped-run rule (seed 1, ticks out from 2 s to the break): 0.145 3, 0.150 2, 0.155 0. `Lodur.Tests` then
fail 2: the seed-1 replay golden and the strain shake (shipped 2.68 cm in second 8, bound 3 cm).
34. **BDS `c55770f` against the gravity feedforward (probe).** Against `63444f0`: 66 of 81 (the report's 15). With
Lodur's pose -0.70, -0.36 and box half 0.145 only: 79 of 81, left the flinch control (seed 1 gap before the
first flinch 5.50 cm, after 6.15) and office settle (seed 100 hand 0.0292 m/s). The same content under the
subtree-external gate: 80 of 81 (only the idle drift, 5.7 cm: the pose was fit for the count gate). With the
subtree refit (-0.68, -0.25, half 0.155): 80 of 81, the flinch control on seed 3 (before 2.06 cm, after 3.98;
rule before < after / 2). The pre-flinch gap is the leak, not a contact: in the Lodur fixture full and
flinch-gain-0 runs part at tick 39-40 (the box ramp), first flinch at 843-1043, and forcing the feedforward's
strength factor to 1 leaves the gap (seeds 1-3 before 1.70-2.69 cm). BDS's world is Lodur's fixture (same
ground, stool, weld, lane order). Probe: `F:\aeth-wt\imag-gravity2-probe-bds.patch`.
## Prior art (research pass `goal-ai-prior-art`)
- The Sims: needs-based utility; objects advertise what they offer, so the data lives on the object and new
objects need no character code. Fits "interact with objects in various ways" and `sandbox-is-content`.
- F.E.A.R. (Orkin, GDC 2006): three states (Goto, Animate, UseSmartObject) plus a STRIPS-like A* planner over
actions. The three states are the motor vocabulary we need. The planner was rejected in the first pass and is
taken now (pass `goal-planner-map`): its depth is plan length, which is what the intelligence ruling names.
Read from the paper's text: the world state is a fixed array of variables, effects and preconditions are
entries in it, search regresses from the goal, and **target and weapon selection run outside the planner**,
which reasons about the one target in focus. That is the split this map keeps: utility picks (goal, target),
the planner finds how.
- HTN (Killzone 2 bots, SHOP-like; Horizon's Decima planner, which backtracks over preconditions as Prolog does):
depth there is the decomposition depth of authored methods. Capping it does not make a duller character, it
truncates a method into a broken one; a dim NPC is one with fewer methods, which is authoring, not a stat.
No published cost figures (Guerrilla's pages give none).
- The Sims: objects advertise and selection is one step; no lookahead (Forbus's lecture notes mention only
routing A*). Wright said the early autonomy was too good and Sims were made dumber for play: the precedent for
intelligence as a tunable limit rather than a fixed competence.
- MCTS (Total War: Rome II campaign AI, Champandard 2014): depth is rollout length and iterations, it needs a
forward simulator of the world, and it is stochastic per decision; built for turn-based campaigns.
- Dave Mark (gamedev.net) on GOAP: long plans in a dynamic world are invalidated each think and replanned
whole. Fella's plans are short (the depth cap) and replanning is the measured 0.5-8.5 us, so the cost he
names is paid and affordable.
- RimWorld: a priority think tree picks a job; a job driver runs a fixed list of toils (go to, reserve, wait,
interact). The tree is what `Brain` already is (priority plus conditions); toils are the shape of an
interaction.
- Utility AI (Dave Mark's infinite-axis system): normalised considerations through response curves, multiplied.
The way `Brain` grows (`lodur:idea:brain-map.brain-extends-to-utility-and-will-mix`), now over (goal, target).
- Gang Beasts: virtual balancing forces not tied to ground contact, and a developer note that the control
mixes the Overgrowth talk with IK and PID on a fully physical ragdoll. Precedent for the will-scaled assist
carrying the body while gait poses and foot IK supply the look.
- Euphoria (GTA IV): behaviours run on a simulated body; reachable sources give no behaviour API. Nothing to
copy below the behaviour level beyond what Lodur already has.
## Target shape
Signal per tick stays one way: perception → reflex → drive → Brain → motor layers → body.
**Percepts (layer 1).** An emitter gains an `Id` (the game's stable id; 0 is anonymous and only loads the
nerve) and a `Kind` (the game's tag; Lodur never interprets it). Perception keeps a bounded percept memory:
one slot per thing sensed (id, kind, last position, salience, seconds since sensed), forgotten after a memory
time. Real and phantom things are **one stream**: a hallucination is a thing in the puppet's reality, sensed
like any other, and nothing the Brain reads tells them apart. Phantom ids carry the top bit, reserved to
Lodur; `Sense` refuses a caller emitter that sets it, so the game cannot forge one and Lodur's hallucination
owner (physiology and substances, `lodur-phantom-perception`) is the only writer.
**Goals with targets (layer 4).** A goal may name a target: a kind filter over percepts. Selection scores each
(goal, percept) pair, Priority times response-curve considerations (distance, salience, drive quantities),
with a commitment bonus on the current pair. Conditions stay eligibility gates. A goal with no target scores
its Priority alone, so OfficeBrain and ChamberBrain select exactly as now.
**The planner (layer 4, between selection and the motor layers).** A goal may name a want: a fact about its
target (open, off, held) or about himself (free, fed). Objects advertise verbs (BDS content, keyed by kind);
each verb carries preconditions and effects as facts over the acting slot, a second slot, or himself, plus the
toil step list that performs it. An emitter carries the thing's facts as the game sees them, and the percept
remembers the facts as last sensed, so a remembered door is still locked to him after it was opened out of
sight. Lodur never interprets a fact key, as it never interprets a kind.
Search is regressive and depth-first with iterative deepening, as F.E.A.R.'s, over verbs grounded on the
percept slots, to a depth limit that is the intelligence stat; it returns the shallowest plan, ties to the
lowest verb order, and allocates nothing. Selection stays utility (`brain-goal-targets`), and the planner is a gate
on its pairs, built in `Brain.Select` and the Actor's `Deliberation`: a pair whose want already holds is not offered;
a pair planned within `PlanDepth` steps scores raw times the `PlanSteps` responses at its length; a pair with no
plan (none within the depth, or the think budget gone) is tried direct at `DirectDiscount`, reading `PlanSteps`
at depth + 1 (ruling `bds-unplannable-tries-direct`, which answers `bds-unplannable-goal`: he goes at the target
and fails where the player can see it; a direct try that reads `PlanLength` -1 for `FrustrationSeconds` bars that pair's
direct try, reports `TickEvents.Frustrated` and decides again past the dwell, and the bar lifts on forgetting the target or
`RetrySeconds`; a changed fact does not lift it, since his own try can change one, and a change that makes the goal
achievable shows as a plannable pair offered through the bar, ruling `frustration-lifts-without-fact-changes`). One `ThinkBudget` serves a whole Select, spent by deepening
across the pairs (Korf's iterative deepening, anytime): round k asks every live pair for a plan of exactly k steps,
by a bound on what the pair can still score, so short plans are found first and one pair's dead end cannot starve the
rest; a want about himself is planned once per goal. The plan is the decision's: made by the Select that chose or
re-chose the pair and carried with it to the Actor's commit (`PlanLength`, `PlanStep(i)`), checked against the
percepts on a tick that decides nothing (its want holds, or a thing it names left memory), and made again for the
pair in force when the dwell refuses a Select, from what is left of that Select's budget. Select never reads it;
the pair's commitment keeps the choice stable. A plan step is a verb on a percept, and a phantom
percept advertises as its kind does: a clever Fella plans through a hallucinated door and fails at it as a dim one
fails at a real one. Intelligence 0 is the Fella of `brain-goal-targets`: no plans, every want pair direct. With no
pair offered the goal in force stays and lets go of its target.
**Mind stats.** Four sim stats per `lodur:ruling:bds-intelligence-is-planning-depth`, each derived each step as
a physiology capacity is (base from the character content, then the offsets and factors of live afflictions,
so a potion is an affliction whose effects target a stat): intelligence (planner depth, rounded down),
quickness (scales the deliberate latency and the dwell), judgment (temperature of a seeded softmax over pair
scores; perfect judgment is the argmax of `brain-goal-targets`), memory (percept memory seconds). Player-facing
stats, if fewer, map onto these four and own nothing.
**Motor layers (layer 4 to 5).** A goal's behaviour becomes a set of voluntary layers, each weighted by will:
pose (exists), look (head IK at the target), reach (arm IK to the target), ward off (arms between head and
target), lean or recoil (pose blend by the target's side), and, once the body can stand, locomotion (a desired
ground velocity toward or away from the target). The hallucination behaviours of the ruling are Brain data
over phantom kinds: flee is avoid, the attractive phantom is approach, fight is approach plus strike, ward
off is a layer, stare at hands is look plus reach at a phantom attached to his own hand, fetal is a pose goal
eligible when threat salience is high and no avoid target is reachable.
**Locomotion is its own chain**, after the orienting goals: the assist pin (pelvis and torso, will times
consciousness), standing (BDS drops the stool weld), a Rosen walk gait (pose keys timed by speed, foot IK),
then steering (seek, flee, arrive) that writes the desired velocity the assist carries. Crawl and hop follow
as impairment gaits.
**Interactions** are advertised by objects (BDS content): a verb, an interaction point and a short step list
in the RimWorld toil shape (go to, face, reach, grip, pose, wait, release). Lodur runs the steps; BDS authors
them.
**Grafts.** Every motor layer writes per joint, so a wired brain's authority is a per-joint mask; two brains on
one joint contest by will. Nothing in the cuts below may write a body-wide output that a mask could not split.
## Authority map
- Owner of what the puppet perceives: `Perception` (the game supplies emitters; Lodur decides what is sensed
and remembered). Owner of what is real to him: the same; phantom-ness is not an input the Brain reads.
- Owner of which goal and which target: `Brain` data, committed by the `Actor`.
- Owner of how a goal is reached: the planner, reading percept facts and advertised verbs to the depth the
intelligence stat gives it. The plan belongs to the decision: written by the Select that chooses or re-chooses the
pair (or by its refusal), carried with it, checked on carried ticks; Select never reads it; nothing outside the Actor writes it.
- Owner of the four mind stats' current values: physiology, from character base and live afflictions. Brain,
planner and Perception read them; a potion, a session or BDS never writes a depth, a latency or a memory time.
- Owner of motion: the will mix over voluntary layers; reflexes act against it.
- Forbidden writers: the game writing a phantom (top-bit id), a Brain reading phantom-ness, BDS setting a goal
or target from outside, any layer writing a joint or force (`body-one-interface`), a kinematic root move,
the planner reading phantom-ness or a kind's meaning, BDS handing Lodur a plan or a depth.
- Derived: salience, the target slot, the thought-bubble type (from the phantoms in memory), desired velocity,
the plan, the mind stats.
- Shared paths: a phantom and a real thing go through the same `Sense`; a scenario Brain and a sandbox Brain
are the same data; a player-placed lure and an arena's lure are the same object content.
## Cut order
| # | Cut | Repo | Builds | Waits on | Size |
|---|---|---|---|---|---|
| 1 | `lodur-percepts` | Lodur | emitter id and kind, percept memory, phantom id bit | none | S, specced |
| 2 | `brain-goal-targets` | Lodur | target filters, (goal, percept) utility, commitment | 1 | M |
| 2b | `lodur-goal-planner` | Lodur | percept facts, verbs with needs and gives, depth-limited regressive planner (core, no caller) | 2 | M, specced |
| 2c | `lodur-planner-moves`, `lodur-planner-select` (built), `lodur-planner-frustration` | Lodur | the move rule and a budget per Plan call; wants, the Select gate, direct tries at a discount (`bds-unplannable-tries-direct`), one think budget per Select, the plan on the Actor; the frustration that ends a futile direct try | 2b | S, M, S |
| 3 | `lodur-ik-goals` | Lodur | Look, ArmL, ArmR as a Core producer of joint targets (legs later) | none (parallel to 2) | M |
| 3b | `lodur-reach-path` | Lodur | hand path through a clearance via point when blocked; arm hand-off slewed both ways | 3, 4 | M, landed |
| 3c | `ymir-world-gravity`, then `lodur-gravity-feedforward` | Ymir, Lodur (+ BDS content) | the world reports its gravity; muscles carry their subtree's weight times strength | Q `gravity-feedforward-scope` | S, M |
| 3d | `ymir-touching-pairs`, then `lodur-gravity-subtree-support`, then `bds-gravity-feedforward-content` | Ymir, Lodur, BDS | the world publishes each step's touching pairs (ABI 20); only a touch outside a joint's subtree supports it (facts 32-33); the chamber re-authored against it (fact 34); Lodur and BDS land in one sitting | 3c | S, S, S |
| 4 | `lodur-orient-goals` | Lodur + BDS | look, reach, ward off and recoil as layers; fetal (a key-pose goal) and stare-at-hands (Look and Reach on a phantom) are data; seated Fella demo | 2, 3 | M |
| 5 | `lodur-phantom-percepts` + `bds-thought-bubble` | Lodur, BDS | phantom things by hallucination type; the bubble reads their kinds | 1, 4 | M, S |
| 6 | `lodur-assist-pin` | Lodur | upright assist | none | S |
| 7 | `lodur-stand` | Lodur + BDS | standing puppet scene, stool weld dropped | 6 | S |
| 8 | `lodur-walk-gait` | Lodur | Rosen walk, leg IK | 3, 7 | M |
| 9 | `lodur-steering` | Lodur | approach, avoid, arrive into desired velocity | 2, 8 | M |
| 10 | `lodur-grip`, then `lodur-interaction-steps` | Lodur + BDS | a verb's toil steps run the plan's current step | 2b, 9, Q `bds-sandbox-lures` | M each |
| 11 | `lodur-mind-stats` | Lodur | intelligence, quickness, judgment, memory as derived stats; potions drive them | 2b, `lodur-physiology-core` | S-M |
Cut 1 is `lodur:cut_spec:cut-lodur-percepts.r1` (landed). Cuts 2 and 3 are
`lodur:cut_spec:cut-brain-goal-targets.r1` and `lodur:cut_spec:cut-lodur-ik-goals.r1`; they touch disjoint files.
The rest are follow-ups. `brain-goal-targets.r1` stands unchanged under the planner: its (goal, target) pair is the
planner's unit, F.E.A.R.'s split of target selection from planning; cut 2b adds one admission gate and one
consideration input to its Select.
**IK rationale (pass `goal-targets-ik-map`, research `ik-prior-art`).** IK is a producer of joint targets in
Lodur.Core, as Final IK feeds PuppetMaster's target pose, not a solver in the binding: the binding stays the
muscle layer and the will mix and graft mask see IK like any other layer. Arms are two-bone with a hinge elbow,
so the analytic solve is exact; FABRIK and CCD wait for graft chains that are not two-bone. The elbow swivel is
the one needing no shoulder twist, because the shoulder's twist muscle tracks a twist weakly (fact 7); what this
gives up is an authored elbow direction. Where that swivel leaves the cone, the swivel is the nearest one inside
the cone and the twist limits, the feasible swivel range of Tolani, Goswami and Badler (2000) (fact 8). When no
swivel is feasible, the swivel is the one whose limit violation (swing past the cone plus twist past its range) is
least, with swing and twist clamped to the limits: at the edge of the feasible set that is the last feasible swivel,
so a goal crossing the edge moves the targets continuously (the zero-twist clamp it replaces jumped 1.4 rad there).
That choice is stateless, and mirrored swivels tie under it (at the shoulder's sagittal plane, unreached or reached),
so it must jump somewhere on the tie set. Ruling `ik-swivel-temporal-coherence` makes each `ArmChain` the arm's solver
across ticks: it holds the previous swivel's basin, takes the stateless choice only when that is better by
`BasinMargin` (less violation, or less twist when both are feasible), and turns the swivel no faster than
`SwivelRate`; the first solve after construction or `Reset` is stateless. Both constants are placeholders. What it
gives up: IK is no longer a pure function of the goal. Near a half-turn swing the swing-twist split in the clamp is
singular, so the clamped solution can still jump; ruling `ik-output-slew-limit` covers it at the output: the returned
shoulder and elbow targets move toward the solution no faster than `MaxAngularRate` (a placeholder near human peak
arm speed), everywhere, and the singular-band special case is deleted. What that gives up: a leaping goal is followed
at the rate, not at once. The slew holds across the hand-off too (cut `lodur-reach-path`, fact 27): an arm that engages
slews from the base pose, one the layer stops driving slews back to it, and `OrientRig.Compose` runs on every tick of an
Actor with a rig, so the arm layer's own contribution to the written arm targets moves at most `MaxAngularRate` times the tick across engage
and disengage while the base pose is constant. A goal switch to a different key pose steps the base itself, and the written arm targets
with it by the base difference (0.2-0.4 rad measured at weights 0.2-0.5), as every other joint's target steps by its key difference;
that step is not slewed. Reach under gravity
lands short by PD sag (facts 9, 23); that is follow-up `lodur-gravity-feedforward`.
**Reach rationale (pass `reach-tracking-map`, ruling `reach-clears-body-by-via-point`).** One owner of an arm's motion
across ticks: `ArmChain` holds the held swivel, the slewed output and now the hand path and the hand-off state, so a
teleport's `Reset` forgets all of it at once. The path is minimum-jerk (Flash and Hogan 1985) in the arm parent's creation
frame, where the chain already solves; it starts at the measured wrist when the arm engages or the Actor commits a (goal,
target) pair, and it is taken only when the straight wrist segment is blocked by the trunk (fact 25). An unblocked reach
solves the goal directly each tick, slewed (ruling `reach-path-blocked-only`; a path there ends further off, fact 26;
it gives up the bell-shaped hand speed of an unobstructed human reach). The via point sits ahead of the wrist's own side,
not of the midpoint (`ArmChain.ViaClearance` 0.2 m and `PathSegmentSeconds` 0.3 s are placeholders; blocked is decided once per
path start, against the trunk bounds the chain derives from the arm's parent part and its ancestors): the arm comes forward first, then across, as a person reaching across their body does. Gravity is a
muscle-layer term, not a reach-layer correction (fact 23): computed-torque practice (PD plus gravity compensation,
Takegaki and Arimoto 1981; Coros et al. 2010 for simulated characters) puts it in the torque, scaled here by strength so a
failing will still sags; a task-space loop on the target was unstable (fact 9) and fights a weak will. PuppetMaster's
alternative, pin forces pulling bodies to the target pose, is an external force and breaks `body-one-interface`.
**Goal-target rationale.** A target is tracked by percept Id (fact 11), selection scores (goal, percept) pairs,
and a retarget inside the goal waits the deliberate latency but not the dwell, held only by the commitment
multiplier. No `TargetChanged` event: nothing reads one.
**Planner rationale (pass `goal-planner-map`).** The ruling makes intelligence the lookahead, and utility
selection has none, so a planner exists. Regression over verbs (F.E.A.R.) is taken because its depth is plan
length, the ruling's own words, and because it visits about a tenth of forward search's nodes at depth 4
(fact 13). HTN is not taken: its depth is authored decomposition, so lowering it breaks methods rather than
dulling the puppet. MCTS is not taken: it needs a forward simulator and is stochastic per decision. What this
gives up: verbs now need preconditions and effects authored as facts (the cost the first pass named), a failed
plan has to be read by a debug view of the plan, and facts on emitters widen the game's interface to Lodur by
one field.
**Planner cut rationale (pass `goal-planner-cut`).** Facts are one `ulong` per thing, the game's bits; bit 63 is
Lodur's in-reach, derived per call from the sense point and the percept's position and refused from the game, as
`PhantomIdBit` is (idea `goal-planner-cut.rejected-reach-as-game-fact`: a game-supplied near goes stale as soon as
he moves; what it gives up is one bit). Verbs are the world's list, given to the planner, not each Brain's
(`rejected-verbs-on-brain`, ruling `bds-lures-tagged-props`). Verbs carry only needs and gives now; the interaction
point and toil steps join the same record in `lodur-interaction-steps`, which waits on locomotion
(`rejected-interaction-steps-first`). Plan steps name percept ids, not slots. A verb that gives its This in-reach is a move
(no Verb field marks it; the give is the mark): after it every other thing is in reach exactly when it is within reach
of that This, by the percepts' remembered positions, so a plan cannot hold two far things in reach (finding
`reach-is-monotone`). A carried thing is reached through a game fact, not reach, so a give of in-reach on a Tool or a
false one is a plain literal. A Plan call takes a budget, defaulting to `NodeBudget`, and `LastExhausted` says it spent
it; a spent budget drops legitimate plans (finding `budget-drops-legit-plans`), and not worked out is tried direct
(ruling `bds-unplannable-tries-direct`).
Intelligence 0 is read as: want goals go direct at the discount and still end in frustration, and every Brain
without wants selects exactly as `brain-goal-targets` (idea `depth-zero-is-direct-with-frustration`, in force for
the part-2 mapper).
**Planner-select rationale (pass `planner-select-cut`).** Cut 2c is three cuts: `lodur-planner-moves` (Planner only:
a This give of in-reach is a move, so after it another thing is in reach only if near the move's target; a budget per
Plan call and `LastExhausted`), `lodur-planner-select` (wants, the gate, the plan on the Actor) and follow-up
`lodur-planner-frustration`. The gate: a satisfied want is not offered; a planned pair scores through `PlanSteps`; an
unplanned or not-worked-out pair is tried direct at `DirectDiscount`, reading `PlanSteps` at depth + 1 so a futile try
never outranks an equal pair he can plan. Pairs are planned by deepening across them (round k, a bound per pair, a round
ends when no bound can win; with an unbounded budget this chooses exactly as planning every pair), so a pair that no plan
reaches cannot spend the budget before a cheap plan is found; fact 31 measures best raw first starving at 59 of 100
decisions at depth 6 and deepening at 0. One `ThinkBudget` per Select bounds cost (fact 22) at the price of 4-7% of choices in crowds at depth 5 and up (fact 21), and 0-2% in fact 31's room:
question `bds-think-budget-per-decision` (Deru). With no pair offered, the goal in force stays and lets go of its
target (finding `stale-target-without-pair`); the orient layers then rest. The pair's plan is made with the decision (the
Select that chose it, or re-chose it, or was refused and plans the pair in force) and carried; it is not derived each tick, which cost a
second Plan call per tick (fact 31).
## Mind stats
`lodur:ruling:bds-intelligence-is-planning-depth` answers the withdrawn `bds-intelligence-in-goal-ai`: four
stats, not one scalar. Follow-up `lodur-mind-stats` holds them (see Target shape).

View file

@ -1,123 +1,190 @@
# Lodur: target
Campaign `lodur`. The operator's rulings live in the eureka-state mind under
root `motion-pipeline` (the workshop ran there); this document holds the
rationale and the design truths the campaign will produce. Where it and a
Campaign `lodur`. The operator's rulings live in Nibu's mind under roots `lodur` and `motion-pipeline` (the
workshop ran under `motion-pipeline`; some of those show as moved in Eureka's mind, and Nibu's copies are the
ones in force). This document holds the rationale and the design truths the campaign produces. Where it and a
ruling disagree, the ruling wins and this file is stale.
## What it is for
A character that reacts to forces and stimuli, and compensates for injury,
the way a person would: it pulls back from something hot, jumps when poked,
and crawls toward its objective on one leg if it wants that objective badly
enough. (`motion-pipeline:ruling:euphoria-stimulus-and-impairment`.)
A character that reacts to forces and stimuli, and compensates for injury, the way a person would: it pulls
back from something hot, jumps when poked, and crawls toward its objective on one leg if it wants that
objective badly enough. (`motion-pipeline:ruling:euphoria-stimulus-and-impairment`.)
The field has the physics and the balance. NaturalMotion's Euphoria shipped
active, physically simulated characters in GTA IV through Red Dead Redemption
2, and learned trackers (DReCon, ProtoMotions, MaskedMimic) follow arbitrary
motion while keeping their feet. What the field does not have, per the prior-art
pass, is the nervous system on top: senses that are not forces, reflexes layered
under deliberate behaviour with their own latencies, and a character whose will
competes with its pain. Euphoria's reactions are whole-body behaviours a game
starts; nothing in the record senses heat or a light touch, and nothing models
the twenty seconds in which a wounded character crawls, slows, and passes out.
That layer is Lodur. Evidence: `gamecult-ops/docs/research/euphoria-at-home-prior-art.md`
(sections 1-9 at `8320c18`, section 10 at `15d9a4e`).
The field has the physics and the balance. NaturalMotion's Euphoria shipped active, physically simulated
characters in GTA IV through Red Dead Redemption 2, and learned trackers (DReCon, ProtoMotions, MaskedMimic)
follow arbitrary motion while keeping their feet. What the field does not have, per the prior-art pass, is the
nervous system on top: senses that are not forces, reflexes layered under deliberate behaviour with their own
latencies, and a character whose will competes with its pain. That layer is Lodur. Evidence:
`gamecult-ops/docs/research/euphoria-at-home-prior-art.md` (sections 1-9 at `8320c18`, section 10 at
`15d9a4e`).
Named after the god in Voluspa who gives the first humans blood, warmth and
good colour (`motion-pipeline:ruling:euphoria-middleware-named-lodur`).
Named after the god in Voluspa who gives the first humans blood, warmth and good colour
(`motion-pipeline:ruling:euphoria-middleware-named-lodur`).
## Layers
Signal flows one way per tick; each layer has one owner.
Signal flows one way per tick, in this order; each layer has one owner. Layers 1-4 are `Lodur.Core`
(`netstandard2.1`, no references); layer 5 is a body binding.
1. **Perception.** Contacts, impulses, temperature, proximity and named game
stimuli become typed stimuli on body regions. A poke that barely moves the
body is still a stimulus.
2. **Reflex.** Fast, local responses to stimuli (withdrawal, startle,
bracing), each with a latency, overlaid on whatever the body is doing.
Their gain is set from above by the drive, the way descending pathways
modulate spinal reflexes: the Gom Jabbar case. Physiology sets the scale: withdrawal roughly 60-150 ms, voluntary
reaction about 200 ms (figures `[M]` in the research doc; verify before
they become constants).
3. **Drive.** Per-character state that evolves every tick: pain accumulates
and decays, shock runs on a clock that blood loss speeds, adrenaline spikes
on threat and fades; resolve is a trait, and the objective pulls. Static
per-character values are this state with its dynamics frozen.
(`motion-pipeline:ruling:euphoria-drive-is-dynamic-state`.)
4. **Behaviour.** The drive selects and weights behaviours (writhe, crawl to
the objective, pass out, get up, the reflex overlay) that emit targets.
5. **Body.** Follows targets (poses, IK goals) with per-muscle strength on the
host engine's articulated physics. v1 is GameCult's own PD-tracking active
ragdoll and ships the ground behaviours; v2 is a small learned tracker
(DReCon scale: 340 us per character per frame measured, 60 us of it the
policy) for upright states, behind the same interface.
(`motion-pipeline:ruling:euphoria-body-layer-order`.)
1. **Perception** (`Perception`, `NerveParameters`, `BoxStimulus`, `Emitter`). Contacts, impulses, temperature,
proximity and named game stimuli become typed signals on body regions. Input: one point per body region
(from the body binding, read-only) and the game's stimulus sources. Two source kinds today: noxious box
volumes with an intensity the game writes each tick, and point emitters on the audio, visual and interrupt
channels (position, radius and intensity written each tick, falling off linearly to the radius), sensed at
one region and combined into one load, `1 - prod(1 - afferent)`. An emitter may carry an `Id` (the game's
stable id; 0 is anonymous and only loads the nerve) and a `Kind` (the game's tag, never interpreted by Lodur).
Perception keeps a bounded percept memory (`PerceptParameters`, `Percept`): one slot per identified thing
strictly inside an emitter's radius, with its kind, the position of the emitter that reached it hardest,
salience (that reach times the sensory gain) and seconds since sensed, forgotten after a memory time. The top
id bit (`PhantomIdBit`) is reserved to Lodur's phantoms and `Sense` refuses it from the game. Percepts also remember the thing's `Facts`
(a `ulong`, bit i is fact i) as last sensed; the game owns every bit but 63 (`InReachFact`), which is Lodur's and which `Sense` refuses, like `PhantomIdBit`. Output per region: the stimulus, and
the afferent signal after threshold, sensitisation and conduction delay; and the load, and the percepts. A poke that barely moves the body
is still a stimulus.
2. **Reflex** (`WithdrawalReflex`, `WithdrawalParameters`). Fast, local responses to afferent signals
(withdrawal now; startle and bracing later), each with a latency, overlaid on whatever the body is doing.
Each reflex's gain is set ahead of time by the drive, the way descending pathways modulate spinal reflexes
(the Gom Jabbar case): a reflex reads the drive state of the previous tick, never waits for behaviour.
Output: the reflex command that leaks past suppression, the strain load of holding the rest down, and
flinch events. Physiology sets the scale: withdrawal roughly 60-150 ms, voluntary reaction about 200 ms
(figures `[M]` in the research doc; verify before they become constants).
3. **Drive** (`DriveState`, `DriveParameters`). Per-character state that evolves every tick: pain from
afferent input, strain from suppressed reflexes, arousal from sensory load; resolve drained by all three and
scaled by the active goal's pull, recovering only when pain and arousal are both low;
later shock on a clock that blood loss speeds and adrenaline that spikes on threat. Resolve reaching zero
breaks the will, which releases every suppression; the break is an event that counts (`Breaks`) and recurs:
the will mends when resolve climbs back to `WillMendsAt`. `Will` is what is available to hold a reflex down
and to power a voluntary layer: resolve times `Attention`, capped by `Consciousness` (both slots that read 1
until startle and physiology fill them). Static per-character values are this state with its
dynamics frozen. (`motion-pipeline:ruling:euphoria-drive-is-dynamic-state`.)
4. **The Brain.** The consumer's authored goals (a behaviour, a priority, a pull in [0, 1] that defaults to 0, no pull (the former objective pull
defaulted to 0.5), an optional minimum dwell, conditions over the drive
state), selected after a deliberate latency: the eligible goal of highest priority is wanted, and the
Actor commits it. Lodur has no flip rule of its own; every rule is Brain data
(`lodur:ruling:npc-brain-authors-goals`). One behaviour, `PoseBehaviour`: a pose held or a loop of pose keys,
blended toward a flinch pose by the reflex leak and shaking with strain, emitting targets and per-muscle
strength into caller-owned arrays and nothing else. Commitment is soft: a goal with a minimum dwell, counted
in ticks from the tick it took over, is left for a goal that ties or ranks below it only once the dwell has
passed, while a strictly higher-priority goal preempts during the dwell (after the deliberate latency); the
return trip from an entered goal is gated by that goal's own dwell, which is what bounds chatter at a threshold.
A goal also carries an entry effect on the drive (`EntryResolve`: the tick it takes over, resolve is set, which
is how rage resets the will), an `Effort` (resolve drained per second to sustain it) and `InvoluntarySeconds`
(an onset that runs without will and without paying the effort; +infinity is involuntary throughout)
(`lodur:ruling:rage-involuntary-onset-then-voluntary`). The will mix: a voluntary goal writes each muscle at
`HoldStrength x min(1, Will^WillCurve + leak x FlinchGain)` (the Actor passes `Will^WillCurve` as the weight), an involuntary one at `HoldStrength`, so a failing
will slackens the layer while a reflex that gets past it still moves the muscle
(`lodur:ruling:bds-sandbox-arenas-will-economy`).
A goal can also carry a sensory gain and an arousal target (`SensoryGain`, `EntryArousal`), reached linearly over `EntrySeconds`
from their values at takeover (0, the default, is at the takeover tick; the Start goal's apply at construction). The gain multiplies the sense
channels' afferents as they leave the conduction delay, so sensitisation still follows the world; `Load` is built from the gated afferents and
`ChannelStimulus` stays the world's. Sense reads the gain at the start of each tick, so a change of gain reaches `Load` one tick after the Actor sets it;
the ramp's last tick assigns the targets exactly. The nociceptive region afferents, the withdrawal reflex and its flinch are never gated. The Actor owns the gain
in force (`DriveState.SensoryGain`) and, through the ramp, arousal; after it the drive owns arousal again. Calm uses it to silence the office's
stressors and drain the stress bar, tailing off over a few seconds rather than cutting
(`lodur:ruling:stress-bar-shows-arousal-calm-silences`, `lodur:ruling:flinch-tail-after-stimulus`).
A built Brain owns copies of its data and reads back as read-only views. Considerations extend it.
5. **Body.** Follows targets with per-muscle strength in the game's physics world. v1 is GameCult's own
PD-tracking active ragdoll on **Ymir**, GameCult's boundary around a pinned Box3D, read and driven through
Ymir's structure-of-arrays world in place (`lodur:ruling:lodur-body-on-ymir`): `Lodur.Body.Ymir`. It owns
the puppet's shapes, joints and gains and reports body-region points upward to perception. v2 is a small
learned tracker for upright states (DReCon scale: 340 us per character per frame measured, 60 us of it the
policy) behind the same interface. (`motion-pipeline:ruling:euphoria-body-layer-order`.)
Layers 1-4 are the core: C# with no engine references, testable without an
engine. Layer 5 binds to the host: Unity `ArticulationBody` first; v2 inference
through the engine's runner (Unity Inference Engine, ONNX Runtime).
(`motion-pipeline:ruling:euphoria-first-consumer-sandbox-csharp-core`.)
`Actor` runs layers 1-4 for one character in that order once per physics step, from caller-owned inputs into
caller-owned outputs, and reports its events (flinch, will broke, goal changed, died) as flags.
### Who writes what, per tick
One order inside `Actor.Tick`: the Physiology steps and writes Consciousness (an actor with a physiology; a dead one
goes limp and ends the tick) → Perception senses (with the sensory gain in force) → each reflex steps on its
afferent (gain from the previous tick's drive) → the drive steps (pain, strain, arousal, resolve, the break and
the mend; the goal's effort is paid here) → the Brain decides (a decision is pending for the deliberate latency)
and a due decision commits (entry resolve is set) → the entry ramp assigns gain and arousal → the goal's
behaviour writes strengths and targets at the will's weight (the key pose, then the orient layers (recoil, look, arms) toward the committed target from the caller's part poses, then the flinch blend over every joint), and the strengths are scaled by the motor ceiling. The tick that
commits a goal already writes under it.
| Owner | Inputs | Outputs | Derived state | Forbidden writers |
|---|---|---|---|---|
| `Perception` | region points, the game's stimulus sources and emitters, the sensory gain passed in | per-region stimulus and afferent, per-channel stimulus and afferent, `Load`, the percept slots | sensitisation, the conduction rings, percept salience and slot occupancy; the channel afferents are gated, the stimuli are not | the drive or a goal writing an afferent; the game setting `PhantomIdBit` (`Sense` refuses it); the Brain or a session writing a percept; a gain outside [0, 1] (`Sense` refuses it, NaN and infinity included); gating a region (nociceptive) afferent |
| Reflex (`WithdrawalReflex`) | its region's afferent and the drive's `Will` (the pull acts through resolve's drain, not here) | leak, strain load, flinch | none beyond its latency ring | the Brain or the behaviour setting a reflex gain |
| Drive (`DriveState`) | afferent sum, strain load, `Load`, the goal's pull and effort | pain, strain, arousal, resolve, `Breaks`, `Will` (= min(resolve x attention, consciousness)), the break and mend events | `Will` is derived and never stored; the break recurs (it mends at `WillMendsAt`) | the Brain, a session or the body writing resolve, arousal or `Will`; the one sanctioned jumps are `Enter` (a goal's entry resolve) and the Actor's entry ramp (arousal) |
| Attention slot | nothing yet: reads 1 (startle is the writer to come) | a factor of `Will` | none | anything but the startle reflex (`lodur-startle-attention`); the Actor's test seam `SetAttention` is internal |
| Consciousness slot | `Physiology.Consciousness`, written by the Actor each tick; 1 for an actor with no physiology | the cap of `Will` | derived from the physiology each tick | anything but the Actor reading its Physiology; no test seam: tests lower it through a Physiology |
| `Physiology` | its `BodyPlan` and `PhysiologyPlan` (tissue stacks, joined to the `BodyPlan` by `PhysiologyPlan.Resolve`, the one (label, side) join; a stack also carries thickness and sheet material that Physiology does not read; afflictions with data effects, blood) at construction; `Afflict` (the one entry for harm); `Step(dt)` from the Actor; the slow scale at construction | capacities (`Consciousness`, `BloodPumping`), `Bleed` per part, `BloodVolume` and `BloodLoss`, `MotorCeiling` per joint, `Integrity` per tissue, `Dead`, `Cause`, `Refused` | integrity (from Injures afflictions: part HP is never stored), capacities, bleed and the ceiling, recomputed each step; death is judged once at the end of a step (vital tissue, blood loss, consciousness: `lodur:ruling:bds-death`) and is permanent | anything else writing tissue, blood or the slot; a game writing integrity, volume or severity (harm enters through `Afflict`); an effect writing state; an affliction killing by its own severity; tissue, organ or affliction labels outside content (`PhysiologyPlans`) |
| Brain (`Brain`, `GoalSpec`) | the drive state it reads through conditions | the wanted goal; each goal's pull, priority, dwell, entry effects (`EntryResolve`, `EntryArousal`, `SensoryGain`, `EntrySeconds`), `Effort`, `InvoluntarySeconds` and behaviour | none: it is data, copied at build and read back read-only | a flip rule anywhere else (`lodur:ruling:npc-brain-authors-goals`) |
| `Actor` | all of the above, one tick | the committed goal; `DriveState.SensoryGain`; arousal during a goal's `EntrySeconds`; the events | the pending decision and its tick, the dwell, the ramp's start values, the onset in whole ticks | a consumer setting the goal or the gain from outside |
| Behaviour (`PoseBehaviour`) | the weight (the will's `Will^WillCurve` once the goal's involuntary onset is over, else 1), the leak, strain, time | strengths and targets into caller arrays: `HoldStrength x min(1, weight + leak x FlinchGain)` | none | writing a joint or a force (`body-one-interface`); any strength not under the will mix |
| Orient layers (`LookLayer`, `ArmLayer`, `RecoilLayer` on the goal's `PoseBehaviour`; solved by the Actor's `OrientRig`) | the committed target (`Actor.Target`), the caller's part poses (`Ragdoll.ReadPartPoses`), the `BodyPlan` at construction | joint targets only: the neck, the shoulders and elbows, and the recoil poses' joints, blended in before the flinch | the Nearer arm side, set when a (goal, target) pair commits and held until the next commit; layer targets are recomputed each tick and never stored | a layer writing strength; the game solving IK around the Actor or overwriting targets after `Tick`; IK in the Ymir binding; a layer reading `PhantomIdBit`; a mid-pair arm-side flip; an arm the closed form cannot solve (bent at creation, an elbow range straddling zero) is refused at construction, naming the goal and side |
| `Planner` | percept facts and positions, self facts, the verb list (`Verb`: kind filters, needs, gives), a depth, the reach | `Plan`'s length (0 holds, n steps, -1 none within depth or within the 4096-grounding `NodeBudget`, a counter) and the steps as (verb index, This id, Tool id) in the caller's buffer | reach (bit 63) from distance, per call; the plan, per call | reading phantom-ness or a kind's or fact's meaning; storing a plan; the game supplying bit 63; allocating after construction |
## Invariants
- `core-engine-free`: the core assemblies reference no engine. A Unity type in
the core is a defect, not a convenience.
- `body-one-interface`: the body consumes only targets and per-muscle strength.
Drive, behaviour and reflex never set a joint, force or physics property
directly; swapping the PD ragdoll for a learned tracker changes no layer above.
- `one-physics-world`: the body simulates in the host's physics world. No
second world that the game's objects cannot touch.
- `reflex-gain-from-drive`: a reflex fires on its own shorter latency and
overlays the running behaviour; it never waits for behaviour selection. Will
acts on reflexes ahead of time, not after: drive state (resolve, the pull of
the objective) sets each reflex's gain, so a resolved character can hold its
hand in the box. Suppression is never free: the stimulus still feeds pain,
and holding a reflex down shows as visible strain until resolve breaks.
Deliberate behaviour takes over a fired reflex only after its own, longer
latency. (`motion-pipeline:ruling:lodur-reflexes-suppressible-by-will`.)
- `drive-is-state`: what a hurt character does is decided by drive state
evolving over time, never by a per-wound lookup.
- `bounded-tick`: per-character work per tick is bounded and allocates nothing
in steady state. A middleware that hitches is unusable in a game.
- `content-is-cultcache`: persistent content (puppet and object definitions,
drive parameters, saved levels in Bad Day Simulator) is CultCache, per the
GameCult substrate doctrine. JSON is schema publication only.
- `core-engine-free`: the core assemblies reference no engine and no physics. A Unity or Ymir type in the
core is a defect, not a convenience. The core's tests build without Ymir.
- `body-one-interface`: the body consumes only targets and per-muscle strength. Drive, behaviour and reflex
never set a joint, force or physics property directly; swapping the PD ragdoll for a learned tracker changes
no layer above.
- `one-physics-world`: the game creates and owns one physics world, Ymir's; Lodur adds its bodies to that
world and never creates one of its own. Game objects (a restraint, a box, a thrown chair) act on a puppet
through that world.
- `reflex-gain-from-drive`: a reflex fires on its own shorter latency and overlays the running behaviour; it
never waits for behaviour selection. Will acts on reflexes ahead of time, not after: drive state (resolve,
the pull of the active goal) sets each reflex's gain, so a resolved character can hold its hand in the box.
Suppression is never free: the stimulus still feeds pain, and holding a reflex down shows as visible strain
until resolve breaks. Deliberate behaviour takes over a fired reflex only after its own, longer latency.
(`motion-pipeline:ruling:lodur-reflexes-suppressible-by-will`.)
- `drive-is-state`: what a hurt character does is decided by drive state evolving over time, never by a
per-wound lookup.
- `bounded-tick`: per-character work per tick is bounded and allocates nothing in steady state, and the same
inputs give the same outputs. A middleware that hitches is unusable in a game.
- `content-is-cultcache`: persistent content (puppet and object definitions, drive parameters, saved levels
in Bad Day Simulator) is CultCache, per the GameCult substrate doctrine. JSON is schema publication only.
Parameters that are only code defaults are not yet content.
- `one-severance-owner`: a part is damaged, disabled or severed only by Lodur's physiology. Ymir reports
contacts and joint stress and removes a joint only on command; no physics threshold removes anything by
itself.
- `will-is-the-budget`: every voluntary motor layer (hold, clip, IK reach, look, aim, grip) is weighted by
available will (resolve times attention, capped by consciousness); reflexes act against it with their own
gains; nothing writes targets outside that mix. A distraction such as a startle lowers attention, and so the
will every layer can spend (`lodur:ruling:bds-sandbox-arenas-will-economy`).
- `sandbox-is-content`: in Bad Day Simulator an arena is a level built from the commands the player has; no
engine path exists only for an arena; levels are CultCache.
## First consumer
Bad Day Simulator (`GameCult/BadDaySimulator`): a 3D sandbox in the spirit of
how People Playground plays, not its camera or UI. The player gets a level and
places puppets of various sorts and objects with set behaviours and
interactions. (`motion-pipeline:ruling:euphoria-sandbox-shape`,
`motion-pipeline:ruling:euphoria-sandbox-named-bad-day-simulator`.) It is a
separate repo so that Lodur's boundary has a real consumer from the first cut.
Bad Day Simulator (`GameCult/BadDaySimulator`): a 3D sandbox in the spirit of how People Playground plays,
not its camera or UI. The player gets a level and places puppets of various sorts and objects with set
behaviours and interactions. (`motion-pipeline:ruling:euphoria-sandbox-shape`,
`motion-pipeline:ruling:euphoria-sandbox-named-bad-day-simulator`.) Its one physics world is Ymir's. It is a
separate repo so that Lodur's boundary has a real consumer from the first cut. Its first item is the pain box,
the Synaptic Induction Chamber (`lodur:ruling:bds-pain-box-item`,
`lodur:ruling:bds-pain-box-named-synaptic-induction-chamber`).
## Not in scope
- Adapting to arbitrary changes of body topology. The operator called it too
ambitious; impairment is handled through the drive and the behaviour set.
- A Rust port of the core, until a first consumer outside Unity exists.
- Adapting to body topology outside the authored part tree (new limbs, re-rooted trees, morphology-agnostic
learned control). Losing a subtree of the authored tree is in scope as a closed set of impairment states per
limb slot (intact, impaired, disabled, severed), mirror-symmetric; the behaviour set compensates for each
(`lodur:ruling:bds-mvp-scope`).
- Weapons, ballistics, gore and wound presentation: Bad Day Simulator content, not Lodur.
- A Rust port of the core.
- The StreamPixels overlay as a consumer before StreamPixels M1 ships.
- Depending on RootMotion PuppetMaster (paid, not redistributable, and no
balance control: research section 10.1).
- Hand-tuned balance controllers of the SIMBICON family as the upright path.
- Depending on RootMotion PuppetMaster (paid, not redistributable, and no balance control: research
section 10.1).
- A hand-tuned balance controller of the SIMBICON family as the upright path. What holds the body up is the PD
muscles plus a will-scaled assist (and later a learned tracker). Stepping strategies that only re-plan targets
(capture-point foot placement after a shove, stumble, brace, get up) are in scope as behaviours.
## Open before the first cut is mapped
## Open
The identity, lifecycle and authority table (one row per persistent kind) is
written before any cut; these feed it.
- **Impairment states.** Self's proposal, not ruled: impairment as a closed set
of named body states (intact, missing a leg, missing an arm, both legs), with
mirror symmetry; crawling as the first locomotion after any leg loss; one-leg
hopping a stretch goal.
- **Rig.** Which humanoid the sandbox ships with, and its licence for a public
repo. The StreamPixels Little Heroes Mega Pack is a paid asset and cannot be
committed to a public repo.
- **Unity version** for Bad Day Simulator, and how Lodur's core is consumed
(UPM package from the Lodur repo, or a built assembly).
- **The MVP map** (`docs/bds-mvp-map.md`): systems by owner, authority map, model page and cut order for
grab, poke, physiology, dismemberment, will-weighted animation and IK, and sandbox levels.
- **How Bad Day Simulator consumes Lodur** (`lodur:question:bds-consumes-lodur`).
- **The pain measure** (`lodur:question:pain-sweep-measure`).
- **Ymir gaps Lodur needs next**: contact facts, joint stress and removal, a grab anchor and impulses are
specced (`lodur:cut_spec:cut-ymir-contact-facts`, `cut-ymir-grab-anchor`, `cut-ymir-break-and-remove`);
joint springs for stiff ankles remain (`nibu-body:follow_up:ymir-soa-lodur-needs`).
- **Renderer**: a Godot client (`lodur:ruling:bds-client-godot`), specced as `lodur:cut_spec:cut-godot-client-v1`.
- **Training host for v2.** Raven trains only when the household's GPU allows
(`motion-pipeline:ruling:raven-gpu-defers-to-household`).
- **Trademark search** on "Bad Day Simulator" before anything public is
announced.
- **Trademark search** on "Bad Day Simulator" before anything public is announced.

View file

@ -0,0 +1,18 @@
# Flesh cost probes
Probes behind `docs/flesh-map.md` and the Nibu research notes
`lodur:research:flesh-bones-map.probe-flesh-cost`, `.probe-flesh-commands` and
`.probe-skin-sieve`.
- `ymir_particles.probe.patch`: the probe's changes to Ymir's
`native/Ymir.Box3D/ymir_particles.{c,h}` at GameCult/Ymir d82da6d (pin
skipping by flag, a no-contact phase switch). Probe only; not a Ymir change.
- `fella.c`: one or more Fellas of skin and muscle sheets on rigid bones,
stepped at 120 Hz x 4 substeps. `matrix.sh` / `matrix2.sh` run the
configurations interleaved, five repetitions; `matrix*.out` are the runs the
notes cite.
- `sieve.c`: a skin sheet attached along a bone under fluid and solid load at
4 substeps.
Build against a patched copy of the two Ymir files with the same flags Ymir
uses (`-O2 -std=c17 -ffp-contract=off`).

502
docs/probes/flesh/fella.c Normal file
View file

@ -0,0 +1,502 @@
// Probe: Fella flesh on Ymir's particle solver (ymir_particles.c at d82da6d, scratch copy with two opt-in patches:
// probe_pinned excludes pinned particles from grid and constraints; probe_body_group replaces held_by with a group filter).
// Bones are kinematic proxies animated by FK (one-way coupling). 120 Hz x 4 substeps.
// usage: fella F skin_m muscle_m live pinmode filter gut ticks [cut]
// live: 0 none, 1 left forearm of each Fella, 2 all of Fella 0, 3 everything
// pinmode: 0 pinned = mass 0 in the solve (shipped code), 1 pinned excluded (patch)
// filter: 0 held_by (shipped), 1 body group filter (patch)
#include "ymir_particles.h"
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <windows.h>
extern uint8_t* probe_pinned;
extern int32_t* probe_body_group;
extern double probe_t[8];
extern int probe_nocontact;
typedef struct { float x, y, z; } v3;
typedef struct { float x, y, z, w; } q4;
static v3 V(float x, float y, float z) { return (v3){x, y, z}; }
static v3 add(v3 a, v3 b) { return V(a.x + b.x, a.y + b.y, a.z + b.z); }
static v3 sub(v3 a, v3 b) { return V(a.x - b.x, a.y - b.y, a.z - b.z); }
static v3 mul(v3 a, float s) { return V(a.x * s, a.y * s, a.z * s); }
static float dot(v3 a, v3 b) { return a.x * b.x + a.y * b.y + a.z * b.z; }
static float len(v3 a) { return sqrtf(dot(a, a)); }
static v3 cross(v3 a, v3 b) { return V(a.y * b.z - a.z * b.y, a.z * b.x - a.x * b.z, a.x * b.y - a.y * b.x); }
static q4 qmul(q4 a, q4 b)
{
return (q4){a.w * b.x + a.x * b.w + a.y * b.z - a.z * b.y, a.w * b.y - a.x * b.z + a.y * b.w + a.z * b.x,
a.w * b.z + a.x * b.y - a.y * b.x + a.z * b.w, a.w * b.w - a.x * b.x - a.y * b.y - a.z * b.z};
}
static v3 qrot(q4 q, v3 v)
{
v3 u = V(q.x, q.y, q.z);
v3 t = mul(cross(u, v), 2.0f);
return add(add(v, mul(t, q.w)), cross(u, t));
}
static q4 qaxis(v3 a, float ang) { float s = sinf(ang / 2); return (q4){a.x * s, a.y * s, a.z * s, cosf(ang / 2)}; }
// The 19-part humanoid of Lodur BodyPlans.Humanoid (fbc3501), rotations taken as identity.
enum { BOX, CAP, SPH };
typedef struct { int shape; v3 size, pos; } part;
typedef struct { int parent, child; v3 anchor, axis; float amp, phase; } joint;
static part P[19];
static joint J[18];
static int np = 0, nj = 0;
static int addp(int sh, v3 sz, v3 pos) { P[np] = (part){sh, sz, pos}; return np++; }
static void addj(int pa, int ch, v3 an, v3 ax, float amp) { J[nj] = (joint){pa, ch, an, ax, amp, 0.7f * nj}; nj++; }
static int LOWERARM_L;
static void humanoid(void)
{
int pelvis = addp(BOX, V(.15f, .08f, .09f), V(0, 1.11f, 0));
int torso = addp(BOX, V(.15f, .22f, .09f), V(0, 1.41f, 0));
int head = addp(SPH, V(.11f, 0, 0), V(0, 1.74f, 0));
int ua[2], la[2], th[2], sh[2], ft[2], pa[2], tb[2], fg[2];
for (int k = 0; k < 2; k++)
{
float sx = k == 0 ? 1.f : -1.f;
ua[k] = addp(CAP, V(.045f, .11f, 0), V(sx * .21f, 1.395f, 0));
la[k] = addp(CAP, V(.04f, .10f, 0), V(sx * .21f, 1.10f, 0));
th[k] = addp(CAP, V(.07f, .18f, 0), V(sx * .09f, .79f, 0));
sh[k] = addp(CAP, V(.06f, .17f, 0), V(sx * .09f, .31f, 0));
ft[k] = addp(BOX, V(.05f, .04f, .12f), V(sx * .09f, .04f, .05f));
}
for (int k = 0; k < 2; k++)
{
float sx = k == 0 ? 1.f : -1.f;
pa[k] = addp(BOX, V(.014f, .045f, .040f), V(sx * .21f, .930f, 0));
tb[k] = addp(CAP, V(.011f, .03f, 0), V(sx * .206f, .93f, .055f));
fg[k] = addp(BOX, V(.011f, .0425f, .038f), V(sx * .21f - sx * .0145f, .845f, 0));
}
LOWERARM_L = la[0];
v3 up = V(0, 1, 0), ac = V(1, 0, 0);
addj(pelvis, torso, V(0, 1.19f, 0), ac, .15f);
addj(torso, head, V(0, 1.63f, 0), ac, .2f);
for (int k = 0; k < 2; k++)
{
float sx = k == 0 ? 1.f : -1.f;
addj(torso, ua[k], V(sx * .21f, 1.55f, 0), ac, .6f);
addj(ua[k], la[k], V(sx * .21f, 1.24f, 0), ac, .7f);
addj(pelvis, th[k], V(sx * .09f, 1.04f, 0), ac, .5f);
addj(th[k], sh[k], V(sx * .09f, .54f, 0), ac, .6f);
addj(sh[k], ft[k], V(sx * .09f, .08f, 0), ac, .3f);
}
for (int k = 0; k < 2; k++)
{
float sx = k == 0 ? 1.f : -1.f;
addj(la[k], pa[k], V(sx * .21f, .975f, 0), ac, .4f);
addj(pa[k], tb[k], V(sx * .206f, .955f, .03f), ac, .3f);
addj(pa[k], fg[k], V(sx * .21f, .885f, 0), ac, .5f);
}
(void)up;
}
// signed distance to a part's shape in its local frame
static float sdf(const part* p, v3 x)
{
if (p->shape == SPH) return len(x) - p->size.x;
if (p->shape == CAP)
{
float y = x.y < -p->size.y ? -p->size.y : x.y > p->size.y ? p->size.y : x.y;
return len(V(x.x, x.y - y, x.z)) - p->size.x;
}
v3 q = V(fabsf(x.x) - p->size.x, fabsf(x.y) - p->size.y, fabsf(x.z) - p->size.z);
v3 m = V(q.x > 0 ? q.x : 0, q.y > 0 ? q.y : 0, q.z > 0 ? q.z : 0);
float in = fmaxf(q.x, fmaxf(q.y, q.z));
return len(m) + (in < 0 ? in : 0);
}
// surface samples of a part at spacing s, inset d (local frame)
static int sample(const part* p, float s, float d, v3* out)
{
int n = 0;
if (p->shape == SPH || p->shape == CAP)
{
float r = p->size.x - d;
if (r < 0.005f) r = 0.005f;
float half = p->shape == CAP ? p->size.y : 0;
int rings = (int)ceilf(2 * half / s);
for (int i = 0; i <= rings && half > 0; i++)
{
float y = -half + 2 * half * i / (rings ? rings : 1);
int m = (int)fmaxf(getenv("MINRING") ? atoi(getenv("MINRING")) : 6, roundf(2 * 3.14159f * r / s));
for (int k = 0; k < m; k++)
{
float a = 2 * 3.14159f * (k + 0.5f * (i & 1)) / m;
out[n++] = V(r * cosf(a), y, r * sinf(a));
}
}
// caps (whole sphere for SPH): latitude rings
int lat = (int)fmaxf(2, roundf(3.14159f * r / 2 / s));
for (int c = 0; c < 2; c++)
for (int i = (half > 0 ? 1 : 0); i <= lat; i++)
{
if (half == 0 && c == 1 && i == 0) continue;
float phi = 3.14159f / 2 * i / lat; // 0 at equator
float rr = r * cosf(phi), yy = r * sinf(phi) * (c ? -1 : 1);
int m = i == lat ? 1 : (int)fmaxf(3, roundf(2 * 3.14159f * rr / s));
for (int k = 0; k < m; k++)
{
float a = 2 * 3.14159f * (k + 0.5f * (i & 1)) / m;
out[n++] = V(rr * cosf(a), (c ? -half : half) + yy, rr * sinf(a));
}
}
return n;
}
v3 h = V(fmaxf(p->size.x - d, .004f), fmaxf(p->size.y - d, .004f), fmaxf(p->size.z - d, .004f));
for (int ax = 0; ax < 3; ax++)
for (int sg = -1; sg <= 1; sg += 2)
{
float hu = ax == 0 ? h.y : h.x, hv = ax == 2 ? h.y : h.z;
int nu = (int)fmaxf(1, ceilf(2 * hu / s)), nv = (int)fmaxf(1, ceilf(2 * hv / s));
for (int i = 0; i <= nu; i++)
for (int k = 0; k <= nv; k++)
{
// skip the shared edges of faces already done
float u = -hu + 2 * hu * i / nu, v = -hv + 2 * hv * k / nv;
v3 x = ax == 0 ? V(sg * h.x, u, v) : ax == 1 ? V(u, sg * h.y, v) : V(u, v, sg * h.z);
int dup = 0;
for (int q = 0; q < n; q++) if (len(sub(out[q], x)) < 0.3f * s) { dup = 1; break; }
if (!dup) out[n++] = x;
}
}
return n;
}
// ---- world ----
static ymir_particles* W;
static int F; // Fellas
static uint64_t stepc = 1;
typedef struct { int fella, part, layer; v3 local; } pinfo;
static pinfo* PI;
static float* pmass;
static int nparticles = 0;
static ymir_handle* PH;
static int ndist = 0, nbend = 0, natt = 0, nstitch = 0;
static ymir_handle* DH; static int* Dlayer; static int* Dpart; static int* Dfella;
static int nfloor;
static v3 bonepos[64][19]; static q4 bonerot[64][19];
static void pose(int f, float t, v3* pos, q4* rot)
{
v3 off = V(1.2f * f, 0, 0);
q4 R[19]; v3 X[19];
R[0] = qaxis(V(0, 1, 0), 0.3f * sinf(1.3f * t));
X[0] = add(add(P[0].pos, off), V(0, 0.02f * sinf(6 * t), 0));
for (int j = 0; j < nj; j++)
{
joint* J0 = &J[j];
int a = J0->parent, c = J0->child;
q4 rj = qaxis(J0->axis, J0->amp * sinf(3.0f * t + J0->phase + f));
R[c] = qmul(R[a], rj);
v3 an = add(X[a], qrot(R[a], sub(J0->anchor, P[a].pos)));
X[c] = add(an, qrot(R[c], sub(P[c].pos, J0->anchor)));
}
for (int i = 0; i < 19; i++) { pos[i] = X[i]; rot[i] = R[i]; }
}
static void fill_proxies(float t, float h)
{
for (int f = 0; f < F; f++)
{
v3 x0[19], x1[19]; q4 r0[19], r1[19];
pose(f, t, x0, r0);
pose(f, t + h, x1, r1);
for (int i = 0; i < 19; i++)
{
ymir_particle_proxy* b = W->proxies + f * 19 + i;
memset(b, 0, sizeof *b);
b->shape = P[i].shape == SPH ? YMIR_PROXY_SPHERE : P[i].shape == CAP ? YMIR_PROXY_CAPSULE : YMIR_PROXY_BOX;
b->size[0] = P[i].size.x; b->size[1] = P[i].size.y; b->size[2] = P[i].size.z;
b->position[0] = x0[i].x; b->position[1] = x0[i].y; b->position[2] = x0[i].z;
b->rotation[0] = r0[i].x; b->rotation[1] = r0[i].y; b->rotation[2] = r0[i].z; b->rotation[3] = r0[i].w;
v3 v = mul(sub(x1[i], x0[i]), 1 / h);
b->velocity[0] = v.x; b->velocity[1] = v.y; b->velocity[2] = v.z;
q4 inv0 = {-r0[i].x, -r0[i].y, -r0[i].z, r0[i].w};
q4 dq = qmul(r1[i], inv0);
if (dq.w < 0) { dq.x = -dq.x; dq.y = -dq.y; dq.z = -dq.z; dq.w = -dq.w; }
b->angular_velocity[0] = 2 * dq.x / h; b->angular_velocity[1] = 2 * dq.y / h; b->angular_velocity[2] = 2 * dq.z / h;
bonepos[f][i] = x0[i]; bonerot[f][i] = r0[i];
}
}
ymir_particle_proxy* fl = W->proxies + F * 19;
memset(fl, 0, sizeof *fl);
fl->shape = YMIR_PROXY_BOX; fl->size[0] = 50; fl->size[1] = 0.5f; fl->size[2] = 50; fl->position[1] = -0.5f; fl->rotation[3] = 1;
W->body_count = F * 19 + 1;
}
static double now_ms(void)
{
LARGE_INTEGER c, fq; QueryPerformanceCounter(&c); QueryPerformanceFrequency(&fq);
return 1000.0 * (double)c.QuadPart / (double)fq.QuadPart;
}
int main(int argc, char** argv)
{
F = argc > 1 ? atoi(argv[1]) : 1;
float s = argc > 2 ? (float)atof(argv[2]) : 0.08f, sm = argc > 3 ? (float)atof(argv[3]) : 0.10f;
int live = argc > 4 ? atoi(argv[4]) : 0, pinmode = argc > 5 ? atoi(argv[5]) : 0, filter = argc > 6 ? atoi(argv[6]) : 0;
int gut = argc > 7 ? atoi(argv[7]) : 0, ticks = argc > 8 ? atoi(argv[8]) : 600, cut = argc > 9 ? atoi(argv[9]) : 0;
humanoid();
int cap = 4000 * F + 400;
ymir_particle_capacities c = {cap, cap * 6, cap * 4, cap * 2, cap * 2, 4, 0, 0, 0};
W = ymir_particles_create(&c, F * 19 + 1);
PI = calloc(cap, sizeof *PI); pmass = calloc(cap, sizeof *pmass); PH = calloc(cap, sizeof *PH);
DH = calloc(cap * 6, sizeof *DH); Dlayer = calloc(cap * 6, sizeof(int)); Dpart = calloc(cap * 6, sizeof(int)); Dfella = calloc(cap * 6, sizeof(int));
uint8_t* pinned = calloc(cap, 1);
int32_t* bgroup = calloc(F * 19 + 1, sizeof(int32_t));
for (int f = 0; f < F; f++) for (int i = 0; i < 19; i++) bgroup[f * 19 + i] = f + 1;
bgroup[F * 19] = -1;
fill_proxies(0, 1.f / 480);
double build0 = now_ms();
v3* tmp = malloc(sizeof(v3) * 4000);
int per_layer[2] = {0, 0};
for (int f = 0; f < F; f++)
{
int first[2][19], cnt[2][19];
for (int layer = 0; layer < 2; layer++)
{
float sp = layer == 0 ? s : sm, d = layer == 0 ? 0 : 0.012f;
float mass = layer == 0 ? 0.012f * (sp * sp / 0.0064f) : 0.05f, rad = 0.45f * sp;
for (int i = 0; i < 19; i++)
{
first[layer][i] = nparticles; cnt[layer][i] = 0;
if (layer == 1 && (P[i].shape == BOX && P[i].size.x < 0.02f)) continue; // no muscle sheet in palm/fingers
if (layer == 1 && P[i].size.x < 0.02f) continue;
int n = sample(&P[i], sp, d, tmp);
for (int k = 0; k < n; k++)
{
v3 w = add(P[i].pos, tmp[k]);
int inside = 0;
for (int o = 0; o < 19; o++) if (o != i && sdf(&P[o], sub(w, P[o].pos)) < -0.25f * sp) { inside = 1; break; }
if (inside) continue;
v3 wp = add(bonepos[f][i], qrot(bonerot[f][i], tmp[k]));
int live_p = live == 3 || (live == 2 && f == 0) || (live == 1 && i == LOWERARM_L);
if (!live_p && getenv("ABSENT")) continue;
ymir_particle_desc pd = {{wp.x, wp.y, wp.z}, {w.x + 1.2f * f, w.y, w.z}, {0, 0, 0}, mass, rad, (uint32_t)(f + 1), 0};
pd.mass = live_p ? mass : 0.0f;
if (ymir_particles_create_particles(W, 1, &pd, stepc, &PH[nparticles]) != 0) { printf("create failed\n"); return 1; }
PI[nparticles] = (pinfo){f, i, layer, tmp[k]};
pmass[nparticles] = mass;
pinned[PH[nparticles].lane] = !live_p;
nparticles++; cnt[layer][i]++; if (f == 0) per_layer[layer]++;
}
}
}
if (f == 0 && getenv("PARTS")) { for (int i = 0; i < 19; i++) printf("part %d skin %d muscle %d;", i, cnt[0][i], cnt[1][i]); }
// edges within a part and layer: 6 nearest within 1.6 spacing; bends over near-opposite pairs
for (int layer = 0; layer < 2; layer++)
{
float sp = layer == 0 ? s : sm;
for (int i = 0; i < 19; i++)
{
int a0 = first[layer][i], n = cnt[layer][i];
int* nb = calloc((size_t)n * 6, sizeof(int)); int* nbe = calloc((size_t)n * 6, sizeof(int)); int* nn = calloc(n, sizeof(int));
for (int a = 0; a < n; a++)
{
int best[6]; float bd[6]; int nb6 = 0;
for (int b = 0; b < n; b++)
{
if (b == a) continue;
float dd = len(sub(PI[a0 + a].local, PI[a0 + b].local));
if (dd > 1.6f * sp) continue;
int q;
if (nb6 < 6) q = nb6++;
else { if (bd[5] <= dd) continue; q = 5; }
best[q] = b; bd[q] = dd;
for (int z = q; z > 0 && bd[z] < bd[z - 1]; z--) { float t = bd[z]; bd[z] = bd[z - 1]; bd[z - 1] = t; int u = best[z]; best[z] = best[z - 1]; best[z - 1] = u; }
}
for (int q = 0; q < nb6; q++)
{
int b = best[q];
if (b < a) { int seen = 0; for (int z = 0; z < nn[b]; z++) if (nb[b * 6 + z] == a) seen = 1; if (seen) continue; }
ymir_distance_desc dd = {PH[a0 + a], PH[a0 + b], -1.0f, layer == 0 ? 2e-4f : 1e-4f};
{ int rc = ymir_particles_create_distances(W, 1, &dd, stepc, &DH[ndist]); if (rc) { printf("dist failed rc %d layer %d part %d a %d b %d n %d lanes %d %d\n", rc, layer, i, a, b, n, PH[a0+a].lane, PH[a0+b].lane); return 1; } }
Dlayer[ndist] = layer; Dpart[ndist] = i; Dfella[ndist] = f;
if (nn[a] < 6) { nb[a * 6 + nn[a]] = b; nbe[a * 6 + nn[a]] = ndist; nn[a]++; }
if (nn[b] < 6) { nb[b * 6 + nn[b]] = a; nbe[b * 6 + nn[b]] = ndist; nn[b]++; }
ndist++;
}
}
for (int b = 0; b < n; b++)
for (int x = 0; x < nn[b]; x++)
for (int y = x + 1; y < nn[b]; y++)
{
v3 u = sub(PI[a0 + nb[b * 6 + x]].local, PI[a0 + b].local), v = sub(PI[a0 + nb[b * 6 + y]].local, PI[a0 + b].local);
if (dot(u, v) / (len(u) * len(v)) > -0.85f) continue;
ymir_bend_desc bd = {DH[nbe[b * 6 + x]], DH[nbe[b * 6 + y]], 1e-3f, -1.0f};
ymir_handle hb;
if (ymir_particles_create_bends(W, 1, &bd, stepc, &hb) == 0) nbend++;
}
free(nb); free(nbe); free(nn);
}
}
// stitches across each joint (skin and muscle): child particles within 1.5 sp of the anchor to the nearest parent particle within 2 sp
for (int layer = 0; layer < 2; layer++)
{
float sp = layer == 0 ? s : sm;
for (int j = 0; j < nj; j++)
{
int pa = J[j].parent, ch = J[j].child;
for (int a = first[layer][ch]; a < first[layer][ch] + cnt[layer][ch]; a++)
{
v3 wa = add(P[ch].pos, PI[a].local);
if (len(sub(wa, J[j].anchor)) > 1.5f * sp + P[ch].size.x) continue;
int best = -1; float bd = 2.0f * sp;
for (int b = first[layer][pa]; b < first[layer][pa] + cnt[layer][pa]; b++)
{
float dd = len(sub(wa, add(P[pa].pos, PI[b].local)));
if (dd < bd) { bd = dd; best = b; }
}
if (best < 0) continue;
ymir_distance_desc dd = {PH[a], PH[best], -1.0f, 2e-4f};
if (ymir_particles_create_distances(W, 1, &dd, stepc, &DH[ndist]) != 0) { printf("stitch failed\n"); return 1; }
Dlayer[ndist] = 2 + layer; Dpart[ndist] = ch; Dfella[ndist] = f; ndist++; nstitch++;
}
}
}
// skin to nearest muscle of the same part
for (int i = 0; i < 19; i++)
for (int a = first[0][i]; a < first[0][i] + cnt[0][i]; a++)
{
int best = -1; float bd = 1e9f;
for (int b = first[1][i]; b < first[1][i] + cnt[1][i]; b++) { float dd = len(sub(PI[a].local, PI[b].local)); if (dd < bd) { bd = dd; best = b; } }
if (best < 0) continue;
ymir_distance_desc dd = {PH[a], PH[best], -1.0f, 5e-4f};
if (ymir_particles_create_distances(W, 1, &dd, stepc, &DH[ndist]) != 0) { printf("sm failed\n"); return 1; }
Dlayer[ndist] = 4; Dpart[ndist] = i; Dfella[ndist] = f; ndist++;
}
}
// attachments: every flesh particle to its bone point
for (int k = 0; k < nparticles; k++)
{
ymir_attachment_desc ad = {YMIR_ATTACH_BODY, 0, PH[k], PI[k].fella * 19 + PI[k].part, {PI[k].local.x, PI[k].local.y, PI[k].local.z}, PI[k].layer == 0 ? 1e-3f : 1e-4f, 0};
ymir_handle ha;
if (ymir_particles_attach(W, &ad, W->body_count, stepc, &ha) != 0) { printf("attach failed\n"); return 1; }
natt++;
}
int flesh = nparticles;
double build_ms = now_ms() - build0;
// gut: a released real-length rope of 300 particles hanging from the pelvis of Fella 0
int gut0 = nparticles, ngut = gut ? 300 : 0;
ymir_handle* GE = calloc(400, sizeof *GE);
for (int k = 0; k < ngut; k++)
{
float a = k * 0.18f, r = 0.05f + 0.0012f * k;
v3 x = V(r * cosf(a), 0.9f, 0.25f + r * sinf(a));
ymir_particle_desc pd = {{x.x, x.y, x.z}, {0.0267f * k, 0, 0}, {0, 0, 0}, 0.0267f * 0.0003f * 1050.0f / 0.0267f * 0.0267f, 0.0125f, 99u | YMIR_PHASE_SELF_COLLIDE | YMIR_PHASE_SELF_FILTER, 0};
pd.mass = 0.008f;
ymir_particles_create_particles(W, 1, &pd, stepc, &PH[nparticles]);
PI[nparticles] = (pinfo){0, -1, 9, x}; nparticles++;
}
int ngutd = 0;
for (int k = 1; k < ngut; k++)
{
ymir_distance_desc dd = {PH[gut0 + k - 1], PH[gut0 + k], 0.0267f, 0};
ymir_particles_create_distances(W, 1, &dd, stepc, &GE[k - 1]); ngutd++;
}
for (int k = 1; k + 1 < ngut; k++) { ymir_bend_desc bd = {GE[k - 1], GE[k], 1e-2f, -1}; ymir_handle hb; ymir_particles_create_bends(W, 1, &bd, stepc, &hb); }
if (ngut)
{
for (int e = 0; e < 2; e++)
{
int k = e ? ngut - 1 : 0;
ymir_attachment_desc ad = {YMIR_ATTACH_BODY, YMIR_ATTACH_FLAG_TETHER, PH[gut0 + k], 0, {0.02f * (e ? 1 : -1), -0.02f, 0.09f}, 0, 0};
ymir_handle ha; ymir_particles_attach(W, &ad, W->body_count, stepc, &ha);
}
}
if (pinmode) probe_pinned = pinned;
if (getenv("NOCONTACT")) probe_nocontact = 1;
if (filter) probe_body_group = bgroup;
if (filter && ngut) bgroup[0] = 0; // the gut (group 99) collides with every bone; nothing to do
// per-Fella counts
int fd = 0, fs = 0;
for (int e = 0; e < ndist; e++) if (Dfella[e] == 0) { fd++; if (Dlayer[e] >= 2 && Dlayer[e] <= 3) fs++; }
float h = 1.0f / 480.0f;
double* tk = malloc(sizeof(double) * (ticks + 240));
float t = 0;
int warm = 120;
double cut_ms = -1, sever_ms = -1, wake_ms = -1;
float maxdev = 0;
for (int n = 0; n < warm + ticks; n++)
{
// pinned particles are written from their bone at the tick's start (Ymir's pin write, one per tick)
double t0 = now_ms();
fill_proxies(t, h);
for (int k = 0; k < flesh; k++)
{
int l = PH[k].lane;
if (!pinned[l]) continue;
v3 w = add(bonepos[PI[k].fella][PI[k].part], qrot(bonerot[PI[k].fella][PI[k].part], PI[k].local));
W->pos_x[l] = w.x; W->pos_y[l] = w.y; W->pos_z[l] = w.z;
}
ymir_particles_begin(W);
for (int sstep = 0; sstep < 4; sstep++)
{
if (sstep) fill_proxies(t + sstep * h, h);
ymir_particles_substep(W, h, 0, -9.81f, 0);
}
ymir_particles_end(W, 4);
double t1 = now_ms();
t += 4 * h;
stepc++;
if (n >= warm) tk[n - warm] = t1 - t0;
if (cut && n == warm + ticks / 2)
{
// wound: remove the skin edges of Fella 0's left forearm within 6 cm of its front point; then sever at the left elbow (stitches)
ymir_handle hs[64]; int m = 0;
for (int e = 0; e < ndist && m < 64; e++)
if (Dfella[e] == 0 && Dpart[e] == LOWERARM_L && Dlayer[e] == 0)
{
int a = W->dist_a[DH[e].lane];
v3 x = V(W->pos_x[a], W->pos_y[a], W->pos_z[a]);
v3 c0 = add(bonepos[0][LOWERARM_L], qrot(bonerot[0][LOWERARM_L], V(0, 0, .04f)));
if (len(sub(x, c0)) < 0.06f) hs[m++] = DH[e];
}
double c0 = now_ms();
ymir_particles_remove(W, YMIR_LANES_DISTANCE, m, hs, stepc);
cut_ms = now_ms() - c0;
printf("cut: %d skin edges\n", m);
m = 0;
for (int e = 0; e < ndist && m < 64; e++) if (Dfella[e] == 0 && Dpart[e] == LOWERARM_L && (Dlayer[e] == 2 || Dlayer[e] == 3)) hs[m++] = DH[e];
c0 = now_ms();
ymir_particles_remove(W, YMIR_LANES_DISTANCE, m, hs, stepc);
sever_ms = now_ms() - c0;
printf("sever: %d stitches; forearm skin component %d, upper arm skin component %d\n", m,
W->component[PH[0].lane], 0);
// wake Fella 0's thigh flesh: pinned -> live (mass back, velocity of the bone point)
c0 = now_ms();
for (int k = 0; k < flesh; k++)
if (PI[k].fella == 0 && PI[k].part == 7)
{
int l = PH[k].lane;
if (!pinned[l]) continue;
pinned[l] = 0; W->inv_mass[l] = 1.0f / pmass[k];
}
wake_ms = now_ms() - c0;
}
if (n == warm + ticks - 1)
for (int k = 0; k < flesh; k++)
{
int l = PH[k].lane;
if (pinned[l]) continue;
v3 w = add(bonepos[PI[k].fella][PI[k].part], qrot(bonerot[PI[k].fella][PI[k].part], PI[k].local));
float dv = len(sub(V(W->pos_x[l], W->pos_y[l], W->pos_z[l]), w));
if (dv > maxdev) maxdev = dv;
}
}
// median and mean
int nt = ticks;
for (int a = 1; a < nt; a++) { double v = tk[a]; int b = a - 1; while (b >= 0 && tk[b] > v) { tk[b + 1] = tk[b]; b--; } tk[b + 1] = v; }
double mean = 0; for (int a = 0; a < nt; a++) mean += tk[a]; mean /= nt;
int livec = 0; for (int k = 0; k < nparticles; k++) livec += !pinned[PH[k].lane] || k >= flesh;
printf("FELLA F=%d skin=%.3f muscle=%.3f live=%d pinmode=%d filter=%d gut=%d | per Fella: skin %d muscle %d particles, %d distances (%d stitches), bends total %d, attachments total %d | live particles %d | ms/tick median %.3f mean %.3f p95 %.3f max %.3f | max live deviation %.3f m",
F, s, sm, live, pinmode, filter, gut, per_layer[0], per_layer[1], fd, fs, nbend, natt, livec, tk[nt / 2], mean, tk[(int)(nt * 0.95)], tk[nt - 1], maxdev);
printf(" | phases ms/tick grid %.3f pcontact %.3f att %.3f dist %.3f bend %.3f tether %.3f body %.3f", probe_t[0]/(warm+ticks), probe_t[1]/(warm+ticks), probe_t[2]/(warm+ticks), probe_t[3]/(warm+ticks), probe_t[4]/(warm+ticks), probe_t[5]/(warm+ticks), probe_t[6]/(warm+ticks));
if (cut) printf(" | cut %.3f ms sever %.3f ms wake %.4f ms", cut_ms, sever_ms, wake_ms);
printf("\n");
printf("BUILD %.1f ms;", build_ms); return 0;
}

View file

@ -0,0 +1,15 @@
1 full median 0.980 HASH ce534bd202fabaca
1 sized median 0.476 HASH ce534bd202fabaca
1 empty median 0.094 HASH 14650fb0739d0383
2 full median 0.991 HASH ce534bd202fabaca
2 sized median 0.456 HASH ce534bd202fabaca
2 empty median 0.095 HASH 14650fb0739d0383
3 full median 0.987 HASH ce534bd202fabaca
3 sized median 0.496 HASH ce534bd202fabaca
3 empty median 0.097 HASH 14650fb0739d0383
4 full median 1.011 HASH ce534bd202fabaca
4 sized median 0.488 HASH ce534bd202fabaca
4 empty median 0.097 HASH 14650fb0739d0383
5 full median 0.988 HASH ce534bd202fabaca
5 sized median 0.486 HASH ce534bd202fabaca
5 empty median 0.096 HASH 14650fb0739d0383

View file

@ -0,0 +1,20 @@
1 H X median 0.096 HASH 14650fb0739d0383
1 H MASKSIZED median 0.095 HASH 14650fb0739d0383
1 K X median 3.980 HASH 7c43ed61a4d7e339
1 K MASKSIZED median 3.464 HASH 7c43ed61a4d7e339
2 H X median 0.094 HASH 14650fb0739d0383
2 H MASKSIZED median 0.094 HASH 14650fb0739d0383
2 K X median 4.025 HASH 7c43ed61a4d7e339
2 K MASKSIZED median 3.519 HASH 7c43ed61a4d7e339
3 H X median 0.093 HASH 14650fb0739d0383
3 H MASKSIZED median 0.094 HASH 14650fb0739d0383
3 K X median 3.883 HASH 7c43ed61a4d7e339
3 K MASKSIZED median 3.424 HASH 7c43ed61a4d7e339
4 H X median 0.096 HASH 14650fb0739d0383
4 H MASKSIZED median 0.096 HASH 14650fb0739d0383
4 K X median 3.975 HASH 7c43ed61a4d7e339
4 K MASKSIZED median 3.378 HASH 7c43ed61a4d7e339
5 H X median 0.096 HASH 14650fb0739d0383
5 H MASKSIZED median 0.096 HASH 14650fb0739d0383
5 K X median 3.946 HASH 7c43ed61a4d7e339
5 K MASKSIZED median 3.565 HASH 7c43ed61a4d7e339

View file

@ -0,0 +1,27 @@
--- fella.c
+++ fella.c
@@ -15,7 +15,7 @@
extern uint8_t* probe_pinned;
extern int32_t* probe_body_group;
extern double probe_t[8];
-extern int probe_nocontact;
+extern int probe_nocontact; extern int probe_mask_sized;
typedef struct { float x, y, z; } v3;
typedef struct { float x, y, z, w; } q4;
@@ -410,6 +410,7 @@
}
if (pinmode) probe_pinned = pinned;
if (getenv("NOCONTACT")) probe_nocontact = 1;
+ if (getenv("MASKSIZED")) probe_mask_sized = 1;
if (filter) probe_body_group = bgroup;
if (filter && ngut) bgroup[0] = 0; // the gut (group 99) collides with every bone; nothing to do
// per-Fella counts
@@ -496,6 +497,7 @@
printf("FELLA F=%d skin=%.3f muscle=%.3f live=%d pinmode=%d filter=%d gut=%d | per Fella: skin %d muscle %d particles, %d distances (%d stitches), bends total %d, attachments total %d | live particles %d | ms/tick median %.3f mean %.3f p95 %.3f max %.3f | max live deviation %.3f m",
F, s, sm, live, pinmode, filter, gut, per_layer[0], per_layer[1], fd, fs, nbend, natt, livec, tk[nt / 2], mean, tk[(int)(nt * 0.95)], tk[nt - 1], maxdev);
printf(" | phases ms/tick grid %.3f pcontact %.3f att %.3f dist %.3f bend %.3f tether %.3f body %.3f", probe_t[0]/(warm+ticks), probe_t[1]/(warm+ticks), probe_t[2]/(warm+ticks), probe_t[3]/(warm+ticks), probe_t[4]/(warm+ticks), probe_t[5]/(warm+ticks), probe_t[6]/(warm+ticks));
+ { uint64_t hh = 1469598103934665603ull; for (int i = 0; i < W->particle_count; i++) { const unsigned char* b; b=(const unsigned char*)&W->pos_x[i]; for(int c=0;c<4;c++){hh^=b[c];hh*=1099511628211ull;} b=(const unsigned char*)&W->pos_y[i]; for(int c=0;c<4;c++){hh^=b[c];hh*=1099511628211ull;} b=(const unsigned char*)&W->vel_z[i]; for(int c=0;c<4;c++){hh^=b[c];hh*=1099511628211ull;} } printf(" | HASH %016llx", (unsigned long long)hh); }
if (cut) printf(" | cut %.3f ms sever %.3f ms wake %.4f ms", cut_ms, sever_ms, wake_ms);
printf("\n");
printf("BUILD %.1f ms;", build_ms); return 0;

View file

@ -0,0 +1,135 @@
--- ymir_particles.c
+++ ymir_particles.c
@@ -5,6 +5,16 @@
// every sum in a fixed order. See ymir_particles.h.
#include "ymir_particles.h"
+#include <stdint.h>
+uint8_t* probe_pinned = 0; int32_t* probe_body_group = 0;
+#include <windows.h>
+double probe_t[8];
+static double pnow(void){LARGE_INTEGER c,f;QueryPerformanceCounter(&c);QueryPerformanceFrequency(&f);return 1000.0*(double)c.QuadPart/(double)f.QuadPart;}
+#define T(k,x) do{double _t=pnow(); x; probe_t[k]+=pnow()-_t;}while(0)
+int probe_nocontact = 0;
+#define PIN(i) ((probe_pinned && probe_pinned[i]) || (probe_nocontact && !(p->phase[i] & (YMIR_PHASE_SELF_COLLIDE|YMIR_PHASE_FLUID)) && grid_ctx))
+static int grid_ctx = 0;
+
#include <math.h>
#include <stdlib.h>
@@ -1358,20 +1368,24 @@
// Counting sort into a hash grid of cell 1 / inv_cell: the live particles' predicted positions, fluid lanes left out when
// `solids` is set. Within a bucket particles keep index order, so every neighbour walk is the same on every run.
+int probe_mask_sized = 0; static uint32_t g_mask;
static void grid_sort(ymir_particles* p, float inv_cell, int solids)
{
- int32_t buckets = (int32_t)p->table_mask + 1;
+ uint32_t mask = p->table_mask;
+ if (solids && probe_mask_sized) { int32_t n = 0; for (int32_t i = 0; i < p->particle_count; ++i) n += p->particle_live[i] && !PIN(i) && !(p->phase[i] & YMIR_PHASE_FLUID); uint32_t t = 16; while (t < 2u * (uint32_t)n) t <<= 1; if (t - 1 < mask) mask = t - 1; }
+ g_mask = mask;
+ int32_t buckets = (int32_t)mask + 1;
memset(p->cell_start, 0, sizeof(int32_t) * (size_t)(buckets + 1));
for (int32_t i = 0; i < p->particle_count; ++i)
{
- if (!p->particle_live[i] || (solids && (p->phase[i] & YMIR_PHASE_FLUID)))
+ if (!p->particle_live[i] || PIN(i) || (solids && (p->phase[i] & YMIR_PHASE_FLUID)))
{
continue;
}
p->cell_x[i] = cell_of(p->pp_x[i], inv_cell);
p->cell_y[i] = cell_of(p->pp_y[i], inv_cell);
p->cell_z[i] = cell_of(p->pp_z[i], inv_cell);
- p->cell_start[cell_hash(p->cell_x[i], p->cell_y[i], p->cell_z[i], p->table_mask) + 1]++;
+ p->cell_start[cell_hash(p->cell_x[i], p->cell_y[i], p->cell_z[i], mask) + 1]++;
}
for (int32_t c = 0; c < buckets; ++c)
{
@@ -1380,9 +1394,9 @@
}
for (int32_t i = 0; i < p->particle_count; ++i)
{
- if (p->particle_live[i] && !(solids && (p->phase[i] & YMIR_PHASE_FLUID)))
+ if (p->particle_live[i] && !PIN(i) && !(solids && (p->phase[i] & YMIR_PHASE_FLUID)))
{
- uint32_t c = cell_hash(p->cell_x[i], p->cell_y[i], p->cell_z[i], p->table_mask);
+ uint32_t c = cell_hash(p->cell_x[i], p->cell_y[i], p->cell_z[i], mask);
p->sorted[p->cell_start[c] + p->cell_fill[c]++] = i;
}
}
@@ -1461,7 +1475,7 @@
{
for (int32_t i = 0; i < p->particle_count; ++i)
{
- if (!p->particle_live[i] || (p->phase[i] & YMIR_PHASE_FLUID)) // the grid holds no fluid lane
+ if (!p->particle_live[i] || PIN(i) || (p->phase[i] & YMIR_PHASE_FLUID)) // the grid holds no fluid lane
{
continue;
}
@@ -1469,7 +1483,7 @@
{
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);
+ uint32_t bucket = cell_hash(ca, cb, cc, g_mask);
for (int32_t q = p->cell_start[bucket]; q < p->cell_start[bucket + 1]; ++q)
{
int32_t j = p->sorted[q];
@@ -1979,7 +1993,7 @@
{
continue;
}
- if (held_by(p, i, k))
+ if (probe_body_group ? probe_body_group[k] == (int32_t)(p->phase[i] & YMIR_PHASE_GROUP_MASK) : held_by(p, i, k))
{
continue;
}
@@ -2056,6 +2070,7 @@
continue;
}
int32_t i = p->att_particle[a];
+ if (PIN(i)) continue;
v3 at = end_point(p, a);
v3 d = vsub(P(p, p->pp_x, p->pp_y, p->pp_z, i), at);
float len = vlen(d);
@@ -2088,6 +2103,7 @@
continue;
}
int32_t i = p->dist_a[e], j = p->dist_b[e];
+ if (PIN(i) && PIN(j)) continue;
float wi = p->inv_mass[i], wj = p->inv_mass[j], alpha = p->dist_compliance[e] / (f->h * f->h);
v3 d = vsub(P(p, p->pp_x, p->pp_y, p->pp_z, j), P(p, p->pp_x, p->pp_y, p->pp_z, i));
float len = vlen(d);
@@ -2117,6 +2133,7 @@
continue;
}
int32_t a = p->bend_a[k], b = p->bend_b[k], c = p->bend_c[k];
+ if (PIN(a) && PIN(b) && PIN(c)) continue;
float wa = p->inv_mass[a], wb = p->inv_mass[b], wc = p->inv_mass[c];
v3 ja = {0.0f, 0.0f, 0.0f}, jc = {0.0f, 0.0f, 0.0f};
for (int pass = 0; pass < 2; ++pass)
@@ -2320,17 +2337,17 @@
}
put(p->pp_x, p->pp_y, p->pp_z, i, x);
}
- build_grid(p);
- particle_contacts(p);
+ grid_ctx = 1; T(0, build_grid(p););
+ T(1, particle_contacts(p);); grid_ctx = 0;
if (p->live_fluid > 0)
{
fluid_density(p);
}
- solve_attachments(&f);
- solve_distances(&f);
- solve_bends(&f);
- solve_tethers(&f);
- body_contacts(&f);
+ T(2, solve_attachments(&f););
+ T(3, solve_distances(&f););
+ T(4, solve_bends(&f););
+ T(5, solve_tethers(&f););
+ T(6, body_contacts(&f););
for (int32_t i = 0; i < p->particle_count; ++i)
{
if (!p->particle_live[i])

View file

@ -0,0 +1,50 @@
1 ship_1pin median 5.345
1 ship_4pin median 21.693
1 pin_1 median 0.242
1 pin_4 median 1.167
1 nc_4_forearms median 1.358
1 nc_4_one_live median 3.038
1 nc_4_one_live_gut median 3.572
1 c_4_one_live median 6.990
1 nc_4_all_live median 7.416
1 nc_1_live median 1.127
2 ship_1pin median 4.701
2 ship_4pin median 20.071
2 pin_1 median 0.245
2 pin_4 median 1.026
2 nc_4_forearms median 1.397
2 nc_4_one_live median 2.712
2 nc_4_one_live_gut median 3.827
2 c_4_one_live median 6.973
2 nc_4_all_live median 7.499
2 nc_1_live median 1.135
3 ship_1pin median 5.612
3 ship_4pin median 24.192
3 pin_1 median 0.248
3 pin_4 median 1.268
3 nc_4_forearms median 1.667
3 nc_4_one_live median 3.134
3 nc_4_one_live_gut median 4.969
3 c_4_one_live median 8.860
3 nc_4_all_live median 9.238
3 nc_1_live median 1.132
4 ship_1pin median 5.626
4 ship_4pin median 23.291
4 pin_1 median 0.249
4 pin_4 median 1.271
4 nc_4_forearms median 1.809
4 nc_4_one_live median 3.429
4 nc_4_one_live_gut median 4.777
4 c_4_one_live median 8.777
4 nc_4_all_live median 8.990
4 nc_1_live median 1.128
5 ship_1pin median 4.790
5 ship_4pin median 23.049
5 pin_1 median 0.247
5 pin_4 median 1.282
5 nc_4_forearms median 1.684
5 nc_4_one_live median 3.326
5 nc_4_one_live_gut median 4.850
5 c_4_one_live median 8.675
5 nc_4_all_live median 9.965
5 nc_1_live median 1.578

View file

@ -0,0 +1,18 @@
#!/bin/sh
# name|env|args
CONF='ship_1pin||1 0.08 0.10 0 0 0 0 600
ship_4pin||4 0.08 0.10 0 0 0 0 600
pin_1||1 0.08 0.10 0 1 1 0 600
pin_4||4 0.08 0.10 0 1 1 0 600
nc_4_forearms|NOCONTACT=1|4 0.08 0.10 1 1 1 0 600
nc_4_one_live|NOCONTACT=1|4 0.08 0.10 2 1 1 0 600
nc_4_one_live_gut|NOCONTACT=1|4 0.08 0.10 2 1 1 1 600
c_4_one_live|CONTACT=1|4 0.08 0.10 2 1 1 0 600
nc_4_all_live|NOCONTACT=1|4 0.08 0.10 3 1 1 0 600
nc_1_live|NOCONTACT=1|1 0.08 0.10 3 1 1 0 600'
for rep in 1 2 3 4 5; do
echo "$CONF" | while IFS='|' read name env args; do
if [ -n "$env" ]; then out=$(env $env ./fella.exe $args); else out=$(./fella.exe $args); fi
echo "$rep $name $(echo "$out" | grep -o 'median [0-9.]*' )"
done
done

View file

@ -0,0 +1,50 @@
1 A_ship_pinned_1 median 4.271 live particles 0
1 B_skipflag_pinned_1 median 0.252 live particles 0
1 D_forearm_live_1 median 0.204 live particles 40
1 E_fella_live_1 median 1.025 live particles 661
1 F_fella_live_gut_1 median 2.244 live particles 961
1 G_fella_live_contact_1 median 5.117 live particles 661
1 I_fella_live_heldby_1 median 6.433 live particles 661
1 H_skipflag_pinned_4 median 1.021 live particles 0
1 J_4_one_live_absent median 2.266 live particles 661
1 K_4_one_live_gut_absent median 4.334 live particles 961
2 A_ship_pinned_1 median 4.918 live particles 0
2 B_skipflag_pinned_1 median 0.253 live particles 0
2 D_forearm_live_1 median 0.205 live particles 40
2 E_fella_live_1 median 1.036 live particles 661
2 F_fella_live_gut_1 median 2.428 live particles 961
2 G_fella_live_contact_1 median 12.285 live particles 661
2 I_fella_live_heldby_1 median 5.280 live particles 661
2 H_skipflag_pinned_4 median 1.014 live particles 0
2 J_4_one_live_absent median 2.270 live particles 661
2 K_4_one_live_gut_absent median 4.166 live particles 961
3 A_ship_pinned_1 median 5.341 live particles 0
3 B_skipflag_pinned_1 median 0.256 live particles 0
3 D_forearm_live_1 median 0.204 live particles 40
3 E_fella_live_1 median 1.046 live particles 661
3 F_fella_live_gut_1 median 2.349 live particles 961
3 G_fella_live_contact_1 median 5.441 live particles 661
3 I_fella_live_heldby_1 median 5.310 live particles 661
3 H_skipflag_pinned_4 median 1.046 live particles 0
3 J_4_one_live_absent median 2.317 live particles 661
3 K_4_one_live_gut_absent median 4.218 live particles 961
4 A_ship_pinned_1 median 5.124 live particles 0
4 B_skipflag_pinned_1 median 0.255 live particles 0
4 D_forearm_live_1 median 0.204 live particles 40
4 E_fella_live_1 median 1.028 live particles 661
4 F_fella_live_gut_1 median 2.359 live particles 961
4 G_fella_live_contact_1 median 5.683 live particles 661
4 I_fella_live_heldby_1 median 5.232 live particles 661
4 H_skipflag_pinned_4 median 1.023 live particles 0
4 J_4_one_live_absent median 2.271 live particles 661
4 K_4_one_live_gut_absent median 4.319 live particles 961
5 A_ship_pinned_1 median 4.507 live particles 0
5 B_skipflag_pinned_1 median 0.257 live particles 0
5 D_forearm_live_1 median 0.205 live particles 40
5 E_fella_live_1 median 1.050 live particles 661
5 F_fella_live_gut_1 median 2.369 live particles 961
5 G_fella_live_contact_1 median 5.268 live particles 661
5 I_fella_live_heldby_1 median 5.052 live particles 661
5 H_skipflag_pinned_4 median 1.039 live particles 0
5 J_4_one_live_absent median 2.284 live particles 661
5 K_4_one_live_gut_absent median 4.262 live particles 961

View file

@ -0,0 +1,17 @@
#!/bin/sh
CONF='A_ship_pinned_1|MINRING=4|1 0.10 0.14 0 0 0 0 600
B_skipflag_pinned_1|MINRING=4|1 0.10 0.14 0 1 1 0 600
D_forearm_live_1|MINRING=4 NOCONTACT=1 ABSENT=1|1 0.10 0.14 1 1 1 0 600
E_fella_live_1|MINRING=4 NOCONTACT=1|1 0.10 0.14 3 1 1 0 600
F_fella_live_gut_1|MINRING=4 NOCONTACT=1|1 0.10 0.14 3 1 1 1 600
G_fella_live_contact_1|MINRING=4|1 0.10 0.14 3 1 1 0 600
I_fella_live_heldby_1|MINRING=4 NOCONTACT=1|1 0.10 0.14 3 1 0 0 600
H_skipflag_pinned_4|MINRING=4|4 0.10 0.14 0 1 1 0 600
J_4_one_live_absent|MINRING=4 NOCONTACT=1 ABSENT=1|4 0.10 0.14 2 1 1 0 600
K_4_one_live_gut_absent|MINRING=4 NOCONTACT=1 ABSENT=1|4 0.10 0.14 2 1 1 1 600'
for rep in 1 2 3 4 5; do
echo "$CONF" | while IFS='|' read name env args; do
out=$(env $env ./fella.exe $args)
echo "$rep $name $(echo "$out" | grep -o 'median [0-9.]*') $(echo "$out" | grep -o 'live particles [0-9]*')"
done
done

142
docs/probes/flesh/sieve.c Normal file
View file

@ -0,0 +1,142 @@
// Sieve probe: a skin sheet attached along its length to a horizontal static capsule (a BDS thigh: r 0.07, half 0.18) at spacing s,
// under a fluid pour (7x7x7, r 0.0125, 15.6 g) and a dropped solid block (4x4x4 solid particles, r 0.02) at 4 substeps, 60 Hz as the
// Ymir pour test and 120 Hz as BDS. Readings: worst edge stretch, deep overlaps (pairs within half a contact distance), fluid and
// solid particles that reach the bone surface through the skin (centre within r_cap + 1.5 r of the axis segment), and fallen below.
// usage: sieve s hz substeps attach_compliance dropped(0 fluid,1 solid)
#include "ymir_particles.h"
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
static float seglen(float x, float y, float z, float half) // distance from the capsule axis segment (along x here)
{
float cx = x < -half ? -half : x > half ? half : x;
return sqrtf((x - cx) * (x - cx) + y * y + z * z);
}
int main(int argc, char** argv)
{
float s = argc > 1 ? (float)atof(argv[1]) : 0.08f;
float hz = argc > 2 ? (float)atof(argv[2]) : 120.f;
int sub = argc > 3 ? atoi(argv[3]) : 4;
float ac = argc > 4 ? (float)atof(argv[4]) : 1e-3f;
int solid = argc > 5 ? atoi(argv[5]) : 0;
const float R = 0.07f, HALF = 0.18f, Y = 0.5f;
ymir_particle_capacities c = {2048, 8192, 8192, 1024, 2048, 2, 512, 0, 0};
ymir_particles* W = ymir_particles_create(&c, 2);
ymir_material_desc m = {0.3f, 0.01f, 0, 0, 1};
ymir_particles_set_material(W, 0, &m);
// the capsule lies along x: Ymir capsules run along local y, so rotate y onto x (90 degrees about z)
float q[4] = {0, 0, sinf(-0.785398f), cosf(-0.785398f)};
ymir_particle_proxy* b = W->proxies;
memset(b, 0, 2 * sizeof *b);
b[0].shape = YMIR_PROXY_CAPSULE; b[0].size[0] = R; b[0].size[1] = HALF; b[0].position[1] = Y; memcpy(b[0].rotation, q, sizeof q);
b[1].shape = YMIR_PROXY_BOX; b[1].size[0] = 5; b[1].size[1] = 0.5f; b[1].size[2] = 5; b[1].position[1] = -0.5f; b[1].rotation[3] = 1;
W->body_count = 2;
// skin: rings along the capsule at spacing s, staggered, centres on the bone surface; caps left open (a limb continues at its joints)
int rings = (int)ceilf(2 * HALF / s), per = (int)fmaxf(6, roundf(2 * 3.14159f * R / s));
int n = (rings + 1) * per;
ymir_handle* ph = calloc(n, sizeof *ph);
float* lx = calloc(n, sizeof(float)); float* ly = calloc(n, sizeof(float)); float* lz = calloc(n, sizeof(float));
for (int i = 0, k = 0; i <= rings; i++)
for (int j = 0; j < per; j++, k++)
{
float a = 2 * 3.14159f * (j + 0.5f * (i & 1)) / per;
float x = -HALF + 2 * HALF * i / rings;
lx[k] = x; ly[k] = R * cosf(a); lz[k] = R * sinf(a);
// local frame of the body is y along the axis: local = (-world y, world x, z) rotated; keep world-space rest and compute the body point
ymir_particle_desc d = {{x, Y + ly[k], lz[k]}, {x, Y + ly[k], lz[k]}, {0, 0, 0}, 0.012f * (s * s / 0.0064f), 0.45f * s, 1u, 0};
ymir_particles_create_particles(W, 1, &d, 1, &ph[k]);
}
// edges: ring neighbours, next ring's two nearest; bends along rings and along the axis
ymir_handle* eh = calloc(n * 4, sizeof *eh);
int ne = 0;
int* ringe = calloc(n, sizeof(int)); int* axe = calloc(n, sizeof(int));
for (int i = 0; i <= rings; i++)
for (int j = 0; j < per; j++)
{
int k = i * per + j;
ymir_distance_desc d = {ph[k], ph[i * per + (j + 1) % per], -1, 2e-4f};
ymir_particles_create_distances(W, 1, &d, 1, &eh[ne]); ringe[k] = ne++;
if (i < rings)
{
int j2 = (i & 1) ? (j + 1) % per : j, j3 = (i & 1) ? j : (j + per - 1) % per;
ymir_distance_desc d2 = {ph[k], ph[(i + 1) * per + j2], -1, 2e-4f}, d3 = {ph[k], ph[(i + 1) * per + j3], -1, 2e-4f};
ymir_particles_create_distances(W, 1, &d2, 1, &eh[ne]); axe[k] = ne++;
ymir_particles_create_distances(W, 1, &d3, 1, &eh[ne]); ne++;
}
}
for (int i = 0; i <= rings; i++)
for (int j = 0; j < per; j++)
{
int k = i * per + j, kp = i * per + (j + per - 1) % per;
ymir_bend_desc bd = {eh[ringe[kp]], eh[ringe[k]], 1e-3f, -1};
ymir_handle hb; ymir_particles_create_bends(W, 1, &bd, 1, &hb);
}
for (int k = 0; k < n; k++)
{
// the body frame: rotation q maps local y onto world x; local = q^-1 (world - centre): (x, y', z) world -> local (y', -x ... ) computed numerically
float wx = lx[k], wy = ly[k], wz = lz[k];
// inverse of a -90 degree turn about z: local x = -wy? Use the exact inverse: rotate by +90 about z: (x, y) -> (-y, x)
float px = -wy, py = wx, pz = wz;
(void)px;
ymir_attachment_desc ad = {YMIR_ATTACH_BODY, 0, ph[k], 0, {-wy * -1.0f * 0 + (-wy) * 0 + wy * 0 + (-wy) , py, pz}, ac, 0};
ad.point[0] = -wy; ad.point[1] = wx; ad.point[2] = wz;
// check: q (y-axis -> x-axis) applied to (px, py, pz) must give (wx, wy, wz)
ad.point[0] = -wy; ad.point[1] = wx; ad.point[2] = wz;
ymir_handle ha; ymir_particles_attach(W, &ad, 2, 1, &ha);
}
// the load: a 7x7x7 block 0.25 m above the capsule's top, centred on it
int nl = solid ? 64 : 343, side = solid ? 4 : 7;
float lr = solid ? 0.02f : 0.0125f, sp = 2 * lr;
ymir_handle* lh = calloc(nl, sizeof *lh);
for (int a = 0; a < side; a++) for (int bb = 0; bb < side; bb++) for (int cc = 0; cc < side; cc++)
{
int k = (a * side + bb) * side + cc;
float x = -0.5f * (side - 1) * sp + a * sp, y = Y + R + 0.25f + bb * sp, z = -0.5f * (side - 1) * sp + cc * sp;
ymir_particle_desc d = {{x, y, z}, {x, y, z}, {0, 0, 0}, solid ? 0.06f : 0.015625f, lr, solid ? (6u | YMIR_PHASE_SELF_COLLIDE) : (6u | YMIR_PHASE_FLUID), 0};
ymir_particles_create_particles(W, 1, &d, 1, &lh[k]);
}
float h = 1.0f / hz / sub, worst = 0;
int deep = 0, through = 0, inside = 0, ticks = (int)(3 * hz);
char* hit = calloc(nl, 1);
for (int t = 0; t < ticks; t++)
{
ymir_particles_begin(W);
for (int ss = 0; ss < sub; ss++)
{
for (int k = 0; k < 2; k++) { /* static: pose fixed, velocities zero */ }
ymir_particles_substep(W, h, 0, -9.81f, 0);
b[0].position[1] = Y; b[0].position[0] = 0; b[0].position[2] = 0; memcpy(b[0].rotation, q, sizeof q);
b[1].position[1] = -0.5f; b[1].position[0] = b[1].position[2] = 0; b[1].rotation[0] = b[1].rotation[1] = b[1].rotation[2] = 0; b[1].rotation[3] = 1;
}
ymir_particles_end(W, sub);
for (int e = 0; e < ne; e++)
{
int i = W->dist_a[eh[e].lane], j = W->dist_b[eh[e].lane];
float dx = W->pos_x[i] - W->pos_x[j], dy = W->pos_y[i] - W->pos_y[j], dz = W->pos_z[i] - W->pos_z[j];
float st = sqrtf(dx * dx + dy * dy + dz * dz) / W->dist_rest[eh[e].lane] - 1;
if (st > worst) worst = st;
}
for (int k = 0; k < nl; k++)
{
int l = lh[k].lane;
for (int s2 = 0; s2 < n; s2++)
{
int i = ph[s2].lane;
float dx = W->pos_x[i] - W->pos_x[l], dy = W->pos_y[i] - W->pos_y[l], dz = W->pos_z[i] - W->pos_z[l];
if (sqrtf(dx * dx + dy * dy + dz * dz) < 0.5f * (W->radius[i] + lr)) deep++;
}
if (fabsf(W->pos_x[l]) < HALF && seglen(W->pos_x[l], W->pos_y[l] - Y, W->pos_z[l], HALF) < R) inside++;
if (!hit[k] && fabsf(W->pos_x[l]) < HALF && seglen(W->pos_x[l], W->pos_y[l] - Y, W->pos_z[l], HALF) < R + 1.5f * lr) { hit[k] = 1; through++; }
}
}
// a sanity read of the skin's place: mean distance of skin centres from the axis (R when held)
float md = 0;
for (int k = 0; k < n; k++) { int i = ph[k].lane; md += seglen(W->pos_x[i], W->pos_y[i] - Y, W->pos_z[i], HALF); }
int below = 0; for (int k = 0; k < nl; k++) below += W->pos_y[lh[k].lane] < 0.05f;
printf("SIEVE s=%.3f %gHz x%d attach_c=%g load=%s: skin %d particles r %.3f, %d edges | worst stretch %.4f | deep (tick x pair) %d | load reaching the bone through the skin %d of %d | inside the bone (tick x particle) %d | on the floor at 3 s %d | skin mean axis distance %.4f (R %.3f)\n",
s, hz, sub, ac, solid ? "solid" : "fluid", n, 0.45f * s, ne, worst, deep, through, nl, inside, below, md / n, R);
return 0;
}

View file

@ -0,0 +1,691 @@
--- /tmp/base_ymir_particles.c 2026-11-25 20:46:03.839493800 +0100
+++ /c/Users/Meta/AppData/Local/Temp/claude/a3c197df03062ea3/0d8e833d-7cf1-4193-ba8c-8babeaf48eda/scratchpad/imag-flesh/ymir_particles.c 2026-11-25 20:14:24.880958500 +0100
@@ -5,6 +5,16 @@
// every sum in a fixed order. See ymir_particles.h.
#include "ymir_particles.h"
+#include <stdint.h>
+uint8_t* probe_pinned = 0; int32_t* probe_body_group = 0;
+#include <windows.h>
+double probe_t[8];
+static double pnow(void){LARGE_INTEGER c,f;QueryPerformanceCounter(&c);QueryPerformanceFrequency(&f);return 1000.0*(double)c.QuadPart/(double)f.QuadPart;}
+#define T(k,x) do{double _t=pnow(); x; probe_t[k]+=pnow()-_t;}while(0)
+int probe_nocontact = 0;
+#define PIN(i) ((probe_pinned && probe_pinned[i]) || (probe_nocontact && !(p->phase[i] & (YMIR_PHASE_SELF_COLLIDE|YMIR_PHASE_FLUID)) && grid_ctx))
+static int grid_ctx = 0;
+
#include <math.h>
#include <stdlib.h>
@@ -1364,7 +1374,7 @@
memset(p->cell_start, 0, sizeof(int32_t) * (size_t)(buckets + 1));
for (int32_t i = 0; i < p->particle_count; ++i)
{
- if (!p->particle_live[i] || (solids && (p->phase[i] & YMIR_PHASE_FLUID)))
+ if (!p->particle_live[i] || PIN(i) || (solids && (p->phase[i] & YMIR_PHASE_FLUID)))
{
continue;
}
@@ -1380,7 +1390,7 @@
}
for (int32_t i = 0; i < p->particle_count; ++i)
{
- if (p->particle_live[i] && !(solids && (p->phase[i] & YMIR_PHASE_FLUID)))
+ if (p->particle_live[i] && !PIN(i) && !(solids && (p->phase[i] & YMIR_PHASE_FLUID)))
{
uint32_t c = cell_hash(p->cell_x[i], p->cell_y[i], p->cell_z[i], p->table_mask);
p->sorted[p->cell_start[c] + p->cell_fill[c]++] = i;
@@ -1461,7 +1471,7 @@
{
for (int32_t i = 0; i < p->particle_count; ++i)
{
- if (!p->particle_live[i] || (p->phase[i] & YMIR_PHASE_FLUID)) // the grid holds no fluid lane
+ if (!p->particle_live[i] || PIN(i) || (p->phase[i] & YMIR_PHASE_FLUID)) // the grid holds no fluid lane
{
continue;
}
@@ -1979,7 +1989,7 @@
{
continue;
}
- if (held_by(p, i, k))
+ if (probe_body_group ? probe_body_group[k] == (int32_t)(p->phase[i] & YMIR_PHASE_GROUP_MASK) : held_by(p, i, k))
{
continue;
}
@@ -2056,6 +2066,7 @@
continue;
}
int32_t i = p->att_particle[a];
+ if (PIN(i)) continue;
v3 at = end_point(p, a);
v3 d = vsub(P(p, p->pp_x, p->pp_y, p->pp_z, i), at);
float len = vlen(d);
@@ -2088,6 +2099,7 @@
continue;
}
int32_t i = p->dist_a[e], j = p->dist_b[e];
+ if (PIN(i) && PIN(j)) continue;
float wi = p->inv_mass[i], wj = p->inv_mass[j], alpha = p->dist_compliance[e] / (f->h * f->h);
v3 d = vsub(P(p, p->pp_x, p->pp_y, p->pp_z, j), P(p, p->pp_x, p->pp_y, p->pp_z, i));
float len = vlen(d);
@@ -2117,6 +2129,7 @@
continue;
}
int32_t a = p->bend_a[k], b = p->bend_b[k], c = p->bend_c[k];
+ if (PIN(a) && PIN(b) && PIN(c)) continue;
float wa = p->inv_mass[a], wb = p->inv_mass[b], wc = p->inv_mass[c];
v3 ja = {0.0f, 0.0f, 0.0f}, jc = {0.0f, 0.0f, 0.0f};
for (int pass = 0; pass < 2; ++pass)
@@ -2320,17 +2333,17 @@
}
put(p->pp_x, p->pp_y, p->pp_z, i, x);
}
- build_grid(p);
- particle_contacts(p);
+ grid_ctx = 1; T(0, build_grid(p););
+ T(1, particle_contacts(p);); grid_ctx = 0;
if (p->live_fluid > 0)
{
fluid_density(p);
}
- solve_attachments(&f);
- solve_distances(&f);
- solve_bends(&f);
- solve_tethers(&f);
- body_contacts(&f);
+ T(2, solve_attachments(&f););
+ T(3, solve_distances(&f););
+ T(4, solve_bends(&f););
+ T(5, solve_tethers(&f););
+ T(6, body_contacts(&f););
for (int32_t i = 0; i < p->particle_count; ++i)
{
if (!p->particle_live[i])
--- /tmp/base_ymir_particles.h 2026-11-25 20:46:03.949325900 +0100
+++ /c/Users/Meta/AppData/Local/Temp/claude/a3c197df03062ea3/0d8e833d-7cf1-4193-ba8c-8babeaf48eda/scratchpad/imag-flesh/ymir_particles.h 2026-11-25 20:09:57.828286700 +0100
@@ -1,292 +1,292 @@
-// Particles and the constraints between them: Ymir's own position-based solver, stepped inside Box3D's substeps
-// (see ymir_box3d_soa.c, the only Box3D caller). This module knows nothing of Box3D. soa.c fills one proxy per body
-// (pose, velocity, shape, inverse mass and inertia) before each substep, the solver moves those proxies by the
-// constraints it solves, and the impulse each body accumulated comes back in the proxy for soa.c to apply.
-// See docs/soa-world.md.
-//
-// There is no object above the lanes: particles are one lane set with a phase word, and every constraint type
-// (distance, bend, attachment) is a lane set of its own. A thing made of particles is whatever constraints a
-// caller emitted. Tethers and components are derived from the distance graph by rederive_topology, which every
-// topology command ends in and which is their only writer.
-//
-// Determinism: single thread; constraints are Gauss-Seidel in lane order; the one Jacobi pass (particle-particle
-// contact) accumulates and applies after the walk (each pair once, from the lower of its two cells, neighbours read in cell then index order
-// from a stable counting-sort grid, a pair weighted the same at both ends); proxy impulses are summed per body
-// in lane order; heap and breadth-first orders break ties by lane. Compiled with -ffp-contract=off (/fp:precise
-// on MSVC) so no fused multiply-add changes a byte.
-//
-// Licence note: the formulas come from the papers (Kelager 2010 bend, Kim 2012 tethers, Macklin 2014, 2016, 2019).
-// No code of PhysX 5.6.0 or any other solver is adapted here.
-
-#ifndef YMIR_PARTICLES_H
-#define YMIR_PARTICLES_H
-
-#include <stdint.h>
-
-enum
-{
- YMIR_PARTICLES_OK = 0,
- YMIR_PARTICLES_INVALID_ARGUMENT = 1,
- YMIR_PARTICLES_DUPLICATE_ID = 2,
- YMIR_PARTICLES_FULL = 3,
- YMIR_PARTICLES_OUT_OF_MEMORY = 4
-};
-
-// Phase word: bits 0-19 are the group; the three flags below are the only other bits.
-enum
-{
- YMIR_PHASE_GROUP_MASK = 0xFFFFFu,
- YMIR_PHASE_SELF_COLLIDE = 1u << 20, // particles of one group collide (both must set it)
- YMIR_PHASE_SELF_FILTER = 1u << 21, // ... except pairs closer than 1.5 (ri + rj) in the rest pose (either sets it)
- YMIR_PHASE_FLUID = 1u << 22, // a fluid particle: number density, not contact, with other fluid; contact with solids. Group and
- // the SELF_* flags are ignored between two fluid particles (all fluid shares one density field)
- YMIR_PHASE_VALID = YMIR_PHASE_GROUP_MASK | YMIR_PHASE_SELF_COLLIDE | YMIR_PHASE_SELF_FILTER | YMIR_PHASE_FLUID
-};
-
-// Lane sets a command names (a type for remove, a set for free_slots).
-enum
-{
- YMIR_LANES_PARTICLE = 0,
- YMIR_LANES_DISTANCE = 1,
- YMIR_LANES_BEND = 2,
- YMIR_LANES_ATTACHMENT = 3,
- YMIR_LANES_WET = 4, // a wet patch: settled liquid on a body or a solid particle
- YMIR_LANES_SENSOR = 5 // a liquid sensor: a sphere fixed in a body that reads the liquid volume inside it
-};
-
-enum
-{
- YMIR_ATTACH_BODY = 0, // particle to a point fixed in a body (its lane)
- YMIR_ATTACH_STATIC = 1, // particle to a world point
- YMIR_ATTACH_REMOVED = 2
-};
-
-enum
-{
- YMIR_ATTACH_FLAG_TETHER = 1u // bounds each particle by the rest path to the nearest point of its two nearest islands of tether attachments
-};
-
-enum
-{
- YMIR_PROXY_NONE = 0, // no shape (an anchor): attachments reach it, particles never touch it
- YMIR_PROXY_SPHERE = 1,
- YMIR_PROXY_CAPSULE = 2, // segment along local Y
- YMIR_PROXY_BOX = 3
-};
-
-// A lane and the generation it had when the handle was made.
-typedef struct ymir_handle
-{
- int32_t lane;
- uint32_t generation;
-} ymir_handle;
-
-typedef struct ymir_particle_capacities
-{
- int32_t particles, distances, bends, attachments, tethers, materials, fluid, wets, sensors; // fluid: the most live particles with the FLUID phase; wets: the most wet patches; sensors: the most liquid sensors
-} ymir_particle_capacities;
-
-// A particle to create. `mass` kg (0 = immovable); `velocity` m/s; `rest` is its place in the rest pose (rest lengths, bends and
-// the self-collision filter read it); `material` indexes the material table.
-typedef struct ymir_particle_desc
-{
- float position[3];
- float rest[3];
- float velocity[3];
- float mass;
- float radius;
- uint32_t phase;
- uint32_t material;
-} ymir_particle_desc;
-
-// A distance constraint. `rest` < 0 takes the rest-pose length. `compliance` m/N, >= 0.
-typedef struct ymir_distance_desc
-{
- ymir_handle a, b;
- float rest;
- float compliance;
-} ymir_distance_desc;
-
-// A bend over two distance constraints that share one particle. `compliance` < 0 switches the soft pass off;
-// `max_angle` (radians, the deflection from straight) < 0 switches the hard limit off.
-typedef struct ymir_bend_desc
-{
- ymir_handle e1, e2;
- float compliance;
- float max_angle;
-} ymir_bend_desc;
-
-// An attachment of `particle`. `body` is the body lane (body kind) or -1. `point` is in the body's frame (body)
-// or the world (static).
-typedef struct ymir_attachment_desc
-{
- uint32_t kind;
- uint32_t flags;
- ymir_handle particle;
- int32_t body;
- float point[3];
- float compliance; // m/N, >= 0
- uint32_t reserved;
-} ymir_attachment_desc;
-
-// A liquid sensor to create: a sphere of `radius` m (> 0) centred on `point` in the frame of body lane `body`.
-typedef struct ymir_sensor_desc
-{
- int32_t body;
- float point[3];
- float radius;
-} ymir_sensor_desc;
-
-typedef struct ymir_material_desc
-{
- float friction; // >= 0
- float viscosity; // >= 0, XSPH c (dimensionless): a fluid pair's velocities relax toward each other by c W / n0 per substep; mean of the pair's two
- float wet_friction; // >= 0: what settled liquid of this material does to friction where it lands; stored for the friction cut, read by nothing here
- uint32_t pad;
- uint64_t material_id;
-} ymir_material_desc;
-
-// A body as the particle phase sees it. Filled by the caller before a step; `impulse` and `angular_impulse`
-// (N s, world, about the body position) are the totals the particle phase delivered, written by it.
-typedef struct ymir_particle_proxy
-{
- uint32_t shape;
- float size[3];
- float position[3];
- float rotation[4]; // x y z w
- float velocity[3];
- float angular_velocity[3];
- float inv_mass; // 0 for static, kinematic and anchor bodies
- float inv_inertia[6]; // world inverse inertia, symmetric: xx xy xz yy yz zz
- float impulse[3]; // N s, world: the tick's total, the sum of every substep's
- float angular_impulse[3];
- float sub_impulse[3]; // N s: this substep's, applied by the caller before the body's positions integrate
- float sub_angular[3];
-} ymir_particle_proxy;
-
-typedef struct ymir_particles
-{
- int32_t particle_capacity, distance_capacity, bend_capacity, attachment_capacity, tether_capacity, material_capacity;
- int32_t body_capacity, fluid_capacity; // fluid_capacity: the most live fluid particles; it sizes the neighbour arena
- int32_t particle_count, distance_count, bend_count, attachment_count; // high-water marks
- int32_t tether_count; // derived: the live tethers
- int32_t body_count; // bodies filled in `proxies` this step
- int32_t live_particles;
- int32_t fluid_rings; // derived by fluid_density: rings of kernel cells (4 rfmax) that hold a kernel pair, 0 without fluid
- int32_t fluid_overflow; // kernel neighbours past a fluid particle's list in the last step, summed over substeps: a sensor
- int32_t wet_capacity, wet_count; // wet patches: the capacity and the high-water mark
- int32_t sensor_capacity, sensor_count; // liquid sensors: the capacity and the high-water mark
- int32_t live_fluid; // derived: the live particles with the FLUID phase bit; the create and destroy commands are its only writers
- ymir_particle_proxy* proxies;
-
- // particle lanes; a free lane reads live 0 and every other lane 0 except generation and removed_at
- float *pos_x, *pos_y, *pos_z, *vel_x, *vel_y, *vel_z, *radius, *inv_mass;
- float *rest_x, *rest_y, *rest_z;
- uint32_t *phase, *material, *particle_live, *particle_generation;
- uint64_t* particle_removed_at;
- int32_t* component; // derived: the lowest lane of the particle's distance-connected component
- int32_t *nbr, *nbr_start, *nbr_count; // scratch: the fluid rows' kernel neighbours in walk order, packed (CSR) in an arena of fluid_capacity * YMIR_FLUID_NEIGHBOURS; row i holds nbr_count[i] from nbr_start[i], this substep's
- int32_t *support_body, *support_particle; // sensor: what a fluid particle touched in the last substep, the highest body lane / the first solid lane its row listed touching it; -1 for none, and always -1 for a solid or free lane
- float* density; // sensor: a fluid particle's number density over its rest density n_i / n0 in the last substep it ran, else 0
-
- // wet lanes: a patch of settled liquid on one support, a body (wet_body, its point in the body frame) or a solid particle (wet_particle, point 0);
- // one of the two is -1, and a free lane holds -1 in both. Written by settle, remove and destroy_particles only; the step never touches them.
- int32_t *wet_body, *wet_particle;
- float *wet_x, *wet_y, *wet_z, *wet_radius, *wet_volume; // wet_volume m^3; wet_radius = sqrt(volume / (pi YMIR_WET_FILM))
- uint32_t *wet_material, *wet_live, *wet_generation;
- uint64_t* wet_removed_at;
- int32_t *wet_order, *wet_body_start, *wet_body_count; // derived lookup index (rederive_wet): live body patches by body then centre x; each body's slice
- float* wet_body_box; // derived, 7 per body: min xyz and max xyz of its discs' boxes, then its largest radius
- float* particle_wet_mu; // derived, per particle lane: the wet friction of the lowest live patch on that solid particle, +inf when dry (rederive_wet)
- float* wet_volume_body; // derived, per body lane: the sum of the live patches on it in wet lane order (rederive_wet, at command time only)
- int32_t* wu_code; // settle's undo log, one entry per distinct drop: a patch lane (merged: its old lanes below) or -(lane + 1) (created)
- float *wu_x, *wu_y, *wu_z, *wu_volume;
-
- // sensor lanes: a sphere fixed in a body; a free lane reads live 0, body -1 and 0 elsewhere except generation and removed_at. Written by create_sensors and
- // remove; sensor_liquid_volume and sensor_wet_volume are written by end alone, at the step's end (m^3): the sum of (2 r)^3 over the live fluid particles whose centre is inside,
- // and the sum of the volumes of the live wet patches whose centre is inside, on any body or solid particle
- int32_t* sensor_body;
- float *sensor_x, *sensor_y, *sensor_z, *sensor_radius, *sensor_liquid_volume, *sensor_wet_volume;
- uint32_t *sensor_live, *sensor_generation;
- uint64_t* sensor_removed_at;
-
- // distance lanes
- int32_t *dist_a, *dist_b;
- float *dist_rest, *dist_compliance;
- float* dist_tension; // N, the load the constraint carries, mean over the substeps: a sensor
- uint32_t *dist_live, *dist_generation;
- uint64_t* dist_removed_at;
-
- // bend lanes: e1 and e2 are distance lanes; a, b, c the particles (b shared)
- int32_t *bend_e1, *bend_e2, *bend_a, *bend_b, *bend_c;
- float *bend_rest, *bend_limit, *bend_compliance; // offsets of b from the centroid; limit < 0 is off
- uint32_t *bend_live, *bend_generation;
- uint64_t* bend_removed_at;
-
- // attachment lanes
- uint32_t *att_kind, *att_flags, *att_generation;
- int32_t *att_particle, *att_body;
- float *att_point_x, *att_point_y, *att_point_z, *att_compliance;
- float *att_force_x, *att_force_y, *att_force_z; // N, the force the attachment exerts on its particles (mean): a sensor
- uint64_t* att_removed_at;
-
- // tether lanes: derived: grouped by island in lane order (an island: tether particles joined by live distances, named by its
- // lowest tether attachment), settle order within; per island one for each particle that is not a tether particle and holds the island
- // among its two nearest, to the attachment point it is nearest; then per attachment pair with a body among them a route of
- // booking lanes (attachment -1, edge only) along their rest path and the pair tether; parents come first;
- // other >= 0 makes the tether a bound between two attachment points (edge -1) instead of a particle and a point
- int32_t *tether_att, *tether_particle, *tether_parent, *tether_edge, *tether_other;
- float* tether_bound;
-
- // material table
- float *mat_friction, *mat_viscosity, *mat_wet_friction;
- uint64_t* mat_id;
-
- // solver scratch, allocated once at create
- float *pp_x, *pp_y, *pp_z, *dp_x, *dp_y, *dp_z, *dist_acc, *tacc_x, *tacc_y, *tacc_z, *lambda;
- float fluid_k; // n0(h) = fluid_k / h^3: the Poly6 sum over the simple-cubic lattice of spacing h / 2, a create-time constant
- int32_t *lane_list, *cell_x, *cell_y, *cell_z, *cell_start, *cell_fill, *sorted, *contacts;
- float *sx, *sy, *sz, *sw; // the fluid grid's lanes in sorted order (predicted position, inverse mass): scratch, only fluid_density reads them
- uint32_t* sphase; // the sorted lanes' phase
- int32_t *adj_start, *adj_edge, *heap_node, *heap_edge, *via, *owner, *tether_of, *queue, *comp_size, *isle, *near_isle;
- float *heap_key, *path, *near_path;
- uint8_t* done;
- uint32_t table_mask;
- void* arena;
-} ymir_particles;
-
-// Creates the state for the capacities (all >= 0) and `body_capacity` proxies; NULL on failure.
-ymir_particles* ymir_particles_create(const ymir_particle_capacities* capacities, int32_t body_capacity);
-void ymir_particles_free(ymir_particles* p);
-
-// The friction on body lane `body` at body-frame point (x, y, z): the wet friction of the lowest live patch whose disc holds it, never above mu.
-float ymir_particles_wet_mu(const ymir_particles* p, int32_t body, float x, float y, float z, float mu);
-
-// Commands. `step_count` is the world's completed steps: a removed lane is reused once a step has passed, lowest
-// lane first. Every refusal happens before anything changes; a command that would need more tethers than the
-// capacity is refused whole (tether capacity: up to two per particle reached, plus the pair routes). Every topology command ends in the one rederive_topology.
-int32_t ymir_particles_create_particles(ymir_particles* p, int32_t n, const ymir_particle_desc* d, uint64_t step_count, ymir_handle* out);
-int32_t ymir_particles_destroy_particles(ymir_particles* p, int32_t n, const ymir_handle* h, uint64_t step_count);
-int32_t ymir_particles_create_distances(ymir_particles* p, int32_t n, const ymir_distance_desc* d, uint64_t step_count, ymir_handle* out);
-int32_t ymir_particles_create_bends(ymir_particles* p, int32_t n, const ymir_bend_desc* d, uint64_t step_count, ymir_handle* out);
-int32_t ymir_particles_attach(ymir_particles* p, const ymir_attachment_desc* d, int32_t body_count, uint64_t step_count, ymir_handle* out);
-int32_t ymir_particles_remove(ymir_particles* p, uint32_t type, int32_t n, const ymir_handle* h, uint64_t step_count);
-// Settles the named fluid particles into wet patches and destroys them. Each reads its support from the last step (support_body, else
-// support_particle) and its contact point from the proxies the caller has just filled; a drop's volume is (2 r)^3. Refuses whole
-// (INVALID_ARGUMENT) a dead or non-fluid particle or one with no support, FULL when a drop finds no lane and no 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);
-
-// The particle phase runs inside the rigid solver's substeps: begin once per tick (after the caller filled the
-// proxies' shape, size, inverse mass and inertia), substep once per rigid substep (after the caller refreshed each
-// proxy's pose and velocity; it then applies each proxy's sub_impulse before positions integrate), end once.
-int32_t ymir_particles_begin(ymir_particles* p);
-void ymir_particles_substep(ymir_particles* p, float h, float gx, float gy, float gz);
-void ymir_particles_end(ymir_particles* p, int32_t substeps);
-
-#endif
+// Particles and the constraints between them: Ymir's own position-based solver, stepped inside Box3D's substeps
+// (see ymir_box3d_soa.c, the only Box3D caller). This module knows nothing of Box3D. soa.c fills one proxy per body
+// (pose, velocity, shape, inverse mass and inertia) before each substep, the solver moves those proxies by the
+// constraints it solves, and the impulse each body accumulated comes back in the proxy for soa.c to apply.
+// See docs/soa-world.md.
+//
+// There is no object above the lanes: particles are one lane set with a phase word, and every constraint type
+// (distance, bend, attachment) is a lane set of its own. A thing made of particles is whatever constraints a
+// caller emitted. Tethers and components are derived from the distance graph by rederive_topology, which every
+// topology command ends in and which is their only writer.
+//
+// Determinism: single thread; constraints are Gauss-Seidel in lane order; the one Jacobi pass (particle-particle
+// contact) accumulates and applies after the walk (each pair once, from the lower of its two cells, neighbours read in cell then index order
+// from a stable counting-sort grid, a pair weighted the same at both ends); proxy impulses are summed per body
+// in lane order; heap and breadth-first orders break ties by lane. Compiled with -ffp-contract=off (/fp:precise
+// on MSVC) so no fused multiply-add changes a byte.
+//
+// Licence note: the formulas come from the papers (Kelager 2010 bend, Kim 2012 tethers, Macklin 2014, 2016, 2019).
+// No code of PhysX 5.6.0 or any other solver is adapted here.
+
+#ifndef YMIR_PARTICLES_H
+#define YMIR_PARTICLES_H
+
+#include <stdint.h>
+
+enum
+{
+ YMIR_PARTICLES_OK = 0,
+ YMIR_PARTICLES_INVALID_ARGUMENT = 1,
+ YMIR_PARTICLES_DUPLICATE_ID = 2,
+ YMIR_PARTICLES_FULL = 3,
+ YMIR_PARTICLES_OUT_OF_MEMORY = 4
+};
+
+// Phase word: bits 0-19 are the group; the three flags below are the only other bits.
+enum
+{
+ YMIR_PHASE_GROUP_MASK = 0xFFFFFu,
+ YMIR_PHASE_SELF_COLLIDE = 1u << 20, // particles of one group collide (both must set it)
+ YMIR_PHASE_SELF_FILTER = 1u << 21, // ... except pairs closer than 1.5 (ri + rj) in the rest pose (either sets it)
+ YMIR_PHASE_FLUID = 1u << 22, // a fluid particle: number density, not contact, with other fluid; contact with solids. Group and
+ // the SELF_* flags are ignored between two fluid particles (all fluid shares one density field)
+ YMIR_PHASE_VALID = YMIR_PHASE_GROUP_MASK | YMIR_PHASE_SELF_COLLIDE | YMIR_PHASE_SELF_FILTER | YMIR_PHASE_FLUID
+};
+
+// Lane sets a command names (a type for remove, a set for free_slots).
+enum
+{
+ YMIR_LANES_PARTICLE = 0,
+ YMIR_LANES_DISTANCE = 1,
+ YMIR_LANES_BEND = 2,
+ YMIR_LANES_ATTACHMENT = 3,
+ YMIR_LANES_WET = 4, // a wet patch: settled liquid on a body or a solid particle
+ YMIR_LANES_SENSOR = 5 // a liquid sensor: a sphere fixed in a body that reads the liquid volume inside it
+};
+
+enum
+{
+ YMIR_ATTACH_BODY = 0, // particle to a point fixed in a body (its lane)
+ YMIR_ATTACH_STATIC = 1, // particle to a world point
+ YMIR_ATTACH_REMOVED = 2
+};
+
+enum
+{
+ YMIR_ATTACH_FLAG_TETHER = 1u // bounds each particle by the rest path to the nearest point of its two nearest islands of tether attachments
+};
+
+enum
+{
+ YMIR_PROXY_NONE = 0, // no shape (an anchor): attachments reach it, particles never touch it
+ YMIR_PROXY_SPHERE = 1,
+ YMIR_PROXY_CAPSULE = 2, // segment along local Y
+ YMIR_PROXY_BOX = 3
+};
+
+// A lane and the generation it had when the handle was made.
+typedef struct ymir_handle
+{
+ int32_t lane;
+ uint32_t generation;
+} ymir_handle;
+
+typedef struct ymir_particle_capacities
+{
+ int32_t particles, distances, bends, attachments, tethers, materials, fluid, wets, sensors; // fluid: the most live particles with the FLUID phase; wets: the most wet patches; sensors: the most liquid sensors
+} ymir_particle_capacities;
+
+// A particle to create. `mass` kg (0 = immovable); `velocity` m/s; `rest` is its place in the rest pose (rest lengths, bends and
+// the self-collision filter read it); `material` indexes the material table.
+typedef struct ymir_particle_desc
+{
+ float position[3];
+ float rest[3];
+ float velocity[3];
+ float mass;
+ float radius;
+ uint32_t phase;
+ uint32_t material;
+} ymir_particle_desc;
+
+// A distance constraint. `rest` < 0 takes the rest-pose length. `compliance` m/N, >= 0.
+typedef struct ymir_distance_desc
+{
+ ymir_handle a, b;
+ float rest;
+ float compliance;
+} ymir_distance_desc;
+
+// A bend over two distance constraints that share one particle. `compliance` < 0 switches the soft pass off;
+// `max_angle` (radians, the deflection from straight) < 0 switches the hard limit off.
+typedef struct ymir_bend_desc
+{
+ ymir_handle e1, e2;
+ float compliance;
+ float max_angle;
+} ymir_bend_desc;
+
+// An attachment of `particle`. `body` is the body lane (body kind) or -1. `point` is in the body's frame (body)
+// or the world (static).
+typedef struct ymir_attachment_desc
+{
+ uint32_t kind;
+ uint32_t flags;
+ ymir_handle particle;
+ int32_t body;
+ float point[3];
+ float compliance; // m/N, >= 0
+ uint32_t reserved;
+} ymir_attachment_desc;
+
+// A liquid sensor to create: a sphere of `radius` m (> 0) centred on `point` in the frame of body lane `body`.
+typedef struct ymir_sensor_desc
+{
+ int32_t body;
+ float point[3];
+ float radius;
+} ymir_sensor_desc;
+
+typedef struct ymir_material_desc
+{
+ float friction; // >= 0
+ float viscosity; // >= 0, XSPH c (dimensionless): a fluid pair's velocities relax toward each other by c W / n0 per substep; mean of the pair's two
+ float wet_friction; // >= 0: what settled liquid of this material does to friction where it lands; stored for the friction cut, read by nothing here
+ uint32_t pad;
+ uint64_t material_id;
+} ymir_material_desc;
+
+// A body as the particle phase sees it. Filled by the caller before a step; `impulse` and `angular_impulse`
+// (N s, world, about the body position) are the totals the particle phase delivered, written by it.
+typedef struct ymir_particle_proxy
+{
+ uint32_t shape;
+ float size[3];
+ float position[3];
+ float rotation[4]; // x y z w
+ float velocity[3];
+ float angular_velocity[3];
+ float inv_mass; // 0 for static, kinematic and anchor bodies
+ float inv_inertia[6]; // world inverse inertia, symmetric: xx xy xz yy yz zz
+ float impulse[3]; // N s, world: the tick's total, the sum of every substep's
+ float angular_impulse[3];
+ float sub_impulse[3]; // N s: this substep's, applied by the caller before the body's positions integrate
+ float sub_angular[3];
+} ymir_particle_proxy;
+
+typedef struct ymir_particles
+{
+ int32_t particle_capacity, distance_capacity, bend_capacity, attachment_capacity, tether_capacity, material_capacity;
+ int32_t body_capacity, fluid_capacity; // fluid_capacity: the most live fluid particles; it sizes the neighbour arena
+ int32_t particle_count, distance_count, bend_count, attachment_count; // high-water marks
+ int32_t tether_count; // derived: the live tethers
+ int32_t body_count; // bodies filled in `proxies` this step
+ int32_t live_particles;
+ int32_t fluid_rings; // derived by fluid_density: rings of kernel cells (4 rfmax) that hold a kernel pair, 0 without fluid
+ int32_t fluid_overflow; // kernel neighbours past a fluid particle's list in the last step, summed over substeps: a sensor
+ int32_t wet_capacity, wet_count; // wet patches: the capacity and the high-water mark
+ int32_t sensor_capacity, sensor_count; // liquid sensors: the capacity and the high-water mark
+ int32_t live_fluid; // derived: the live particles with the FLUID phase bit; the create and destroy commands are its only writers
+ ymir_particle_proxy* proxies;
+
+ // particle lanes; a free lane reads live 0 and every other lane 0 except generation and removed_at
+ float *pos_x, *pos_y, *pos_z, *vel_x, *vel_y, *vel_z, *radius, *inv_mass;
+ float *rest_x, *rest_y, *rest_z;
+ uint32_t *phase, *material, *particle_live, *particle_generation;
+ uint64_t* particle_removed_at;
+ int32_t* component; // derived: the lowest lane of the particle's distance-connected component
+ int32_t *nbr, *nbr_start, *nbr_count; // scratch: the fluid rows' kernel neighbours in walk order, packed (CSR) in an arena of fluid_capacity * YMIR_FLUID_NEIGHBOURS; row i holds nbr_count[i] from nbr_start[i], this substep's
+ int32_t *support_body, *support_particle; // sensor: what a fluid particle touched in the last substep, the highest body lane / the first solid lane its row listed touching it; -1 for none, and always -1 for a solid or free lane
+ float* density; // sensor: a fluid particle's number density over its rest density n_i / n0 in the last substep it ran, else 0
+
+ // wet lanes: a patch of settled liquid on one support, a body (wet_body, its point in the body frame) or a solid particle (wet_particle, point 0);
+ // one of the two is -1, and a free lane holds -1 in both. Written by settle, remove and destroy_particles only; the step never touches them.
+ int32_t *wet_body, *wet_particle;
+ float *wet_x, *wet_y, *wet_z, *wet_radius, *wet_volume; // wet_volume m^3; wet_radius = sqrt(volume / (pi YMIR_WET_FILM))
+ uint32_t *wet_material, *wet_live, *wet_generation;
+ uint64_t* wet_removed_at;
+ int32_t *wet_order, *wet_body_start, *wet_body_count; // derived lookup index (rederive_wet): live body patches by body then centre x; each body's slice
+ float* wet_body_box; // derived, 7 per body: min xyz and max xyz of its discs' boxes, then its largest radius
+ float* particle_wet_mu; // derived, per particle lane: the wet friction of the lowest live patch on that solid particle, +inf when dry (rederive_wet)
+ float* wet_volume_body; // derived, per body lane: the sum of the live patches on it in wet lane order (rederive_wet, at command time only)
+ int32_t* wu_code; // settle's undo log, one entry per distinct drop: a patch lane (merged: its old lanes below) or -(lane + 1) (created)
+ float *wu_x, *wu_y, *wu_z, *wu_volume;
+
+ // sensor lanes: a sphere fixed in a body; a free lane reads live 0, body -1 and 0 elsewhere except generation and removed_at. Written by create_sensors and
+ // remove; sensor_liquid_volume and sensor_wet_volume are written by end alone, at the step's end (m^3): the sum of (2 r)^3 over the live fluid particles whose centre is inside,
+ // and the sum of the volumes of the live wet patches whose centre is inside, on any body or solid particle
+ int32_t* sensor_body;
+ float *sensor_x, *sensor_y, *sensor_z, *sensor_radius, *sensor_liquid_volume, *sensor_wet_volume;
+ uint32_t *sensor_live, *sensor_generation;
+ uint64_t* sensor_removed_at;
+
+ // distance lanes
+ int32_t *dist_a, *dist_b;
+ float *dist_rest, *dist_compliance;
+ float* dist_tension; // N, the load the constraint carries, mean over the substeps: a sensor
+ uint32_t *dist_live, *dist_generation;
+ uint64_t* dist_removed_at;
+
+ // bend lanes: e1 and e2 are distance lanes; a, b, c the particles (b shared)
+ int32_t *bend_e1, *bend_e2, *bend_a, *bend_b, *bend_c;
+ float *bend_rest, *bend_limit, *bend_compliance; // offsets of b from the centroid; limit < 0 is off
+ uint32_t *bend_live, *bend_generation;
+ uint64_t* bend_removed_at;
+
+ // attachment lanes
+ uint32_t *att_kind, *att_flags, *att_generation;
+ int32_t *att_particle, *att_body;
+ float *att_point_x, *att_point_y, *att_point_z, *att_compliance;
+ float *att_force_x, *att_force_y, *att_force_z; // N, the force the attachment exerts on its particles (mean): a sensor
+ uint64_t* att_removed_at;
+
+ // tether lanes: derived: grouped by island in lane order (an island: tether particles joined by live distances, named by its
+ // lowest tether attachment), settle order within; per island one for each particle that is not a tether particle and holds the island
+ // among its two nearest, to the attachment point it is nearest; then per attachment pair with a body among them a route of
+ // booking lanes (attachment -1, edge only) along their rest path and the pair tether; parents come first;
+ // other >= 0 makes the tether a bound between two attachment points (edge -1) instead of a particle and a point
+ int32_t *tether_att, *tether_particle, *tether_parent, *tether_edge, *tether_other;
+ float* tether_bound;
+
+ // material table
+ float *mat_friction, *mat_viscosity, *mat_wet_friction;
+ uint64_t* mat_id;
+
+ // solver scratch, allocated once at create
+ float *pp_x, *pp_y, *pp_z, *dp_x, *dp_y, *dp_z, *dist_acc, *tacc_x, *tacc_y, *tacc_z, *lambda;
+ float fluid_k; // n0(h) = fluid_k / h^3: the Poly6 sum over the simple-cubic lattice of spacing h / 2, a create-time constant
+ int32_t *lane_list, *cell_x, *cell_y, *cell_z, *cell_start, *cell_fill, *sorted, *contacts;
+ float *sx, *sy, *sz, *sw; // the fluid grid's lanes in sorted order (predicted position, inverse mass): scratch, only fluid_density reads them
+ uint32_t* sphase; // the sorted lanes' phase
+ int32_t *adj_start, *adj_edge, *heap_node, *heap_edge, *via, *owner, *tether_of, *queue, *comp_size, *isle, *near_isle;
+ float *heap_key, *path, *near_path;
+ uint8_t* done;
+ uint32_t table_mask;
+ void* arena;
+} ymir_particles;
+
+// Creates the state for the capacities (all >= 0) and `body_capacity` proxies; NULL on failure.
+ymir_particles* ymir_particles_create(const ymir_particle_capacities* capacities, int32_t body_capacity);
+void ymir_particles_free(ymir_particles* p);
+
+// The friction on body lane `body` at body-frame point (x, y, z): the wet friction of the lowest live patch whose disc holds it, never above mu.
+float ymir_particles_wet_mu(const ymir_particles* p, int32_t body, float x, float y, float z, float mu);
+
+// Commands. `step_count` is the world's completed steps: a removed lane is reused once a step has passed, lowest
+// lane first. Every refusal happens before anything changes; a command that would need more tethers than the
+// capacity is refused whole (tether capacity: up to two per particle reached, plus the pair routes). Every topology command ends in the one rederive_topology.
+int32_t ymir_particles_create_particles(ymir_particles* p, int32_t n, const ymir_particle_desc* d, uint64_t step_count, ymir_handle* out);
+int32_t ymir_particles_destroy_particles(ymir_particles* p, int32_t n, const ymir_handle* h, uint64_t step_count);
+int32_t ymir_particles_create_distances(ymir_particles* p, int32_t n, const ymir_distance_desc* d, uint64_t step_count, ymir_handle* out);
+int32_t ymir_particles_create_bends(ymir_particles* p, int32_t n, const ymir_bend_desc* d, uint64_t step_count, ymir_handle* out);
+int32_t ymir_particles_attach(ymir_particles* p, const ymir_attachment_desc* d, int32_t body_count, uint64_t step_count, ymir_handle* out);
+int32_t ymir_particles_remove(ymir_particles* p, uint32_t type, int32_t n, const ymir_handle* h, uint64_t step_count);
+// Settles the named fluid particles into wet patches and destroys them. Each reads its support from the last step (support_body, else
+// support_particle) and its contact point from the proxies the caller has just filled; a drop's volume is (2 r)^3. Refuses whole
+// (INVALID_ARGUMENT) a dead or non-fluid particle or one with no support, FULL when a drop finds no lane and no 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);
+
+// The particle phase runs inside the rigid solver's substeps: begin once per tick (after the caller filled the
+// proxies' shape, size, inverse mass and inertia), substep once per rigid substep (after the caller refreshed each
+// proxy's pose and velocity; it then applies each proxy's sub_impulse before positions integrate), end once.
+int32_t ymir_particles_begin(ymir_particles* p);
+void ymir_particles_substep(ymir_particles* p, float h, float gx, float gy, float gz);
+void ymir_particles_end(ymir_particles* p, int32_t substeps);
+
+#endif

View file

@ -0,0 +1,60 @@
using System; using System.Diagnostics; using System.Collections.Generic;
// Facts: 128 bits. Self: Near(s)=s (0..15), Holding(s)=16+s, HandFree=32, Free=33, Fed=34.
// Per slot: Unlocked(s)=64+s, Open(s)=80+s, Off(s)=96+s.
struct F { public ulong A, B;
public static F Bit(int i){ var f=new F(); if(i<64) f.A=1UL<<i; else f.B=1UL<<(i-64); return f; }
public static F operator|(F x,F y)=>new F{A=x.A|y.A,B=x.B|y.B};
public static F operator&(F x,F y)=>new F{A=x.A&y.A,B=x.B&y.B};
public static F operator~(F x)=>new F{A=~x.A,B=~x.B};
public bool Any=>(A|B)!=0; }
struct Act { public F Pre, Add, Del; public float Cost; }
static class P {
const int N=16; static Act[] acts; static int nActs; static F start;
// per goal: want fact per target slot
static int[] doors={0,1}, keys={2,3}; const int knife=4, strap=5, sw=6, food=7;
static int HB(int s)=>16+s;
static void Build(){
var l=new List<Act>(); F nearAll=new F{A=0xFFFF};
for(int s=0;s<N;s++){ if(s==strap) continue; l.Add(new Act{Pre=F.Bit(33),Add=F.Bit(s),Del=nearAll&~F.Bit(s),Cost=2}); }
foreach(int s in new[]{2,3,knife,food}){ l.Add(new Act{Pre=F.Bit(s)|F.Bit(32),Add=F.Bit(HB(s)),Del=F.Bit(32),Cost=1});
l.Add(new Act{Pre=F.Bit(HB(s)),Add=F.Bit(32),Del=F.Bit(HB(s)),Cost=1}); }
foreach(int k in keys) foreach(int d in doors) l.Add(new Act{Pre=F.Bit(HB(k))|F.Bit(d),Add=F.Bit(64+d),Cost=1});
foreach(int d in doors) l.Add(new Act{Pre=F.Bit(d)|F.Bit(64+d),Add=F.Bit(80+d),Cost=1});
l.Add(new Act{Pre=F.Bit(HB(knife)),Add=F.Bit(33),Cost=2}); // cut strap
l.Add(new Act{Pre=F.Bit(sw),Add=F.Bit(96+sw),Cost=1}); // switch off
l.Add(new Act{Pre=F.Bit(HB(food)),Add=F.Bit(34),Cost=1}); // eat
// distractor verbs on other things (poke, shove, look) that achieve per-slot facts nobody wants
for(int s=8;s<N;s++){ l.Add(new Act{Pre=F.Bit(s),Add=F.Bit(96+s),Cost=1}); l.Add(new Act{Pre=F.Bit(s)|F.Bit(32),Add=F.Bit(80+s),Cost=1}); }
acts=l.ToArray(); nActs=acts.Length;
start=F.Bit(knife)|F.Bit(32); // restrained, knife in reach, hand free
}
static bool Sub(F r,F s)=>((r.A&~s.A)|(r.B&~s.B))==0;
static long nodes;
// regressive DFS: required set r, depth left d
static bool Reg(F r,int d){ nodes++; if(Sub(r,start)) return true; if(d==0) return false;
for(int i=0;i<nActs;i++){ ref Act a=ref acts[i]; if(!(a.Add&r).Any) continue; if((a.Del&r).Any) continue;
var r2=(r&~a.Add)|a.Pre; if(Reg(r2,d-1)) return true; } return false; }
static bool Fwd(F s,F want,int d){ nodes++; if(Sub(want,s)) return true; if(d==0) return false;
for(int i=0;i<nActs;i++){ ref Act a=ref acts[i]; if(!Sub(a.Pre,s)) continue; if(Sub(a.Add,s)) continue;
var s2=(s&~a.Del)|a.Add; if(Fwd(s2,want,d-1)) return true; } return false; }
// planned wants: escape x2 doors (8 steps), stop pain (4), eat (5), plus 2 near ones: reach knife (1), and look-poke (2)
static F[] wants;
static int Plan(int depth,bool fwd){ int found=0; foreach(var w in wants){ for(int d=0; d<=depth; d++){ bool ok= fwd? Fwd(start,w,d): Reg(w,d); if(ok){found++;break;} } } return found; }
static double sink;
static void Utility(){ double best=0; for(int g=0;g<6;g++) for(int s=0;s<N;s++){ double x=(s*0.37+g)%1.0; double y=1-x*x; y*=Math.Pow(0.5+0.5*x,2); if(y>best) best=y; } sink+=best; }
static void Main(string[] args){ Build(); wants=new[]{F.Bit(80+0),F.Bit(80+1),F.Bit(96+sw),F.Bit(34),F.Bit(HB(knife)),F.Bit(80+9)};
Console.WriteLine($"grounded actions {nActs}");
for(int d=1;d<=8;d++){ nodes=0; int f=Plan(d,false); long rn=nodes; nodes=0; int ff= d<=5? Plan(d,true):-1; Console.WriteLine($"depth {d}: plans found {f}/6, regressive nodes {rn}, forward nodes {(d<=5?nodes:-1)} found {ff}"); }
// timing: paired interleaved medians, rounds x conditions in shuffled order
var conds=new List<(string,Action)>{("utility-only",()=>Utility())};
for(int d=1;d<=4;d++){int dd=d; conds.Add(($"reg d{d}",()=>{Utility();Plan(dd,false);})); }
for(int d=1;d<=4;d++){int dd=d; conds.Add(($"fwd d{d}",()=>{Utility();Plan(dd,true);})); }
int rounds=41, reps=200; var t=new double[conds.Count,rounds]; var rng=new Random(7); var sw2=new Stopwatch();
for(int w=0;w<3;w++) foreach(var c in conds) for(int i=0;i<reps;i++) c.Item2();
for(int r=0;r<rounds;r++){ var order=new int[conds.Count]; for(int i=0;i<order.Length;i++)order[i]=i; for(int i=order.Length-1;i>0;i--){int j=rng.Next(i+1);(order[i],order[j])=(order[j],order[i]);}
foreach(int c in order){ sw2.Restart(); for(int i=0;i<reps;i++) conds[c].Item2(); sw2.Stop(); t[c,r]=sw2.Elapsed.TotalMilliseconds*1000.0/reps; } }
double Med(double[] a){Array.Sort(a);return a[a.Length/2];}
var b=new double[rounds]; for(int r=0;r<rounds;r++) b[r]=t[0,r];
for(int c=0;c<conds.Count;c++){ var a=new double[rounds]; var dlt=new double[rounds]; for(int r=0;r<rounds;r++){a[r]=t[c,r]; dlt[r]=t[c,r]-t[0,r];}
Console.WriteLine($"{conds[c].Item1,-14} median {Med(a),9:F2} us/Select paired delta over utility {Med(dlt),9:F2} us"); }
Console.WriteLine(sink>0?"":"."); } }

View file

@ -0,0 +1,3 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup><OutputType>Exe</OutputType><TargetFramework>net10.0</TargetFramework><Nullable>disable</Nullable><Optimize>true</Optimize><TieredPGO>true</TieredPGO></PropertyGroup>
</Project>

View file

@ -0,0 +1,15 @@
<Project Sdk="Microsoft.NET.Sdk">
<!-- Layer 5, bound to Ymir's SoA world. The core never references this assembly. -->
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<RootNamespace>Lodur.Body.Ymir</RootNamespace>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\Lodur.Core\Lodur.Core.csproj" />
<ProjectReference Include="$(YmirRoot)\src\Ymir.Box3D\Ymir.Box3D.csproj" />
</ItemGroup>
</Project>

View file

@ -0,0 +1,408 @@
using System;
using Ymir.Box3D;
namespace Lodur.Body.Ymir
{
/// <summary>
/// A <see cref="BodyPlan"/> built in a caller-owned Ymir SoA world (invariant one-physics-world): parts in plan order, then joints
/// in plan order, the stable id firstStableId + part ordinal, the limb lane the part ordinal, the parent lane the lane of the part's
/// parent in the plan. The game owns the physics world: Build adds bodies to the caller's world and Lodur never creates or steps one.
/// <see cref="Drive"/> is the muscle layer: it turns caller-owned strengths and target rotations into torques on the world's
/// torque lanes and does nothing else to the physics. Each muscle's torque is a PD term toward its target plus the gravity load of the
/// muscle's unsupported subtree times its strength, projected on the axes it has gains for (ruling gravity-feedforward-all-muscles), so
/// sag comes only from weakness. Each body's weight is carried from the lowest common ancestor of it and every body it touches, and by
/// no joint when it touches anything outside this ragdoll: only a touch outside a joint's subtree supports that joint's load (ruling
/// gravity-support-subtree-external, superseding gravity-feedforward-count-gate). The load reads Ymir's Mass, Facts.Touching, JointOrigin and
/// Gravity. The binding holds no body numbers; the plan owns them.
/// In a world with a particle system Build also places one liquid sensor per plan airway opening, and <see cref="ReadAirway"/> reads them.
/// </summary>
public sealed class Ragdoll
{
private readonly Box3DSoaWorld _world;
private readonly int[] _bodyLane;
private readonly int[] _jointLane;
// The airway sensors, one per plan opening, when Build created them (a world with no particle system has none); Ragdoll is their one owner. Ask and taken are TakeDrawn's scratch.
private readonly Box3DSoaConstraintHandle[] _sensors;
private readonly float[] _ask, _taken;
private bool _hasSensors;
// LowestOpening's last answer (-1 before the first): the opening it keeps until another's rim lies LowestHysteresis lower.
private int _lowest = -1;
private readonly MuscleGains[] _gains;
// Subtree mass and mass-weighted position per part: scratch rebuilt every Drive, never read across ticks.
private readonly float[] _mass, _momentX, _momentY, _momentZ;
// Depth in the plan's tree, fixed at construction, and the part each part's weight is deposited at (-1: carried from outside): the deposit is scratch rebuilt every Drive.
private readonly int[] _depth, _deposit;
private ulong _firstStableId;
private Ragdoll(Box3DSoaWorld world, BodyPlan plan)
{
_world = world;
Plan = plan;
_bodyLane = new int[plan.Parts.Count];
_jointLane = new int[plan.Joints.Count];
_sensors = new Box3DSoaConstraintHandle[plan.AirwayOpenings.Count];
_ask = new float[plan.AirwayOpenings.Count];
_taken = new float[plan.AirwayOpenings.Count];
_gains = new MuscleGains[plan.Joints.Count];
_mass = new float[plan.Parts.Count];
_momentX = new float[plan.Parts.Count];
_momentY = new float[plan.Parts.Count];
_momentZ = new float[plan.Parts.Count];
_depth = new int[plan.Parts.Count];
_deposit = new int[plan.Parts.Count];
for (var i = 1; i < _depth.Length; i++) _depth[i] = plan.ParentOf(i) < 0 ? 0 : _depth[plan.ParentOf(i)] + 1; // parent before child
}
/// <summary>The plan this ragdoll was built from.</summary>
public BodyPlan Plan { get; }
/// <summary>World lane index of a part's body, by plan part ordinal.</summary>
public int BodyLane(int part) => _bodyLane[part];
/// <summary>World lane index of a joint, by plan joint ordinal.</summary>
public int JointLane(int joint) => _jointLane[joint];
/// <summary>
/// Body and joint capacity a world needs to hold one ragdoll of <paramref name="plan"/> (plus whatever else the caller adds), and the sensor
/// capacity: a world with a particle system must hold Sensors sensor lanes (a world without one needs none).
/// </summary>
public static (int Bodies, int Joints, int Sensors) Needs(BodyPlan plan) => (plan.Parts.Count, plan.Joints.Count, plan.AirwayOpenings.Count);
/// <summary>Builds <paramref name="plan"/> at <paramref name="origin"/> (x, z used). Stable ids are firstStableId + part ordinal.</summary>
public static Ragdoll Build(Box3DSoaWorld world, BodyPlan plan, (float X, float Z) origin, ulong firstStableId)
{
var r = new Ragdoll(world, plan);
r._firstStableId = firstStableId;
var ox = origin.X;
var oz = origin.Z;
for (var i = 0; i < plan.Parts.Count; i++)
{
var p = plan.Parts[i];
var id = firstStableId + (ulong)i;
var position = (ox + p.Position.X, p.Position.Y, oz + p.Position.Z);
var parent = plan.ParentOf(i) < 0 ? -1 : r._bodyLane[plan.ParentOf(i)];
switch (p.Shape)
{
case PartShape.Box:
r._bodyLane[i] = world.AddBox(id, position, p.Size, p.Density, (p.Rotation.X, p.Rotation.Y, p.Rotation.Z, p.Rotation.W),
friction: p.Friction, parent: parent, limb: i);
break;
case PartShape.Capsule:
r._bodyLane[i] = world.AddCapsule(id, position, p.Size.X, p.Size.Y, p.Density, (p.Rotation.X, p.Rotation.Y, p.Rotation.Z, p.Rotation.W),
friction: p.Friction, parent: parent, limb: i, rollingResistance: p.RollingResistance);
break;
default:
r._bodyLane[i] = world.AddSphere(id, position, p.Size.X, p.Density,
friction: p.Friction, parent: parent, limb: i, rollingResistance: p.RollingResistance);
break;
}
}
for (var j = 0; j < plan.Joints.Count; j++)
{
var d = plan.Joints[j];
var kind = d.Kind == JointKind.Spherical ? Box3DSoaJointKind.Spherical : Box3DSoaJointKind.Revolute;
r._jointLane[j] = world.AddJoint(kind, r._bodyLane[d.Parent], r._bodyLane[d.Child],
(ox + d.Anchor.X, d.Anchor.Y, oz + d.Anchor.Z), d.Axis, limit: true, lower: d.Lower, upper: d.Upper, coneAngle: d.Cone);
r._gains[j] = d.Gains;
}
if (plan.AirwayOpenings.Count > 0 && world.View.ParticleCapacity > 0)
{
// Ymir refuses the whole batch when it lacks lanes: a particle world that cannot hold the airway fails here, never silently.
var sensors = new (int Body, (float X, float Y, float Z) Point, float Radius)[plan.AirwayOpenings.Count];
for (var k = 0; k < sensors.Length; k++)
{
var a = plan.AirwayOpenings[k];
sensors[k] = (r._bodyLane[a.Part], a.Offset, a.Radius);
}
world.CreateSensors(sensors, r._sensors);
r._hasSensors = true;
}
return r;
}
/// <summary>
/// Writes this tick's muscle torques onto the world's torque lanes: for each joint a PD torque toward
/// <paramref name="targets"/>[joint] (the child's rotation relative to the parent in the joint frame, whose z axis is a hinge's axis; a hinge has no swing gains, so it takes torque about that axis only) scaled by <paramref name="strengths"/>[joint], applied to the child
/// and, equal and opposite, to the parent, plus the gravity feedforward: the torque about the joint origin that holds up the weight of the child's
/// subtree, except each body in it that touches something outside the subtree (the floor, an object, another body: ruling
/// gravity-support-subtree-external), times the strength and kept to the joint frame axes the muscle has gains for. A world with no gravity skips it.
/// Both arrays are the caller's, one entry per plan joint; nothing is copied or retained. Allocates nothing. Throws when the world dropped
/// touching pairs for want of fact capacity: a load from a partial list is wrong without a trace. Call once per step, before <c>world.Step</c>; the
/// world clears the lanes when it applies them.
/// </summary>
public void Drive(ReadOnlySpan<float> strengths, ReadOnlySpan<Quat> targets)
{
if (strengths.Length != _gains.Length || targets.Length != _gains.Length)
{
throw new ArgumentException($"strengths and targets need {_gains.Length} entries, one per plan joint.");
}
var v = _world.View;
for (var m = 0; m < _gains.Length; m++)
{
var j = _jointLane[m];
var rotation = new Quat(v.JointRotationX[j], v.JointRotationY[j], v.JointRotationZ[j], v.JointRotationW[j]);
PdMuscle.Torque(rotation, v.JointAngularVelocityX[j], v.JointAngularVelocityY[j], v.JointAngularVelocityZ[j],
targets[m], _gains[m], strengths[m], out var tx, out var ty, out var tz);
new Quat(v.JointFrameX[j], v.JointFrameY[j], v.JointFrameZ[j], v.JointFrameW[j])
.Rotate(tx, ty, tz, out var wx, out var wy, out var wz);
var child = v.JointBodyB[j];
var parent = v.JointBodyA[j];
v.TorqueX[child] += wx; v.TorqueY[child] += wy; v.TorqueZ[child] += wz;
v.TorqueX[parent] -= wx; v.TorqueY[parent] -= wy; v.TorqueZ[parent] -= wz;
}
var (gx, gy, gz) = _world.Gravity;
if (gx == 0f && gy == 0f && gz == 0f) return;
var n = _mass.Length;
var facts = _world.Facts;
if (facts.Dropped.Touching > 0)
{
throw new InvalidOperationException("The world dropped touching pairs past its fact capacity; the gravity load needs every pair. Raise the world's fact capacity.");
}
for (var p = 0; p < n; p++) _deposit[p] = p;
foreach (var t in facts.Touching)
{
var a = PartOf(t.LaneA, t.StableIdA);
var b = PartOf(t.LaneB, t.StableIdB);
if (a >= 0 && b >= 0)
{
if (_deposit[a] >= 0) _deposit[a] = CommonAncestor(_deposit[a], b);
if (_deposit[b] >= 0) _deposit[b] = CommonAncestor(_deposit[b], a);
}
else if (a >= 0) _deposit[a] = -1;
else if (b >= 0) _deposit[b] = -1;
}
Array.Clear(_mass);
Array.Clear(_momentX);
Array.Clear(_momentY);
Array.Clear(_momentZ);
for (var p = 0; p < n; p++)
{
var d = _deposit[p];
if (d < 0) continue;
var b = _bodyLane[p];
var load = v.Mass[b];
_mass[d] += load;
_momentX[d] += load * v.PositionX[b];
_momentY[d] += load * v.PositionY[b];
_momentZ[d] += load * v.PositionZ[b];
}
for (var p = n - 1; p > 0; p--) // BodyPlan puts every parent before its child
{
var q = Plan.ParentOf(p);
if (q < 0) continue;
_mass[q] += _mass[p];
_momentX[q] += _momentX[p];
_momentY[q] += _momentY[p];
_momentZ[q] += _momentZ[p];
}
for (var m = 0; m < _gains.Length; m++)
{
var j = _jointLane[m];
var c = Plan.Joints[m].Child;
var rx = _momentX[c] - _mass[c] * v.JointOriginX[j];
var ry = _momentY[c] - _mass[c] * v.JointOriginY[j];
var rz = _momentZ[c] - _mass[c] * v.JointOriginZ[j];
var k = MathF.Max(strengths[m], 0f);
// The muscle holds the load up: minus the gravity torque of the subtree's weight about the joint origin.
var tx = -k * (ry * gz - rz * gy);
var ty = -k * (rz * gx - rx * gz);
var tz = -k * (rx * gy - ry * gx);
var frame = new Quat(v.JointFrameX[j], v.JointFrameY[j], v.JointFrameZ[j], v.JointFrameW[j]);
frame.Conjugate().Rotate(tx, ty, tz, out var lx, out var ly, out var lz);
if (_gains[m].SwingStiffness <= 0f) { lx = 0f; ly = 0f; }
if (_gains[m].TwistStiffness <= 0f) lz = 0f;
frame.Rotate(lx, ly, lz, out var wx, out var wy, out var wz);
var child = v.JointBodyB[j];
var parent = v.JointBodyA[j];
v.TorqueX[child] += wx; v.TorqueY[child] += wy; v.TorqueZ[child] += wz;
v.TorqueX[parent] -= wx; v.TorqueY[parent] -= wy; v.TorqueZ[parent] -= wz;
}
}
/// <summary>The plan part a touch end is, or -1 when the body is not this ragdoll's (its stable id is outside the range, or its lane is not the part's).</summary>
private int PartOf(int lane, ulong stableId)
{
var part = stableId - _firstStableId;
return stableId >= _firstStableId && part < (ulong)_bodyLane.Length && _bodyLane[(int)part] == lane ? (int)part : -1;
}
private int CommonAncestor(int a, int b)
{
while (_depth[a] > _depth[b]) a = Plan.ParentOf(a);
while (_depth[b] > _depth[a]) b = Plan.ParentOf(b);
while (a != b) { a = Plan.ParentOf(a); b = Plan.ParentOf(b); }
return a;
}
/// <summary>
/// Writes each plan sense point's world position into the caller's arrays, one entry per sense point: its part's position plus
/// the part's rotation applied to the point's offset. Allocates nothing.
/// </summary>
public void ReadSensePoints(Span<float> x, Span<float> y, Span<float> z)
{
var points = Plan.SensePoints;
if (x.Length != points.Count || y.Length != points.Count || z.Length != points.Count)
{
throw new ArgumentException($"x, y and z need {points.Count} entries, one per sense point.");
}
var v = _world.View;
for (var s = 0; s < points.Count; s++)
{
var i = _bodyLane[points[s].Part];
var o = points[s].Offset;
new Quat(v.RotationX[i], v.RotationY[i], v.RotationZ[i], v.RotationW[i]).Rotate(o.X, o.Y, o.Z, out var rx, out var ry, out var rz);
x[s] = v.PositionX[i] + rx;
y[s] = v.PositionY[i] + ry;
z[s] = v.PositionZ[i] + rz;
}
}
/// <summary>Writes each plan part's world rotation and centre into the caller's span, one entry per part, for the Actor's orient layers. Allocates nothing.</summary>
public void ReadPartPoses(Span<PartPose> poses)
{
var count = Plan.Parts.Count;
if (poses.Length != count)
{
throw new ArgumentException($"poses needs {count} entries, one per part.");
}
var v = _world.View;
for (var p = 0; p < count; p++)
{
var i = _bodyLane[p];
poses[p] = new PartPose(new Quat(v.RotationX[i], v.RotationY[i], v.RotationZ[i], v.RotationW[i]), v.PositionX[i], v.PositionY[i], v.PositionZ[i]);
}
}
/// <summary>
/// Writes, per plan airway opening, the end-of-step volume (m^3) of live fluid and of settled (wet patch) liquid inside its sphere
/// (zeros in a world with no particle system), and the opening's drop in m: with d the normalised <paramref name="down"/>, how far the opening's lowest rim point
/// lies below the deepest plan airway sump along d (positive below, negative above). The rim is the opening's circle of Radius in the plane across its outward normal
/// (its part's rotation applied to the normalised offset), so a mouth turned to the side still has its half-width of drop. Drop comes from the body's pose and is written in
/// every world. Refuses spans not one per opening and a zero <paramref name="down"/>. Allocates nothing.
/// </summary>
public void ReadAirway(Span<float> live, Span<float> pooled, Span<float> drop, (float X, float Y, float Z) down)
{
var n = _sensors.Length;
if (live.Length != n || pooled.Length != n || drop.Length != n) throw new ArgumentException($"live, pooled and drop need {n} entries, one per airway opening.");
var (dx, dy, dz) = Unit(down);
var deepest = DeepestSump(dx, dy, dz);
var v = _world.View;
for (var k = 0; k < n; k++)
{
live[k] = _hasSensors ? v.SensorLiquidVolume[_sensors[k].Lane] : 0f;
pooled[k] = _hasSensors ? v.SensorWetVolume[_sensors[k].Lane] : 0f;
drop[k] = OpeningDrop(k, dx, dy, dz, deepest);
}
}
/// <summary>
/// Takes what a breath drew from the pool: <paramref name="drawnPooled"/> (Physiology's DrawnPooled, world m^3) split over the openings by each one's pooled reading at the last step's end
/// (exact, because Physiology's weighted sum is linear in the openings), and removed from the wet patches each opening reads. Returns the summed volume that left the world's patches, m^3:
/// 0 for a <paramref name="drawnPooled"/> of 0 or less, a world with no sensors or no pooled reading; float rounding can leave it below the ask. Readings change at the next step's end. Allocates nothing.
/// </summary>
public double TakeDrawn(double drawnPooled)
{
if (!_hasSensors || !(drawnPooled > 0d)) return 0d;
var v = _world.View;
var sum = 0d;
for (var k = 0; k < _sensors.Length; k++) sum += v.SensorWetVolume[_sensors[k].Lane];
if (!(sum > 0d)) return 0d;
for (var k = 0; k < _sensors.Length; k++) _ask[k] = (float)(drawnPooled * v.SensorWetVolume[_sensors[k].Lane] / sum);
_world.TakeWet(_sensors, _ask, _taken);
var taken = 0d;
for (var k = 0; k < _taken.Length; k++) taken += _taken[k];
return taken;
}
/// <summary>The margin (m) by which another opening's rim must lie below the current lowest one's before <see cref="LowestOpening"/> changes its answer: face down the two rims are 0.2 mm apart and a few degrees of head pitch would swap them.</summary>
public const float LowestHysteresis = 0.005f;
/// <summary>
/// The plan airway opening whose rim lies lowest along <paramref name="down"/> (the largest drop of <see cref="ReadAirway"/>, the first on a tie): where liquid leaves
/// (ruling bds-drain-head-decides, the head's pose alone decides). The answer keeps the previous call's opening until another's drop exceeds that opening's by <see cref="LowestHysteresis"/>, so a head lying face down
/// does not swap nose and mouth with every degree of pitch; the first call (or a ragdoll with no previous answer) takes the largest drop. Refuses a zero <paramref name="down"/>. Allocates nothing.
/// </summary>
public int LowestOpening((float X, float Y, float Z) down)
{
var (dx, dy, dz) = Unit(down);
var deepest = DeepestSump(dx, dy, dz);
var best = 0;
var bestDrop = float.NegativeInfinity;
var keptDrop = float.NegativeInfinity;
for (var k = 0; k < _sensors.Length; k++)
{
var drop = OpeningDrop(k, dx, dy, dz, deepest);
if (k == _lowest) keptDrop = drop;
if (drop > bestDrop)
{
bestDrop = drop;
best = k;
}
}
if (_lowest >= 0 && bestDrop <= keptDrop + LowestHysteresis) best = _lowest;
_lowest = best;
return best;
}
private static (float X, float Y, float Z) Unit((float X, float Y, float Z) down)
{
var dl = MathF.Sqrt(down.X * down.X + down.Y * down.Y + down.Z * down.Z);
if (!(dl > 0f) || !float.IsFinite(dl)) throw new ArgumentException("down needs a nonzero finite direction.", nameof(down));
return (down.X / dl, down.Y / dl, down.Z / dl);
}
/// <summary>The deepest plan airway sump's position along the unit direction d.</summary>
private float DeepestSump(float dx, float dy, float dz)
{
var v = _world.View;
var deepest = float.NegativeInfinity;
for (var m = 0; m < Plan.AirwaySumps.Count; m++)
{
var s = Plan.AirwaySumps[m];
var i = _bodyLane[s.Part];
new Quat(v.RotationX[i], v.RotationY[i], v.RotationZ[i], v.RotationW[i]).Rotate(s.Offset.X, s.Offset.Y, s.Offset.Z, out var rx, out var ry, out var rz);
deepest = MathF.Max(deepest, (v.PositionX[i] + rx) * dx + (v.PositionY[i] + ry) * dy + (v.PositionZ[i] + rz) * dz);
}
return deepest;
}
/// <summary>Opening k's lowest rim point's drop below <paramref name="deepest"/> along the unit direction d.</summary>
private float OpeningDrop(int k, float dx, float dy, float dz, float deepest)
{
var v = _world.View;
var a = Plan.AirwayOpenings[k];
var i = _bodyLane[a.Part];
var o = a.Offset;
var q = new Quat(v.RotationX[i], v.RotationY[i], v.RotationZ[i], v.RotationW[i]);
q.Rotate(o.X, o.Y, o.Z, out var cx, out var cy, out var cz);
var centre = (v.PositionX[i] + cx) * dx + (v.PositionY[i] + cy) * dy + (v.PositionZ[i] + cz) * dz;
var ol = MathF.Sqrt(o.X * o.X + o.Y * o.Y + o.Z * o.Z);
var rim = a.Radius;
if (ol > 0f)
{
q.Rotate(o.X / ol, o.Y / ol, o.Z / ol, out var nx, out var ny, out var nz);
var along = dx * nx + dy * ny + dz * nz;
var px = dx - along * nx;
var py = dy - along * ny;
var pz = dz - along * nz;
rim *= MathF.Sqrt(px * px + py * py + pz * pz);
}
return centre + rim - deepest;
}
}
}

540
src/Lodur.Core/Actor.cs Normal file
View file

@ -0,0 +1,540 @@
using System;
using System.Collections.Generic;
namespace Lodur
{
/// <summary>What happened on one tick.</summary>
[Flags]
public enum TickEvents
{
None = 0,
/// <summary>A reflex leaked past the suppression the will still held. With no will nothing is suppressed, so there is no flinch.</summary>
Flinch = 1,
/// <summary>Resolve reached zero this tick: the will broke (again, if it had mended).</summary>
WillBroke = 2,
/// <summary>The Brain's chosen goal took over, its deliberate latency after the choice.</summary>
GoalChanged = 4,
/// <summary>The physiology died this tick (reported once, on the tick it died).</summary>
Died = 8,
/// <summary>An involuntary breath ended a held breath: the breath reflex leaked past the will, or the will gave out while the breath was wanted held.</summary>
Gasp = 16,
/// <summary>A futile direct try was given up this tick: its (goal, target) pair is barred from being tried direct, and the next decision is made past the goal's dwell.</summary>
Frustrated = 32,
}
/// <summary>
/// One character's nervous state and the per-tick order: perception, reflex, drive, the Brain's goal, behaviour. The caller
/// supplies one point per body region, the game's stimulus sources, and the spans the behaviour writes its
/// strengths and targets into; the Actor writes nothing else of the caller's and never touches physics.
/// Everything is allocated in the constructor, and the same inputs give the same outputs.
/// </summary>
public sealed class Actor
{
private readonly double _dt;
private readonly DriveParameters _driveP;
private readonly Brain _brain;
private readonly long _latency;
private readonly long[] _dwell;
private readonly long[] _onset;
private readonly long[] _entryTicks;
private readonly Perception _perception;
private readonly WithdrawalReflex[] _reflexes;
private readonly Physiology? _physiology;
// The breath-hold's contest with air hunger (null without a physiology), the gasp's length in ticks, the tick of the last gasp, and whether the breath is held for the next step.
private readonly WithdrawalReflex? _breath;
private readonly long _gaspTicks;
private long _lastGasp = long.MinValue / 2;
private bool _held;
private bool _diedReported;
// The mean of the strengths written on the last tick, after the ceiling, 0..1: the exertion the physiology is told about.
private double _effort;
private DriveState _drive = DriveState.Fresh;
private long _tick;
private int _goal;
private int _pending = -1;
private ulong _target;
private ulong _pendingTarget;
private long _switchTick;
private long _goalSince;
// The entry ramp of the goal in force: its length in ticks (-1: none, as for the Start goal) and the gain and arousal it started from.
private long _rampTicks = -1;
private double _rampGain0;
private double _rampArousal0;
// The orient layers' solvers (null when no goal has a layer) and the arm the Nearer mode holds, set when a (goal, target) pair commits.
private readonly OrientRig? _rig;
private readonly bool _layered;
private Side _arm = Side.Right;
// The want gate's thinking space (null when no goal has a want), which also holds the plan of the decision in force, and its length as read.
private readonly Deliberation? _deliberation;
private int _planLength;
// Frustration (ruling bds-unplannable-tries-direct): the ticks a direct try may last and a bar lasts, the tick from which the committed pair has read PlanLength -1 without a break (-1: not), and whether the next Select is accepted past the dwell.
private readonly long _frustrationTicks;
private readonly long _retryTicks;
private long _directSince = -1;
private bool _impatient;
public Actor(
double tickSeconds, int regionCount,
NerveParameters nerve, WithdrawalParameters withdrawal, DriveParameters drive, Brain brain,
NerveParameters? senses = null, int senseRegion = 0, PerceptParameters? percepts = null, Physiology? physiology = null,
WithdrawalParameters? breath = null, BodyPlan? body = null, IReadOnlyList<Verb>? verbs = null)
{
brain.Validate();
drive.Validate();
Body = body;
foreach (var goal in brain.Goals)
{
if (!goal.Behaviour.HasLayers)
{
continue;
}
if (body == null)
{
throw new ArgumentException($"Goal {goal.Id}: a behaviour with orient layers needs the Actor's BodyPlan.");
}
if (goal.Behaviour.MuscleCount != body.Joints.Count)
{
throw new ArgumentException($"Goal {goal.Id}: a behaviour with orient layers needs one muscle per joint of the body ({body.Joints.Count}), not {goal.Behaviour.MuscleCount}.");
}
_layered = true;
}
if (_layered)
{
_rig = new OrientRig(body!, brain, tickSeconds);
}
if (physiology != null && !physiology.TryBind())
{
throw new ArgumentException("this physiology is already bound to an actor; one actor steps one physiology.");
}
_physiology = physiology;
_dt = tickSeconds;
_driveP = drive;
_brain = brain;
_goal = brain.Start;
_drive.SensoryGain = brain.Goals[brain.Start].SensoryGain;
if (brain.Goals[brain.Start].EntryArousal is double startArousal)
{
_drive.Arousal = startArousal;
}
// The Start goal takes over at construction: its entry effect applies like any other goal's.
if (brain.Goals[brain.Start].EntryResolve is double startEntry)
{
_drive.Enter(drive, startEntry);
}
_latency = Math.Max(1, (long)Math.Round(brain.DeliberateLatencySeconds / tickSeconds));
_dwell = new long[brain.Goals.Count];
_onset = new long[brain.Goals.Count];
_entryTicks = new long[brain.Goals.Count];
for (var g = 0; g < _dwell.Length; g++)
{
_dwell[g] = (long)Math.Round(brain.Goals[g].MinDwellSeconds / tickSeconds);
// Rounded to whole ticks once, like the dwell, so the onset is the same number of ticks whatever the tick length does to a product.
// A quotient past the long range (+infinity included) is involuntary throughout: the cast of an out-of-range double is not defined across runtimes.
var onsetTicks = brain.Goals[g].InvoluntarySeconds / tickSeconds;
_onset[g] = onsetTicks >= long.MaxValue ? long.MaxValue : (long)Math.Round(onsetTicks);
// The entry ramp is rounded once as well; EntrySeconds is finite, but its quotient can still pass the long range.
var entryTicks = brain.Goals[g].EntrySeconds / tickSeconds;
_entryTicks[g] = entryTicks >= long.MaxValue ? long.MaxValue : (long)Math.Round(entryTicks);
}
// Rounded once to ticks like the dwell; a quotient past the long range (+infinity included) is never reached.
var frustrationTicks = brain.FrustrationSeconds / tickSeconds;
_frustrationTicks = frustrationTicks >= long.MaxValue ? long.MaxValue : (long)Math.Round(frustrationTicks);
var retryTicks = brain.RetrySeconds / tickSeconds;
_retryTicks = retryTicks >= long.MaxValue ? long.MaxValue : (long)Math.Round(retryTicks);
if (physiology != null)
{
var breathP = breath ?? new WithdrawalParameters();
_breath = new WithdrawalReflex(breathP, tickSeconds);
_gaspTicks = (long)Math.Round(breathP.FlinchRefractorySeconds / tickSeconds);
}
_perception = new Perception(nerve, tickSeconds, regionCount, senses, senseRegion, percepts);
if (brain.HasWants)
{
if (_perception.PerceptCount == 0)
{
throw new ArgumentException("A Brain with a want needs percepts: the planner reads the percepts' facts.");
}
_deliberation = new Deliberation(brain, verbs ?? Array.Empty<Verb>(), _perception.PerceptCount);
}
_reflexes = new WithdrawalReflex[regionCount];
for (var r = 0; r < regionCount; r++)
{
_reflexes[r] = new WithdrawalReflex(withdrawal, tickSeconds);
}
}
public int RegionCount => _reflexes.Length;
/// <summary>The body the orient layers solve against; null when the actor was built without one.</summary>
public BodyPlan? Body { get; }
/// <summary>Ticks run so far.</summary>
public long TickCount => _tick;
/// <summary>A snapshot of the drive; nothing but <see cref="Tick"/> writes it.</summary>
public DriveState Drive => _drive;
/// <summary>The physiology this actor steps and reads, null for an actor with none.</summary>
public Physiology? Physiology => _physiology;
/// <summary>Sets the drive's Attention slot; a seam for the tests until lodur-startle-attention writes it.</summary>
internal void SetAttention(double attention)
{
_drive.Attention = attention;
}
/// <summary>
/// Forgets the arms' history: each arm's next solve is the stateless rule, as on the first tick. For a caller that moves the body
/// discontinuously (a teleport, a respawn) so the arms neither carry a swivel from the old place nor slew from its targets. Nothing for an actor without arms.
/// </summary>
public void ResetArms() => _rig?.ResetArms();
public Brain Brain => _brain;
/// <summary>The index in <see cref="Brain"/>'s goals of the goal in force; it changes only on the tick that reports <see cref="TickEvents.GoalChanged"/>.</summary>
public int GoalIndex => _goal;
/// <summary>How long the goal in force will have been in force at the next tick; 0 on the tick it took over.</summary>
public double SecondsInGoal => (_tick - _goalSince) * _dt;
public double Stimulus(int region) => _perception.Stimulus(region);
public double Afferent(int region) => _perception.Afferent(region);
/// <summary>The sensory load this tick: the channels' afferents combined, 0..1.</summary>
public double Load => _perception.Load;
public double ChannelStimulus(Channel channel) => _perception.ChannelStimulus(channel);
public double ChannelAfferent(Channel channel) => _perception.ChannelAfferent(channel);
/// <summary>The number of percept slots (0 with no senses); a free slot reads as Id 0.</summary>
public int PerceptCount => _perception.PerceptCount;
public Percept Percept(int slot) => _perception.Percept(slot);
/// <summary>The id of the percept the committed goal targets; 0 for an untargeted goal. Only the Brain's choice, committed after the latency, writes it.</summary>
public ulong TargetId => _target;
/// <summary>
/// The length of the plan of the decision in force, made by the Select that chose or re-chose the pair and carried with it (a tick that decides nothing only checks it): n steps,
/// -1 when he goes at it direct (no plan within <see cref="Brain.PlanDepth"/>, the think budget gone, or a step's thing forgotten), 0 when the goal has no want, the want holds,
/// or its target is no longer in memory. A -1 that lasts <see cref="Brain.FrustrationSeconds"/> ends in <see cref="TickEvents.Frustrated"/>.
/// </summary>
public int PlanLength => _planLength;
/// <summary>Step <paramref name="i"/> of the plan of the decision in force, for i below <see cref="PlanLength"/>: a verb of the Actor's list and the percept ids it is grounded on.</summary>
public PlanStep PlanStep(int i)
{
if ((uint)i >= (uint)Math.Max(_planLength, 0))
{
throw new ArgumentOutOfRangeException(nameof(i), "There is no such step in the plan.");
}
return _deliberation!.Step(i);
}
/// <summary>The slot whose Id equals <see cref="TargetId"/>; default (Id 0) when the target is 0 or forgotten.</summary>
public Percept Target
{
get
{
if (_target != 0UL)
{
for (var s = 0; s < _perception.PerceptCount; s++)
{
var p = _perception.Percept(s);
if (p.Id == _target)
{
return p;
}
}
}
return default;
}
}
/// <summary>
/// Runs one physics step's worth of nervous system. The point spans hold one entry per region; the strengths
/// and targets spans one entry per muscle, written for the body to follow. The emitters are the game's point
/// sources, sensed at the sense region's point. The airway is what the caller finds at the body's airway openings; nothing by default.
/// The parts are the body's part poses (one per plan part), read when the goal in force has orient layers and ignored otherwise.
/// <paramref name="selfFacts"/> are the actor's own facts for the planner (the game's; bit 63 is refused), read only by a Brain with wants.
/// </summary>
public TickEvents Tick(
ReadOnlySpan<float> regionX, ReadOnlySpan<float> regionY, ReadOnlySpan<float> regionZ,
ReadOnlySpan<BoxStimulus> sources, Span<float> strengths, Span<Quat> targets,
ReadOnlySpan<Emitter> emitters = default, in AirwaySample airway = default, ReadOnlySpan<PartPose> parts = default, ulong selfFacts = 0UL)
{
if ((selfFacts & Perception.InReachFact) != 0UL)
{
throw new ArgumentException("Bit 63 is Lodur's reach; the actor's own facts have none.", nameof(selfFacts));
}
// The goal that will write this tick: a decision due now commits before the behaviour runs, and one made now cannot (the latency is a tick at least).
if (_layered && _brain.Goals[_pending >= 0 && _tick == _switchTick ? _pending : _goal].Behaviour.HasLayers && parts.Length != Body!.Parts.Count)
{
throw new ArgumentException($"parts needs one pose per part of the body ({Body.Parts.Count}).");
}
var events = TickEvents.None;
if (_physiology != null)
{
if (strengths.Length != _physiology.JointCount)
{
throw new ArgumentException("strengths must have one entry per joint of the physiology's body.");
}
// The physiology steps first, on the drive as the last tick left it, and its consciousness is the slot's only writer.
// A dead physiology is stepped too: that step zeroes its flows, so they stand only on the tick it died.
var wasDead = _physiology.Dead;
_physiology.Step(_dt, new PhysiologyInput(_drive.Arousal, _effort, _held, airway));
if (!wasDead)
{
_drive.Consciousness = _physiology.Consciousness;
_drive.AirHunger = _physiology.BreathUrge;
}
if (_physiology.Dead)
{
// Limp and permanent: the drive, goal and perception never change again; targets are left as they were.
strengths.Clear();
_tick++;
if (_diedReported) return events;
_diedReported = true;
return TickEvents.Died;
}
}
// A flinch is the leak of a suppressed reflex; with no will nothing is suppressed, so none is reported.
var holding = _drive.Will > 0.0;
_perception.Sense(regionX, regionY, regionZ, sources, emitters, _drive.SensoryGain);
double afferent = 0.0, strainLoad = 0.0, leak = 0.0;
for (var r = 0; r < _reflexes.Length; r++)
{
var a = _perception.Afferent(r);
var flinch = _reflexes[r].Step(a, _drive);
afferent += a;
strainLoad += _reflexes[r].StrainLoad;
leak += _reflexes[r].Leak;
if (flinch && holding)
{
events |= TickEvents.Flinch;
}
}
// The breath is held on will while liquid is at the airway, in contest with air hunger as a reflex is with pain: it ends in a gasp when the hunger leaks past the will, or
// when the will gives out. The breath's leak is not the limbs' leak; its strain joins the drive's.
if (_physiology != null)
{
var wanted = _physiology.LiquidAtAirway;
var willing = wanted && _drive.Will > 0.0;
if (willing)
{
if (_breath!.Step(_drive.AirHunger, _drive))
{
events |= TickEvents.Gasp;
_lastGasp = _tick;
}
strainLoad += _breath.StrainLoad;
}
else if (wanted && _held)
{
events |= TickEvents.Gasp;
_lastGasp = _tick;
}
_held = willing && _tick - _lastGasp >= _gaspTicks;
}
// Effort is paid only once the goal is voluntary: the onset (InvoluntarySeconds) runs without will, and without cost.
var inForce = _brain.Goals[_goal];
var effort = _tick - _goalSince >= _onset[_goal] ? inForce.Effort : 0.0;
if (_drive.Step(_driveP, _dt, afferent, strainLoad, _perception.Load, inForce.Pull, effort))
{
events |= TickEvents.WillBroke;
}
// A decision in flight commits at its tick even if the condition that chose it has lapsed; none is made while one is
// pending. Within the goal in force's minimum dwell only a strictly higher-priority goal is decided on.
// Order: the bars lift on time or a forgotten target, then a direct try that has lasted its time is barred (and the next decision made impatient), then the decision.
if (_deliberation != null)
{
_deliberation.Lift(_perception, _tick);
if (_directSince >= 0 && _tick - _directSince >= _frustrationTicks && !_deliberation.Barred(_goal, _target))
{
_deliberation.Bar(_goal, _target, _retryTicks > long.MaxValue - _tick ? long.MaxValue : _tick + _retryTicks);
events |= TickEvents.Frustrated;
_directSince = -1;
_impatient = true;
}
}
var planned = false;
if (_pending < 0)
{
var sr = _perception.SenseRegion;
var now = new Choice(_goal, _target);
if (_deliberation != null)
{
_deliberation.SelfFacts = selfFacts;
}
var wanted = _brain.Select(_drive, _perception, regionX[sr], regionY[sr], regionZ[sr], now, _deliberation);
var impatient = _impatient;
_impatient = false; // one Select is impatient, whatever it returns
if (wanted != new Choice(_goal, _target)
&& (wanted.Goal == _goal || _tick - _goalSince >= _dwell[_goal] || _brain.Goals[wanted.Goal].Priority > _brain.Goals[_goal].Priority || impatient))
{
_pending = wanted.Goal;
_pendingTarget = wanted.Target;
_switchTick = _tick + _latency;
}
else if (_deliberation != null)
{
// The Select re-chose the pair in force, or was refused by the dwell and the pair in force is planned again with what is left of its budget.
if (wanted == now)
{
_deliberation.Refresh();
planned = true;
}
else if (_brain.Goals[_goal].Want is { } inForceWant)
{
planned = _deliberation.ReplanInForce(_perception, regionX[sr], regionY[sr], regionZ[sr], inForceWant, _target);
}
}
}
if (_pending >= 0 && _tick == _switchTick)
{
var changed = _pending != _goal;
if (changed || _pendingTarget != _target)
{
_directSince = -1;
}
_goal = _pending;
_target = _pendingTarget;
_pending = -1;
_rig?.Commit();
if (_deliberation != null)
{
_deliberation.Refresh(); // the pending decision's plan, made up to a latency ago: checked below like any carried plan
}
if (_layered && _brain.Goals[_goal].Behaviour.Arms is { Side: ArmSide.Nearer } && _target != 0UL)
{
var committed = Target;
if (committed.Id != 0UL)
{
_arm = _rig!.NearerArm(parts, committed);
}
}
if (changed)
{
_goalSince = _tick;
events |= TickEvents.GoalChanged;
_rampTicks = _entryTicks[_goal];
_rampGain0 = _drive.SensoryGain;
_rampArousal0 = _drive.Arousal;
if (_brain.Goals[_goal].EntryResolve is double entry)
{
_drive.Enter(_driveP, entry);
}
}
}
// The plan of the decision in force was written above by the Select that chose it, or is carried: a tick that wrote none only checks it against the percepts.
_planLength = 0;
if (_deliberation != null && _brain.Goals[_goal].Want is { } committedWant)
{
if (!planned)
{
var sr = _perception.SenseRegion;
_deliberation.SelfFacts = selfFacts;
_deliberation.CheckCarried(_perception, regionX[sr], regionY[sr], regionZ[sr], committedWant, _target);
}
_planLength = _deliberation.InForceLength;
if (_planLength < 0)
{
if (_directSince < 0)
{
_directSince = _tick;
}
}
else
{
_directSince = -1;
}
}
else
{
_directSince = -1;
}
// For EntrySeconds after a takeover the Actor, not the drive, takes the gain (and the arousal, if the goal declares one) from their values at
// takeover to the goal's targets, linearly; its last tick assigns the targets themselves (a lerp need not land on a nonzero target), and after it the drive
// owns arousal again. Sense reads the gain at the start of the next tick, so a change of gain reaches Load one tick after the Actor sets it.
var sinceGoal = _tick - _goalSince;
if (sinceGoal <= _rampTicks)
{
var goal = _brain.Goals[_goal];
var last = sinceGoal == _rampTicks; // also the takeover tick of a zero-length ramp
var k = last ? 1.0 : (double)sinceGoal / _rampTicks;
_drive.SensoryGain = last ? goal.SensoryGain : _rampGain0 + (goal.SensoryGain - _rampGain0) * k;
if (goal.EntryArousal is double target)
{
_drive.Arousal = last ? target : _rampArousal0 + (target - _rampArousal0) * k;
}
}
// Every voluntary layer is held by will, in contest with the reflex; an involuntary one (the onset of a goal) is not.
var secondsInGoal = (_tick - _goalSince) * _dt;
var weight = _tick - _goalSince >= _onset[_goal] ? Math.Pow(_drive.Will, _driveP.WillCurve) : 1.0;
var behaviour = _brain.Goals[_goal].Behaviour;
if (_rig != null)
{
behaviour.Write(weight, leak, _drive.Strain, _tick * _dt, secondsInGoal, strengths, targets, new OrientInput(_rig, parts, Target, _arm));
}
else
{
behaviour.Write(weight, leak, _drive.Strain, _tick * _dt, secondsInGoal, strengths, targets);
}
if (_physiology != null)
{
// The only scaling of strength: each muscle (plan joint m) is held to its ceiling.
var sum = 0.0;
for (var m = 0; m < strengths.Length; m++)
{
strengths[m] *= (float)_physiology.MotorCeiling(m);
sum += strengths[m];
}
var mean = strengths.Length > 0 ? sum / strengths.Length : 0.0;
_effort = mean < 0.0 ? 0.0 : mean > 1.0 ? 1.0 : mean;
}
_tick++;
return events;
}
}
}

243
src/Lodur.Core/BodyPlan.cs Normal file
View file

@ -0,0 +1,243 @@
using System;
using System.Collections.Generic;
namespace Lodur
{
/// <summary>Which side of the body a part, joint or sense point is on; Center for the midline.</summary>
public enum Side { Center, Left, Right }
/// <summary>A part's collision shape.</summary>
public enum PartShape { Box, Capsule, Sphere }
/// <summary>A joint's degrees of freedom: a ball (swing cone and twist) or a hinge about its axis.</summary>
public enum JointKind { Spherical, Revolute }
/// <summary>
/// One rigid part. <see cref="Size"/> is (x, y, z): half extents for a box; radius, half length, 0 for a capsule;
/// radius, 0, 0 for a sphere. <see cref="Position"/> is the creation pose relative to the build origin.
/// The part tree is not a field here: it is the joint list.
/// </summary>
public readonly record struct PartDef(
string Label, Side Side, PartShape Shape, (float X, float Y, float Z) Size, (float X, float Y, float Z) Position,
Quat Rotation, float Density, float Friction, float RollingResistance);
/// <summary>A joint from <see cref="Parent"/> to <see cref="Child"/> (part ordinals); the child's only joint is the one that attaches it.</summary>
public readonly record struct JointDef(
string Label, Side Side, JointKind Kind, int Parent, int Child, (float X, float Y, float Z) Anchor,
(float X, float Y, float Z) Axis, float Lower, float Upper, float Cone, MuscleGains Gains);
/// <summary>A point on a part that perception senses at: the part's position plus its rotation applied to <see cref="Offset"/>.</summary>
public readonly record struct SensePointDef(string Label, Side Side, int Part, (float X, float Y, float Z) Offset);
/// <summary>
/// Where the airway opens to the outside: a sphere of <see cref="Radius"/> m centred at <see cref="Offset"/> in the part's frame; liquid inside it is liquid
/// at the airway. The sphere must reach outside the part's shape, since liquid never enters a body. Its Radius is also its rim: the opening's half-width.
/// </summary>
public readonly record struct AirwayOpeningDef(string Label, Side Side, int Part, (float X, float Y, float Z) Offset, float Radius);
/// <summary>A point inside the airway, at <see cref="Offset"/> in the part's frame, where liquid pools behind the openings (the oropharynx, the glottis). Nothing reads one by label.</summary>
public readonly record struct AirwaySumpDef(string Label, int Part, (float X, float Y, float Z) Offset);
/// <summary>
/// A body as data: parts, the joints that are also its tree, sense points, airway openings and the sumps behind them, each named by label and side.
/// Engine-free; a physics binding builds it into a world. Validated at construction.
/// </summary>
public sealed class BodyPlan
{
private readonly int[] _parentOf;
private readonly Dictionary<(string, Side), int> _parts = new Dictionary<(string, Side), int>();
private readonly Dictionary<(string, Side), int> _joints = new Dictionary<(string, Side), int>();
private readonly Dictionary<(string, Side), int> _senses = new Dictionary<(string, Side), int>();
private readonly Dictionary<(string, Side), int> _airway = new Dictionary<(string, Side), int>();
public BodyPlan(IReadOnlyList<PartDef> parts, IReadOnlyList<JointDef> joints, IReadOnlyList<SensePointDef> sensePoints,
IReadOnlyList<AirwayOpeningDef>? airwayOpenings = null, IReadOnlyList<AirwaySumpDef>? airwaySumps = null)
{
Parts = new List<PartDef>(parts).AsReadOnly();
Joints = new List<JointDef>(joints).AsReadOnly();
SensePoints = new List<SensePointDef>(sensePoints).AsReadOnly();
AirwayOpenings = new List<AirwayOpeningDef>(airwayOpenings ?? Array.Empty<AirwayOpeningDef>()).AsReadOnly();
AirwaySumps = new List<AirwaySumpDef>(airwaySumps ?? Array.Empty<AirwaySumpDef>()).AsReadOnly();
_parentOf = Validate();
}
public IReadOnlyList<PartDef> Parts { get; }
public IReadOnlyList<JointDef> Joints { get; }
public IReadOnlyList<SensePointDef> SensePoints { get; }
public IReadOnlyList<AirwayOpeningDef> AirwayOpenings { get; }
public IReadOnlyList<AirwaySumpDef> AirwaySumps { get; }
/// <summary>The part ordinal a part hangs from (the parent of the one joint that attaches it), -1 for the root.</summary>
public int ParentOf(int part) => _parentOf[part];
public int PartIndex(string label, Side side = Side.Center) => Find(_parts, "part", label, side);
public int JointIndex(string label, Side side = Side.Center) => Find(_joints, "joint", label, side);
public int SenseIndex(string label, Side side = Side.Center) => Find(_senses, "sense point", label, side);
public int AirwayIndex(string label, Side side = Side.Center) => Find(_airway, "airway opening", label, side);
private static int Find(Dictionary<(string, Side), int> index, string what, string label, Side side) =>
index.TryGetValue((label, side), out var i) ? i : throw new ArgumentException($"no {what} labelled '{label}' on side {side}.");
private static bool IsFinite(float f) => !float.IsNaN(f) && !float.IsInfinity(f);
private static bool Finite((float X, float Y, float Z) v) => IsFinite(v.X) && IsFinite(v.Y) && IsFinite(v.Z);
private int[] Validate()
{
// 1. (Label, Side) unique per list, labels non-empty.
Unique(Parts.Count, i => (Parts[i].Label, Parts[i].Side), _parts, "part");
Unique(Joints.Count, i => (Joints[i].Label, Joints[i].Side), _joints, "joint");
Unique(SensePoints.Count, i => (SensePoints[i].Label, SensePoints[i].Side), _senses, "sense point");
Unique(AirwayOpenings.Count, i => (AirwayOpenings[i].Label, AirwayOpenings[i].Side), _airway, "airway opening");
// 2. Joint ends in range and ordered, so the tree is acyclic and parts are created parent first.
foreach (var d in Joints)
{
if (d.Parent < 0 || d.Parent >= Parts.Count || d.Child < 0 || d.Child >= Parts.Count)
{
throw new ArgumentException($"joint '{d.Label}' {d.Side}: parent {d.Parent} or child {d.Child} is not a part.");
}
if (d.Parent >= d.Child)
{
throw new ArgumentException($"joint '{d.Label}' {d.Side}: parent {d.Parent} must precede child {d.Child}.");
}
}
// 3. Part 0 is the root (rule 2 already leaves it no joint to be the child of); every other part is the child of exactly one joint.
if (Parts.Count == 0) throw new ArgumentException("a body plan needs a root part.");
var parentOf = new int[Parts.Count];
var attached = new int[Parts.Count];
for (var p = 0; p < parentOf.Length; p++) parentOf[p] = -1;
foreach (var d in Joints)
{
parentOf[d.Child] = d.Parent;
attached[d.Child]++;
}
for (var p = 1; p < attached.Length; p++)
{
if (attached[p] != 1)
{
throw new ArgumentException($"part '{Parts[p].Label}' {Parts[p].Side} is the child of {attached[p]} joints, needs 1.");
}
}
// 4. Sense points sit on parts.
foreach (var s in SensePoints)
{
if (s.Part < 0 || s.Part >= Parts.Count) throw new ArgumentException($"sense point '{s.Label}' {s.Side}: part {s.Part} is not a part.");
}
foreach (var a in AirwayOpenings)
{
if (a.Part < 0 || a.Part >= Parts.Count) throw new ArgumentException($"airway opening '{a.Label}' {a.Side}: part {a.Part} is not a part.");
}
foreach (var a in AirwaySumps)
{
if (a.Part < 0 || a.Part >= Parts.Count) throw new ArgumentException($"airway sump '{a.Label}': part {a.Part} is not a part.");
}
// An opening's drop is measured below the deepest sump: openings with none would have nothing to fall below.
if (AirwayOpenings.Count > 0 && AirwaySumps.Count == 0) throw new ArgumentException("airway openings need at least one airway sump to drain below.");
// 5. Numbers a physics world can take.
foreach (var p in Parts)
{
var r = p.Rotation;
var finite = Finite(p.Size) && Finite(p.Position) && IsFinite(r.X) && IsFinite(r.Y) && IsFinite(r.Z) && IsFinite(r.W)
&& IsFinite(p.Density) && IsFinite(p.Friction) && IsFinite(p.RollingResistance);
if (!finite) throw new ArgumentException($"part '{p.Label}' {p.Side} has a non-finite number.");
var sz = p.Size;
var sized = p.Shape == PartShape.Box ? sz.X > 0f && sz.Y > 0f && sz.Z > 0f
: p.Shape == PartShape.Capsule ? sz.X > 0f && sz.Y > 0f : sz.X > 0f;
if (!sized) throw new ArgumentException($"part '{p.Label}' {p.Side}: a size its shape uses is not positive.");
// A binding has no destination for what the shape cannot carry (sphere rotation, box rolling resistance, size components
// beyond the shape's own), so the plan may not say it.
var spare = p.Shape == PartShape.Box ? 0f : p.Shape == PartShape.Capsule ? sz.Z : Math.Abs(sz.Y) + Math.Abs(sz.Z);
if (spare != 0f) throw new ArgumentException($"part '{p.Label}' {p.Side}: a size its shape does not use is not zero.");
if (p.Shape == PartShape.Sphere && (r.X != 0f || r.Y != 0f || r.Z != 0f || r.W != 1f))
{
throw new ArgumentException($"part '{p.Label}' {p.Side}: a sphere carries no rotation.");
}
if (p.Shape == PartShape.Box && p.RollingResistance != 0f) throw new ArgumentException($"part '{p.Label}' {p.Side}: a box carries no rolling resistance.");
if (!(p.Density > 0f)) throw new ArgumentException($"part '{p.Label}' {p.Side}: density is not positive.");
}
foreach (var d in Joints)
{
var g = d.Gains;
var finite = Finite(d.Anchor) && Finite(d.Axis) && IsFinite(d.Lower) && IsFinite(d.Upper) && IsFinite(d.Cone)
&& IsFinite(g.SwingStiffness) && IsFinite(g.SwingDamping) && IsFinite(g.TwistStiffness) && IsFinite(g.TwistDamping) && IsFinite(g.Passive);
if (!finite) throw new ArgumentException($"joint '{d.Label}' {d.Side} has a non-finite number.");
if (d.Lower > d.Upper) throw new ArgumentException($"joint '{d.Label}' {d.Side}: lower limit exceeds upper.");
if (d.Cone < 0f) throw new ArgumentException($"joint '{d.Label}' {d.Side}: cone is negative.");
}
foreach (var s in SensePoints)
{
if (!Finite(s.Offset)) throw new ArgumentException($"sense point '{s.Label}' {s.Side} has a non-finite number.");
}
foreach (var a in AirwayOpenings)
{
if (!Finite(a.Offset) || !IsFinite(a.Radius)) throw new ArgumentException($"airway opening '{a.Label}' {a.Side} has a non-finite number.");
if (!(a.Radius > 0f)) throw new ArgumentException($"airway opening '{a.Label}' {a.Side}: radius is not positive.");
}
foreach (var a in AirwaySumps)
{
if (!Finite(a.Offset)) throw new ArgumentException($"airway sump '{a.Label}' has a non-finite number.");
}
// 6. An opening's sphere reaches outside its part: liquid never enters a body, so a sphere wholly inside reads nothing.
foreach (var a in AirwayOpenings)
{
if (SignedDistance(Parts[a.Part], a.Offset) <= -a.Radius)
{
throw new ArgumentException($"airway opening '{a.Label}' {a.Side} lies inside its part.");
}
}
return parentOf;
}
/// <summary>Signed distance from a point in the part's frame to the part's shape: negative inside.</summary>
private static float SignedDistance(PartDef p, (float X, float Y, float Z) o)
{
var sz = p.Size;
switch (p.Shape)
{
case PartShape.Sphere:
return MathF.Sqrt(o.X * o.X + o.Y * o.Y + o.Z * o.Z) - sz.X;
case PartShape.Capsule:
{
var dy = o.Y - Math.Clamp(o.Y, -sz.Y, sz.Y);
return MathF.Sqrt(o.X * o.X + dy * dy + o.Z * o.Z) - sz.X;
}
default:
{
var qx = Math.Abs(o.X) - sz.X;
var qy = Math.Abs(o.Y) - sz.Y;
var qz = Math.Abs(o.Z) - sz.Z;
var ox = Math.Max(qx, 0f);
var oy = Math.Max(qy, 0f);
var oz = Math.Max(qz, 0f);
return MathF.Sqrt(ox * ox + oy * oy + oz * oz) + Math.Min(Math.Max(qx, Math.Max(qy, qz)), 0f);
}
}
}
private static void Unique(int count, Func<int, (string, Side)> key, Dictionary<(string, Side), int> index, string what)
{
for (var i = 0; i < count; i++)
{
var (label, side) = key(i);
if (string.IsNullOrEmpty(label)) throw new ArgumentException($"a {what} has an empty label.");
if (!index.TryAdd((label, side), i)) throw new ArgumentException($"two {what}s are labelled '{label}' on side {side}.");
}
}
}
}

128
src/Lodur.Core/BodyPlans.cs Normal file
View file

@ -0,0 +1,128 @@
using System;
using System.Collections.Generic;
namespace Lodur
{
/// <summary>Body plans in code, until they live in a store (follow-up lodur-body-plan-cultcache).</summary>
public static class BodyPlans
{
private const float Density = 1000f;
private const float Friction = 0.8f;
/// <summary>The fingers' creation curl at the knuckle, radians: the relaxed resting hand (question hand-rest-curl).</summary>
private const float RestCurl = 0.35f;
private const float Thumb30 = 30f * MathF.PI / 180f; // the thumb's metacarpal, out of the palm plane
private const float HeadRolling = 0.1f; // a bare sphere on the ground rolls on, so the fallen head never settles
/// <summary>
/// A 19-part humanoid: capsule limbs, box pelvis, torso, feet and palms, a sphere head, a thumb capsule and a fingers box per hand,
/// 18 joints: spherical at spine, neck, shoulders, hips, wrists and thumbs, hinges at elbows, knees, ankles and knuckles.
/// Facing +z, left is +x, standing on y = 0 at the creation pose, which is also every joint's zero. Parts and joints are in
/// build order: the trunk, then per side (left, right) the limbs, then per side the hand.
/// </summary>
public static BodyPlan Humanoid()
{
var parts = new List<PartDef>();
var joints = new List<JointDef>();
int Box(string label, Side side, float x, float y, float z, float hx, float hy, float hz) =>
Add(parts, new PartDef(label, side, PartShape.Box, (hx, hy, hz), (x, y, z), Quat.Identity, Density, Friction, 0f));
int Capsule(string label, Side side, float x, float y, float radius, float half) =>
Add(parts, new PartDef(label, side, PartShape.Capsule, (radius, half, 0f), (x, y, 0f), Quat.Identity, Density, Friction, 0f));
var pelvis = Box("Pelvis", Side.Center, 0f, 1.11f, 0f, 0.15f, 0.08f, 0.09f);
var torso = Box("Torso", Side.Center, 0f, 1.41f, 0f, 0.15f, 0.22f, 0.09f);
var head = Add(parts, new PartDef("Head", Side.Center, PartShape.Sphere, (0.11f, 0f, 0f), (0f, 1.74f, 0f), Quat.Identity, Density, Friction, HeadRolling));
var sides = new[] { (Side.Left, 1f), (Side.Right, -1f) };
var upperArm = new int[2]; var lowerArm = new int[2]; var thigh = new int[2]; var shin = new int[2]; var foot = new int[2];
for (var k = 0; k < 2; k++)
{
var (side, sx) = sides[k];
upperArm[k] = Capsule("UpperArm", side, sx * 0.21f, 1.395f, 0.045f, 0.11f);
lowerArm[k] = Capsule("LowerArm", side, sx * 0.21f, 1.10f, 0.04f, 0.10f);
thigh[k] = Capsule("Thigh", side, sx * 0.09f, 0.79f, 0.07f, 0.18f);
shin[k] = Capsule("Shin", side, sx * 0.09f, 0.31f, 0.06f, 0.17f);
foot[k] = Box("Foot", side, sx * 0.09f, 0.04f, 0.05f, 0.05f, 0.04f, 0.12f);
}
// Hands, appended after the base parts. The palm faces -sx with the thumb forward (+z); the thumb capsule
// lies along its metacarpal axis, 30 degrees out of the palm plane; the fingers are created at the rest curl.
var cmcAxis = (0f, -MathF.Cos(Thumb30), MathF.Sin(Thumb30));
var palm = new int[2]; var thumb = new int[2]; var fingers = new int[2];
for (var k = 0; k < 2; k++)
{
var (side, sx) = sides[k];
palm[k] = Box("Palm", side, sx * 0.21f, 0.930f, 0f, 0.014f, 0.045f, 0.040f);
var thumbSpin = Quat.FromAxisAngle(1f, 0f, 0f, -Thumb30);
thumb[k] = Add(parts, new PartDef("Thumb", side, PartShape.Capsule, (0.011f, 0.03f, 0f),
(sx * 0.206f + 0.05f * cmcAxis.Item1, 0.955f + 0.05f * cmcAxis.Item2, 0.03f + 0.05f * cmcAxis.Item3),
thumbSpin, Density, Friction, 0f));
var curl = Quat.FromAxisAngle(0f, 0f, sx, -RestCurl);
fingers[k] = Add(parts, new PartDef("Fingers", side, PartShape.Box, (0.011f, 0.0425f, 0.038f),
(sx * 0.21f - sx * MathF.Sin(RestCurl) * 0.0425f, 0.885f - MathF.Cos(RestCurl) * 0.0425f, 0f),
curl, Density, Friction, 0f));
}
void Joint(string label, Side side, JointKind kind, int parent, int child, float x, float y, float z,
(float, float, float) axis, MuscleGains gains, float lower = 0f, float upper = 0f, float cone = 0f) =>
joints.Add(new JointDef(label, side, kind, parent, child, (x, y, z), axis, lower, upper, cone, gains));
var up = (0f, 1f, 0f);
var across = (1f, 0f, 0f);
// Gains are tuned against measured stand/fall runs at 120 Hz (see the tests), not derived: explicit PD on
// light limbs is stable only while damping * dt stays under the inertia it acts on.
Joint("Spine", Side.Center, JointKind.Spherical, pelvis, torso, 0f, 1.19f, 0f, up, new MuscleGains(500f, 4f, 200f, 8f), -0.4f, 0.4f, 0.5f);
Joint("Neck", Side.Center, JointKind.Spherical, torso, head, 0f, 1.63f, 0f, up, new MuscleGains(30f, 0.8f, 20f, 0.6f), -0.6f, 0.6f, 0.6f);
for (var k = 0; k < 2; k++)
{
var (side, sx) = sides[k];
Joint("Shoulder", side, JointKind.Spherical, torso, upperArm[k], sx * 0.21f, 1.55f, 0f, up, new MuscleGains(20f, 1.5f, 1f, 0.02f), -1f, 1f, 1.5f); // damping carries the hand's mass (hands-gains: 1 and 0.6 before)
Joint("Elbow", side, JointKind.Revolute, upperArm[k], lowerArm[k], sx * 0.21f, 1.24f, 0f, across, new MuscleGains(0f, 0f, 12f, 0.9f), -2.4f, 0f);
Joint("Hip", side, JointKind.Spherical, pelvis, thigh[k], sx * 0.09f, 1.04f, 0f, up, new MuscleGains(600f, 3f, 10f, 0.15f), -0.5f, 0.5f, 1.2f);
Joint("Knee", side, JointKind.Revolute, thigh[k], shin[k], sx * 0.09f, 0.54f, 0f, across, new MuscleGains(0f, 0f, 300f, 8f), 0f, 2.4f);
Joint("Ankle", side, JointKind.Revolute, shin[k], foot[k], sx * 0.09f, 0.08f, 0f, across, new MuscleGains(0f, 0f, 100f, 0.5f), -0.6f, 0.6f);
}
// Hand gains are bounded by each body's own inertia, not the arm subtree's (explicit PD is stable only while
// damping * dt stays under the inertia it acts on; a wrist kd sized for the arm limit-cycles at once), and
// every hand joint keeps passive damping when limp so loose hands settle instead of ringing.
for (var k = 0; k < 2; k++)
{
var (side, sx) = sides[k];
Joint("Wrist", side, JointKind.Spherical, lowerArm[k], palm[k], sx * 0.21f, 0.975f, 0f, up, new MuscleGains(1f, 0.012f, 0.3f, 0.005f, 1f), -1.2f, 1.2f, 1.0f);
Joint("Thumb", side, JointKind.Spherical, palm[k], thumb[k], sx * 0.206f, 0.955f, 0.03f, cmcAxis, new MuscleGains(0.06f, 0.001f, 0f, 0f, 1f), 0f, 0f, 0.7f); // twist locked: a free thumb spins
Joint("Fingers", side, JointKind.Revolute, palm[k], fingers[k], sx * 0.21f, 0.885f, 0f, (0f, 0f, sx), new MuscleGains(0f, 0f, 0.3f, 0.004f, 1f), -1.6f + RestCurl, 0.35f + RestCurl);
}
var senses = new[]
{
new SensePointDef("Hand", Side.Left, palm[0], (0f, 0f, 0f)),
new SensePointDef("Hand", Side.Right, palm[1], (0f, 0f, 0f)),
new SensePointDef("Head", Side.Center, head, (0f, 0f, 0f)),
};
// The airway opens at the face, facing +z, each centred on the head sphere's surface (|offset| 0.110, head r 0.11): fluid never enters
// a body, so a sensor wholly inside the head reads 0 (probe, 512-drop pour: inside 0.0 mL; centred on the surface at the nose up to
// 46.9 mL). Radius 0.025 holds one drop centre (r 1.25 cm) outside the solid; centres 5.05 cm apart, so the spheres do not overlap.
var airway = new[]
{
new AirwayOpeningDef("Mouth", Side.Center, head, (0f, -0.04f, 0.1025f), 0.025f),
new AirwayOpeningDef("Nose", Side.Center, head, (0f, 0.01f, 0.1095f), 0.025f),
};
// Liquid pools behind the openings at the airway's deepest points: the oropharynx 8 cm behind the lips lying on the back, the glottis 7 cm below the mouth upright (placeholders).
// An opening drains by gravity when its lowest rim point lies below the deepest of them: the principle of the recovery position, the mouth dependent so fluid runs out
// (ERC 2021 BLS, Resuscitation 161:98-114), and of postural drainage, the outlet below the reservoir.
var sumps = new[]
{
new AirwaySumpDef("Pharynx", head, (0f, -0.06f, 0.02f)),
new AirwaySumpDef("Glottis", head, (0f, -0.11f, 0.04f)),
};
return new BodyPlan(parts, joints, senses, airway, sumps);
}
private static int Add(List<PartDef> parts, PartDef part)
{
parts.Add(part);
return parts.Count - 1;
}
}
}

675
src/Lodur.Core/Brain.cs Normal file
View file

@ -0,0 +1,675 @@
using System;
using System.Collections.Generic;
namespace Lodur
{
/// <summary>A number the drive carries, as a condition reads it.</summary>
public enum DriveQuantity
{
Pain,
Strain,
Arousal,
Resolve,
/// <summary>1 while the will is broken now (it mends), else 0.</summary>
WillBroken,
/// <summary>How many times the will has broken: the one-way latch, for a goal that must hold after a mend.</summary>
Breaks,
/// <summary>Air hunger, 0..1: the physiology's urge to breathe, carried by the Actor.</summary>
AirHunger,
}
public enum ConditionOp
{
AtLeast,
Below,
}
internal static class DriveReads
{
internal static double Read(in DriveState drive, DriveQuantity quantity) => quantity switch
{
DriveQuantity.Pain => drive.Pain,
DriveQuantity.Strain => drive.Strain,
DriveQuantity.Arousal => drive.Arousal,
DriveQuantity.Resolve => drive.Resolve,
DriveQuantity.Breaks => (double)drive.Breaks,
DriveQuantity.AirHunger => drive.AirHunger,
_ => drive.WillBroken ? 1.0 : 0.0,
};
}
/// <summary>
/// What a consideration reads: a percept's distance from the observer, its salience, the seconds since it was sensed, a drive quantity, or the length of
/// the plan to a want goal's pair.
/// </summary>
public enum ConsiderationInput
{
Distance,
Salience,
SecondsSinceSensed,
Drive,
/// <summary>
/// Only on a goal with a <see cref="GoalSpec.Want"/>: x is the pair's plan length (1..<see cref="Brain.PlanDepth"/>) for a planned pair and
/// <see cref="Brain.PlanDepth"/> + 1 for a direct try. Read by the gate in Brain.Select, never by the raw score.
/// </summary>
PlanSteps,
}
/// <summary>
/// One response curve over an input, in [0, 1]: t = clamp01((x - X0) / (X1 - X0)), y = Y0 + (Y1 - Y0) * t^Exponent, clamped. A goal's pair
/// score is its Priority times every consideration's response. Drive reads <see cref="Quantity"/> off the drive state.
/// </summary>
public readonly record struct Consideration(ConsiderationInput Input, double X0, double X1, double Y0, double Y1, double Exponent = 1.0, DriveQuantity Quantity = default)
{
public double Response(double x)
{
var t = Math.Clamp((x - X0) / (X1 - X0), 0.0, 1.0);
return Math.Clamp(Y0 + (Y1 - Y0) * Math.Pow(t, Exponent), 0.0, 1.0);
}
}
/// <summary>The game's kinds a targeted goal accepts; Lodur never interprets them.</summary>
public sealed record TargetFilter
{
private IReadOnlyList<uint> _kinds = Array.AsReadOnly(Array.Empty<uint>());
/// <summary>Copied when set; read back as a read-only view.</summary>
public IReadOnlyList<uint> Kinds
{
get => _kinds;
init
{
var copy = new uint[value.Count];
for (var i = 0; i < copy.Length; i++)
{
copy[i] = value[i];
}
_kinds = Array.AsReadOnly(copy);
}
}
internal bool Accepts(uint kind)
{
for (var i = 0; i < _kinds.Count; i++)
{
if (_kinds[i] == kind)
{
return true;
}
}
return false;
}
}
/// <summary>The Brain's choice: a goal index and the id of the percept it targets (0: untargeted).</summary>
public readonly record struct Choice(int Goal, ulong Target);
/// <summary>One test of the drive state: the quantity against a threshold.</summary>
public readonly record struct Condition(DriveQuantity Quantity, ConditionOp Op, double Threshold)
{
public bool Holds(in DriveState drive)
{
var v = DriveReads.Read(drive, Quantity);
return Op == ConditionOp.AtLeast ? v >= Threshold : v < Threshold;
}
}
/// <summary>One thing the consumer wants a character to be doing, and when it is eligible to be.</summary>
public sealed record GoalSpec
{
/// <summary>The consumer's name for it; Lodur never reads it.</summary>
public string Id { get; init; } = "";
/// <summary>The eligible goal of the highest priority is wanted.</summary>
public double Priority { get; init; }
/// <summary>How hard the goal pulls, in [0, 1], default 0 (no pull): resolve drain is scaled by (1 - pull) while it is active. It is not a second resolve bar.</summary>
public double Pull { get; init; }
/// <summary>
/// Commitment, soft: until this goal has been active this long (rounded to whole ticks like the latency, counted
/// from the tick it took over), a goal that does not strictly outrank it cannot be decided on; a strictly
/// higher-priority goal preempts at once, after the deliberate latency. 0 (the default) never holds a goal. It keeps
/// a condition hovering at its threshold from making the Brain chatter: the return trip from an entered goal is
/// gated by that goal's own dwell. The dwell holds the decision to leave; a decision already in flight commits.
/// </summary>
public double MinDwellSeconds { get; init; }
/// <summary>
/// The resolve the character has the tick this goal takes over (for the Start goal, at construction), in [0, 1]; null leaves resolve as it is. Rage is what
/// the will breaking leads to, and it resets the will (lodur:ruling:rage-involuntary-onset-then-voluntary).
/// </summary>
public double? EntryResolve { get; init; }
/// <summary>Resolve drained per second to sustain this goal, finite and not negative, default 0; it is not paid during <see cref="InvoluntarySeconds"/> and is scaled by (1 - Pull) like the rest of the drain.</summary>
public double Effort { get; init; }
/// <summary>
/// The gain on the sense channels (not the nociceptive region afferents) while this goal is in force, in [0, 1], default 1; 0 is deaf and blind to the
/// world's stimuli, which keep sounding (lodur:ruling:stress-bar-shows-arousal-calm-silences). Applied like <see cref="EntryResolve"/>: at the tick the goal
/// takes over, and at construction for the Start goal. The sense reads the gain at the start of each tick, so a change reaches
/// <see cref="Perception.Load"/> one tick after the Actor sets it.
/// </summary>
public double SensoryGain { get; init; } = 1.0;
/// <summary>
/// The arousal this goal brings, in [0, 1]; null leaves arousal to the drive. Calm drops it so the stress bar drains
/// (lodur:ruling:stress-bar-shows-arousal-calm-silences). Reached over <see cref="EntrySeconds"/>, then the drive owns arousal again.
/// </summary>
public double? EntryArousal { get; init; }
/// <summary>
/// How long after it takes over the goal's <see cref="EntryArousal"/> and <see cref="SensoryGain"/> are reached, finite and not negative, default 0 (at the
/// takeover tick): a linear ramp from their values at takeover, rounded to whole ticks once like the onset. The aftershock tail
/// of lodur:ruling:flinch-tail-after-stimulus. It does not ramp <see cref="EntryResolve"/>, which stays a snap. For the Start goal the targets apply at construction.
/// </summary>
public double EntrySeconds { get; init; }
/// <summary>
/// How long after it takes over the goal runs without will (rounded to whole ticks once, like the dwell), not negative, default 0 (voluntary from the first tick);
/// +infinity is involuntary throughout. While involuntary the behaviour writes at full weight and pays no Effort;
/// after it the goal is voluntary: sustained by <see cref="DriveState.Will"/> like every other voluntary layer.
/// </summary>
public double InvoluntarySeconds { get; init; }
private Condition[] _when = Array.Empty<Condition>();
private IReadOnlyList<Condition> _whenView = Array.AsReadOnly(Array.Empty<Condition>());
/// <summary>All must hold for the goal to be eligible; none means always eligible. Copied when set; read back as a read-only view.</summary>
public IReadOnlyList<Condition> When
{
get => _whenView;
init
{
_when = new Condition[value.Count];
for (var c = 0; c < _when.Length; c++)
{
_when[c] = value[c];
}
_whenView = Array.AsReadOnly(_when);
}
}
/// <summary>The kind of thing this goal targets; null is an untargeted goal. Whether a target exists is decided in <see cref="Brain.Select"/>, not by Eligible.</summary>
public TargetFilter? Target { get; init; }
/// <summary>
/// A fact the goal wants to make true, about himself (<see cref="FactSubject.Self"/>, never bit 63) or about the goal's target (<see cref="FactSubject.This"/>, which needs a
/// <see cref="Target"/>); null is no want. A want pair whose want already holds is not offered; one that does not is planned to <see cref="Brain.PlanDepth"/> steps and scored
/// by the plan's length through <see cref="ConsiderationInput.PlanSteps"/>, or tried direct at <see cref="Brain.DirectDiscount"/> when no plan is found. A want goal's Priority
/// must not be negative. Only an Actor built with verbs selects a Brain that has wants.
/// </summary>
public Fact? Want { get; init; }
private Consideration[] _considerations = Array.Empty<Consideration>();
private IReadOnlyList<Consideration> _considerationsView = Array.AsReadOnly(Array.Empty<Consideration>());
/// <summary>Multiplied with Priority to score each (goal, percept) pair. Copied when set; read back as a read-only view.</summary>
public IReadOnlyList<Consideration> Considerations
{
get => _considerationsView;
init
{
_considerations = new Consideration[value.Count];
for (var c = 0; c < _considerations.Length; c++)
{
_considerations[c] = value[c];
}
_considerationsView = Array.AsReadOnly(_considerations);
}
}
/// <summary>Priority times every consideration but <see cref="ConsiderationInput.PlanSteps"/>: the raw score, before the plan's length is known.</summary>
internal double Score(in DriveState drive, in Percept percept, float ox, float oy, float oz)
{
var score = Priority;
for (var c = 0; c < _considerations.Length; c++)
{
var k = _considerations[c];
double x;
switch (k.Input)
{
case ConsiderationInput.PlanSteps:
continue;
case ConsiderationInput.Drive:
x = DriveReads.Read(drive, k.Quantity);
break;
case ConsiderationInput.Distance:
{
double dx = percept.X - ox, dy = percept.Y - oy, dz = percept.Z - oz;
x = Math.Sqrt(dx * dx + dy * dy + dz * dz);
break;
}
case ConsiderationInput.Salience:
x = percept.Salience;
break;
default:
x = percept.SecondsSinceSensed;
break;
}
score *= k.Response(x);
}
return score;
}
/// <summary>The product of the <see cref="ConsiderationInput.PlanSteps"/> responses at plan length <paramref name="x"/>; 1 with none.</summary>
internal double PlanFactor(int x)
{
var factor = 1.0;
for (var c = 0; c < _considerations.Length; c++)
{
if (_considerations[c].Input == ConsiderationInput.PlanSteps)
{
factor *= _considerations[c].Response(x);
}
}
return factor;
}
internal bool Eligible(in DriveState drive)
{
for (var c = 0; c < _when.Length; c++)
{
if (!_when[c].Holds(drive))
{
return false;
}
}
return true;
}
public PoseBehaviour Behaviour { get; init; } = new PoseBehaviour();
}
/// <summary>
/// Layer 4: the consumer's goals, selected by conditions over the drive state. Lodur has no flip rule of its
/// own; every rule is this data. Data only: the Actor commits the choice, after the deliberate latency.
/// </summary>
public sealed record Brain
{
private IReadOnlyList<GoalSpec> _goals = Array.Empty<GoalSpec>();
/// <summary>The goals, copied when set: later changes to the caller's list or arrays do not reach a Brain, and the getter is a read-only view.</summary>
public IReadOnlyList<GoalSpec> Goals
{
get => _goals;
init
{
var copy = new GoalSpec[value.Count];
for (var i = 0; i < copy.Length; i++)
{
copy[i] = value[i];
}
_goals = Array.AsReadOnly(copy);
}
}
/// <summary>The index of the goal a character begins in.</summary>
public int Start { get; init; }
/// <summary>How long a chosen switch takes to commit; a decision in flight commits even if its condition lapses.</summary>
public double DeliberateLatencySeconds { get; init; } = 0.1;
/// <summary>How much the current (goal, target) pair's score is multiplied by, finite and at least 1; 1 is no commitment.</summary>
public double TargetCommitment { get; init; } = 1.0;
/// <summary>The planner's depth, the intelligence stat's base: the most steps a want goal's plan may have, 0..8, default 0 (no plans; every want pair is tried direct).</summary>
public int PlanDepth { get; init; }
/// <summary>The factor on a pair's score when its goal's want has no plan within <see cref="PlanDepth"/> (or the think budget ran out): he goes at the target directly, in [0, 1], default 0.5 (a placeholder).</summary>
public double DirectDiscount { get; init; } = 0.5;
/// <summary>How long a direct try (<see cref="Actor.PlanLength"/> -1) of one (goal, target) pair may last before the Actor gives it up: it bars the pair's direct try, reports <see cref="TickEvents.Frustrated"/> and decides again past the goal's dwell. Not NaN, not negative; +infinity never frustrates. Default 5 (a placeholder; ruling bds-unplannable-tries-direct).</summary>
public double FrustrationSeconds { get; init; } = 5.0;
/// <summary>How long a bar on a direct try lasts if its target is not forgotten first: the pair is tried direct again after it. Positive, not NaN; +infinity never lifts by time. Default 30 (a placeholder).</summary>
public double RetrySeconds { get; init; } = 30.0;
/// <summary>The most groundings one Select may regress across all its plans, at least 1, default 4096: one budget per decision, spent by deepening across the want pairs, short plans first (lodur:question:bds-think-budget-per-decision).</summary>
public int ThinkBudget { get; init; } = Planner.NodeBudget;
/// <summary>How close a thing must be to be in reach, in meters, finite and above 0, default 0.6 (an arm's length, 0.575 m, as a placeholder).</summary>
public double ReachMeters { get; init; } = 0.6;
/// <summary>True when any goal has a want: such a Brain is selected through an Actor's Deliberation, not the public Select.</summary>
internal bool HasWants
{
get
{
for (var i = 0; i < Goals.Count; i++)
{
if (Goals[i].Want is not null)
{
return true;
}
}
return false;
}
}
/// <summary>
/// The pair wanted now. Each eligible untargeted goal is one pair (goal, 0) scored Priority times its Drive considerations; each eligible
/// targeted goal is one pair per percept slot with a non-zero Id and a Kind it accepts, scored Priority times every consideration. The pair
/// equal to <paramref name="current"/> is multiplied by <see cref="TargetCommitment"/>. The highest score wins; ties go to the current pair,
/// then the lowest goal index, then the lowest slot. With no pair at all the goal in force stays and lets go of its target: (current.Goal, 0),
/// so a forgotten target is not held (the Actor commits it a latency later and the orient layers rest). A percept Id is only compared, never decoded.
/// Throws for a Brain with a want: the planner's gate needs an Actor's verbs, so the Actor selects it.
/// </summary>
public Choice Select(in DriveState drive, Perception perception, float observerX, float observerY, float observerZ, Choice current)
{
if (HasWants)
{
throw new InvalidOperationException("A Brain with a want is selected by its Actor, which holds the verbs the planner needs.");
}
return Select(drive, perception, observerX, observerY, observerZ, current, null);
}
/// <summary>
/// <see cref="Select(in DriveState, Perception, float, float, float, Choice)"/> with the want gate. Pass 1 scores every pair raw (commitment applied) and offers
/// the untargeted-by-want pairs; a want pair whose want holds is not offered, the rest wait in the Deliberation. Pass 2 deepens across the waiting pairs: round k takes them by
/// bound (raw times the best factor any plan longer than k - 1 steps, or going direct, could earn), asks each for a plan of exactly k steps with what is left of <see cref="ThinkBudget"/>,
/// and offers raw times the plan-length factor for one found; a pair with none of k steps waits for round k + 1, and one with no plan within PlanDepth (or the budget gone) is offered
/// at raw times the factor at PlanDepth + 1 times <see cref="DirectDiscount"/>, unless the Deliberation holds a bar on that pair's direct try (it is then not offered; it is offered when it plans). A round ends when no remaining bound can beat or tie-win the best, so short plans are found
/// first and one pair's dead end cannot starve the rest.
/// </summary>
internal Choice Select(in DriveState drive, Perception perception, float ox, float oy, float oz, Choice current, Deliberation? d)
{
var best = default(Pick);
var slots = perception.PerceptCount;
d?.Begin(perception, ox, oy, oz);
for (var i = 0; i < Goals.Count; i++)
{
var goal = Goals[i];
if (!goal.Eligible(drive))
{
continue;
}
if (goal.Target is null)
{
Consider(i, goal, -1, 0UL, goal.Score(drive, default, ox, oy, oz), current, d, ref best);
continue;
}
for (var s = 0; s < slots; s++)
{
var percept = perception.Percept(s);
if (percept.Id == 0UL || !goal.Target.Accepts(percept.Kind))
{
continue;
}
Consider(i, goal, s, percept.Id, goal.Score(drive, percept, ox, oy, oz), current, d, ref best);
}
}
if (d is not null)
{
for (var k = PlanDepth == 0 ? 0 : 1; ; k++)
{
while (d.TryPop(out var pair))
{
if (best.Found && pair.Bound < best.Score)
{
d.ClearRound();
break;
}
var goal = Goals[pair.Goal];
var length = d.PlanAt(pair.Goal, goal.Want!.Value, pair.Slot, k);
if (length == 0)
{
pair.Bound = pair.Raw * d.BoundFactor(pair.Goal, k);
d.Defer(pair);
continue;
}
if (length < 0 && d.Barred(pair.Goal, pair.Target))
{
continue; // a futile direct try is barred: neither offered nor deferred
}
var factor = length > 0 ? goal.PlanFactor(length) : goal.PlanFactor(PlanDepth + 1) * DirectDiscount;
if (Offer(pair.Goal, pair.Slot, pair.Target, pair.Raw * factor, pair.Current, ref best))
{
d.KeepBest(pair.Goal, length, goal.Want!.Value.Subject == FactSubject.Self);
}
}
if (!d.NextRound())
{
break;
}
}
}
return best.Found ? Pair(best.Goal, best.Target) : Pair(current.Goal, 0UL);
}
private static Choice Pair(int goal, ulong target) => new Choice(goal, target);
// One scored pair: offered now, or (a want pair) held back for the planner's gate. The commitment multiplies the raw score here, so pass 2 orders by the committed raw.
private void Consider(int goal, GoalSpec spec, int slot, ulong target, double raw, Choice current, Deliberation? d, ref Pick best)
{
var isCurrent = goal == current.Goal && target == current.Target;
if (isCurrent)
{
raw *= TargetCommitment;
}
if (spec.Want is not { } want)
{
if (Offer(goal, slot, target, raw, isCurrent, ref best))
{
d?.KeepBest(goal, 0, false);
}
}
else if (!d!.Holds(goal, want, slot))
{
d.Add(goal, slot, target, raw, isCurrent);
}
}
// Ties resolve by key (current, then lowest goal, then lowest slot), not by call order: pass 2 offers out of index order. True when the offer became the best, so its plan is kept.
private static bool Offer(int goal, int slot, ulong target, double score, bool isCurrent, ref Pick best)
{
if (!best.Found || score > best.Score
|| (score == best.Score && (isCurrent != best.IsCurrent ? isCurrent : goal < best.Goal || (goal == best.Goal && slot < best.Slot))))
{
best = new Pick { Goal = goal, Slot = slot, Target = target, Score = score, IsCurrent = isCurrent, Found = true };
return true;
}
return false;
}
private struct Pick
{
public int Goal;
public int Slot;
public ulong Target;
public double Score;
public bool IsCurrent;
public bool Found;
}
internal void Validate()
{
if (Goals.Count == 0)
{
throw new ArgumentException("A brain needs at least one goal.");
}
if (Start < 0 || Start >= Goals.Count)
{
throw new ArgumentException("Start is not a goal index.");
}
if (!(DeliberateLatencySeconds >= 0.0 && double.IsFinite(DeliberateLatencySeconds)))
{
throw new ArgumentException("DeliberateLatencySeconds must be finite and not negative.");
}
if (!(double.IsFinite(TargetCommitment) && TargetCommitment >= 1.0))
{
throw new ArgumentException("TargetCommitment must be finite and at least 1.");
}
if (PlanDepth < 0 || PlanDepth > 8)
{
throw new ArgumentException("PlanDepth must be in 0..8.");
}
if (!(DirectDiscount >= 0.0 && DirectDiscount <= 1.0))
{
throw new ArgumentException("DirectDiscount must be in [0, 1].");
}
if (!(FrustrationSeconds >= 0.0))
{
throw new ArgumentException("FrustrationSeconds must not be NaN or negative.");
}
if (!(RetrySeconds > 0.0))
{
throw new ArgumentException("RetrySeconds must be positive (not NaN, zero or negative): a bar that lifts the next tick is no bar.");
}
if (ThinkBudget < 1)
{
throw new ArgumentException("ThinkBudget must be at least 1.");
}
if (!(double.IsFinite(ReachMeters) && ReachMeters > 0.0))
{
throw new ArgumentException("ReachMeters must be finite and above 0.");
}
var muscles = -1;
foreach (var goal in Goals)
{
if (goal.Target is { } filter && filter.Kinds.Count == 0)
{
throw new ArgumentException($"Goal {goal.Id}: a Target needs at least one kind.");
}
if ((goal.Target != null || goal.Considerations.Count > 0) && !(goal.Priority >= 0.0))
{
throw new ArgumentException($"Goal {goal.Id}: Priority must not be negative on a goal with a Target or considerations.");
}
if (goal.Want is { } want)
{
if (want.Subject != FactSubject.Self && want.Subject != FactSubject.This)
{
throw new ArgumentException($"Goal {goal.Id}: a Want is about himself or the target.");
}
if ((uint)want.Bit > 63u || (want.Subject == FactSubject.Self && want.Bit == 63))
{
throw new ArgumentException($"Goal {goal.Id}: a Want is on a bit in 0..63, and bit 63 is Lodur's reach, which the actor has none of.");
}
if (want.Subject == FactSubject.This && goal.Target is null)
{
throw new ArgumentException($"Goal {goal.Id}: a Want about the target needs a Target.");
}
if (!(goal.Priority >= 0.0))
{
throw new ArgumentException($"Goal {goal.Id}: Priority must not be negative on a goal with a Want.");
}
}
foreach (var k in goal.Considerations)
{
if (!double.IsFinite(k.X0) || !double.IsFinite(k.X1) || k.X1 == k.X0
|| !(k.Y0 >= 0.0 && k.Y0 <= 1.0) || !(k.Y1 >= 0.0 && k.Y1 <= 1.0)
|| !(double.IsFinite(k.Exponent) && k.Exponent > 0.0))
{
throw new ArgumentException($"Goal {goal.Id}: a consideration needs finite X0 != X1, Y0 and Y1 in [0, 1], and Exponent > 0.");
}
if (k.Input == ConsiderationInput.PlanSteps)
{
if (goal.Want is null)
{
throw new ArgumentException($"Goal {goal.Id}: a PlanSteps consideration needs a goal with a Want.");
}
}
else if (k.Input != ConsiderationInput.Drive && goal.Target is null)
{
throw new ArgumentException($"Goal {goal.Id}: Distance, Salience and SecondsSinceSensed considerations need a targeted goal.");
}
}
if (!double.IsFinite(goal.Priority) || !(goal.Pull >= 0.0 && goal.Pull <= 1.0))
{
throw new ArgumentException($"Goal {goal.Id}: priority must be finite and pull in [0, 1].");
}
if (!(goal.MinDwellSeconds >= 0.0 && double.IsFinite(goal.MinDwellSeconds)))
{
throw new ArgumentException($"Goal {goal.Id}: MinDwellSeconds must be finite (not infinite) and not negative.");
}
if (goal.EntryResolve is double entry && !(entry >= 0.0 && entry <= 1.0))
{
throw new ArgumentException($"Goal {goal.Id}: EntryResolve must be in [0, 1].");
}
if (!(goal.SensoryGain >= 0.0 && goal.SensoryGain <= 1.0))
{
throw new ArgumentException($"Goal {goal.Id}: SensoryGain must be in [0, 1].");
}
if (goal.EntryArousal is double entryArousal && !(entryArousal >= 0.0 && entryArousal <= 1.0))
{
throw new ArgumentException($"Goal {goal.Id}: EntryArousal must be in [0, 1].");
}
if (!(goal.EntrySeconds >= 0.0 && double.IsFinite(goal.EntrySeconds)))
{
throw new ArgumentException($"Goal {goal.Id}: EntrySeconds must be finite and not negative.");
}
if (!(goal.Effort >= 0.0 && double.IsFinite(goal.Effort)))
{
throw new ArgumentException($"Goal {goal.Id}: Effort must be finite and not negative.");
}
if (!(goal.InvoluntarySeconds >= 0.0))
{
throw new ArgumentException($"Goal {goal.Id}: InvoluntarySeconds must not be negative or NaN (infinity is allowed).");
}
foreach (var c in goal.When)
{
if (!double.IsFinite(c.Threshold))
{
throw new ArgumentException($"Goal {goal.Id}: a condition threshold is not finite.");
}
}
goal.Behaviour.Validate(goal.Id);
if (muscles >= 0 && goal.Behaviour.MuscleCount != muscles)
{
throw new ArgumentException($"Goal {goal.Id}: every behaviour needs the same muscle count.");
}
muscles = goal.Behaviour.MuscleCount;
}
}
}
}

View file

@ -0,0 +1,459 @@
using System;
using System.Collections.Generic;
namespace Lodur
{
/// <summary>A want pair held back for the planner's gate: its goal, percept slot (-1 for an untargeted goal), the percept's id, its raw score (commitment applied), the most it can still score (raw times the bound factor of the depth searched so far) and whether it is the current pair.</summary>
internal struct WantPair
{
public int Goal;
public int Slot;
public ulong Target;
public double Raw;
public double Bound;
public bool Current;
}
/// <summary>
/// What one Actor thinks with while its Brain selects: the planner, the want pairs waiting for the gate (a max-heap by bound, ties current, lowest goal, lowest slot),
/// the pairs deferred to the next round of deepening, the bound table, and the think budget spent so far in this Select. Pass 2 deepens across pairs (Korf's iterative
/// deepening, anytime): round k asks every live pair for a plan of exactly k steps, so short plans are found first and no pair starves the rest.
/// It also carries the plan of the decision: the plan of the pair best so far in this Select and the plan of the decision in force,
/// each made by the Select that chose (or re-chose) the pair and carried until the next one; Select never reads them. The best plan is also the plan of a pending decision: the Actor runs no Select
/// between a decision becoming pending and its commit, so nothing writes the best plan in that window (that rule is load-bearing here). Owned by one Actor; allocates only in its constructor. Not thread-safe.
/// </summary>
internal sealed class Deliberation
{
private const int Unplanned = int.MinValue;
private readonly Planner _planner;
private readonly Brain _brain;
private readonly PlanStep[] _plan;
private readonly WantPair[] _heap;
private readonly sbyte[] _selfHeld; // per goal this Select: -1 not asked, 0 the Self want does not hold, 1 it holds
private readonly int[] _selfLength; // per goal this Select: the Self want's plan length, -1 direct, Unplanned not asked
private Perception _perception;
private float _ox;
private float _oy;
private float _oz;
private int _count;
private int _spent;
private readonly int _depth;
private readonly double[] _bound; // per goal g and searched depth k in 0..PlanDepth: the most a pair with no plan of k or fewer steps can score, as a factor on raw
private readonly WantPair[] _next; // the pairs with no plan of this round's k steps, waiting for round k + 1
private int _nextCount;
private int _bestLength;
private int _inForceLength;
private readonly int[] _selfDepth; // per goal this Select: the depth a Self want has been searched to
private bool _gone; // this Select's budget is gone: every later pair goes direct
private readonly PlanStep[] _selfPlan; // per goal this Select: the plan found for its Self want, shared by its pairs
private readonly int _width; // the steps a plan buffer holds
private PlanStep[] _best; // the plan of the pair best so far in this Select, BestLength steps
private PlanStep[] _inForce; // the plan of the decision in force
private readonly ulong[] _barTarget; // per goal: the barred target's id (0 for a Self want's untargeted goal)
private readonly long[] _barUntil; // per goal: the tick the bar expires at; -1 is no bar
internal Deliberation(Brain brain, IReadOnlyList<Verb> verbs, int capacity)
{
_brain = brain;
_planner = new Planner(verbs, capacity, brain.PlanDepth, brain.ReachMeters);
_plan = new PlanStep[Math.Max(1, brain.PlanDepth)];
_heap = new WantPair[brain.Goals.Count * capacity];
_selfHeld = new sbyte[brain.Goals.Count];
_selfLength = new int[brain.Goals.Count];
_perception = null!;
_depth = brain.PlanDepth;
_width = Math.Max(1, _depth);
_best = new PlanStep[_width];
_inForce = new PlanStep[_width];
_selfPlan = new PlanStep[brain.Goals.Count * _width];
_next = new WantPair[_heap.Length];
_selfDepth = new int[brain.Goals.Count];
_barTarget = new ulong[brain.Goals.Count];
_barUntil = new long[brain.Goals.Count];
Array.Fill(_barUntil, -1L);
_bound = new double[brain.Goals.Count * (_depth + 1)];
for (var g = 0; g < brain.Goals.Count; g++)
{
var direct = brain.Goals[g].PlanFactor(_depth + 1) * brain.DirectDiscount;
for (var k = 0; k <= _depth; k++)
{
var b = direct;
for (var x = k + 1; x <= _depth; x++)
{
b = Math.Max(b, brain.Goals[g].PlanFactor(x));
}
_bound[g * (_depth + 1) + k] = b;
}
}
}
/// <summary>The most a pair of <paramref name="goal"/> with no plan of <paramref name="k"/> or fewer steps can score, as a factor on its raw score. No monotonicity of the plan-length factor is assumed.</summary>
internal double BoundFactor(int goal, int k) => _bound[goal * (_depth + 1) + k];
/// <summary>The actor's own facts this tick, supplied by the game (bit 63 never set).</summary>
internal ulong SelfFacts { get; set; }
/// <summary>The groundings the current Select has paid out of <see cref="Brain.ThinkBudget"/>.</summary>
internal int Spent => _spent;
/// <summary>The plan of the decision in force, in execution order: step i for i below <see cref="InForceLength"/>.</summary>
internal PlanStep Step(int i) => _inForce[i];
/// <summary>The length of the plan of the decision in force: n steps, -1 to go direct, 0 when its want holds, it has none, or its target left memory.</summary>
internal int InForceLength => _inForceLength;
/// <summary>Bars the direct try of the pair (<paramref name="goal"/>, <paramref name="target"/>) until <paramref name="untilTick"/>. One bar per goal: a new one replaces it.</summary>
internal void Bar(int goal, ulong target, long untilTick)
{
_barTarget[goal] = target;
_barUntil[goal] = untilTick;
}
/// <summary>Whether the direct try of the pair is barred: an equal bar, live (<see cref="Lift"/> runs each tick before the decision).</summary>
internal bool Barred(int goal, ulong target) => _barUntil[goal] >= 0 && _barTarget[goal] == target;
/// <summary>
/// Clears every bar whose time has come or whose target is no longer in memory. A changed fact does not lift a bar (ruling frustration-lifts-without-fact-changes):
/// a pair that becomes plannable is offered through it by Select.
/// </summary>
internal void Lift(Perception perception, long tick)
{
var ids = perception.PerceptIds;
for (var g = 0; g < _barUntil.Length; g++)
{
if (_barUntil[g] < 0)
{
continue;
}
var lift = tick >= _barUntil[g];
if (!lift && _barTarget[g] != 0UL)
{
lift = true;
for (var s = 0; s < ids.Length; s++)
{
if (ids[s] == _barTarget[g])
{
lift = false;
break;
}
}
}
if (lift)
{
_barUntil[g] = -1;
_barTarget[g] = 0UL;
}
}
}
/// <summary>Starts a Select: nothing waits, nothing is spent, nothing is known of the Self wants.</summary>
internal void Begin(Perception perception, float ox, float oy, float oz)
{
_perception = perception;
_ox = ox;
_oy = oy;
_oz = oz;
_count = 0;
_spent = 0;
_nextCount = 0;
_gone = false;
_bestLength = 0;
for (var g = 0; g < _selfHeld.Length; g++)
{
_selfHeld[g] = -1;
_selfLength[g] = Unplanned;
_selfDepth[g] = 0;
}
}
/// <summary>Whether the want already holds for the pair on <paramref name="slot"/> (-1 for an untargeted goal): a depth-0 plan, which spends no budget. A Self want is asked once per goal.</summary>
internal bool Holds(int goal, Fact want, int slot)
{
if (want.Subject != FactSubject.Self)
{
return AskHolds(want, slot);
}
if (_selfHeld[goal] < 0)
{
_selfHeld[goal] = (sbyte)(AskHolds(want, 0) ? 1 : 0);
}
return _selfHeld[goal] == 1;
}
private bool AskHolds(Fact want, int slot) =>
_planner.Plan(_perception, SelfFacts, _ox, _oy, _oz, slot, want, 0, _plan, 1) == 0;
/// <summary>
/// Round <paramref name="k"/> of the deepening for a want pair that does not hold: n = k when the pair has a plan of exactly k steps (none shorter was found in an earlier round),
/// 0 when it has none of k steps and k is below PlanDepth (defer to round k + 1), -1 to go at it direct (no plan within PlanDepth, PlanDepth is 0, or the budget is gone, and then
/// it stays gone for the rest of the Select). A Self want is searched once per goal and depth and shared by its pairs. Spends from the Select's one budget.
/// </summary>
internal int PlanAt(int goal, Fact want, int slot, int k)
{
if (_depth == 0)
{
return -1;
}
var self = want.Subject == FactSubject.Self;
if (self && _selfLength[goal] != Unplanned)
{
return _selfLength[goal]; // planned once for all its pairs, and shared at no cost even when the budget is gone
}
if (_gone)
{
return -1;
}
if (self && _selfDepth[goal] >= k)
{
return k == _depth ? -1 : 0;
}
var left = _brain.ThinkBudget - _spent;
if (left < 1)
{
_gone = true;
return -1;
}
var n = _planner.Plan(_perception, SelfFacts, _ox, _oy, _oz, self ? 0 : slot, want, k, _plan, left, k);
_spent = Math.Min(_brain.ThinkBudget, _spent + _planner.LastNodes);
int result;
if (n > 0)
{
result = n;
if (self)
{
Array.Copy(_plan, 0, _selfPlan, goal * _width, n);
}
}
else if (_planner.LastExhausted)
{
_gone = true;
result = -1;
}
else
{
result = k == _depth ? -1 : 0;
}
if (self)
{
_selfDepth[goal] = k;
if (result != 0)
{
_selfLength[goal] = result;
}
}
return result;
}
/// <summary>Holds a pair with no plan of this round's steps for the next round.</summary>
internal void Defer(in WantPair pair) => _next[_nextCount++] = pair;
/// <summary>Drops every pair still waiting in this round: none of them can beat the best found.</summary>
internal void ClearRound() => _count = 0;
/// <summary>Starts the next round with the deferred pairs; false when nothing was deferred.</summary>
internal bool NextRound()
{
if (_nextCount == 0)
{
return false;
}
_count = 0;
for (var i = 0; i < _nextCount; i++)
{
Push(_next[i]);
}
_nextCount = 0;
return true;
}
/// <summary>The pair just offered is the best so far in this Select: keep its plan (<paramref name="length"/> steps, 0 for a pair without a want, -1 for a direct try).</summary>
internal void KeepBest(int goal, int length, bool self)
{
_bestLength = length;
if (length > 0)
{
Array.Copy(self ? _selfPlan : _plan, self ? goal * _width : 0, _best, 0, length);
}
}
/// <summary>The Select's best pair takes force, as the re-chosen pair in force or the pending decision at its commit: its plan is the plan in force.</summary>
internal void Refresh()
{
(_inForce, _best) = (_best, _inForce);
_inForceLength = _bestLength;
}
/// <summary>
/// The Select was refused (inside the goal's dwell) and the pair in force stays: its plan is made again with what is left of this Select's budget, to PlanDepth.
/// False when none is left or the search exhausts it; the plan is carried, and checked.
/// </summary>
internal bool ReplanInForce(Perception perception, float ox, float oy, float oz, Fact want, ulong target)
{
var left = _brain.ThinkBudget - _spent;
if (left < 1)
{
return false;
}
var slot = SlotOf(perception, want, target);
if (slot < 0)
{
_inForceLength = 0;
return true;
}
var n = _planner.Plan(perception, SelfFacts, ox, oy, oz, slot, want, _depth, _plan, left);
_spent = Math.Min(_brain.ThinkBudget, _spent + _planner.LastNodes);
if (_planner.LastExhausted)
{
return false; // a sliver of budget proves nothing: the plan in force is carried, and checked
}
if (n > 0)
{
Array.Copy(_plan, 0, _inForce, 0, n);
}
_inForceLength = n;
return true;
}
/// <summary>
/// A tick that wrote no plan: the plan in force is checked, never searched. It becomes 0 when the want holds now or its target left memory, and -1 (go direct) when one of its
/// steps' This or Tool left memory. Lodur has no step-execution signal, so a step done shows as a shorter plan at the next Select that re-chooses the pair.
/// </summary>
internal void CheckCarried(Perception perception, float ox, float oy, float oz, Fact want, ulong target)
{
if (_inForceLength == 0)
{
return;
}
var slot = SlotOf(perception, want, target);
if (slot < 0 || _planner.Plan(perception, SelfFacts, ox, oy, oz, slot, want, 0, _inForce, 1) == 0)
{
_inForceLength = 0;
return;
}
var ids = perception.PerceptIds;
for (var i = 0; i < _inForceLength; i++)
{
if (!Has(ids, _inForce[i].This) || (_inForce[i].Tool != 0UL && !Has(ids, _inForce[i].Tool)))
{
_inForceLength = -1;
return;
}
}
}
// The planner's target slot for a want: 0 for a Self want, else the slot holding the target's id, -1 when the target is 0 or not in memory.
private static int SlotOf(Perception perception, Fact want, ulong target)
{
if (want.Subject != FactSubject.This)
{
return 0;
}
var ids = perception.PerceptIds;
for (var s = 0; s < ids.Length; s++)
{
if (target != 0UL && ids[s] == target)
{
return s;
}
}
return -1;
}
private static bool Has(ReadOnlySpan<ulong> ids, ulong id)
{
for (var s = 0; s < ids.Length; s++)
{
if (ids[s] == id)
{
return true;
}
}
return false;
}
internal void Add(int goal, int slot, ulong target, double raw, bool current)
{
Push(new WantPair { Goal = goal, Slot = slot, Target = target, Raw = raw, Bound = raw * BoundFactor(goal, 0), Current = current });
}
private void Push(in WantPair pair)
{
var i = _count++;
_heap[i] = pair;
while (i > 0)
{
var parent = (i - 1) >> 1;
if (!Before(_heap[i], _heap[parent]))
{
break;
}
(_heap[i], _heap[parent]) = (_heap[parent], _heap[i]);
i = parent;
}
}
/// <summary>The waiting want pair with the highest bound (ties current, lowest goal, lowest slot).</summary>
internal bool TryPop(out WantPair pair)
{
if (_count == 0)
{
pair = default;
return false;
}
pair = _heap[0];
_heap[0] = _heap[--_count];
var i = 0;
while (true)
{
var l = 2 * i + 1;
if (l >= _count)
{
break;
}
var c = l + 1 < _count && Before(_heap[l + 1], _heap[l]) ? l + 1 : l;
if (!Before(_heap[c], _heap[i]))
{
break;
}
(_heap[i], _heap[c]) = (_heap[c], _heap[i]);
i = c;
}
return true;
}
private static bool Before(in WantPair a, in WantPair b) =>
a.Bound != b.Bound ? a.Bound > b.Bound
: a.Current != b.Current ? a.Current
: a.Goal != b.Goal ? a.Goal < b.Goal
: a.Slot < b.Slot;
}
}

View file

@ -0,0 +1,149 @@
using System;
namespace Lodur
{
/// <summary>The drive's tunables: how pain, strain and arousal accumulate, and how they drain the will.</summary>
public sealed record DriveParameters
{
public double PainRise { get; init; } = 1.0;
public double PainDecay { get; init; } = 0.05;
public double StrainRecover { get; init; } = 0.1;
public double ResolveDrainPain { get; init; } = 0.012;
public double ResolveDrainStrain { get; init; } = 0.05;
public double ResolveRecovery { get; init; } = 0.02;
public double ResolveRecoversBelowPain { get; init; } = 0.1;
/// <summary>Per-character multiplier on resolve drain (the consumer draws its trait spread).</summary>
public double DrainTrait { get; init; } = 1.0;
/// <summary>How fast arousal rises toward 1 under full sensory load.</summary>
public double ArousalRise { get; init; } = 0.5;
/// <summary>How fast arousal falls back once the load stops.</summary>
public double ArousalDecay { get; init; } = 0.1;
/// <summary>Resolve drained per second at full arousal, before the active goal's pull and the drain trait scale it.</summary>
public double ResolveDrainArousal { get; init; } = 0.1;
/// <summary>Resolve recovers only while arousal is below this, as well as pain being low.</summary>
public double ResolveRecoversBelowArousal { get; init; } = 0.1;
/// <summary>Once the will has broken it mends when resolve climbs back to this, in (0, 1]; it can then break again.</summary>
public double WillMendsAt { get; init; } = 0.25;
/// <summary>
/// How a voluntary layer's strength follows the will: the weight is Will^WillCurve, finite and above 0. Below 1 the layer
/// holds most of its strength until the will is nearly gone; above 1 it fades as soon as the will drops.
/// </summary>
public double WillCurve { get; init; } = 0.25;
/// <summary>Refuses a value the drive cannot run on, at construction rather than as a NaN several ticks in: every rate, trait and threshold is finite and not negative; WillMendsAt is in (0, 1]; WillCurve is above 0.</summary>
internal void Validate()
{
var rates = new[]
{
(PainRise, nameof(PainRise)), (PainDecay, nameof(PainDecay)), (StrainRecover, nameof(StrainRecover)),
(ResolveDrainPain, nameof(ResolveDrainPain)), (ResolveDrainStrain, nameof(ResolveDrainStrain)),
(ResolveRecovery, nameof(ResolveRecovery)), (ResolveRecoversBelowPain, nameof(ResolveRecoversBelowPain)),
(DrainTrait, nameof(DrainTrait)), (ArousalRise, nameof(ArousalRise)), (ArousalDecay, nameof(ArousalDecay)),
(ResolveDrainArousal, nameof(ResolveDrainArousal)), (ResolveRecoversBelowArousal, nameof(ResolveRecoversBelowArousal)),
};
foreach (var (value, name) in rates)
{
if (!(value >= 0.0 && double.IsFinite(value)))
{
throw new ArgumentException($"{name} must be finite and not negative.");
}
}
if (!(WillMendsAt > 0.0 && WillMendsAt <= 1.0))
{
throw new ArgumentException("WillMendsAt must be in (0, 1].");
}
if (!(WillCurve > 0.0 && double.IsFinite(WillCurve)))
{
throw new ArgumentException("WillCurve must be finite and above 0.");
}
}
}
/// <summary>
/// Layer 3: per-character state that evolves every tick. Pain rises with afferent input, strain with the
/// reflex held down, arousal with sensory load; resolve drains under all three and recovers when pain and
/// arousal are both low. Resolve reaching zero breaks the will (counted in <see cref="Breaks"/>); the broken will
/// mends when resolve climbs back to <see cref="DriveParameters.WillMendsAt"/> and can break again. Resolve keeps
/// evolving through a break. Only the owning <see cref="Actor"/> steps it.
/// </summary>
public struct DriveState
{
public double Pain { get; private set; }
public double Strain { get; private set; }
/// <summary>Sensory load carried over time, 0..1; it rises under load and decays when quiet.</summary>
public double Arousal { get; internal set; }
public double Resolve { get; private set; }
/// <summary>True from a break until the will mends: broken now, not "has ever broken" (see <see cref="Breaks"/>).</summary>
public bool WillBroken { get; private set; }
/// <summary>How many times the will has broken.</summary>
public int Breaks { get; private set; }
/// <summary>The fraction of resolve that attention lets through, 0..1. A slot, 1 until lodur-startle-attention fills it.</summary>
public double Attention { get; internal set; }
/// <summary>The ceiling on the will that wakefulness sets, 0..1; written each tick by the Actor from its <see cref="Physiology"/> (the only writer), 1 for an Actor with no physiology.</summary>
public double Consciousness { get; internal set; }
/// <summary>The will that is available to hold reflexes down and to power voluntary behaviour: resolve through attention, capped by consciousness.</summary>
public double Will => Math.Min(Resolve * Attention, Consciousness);
/// <summary>The gain on the sense channels in force, 0..1: the goal in force's <see cref="GoalSpec.SensoryGain"/> as the Actor has reached it. Written only by the Actor.</summary>
public double SensoryGain { get; internal set; }
/// <summary>Air hunger, 0..1: written each tick by the Actor from its <see cref="Physiology"/> (the only writer), 0 for an Actor with no physiology. It raises arousal like sensory load does.</summary>
public double AirHunger { get; internal set; }
internal static DriveState Fresh => new DriveState { Resolve = 1.0, Attention = 1.0, Consciousness = 1.0, SensoryGain = 1.0 };
/// <summary>A goal's entry effect: sets resolve, then the mend check runs (a break the entry lifts past <see cref="DriveParameters.WillMendsAt"/> is mended). It is not a break and counts none.</summary>
internal void Enter(DriveParameters p, double resolve)
{
Resolve = resolve;
if (WillBroken && Resolve >= p.WillMendsAt)
{
WillBroken = false;
}
}
/// <summary>Steps one tick; returns true on the tick the will breaks (each break, not only the first). <paramref name="pull"/> is the active goal's: it scales resolve drain by (1 - pull). <paramref name="effort"/> is the active goal's resolve drained per second to sustain it (0 while it is involuntary); it joins the drain sum, so pull scales it too.</summary>
internal bool Step(DriveParameters p, double dt, double afferent, double strainLoad, double load, double pull, double effort)
{
Arousal = Math.Min(Math.Max(Arousal + dt * (p.ArousalRise * Math.Max(load, AirHunger) * (1.0 - Arousal) - p.ArousalDecay * Arousal), 0.0), 1.0);
Pain = Math.Min(Math.Max(Pain + dt * (p.PainRise * afferent * (1.0 - Pain) - p.PainDecay * Pain), 0.0), 1.0);
Strain = Math.Max(0.0, Strain + dt * (strainLoad - p.StrainRecover * Strain));
var drain = (p.ResolveDrainPain * Pain + p.ResolveDrainStrain * Strain + p.ResolveDrainArousal * Arousal + effort) * (1.0 - pull) * p.DrainTrait;
var recovery = Pain < p.ResolveRecoversBelowPain && Arousal < p.ResolveRecoversBelowArousal ? p.ResolveRecovery * (1.0 - Resolve) : 0.0;
Resolve = Math.Min(Math.Max(Resolve + dt * (recovery - drain), 0.0), 1.0);
if (WillBroken)
{
if (Resolve >= p.WillMendsAt)
{
WillBroken = false;
}
return false;
}
if (Resolve <= 0.0)
{
WillBroken = true;
Breaks++;
return true;
}
return false;
}
}
}

893
src/Lodur.Core/Ik.cs Normal file
View file

@ -0,0 +1,893 @@
using System;
namespace Lodur
{
/// <summary>A plain 3-vector for the solvers; a value type, so solving allocates nothing.</summary>
internal readonly struct IkVec
{
public readonly float X, Y, Z;
public IkVec(float x, float y, float z)
{
X = x; Y = y; Z = z;
}
public IkVec((float X, float Y, float Z) v)
{
X = v.X; Y = v.Y; Z = v.Z;
}
public static IkVec operator +(IkVec a, IkVec b) => new IkVec(a.X + b.X, a.Y + b.Y, a.Z + b.Z);
public static IkVec operator -(IkVec a, IkVec b) => new IkVec(a.X - b.X, a.Y - b.Y, a.Z - b.Z);
public static IkVec operator *(IkVec a, float s) => new IkVec(a.X * s, a.Y * s, a.Z * s);
public float Dot(IkVec b) => X * b.X + Y * b.Y + Z * b.Z;
public IkVec Cross(IkVec b) => new IkVec(Y * b.Z - Z * b.Y, Z * b.X - X * b.Z, X * b.Y - Y * b.X);
public float Length => MathF.Sqrt(Dot(this));
public IkVec Unit()
{
var l = Length;
return l > 0f ? this * (1f / l) : this;
}
public IkVec Rotated(in Quat q)
{
q.Rotate(X, Y, Z, out var x, out var y, out var z);
return new IkVec(x, y, z);
}
}
/// <summary>
/// Inverse kinematics as a producer of joint target rotations: a world point in, target rotations out, in the convention of the
/// body interface. It decides nothing about when to reach or how hard, and it reads the plan, never writes it.
/// <para>
/// Convention: a joint's frame F is the shortest-arc rotation taking +z to the joint's axis (the plan's creation-pose axis). A target q
/// means the child's rotation relative to the parent, from the creation pose, is F q F^-1 in the parent's creation-pose frame. Twist is
/// about the frame's z, swing about its x and y. A spherical joint's Lower and Upper bound twist and Cone bounds swing; a hinge's Lower
/// and Upper bound its angle about frame z.
/// </para>
/// </summary>
public static class Ik
{
/// <summary>The joint frame F of <paramref name="joint"/>: the shortest arc from +z to the unit joint axis.</summary>
public static Quat JointFrame(in JointDef joint) => Arc(new IkVec(0f, 0f, 1f), new IkVec(joint.Axis).Unit());
/// <summary>The shortest-arc rotation taking unit vector a onto unit vector b.</summary>
internal static Quat Arc(IkVec a, IkVec b)
{
var dot = a.Dot(b);
if (dot < -1f + 1e-6f)
{
// Opposite: a half turn about any axis perpendicular to a.
var p = a.Cross(MathF.Abs(a.X) < 0.9f ? new IkVec(1f, 0f, 0f) : new IkVec(0f, 1f, 0f)).Unit();
return new Quat(p.X, p.Y, p.Z, 0f);
}
var c = a.Cross(b);
var w = 1f + dot;
var inv = 1f / MathF.Sqrt(c.Dot(c) + w * w);
return new Quat(c.X * inv, c.Y * inv, c.Z * inv, w * inv);
}
internal static Quat About(IkVec axis, float radians) => Quat.FromAxisAngle(axis.X, axis.Y, axis.Z, radians);
internal static float Clamp(float v, float lo, float hi) => v < lo ? lo : (v > hi ? hi : v);
/// <summary>The target in the parent part's creation-pose frame: where it sits if the parent were still at its creation pose.</summary>
internal static IkVec ToCreationFrame(in Quat parentRotation, in Quat parentRestInverse, IkVec parentCentre,
float px, float py, float pz, float tx, float ty, float tz)
{
var rel = parentRotation * parentRestInverse;
return parentCentre + new IkVec(tx - px, ty - py, tz - pz).Rotated(rel.Conjugate());
}
}
/// <summary>
/// A two-bone arm: shoulder (spherical), elbow (revolute) and wrist anchors of one side, found by label in the plan. Solves a world
/// point for the wrist anchor: the elbow flex is fixed by the distance, and the swivel about the shoulder-to-wrist line is the one that
/// leaves the shoulder target no twist, the shoulder's twist muscle being weak. When that swivel puts the swing past the cone, the swivel
/// is the one nearest it whose swing is inside the cone and whose twist is inside the twist limits (the joint-limit-feasible swivel range of
/// Tolani, Goswami and Badler 2000). When no swivel is feasible, the swivel is the one whose limit violation (swing past the cone plus
/// twist past its limits) is least, and its swing and twist clamp to the limits; as a goal leaves the feasible set that swivel is the
/// last feasible one, so the targets move continuously across the edge.
/// <para>
/// That rule alone is the stateless rule, and mirrored options tie under it: where two swivels are equally good it must jump from one to
/// the other somewhere on the tie set. So a chain is one arm's solver across ticks and carries the arm's previous swivel (ruling
/// lodur:ruling:ik-swivel-temporal-coherence): each solve stays in the basin of the previous swivel and moves to the stateless choice only
/// when that is better by <see cref="BasinMargin"/>, never turning the swivel faster than <see cref="SwivelRate"/>. Better means less limit
/// violation, or, both swivels being feasible, less twist. The first solve after construction or <see cref="Reset"/> is the stateless rule.
/// Identical goals can therefore give different targets depending on history; the same history gives the same targets.
/// </para>
/// <para>
/// The solved targets can still jump where the solution is discontinuous in the goal (the clamp's swing-twist split at a half-turn swing,
/// a basin change, a goal that leaps). So the targets the chain returns move toward the solved ones no faster than
/// <see cref="MaxAngularRate"/>: per solve the shoulder target turns, and the elbow target flexes, by at most MaxAngularRate times the
/// tick (ruling lodur:ruling:ik-output-slew-limit). While the goal holds still they converge on the solution. A goal that leaps is
/// followed at that rate, not at once. The first solve after construction or <see cref="Reset"/> returns the solution itself.
/// </para>
/// </summary>
public sealed class ArmChain
{
private readonly Quat _parentRestInverse, _frame, _frameInverse;
private readonly IkVec _parentCentre, _shoulderAnchor, _upper, _lower, _elbowAxis, _twistAxis;
private readonly float _flexSign, _flexLo, _flexHi, _cone, _twistLo, _twistHi, _coneSin2, _coneSinHalf, _coneCosHalf;
private readonly float _maxSwivelStep, _maxStep, _cosHalfMaxStep, _sinHalfMaxStep;
// The previous solve's shoulder target before clamping, whose swivel the next solve starts from; none after construction or Reset.
// The targets the previous solve returned, which the next one slews from, share the flag.
private Quat _previous, _shoulderOut;
private float _flexOut;
private bool _hasPrevious, _hasOutput;
private enum Hand : byte { Idle, Driving, Releasing }
// The hand-off and the hand path. The path is in the arm parent's creation frame; its time counts the ticks driven since it started.
private Hand _hand;
private double _weight;
private bool _newPath, _pathBlocked, _hasSegGoal;
private IkVec _pathStart, _pathVia, _segGoal, _aim;
private int _pathTicks;
private readonly float _dt;
private readonly IkVec[] _trunkCentre, _trunkHalf;
private readonly float _trunkFront, _forearmRadius;
/// <summary>
/// Radians of limit violation, or of twist when both swivels are feasible, by which the stateless choice must beat the held swivel's
/// basin before the arm leaves it. Placeholder: no measured pose cost sets it. It must sit far above the solver's resolution (about
/// 1e-5 rad), so noise cannot flip a tie, and well below the 1.0-1.57 rad between the mirrored basins Soul measured, so a clearly
/// better basin is taken.
/// </summary>
public const double BasinMargin = 0.05;
/// <summary>
/// The fastest the swivel turns, in radians per second. Placeholder: of the order of a deliberate, unhurried shoulder rotation, not a
/// measured one.
/// </summary>
public const float SwivelRate = 3f;
/// <summary>
/// The fastest the returned targets move, in radians per second: the shoulder target's turn and the elbow target's flex per solve are at
/// most this times the tick. Placeholder: near human peak arm angular speed, not measured for this body.
/// </summary>
public const float MaxAngularRate = 10f;
/// <summary>
/// Metres the via point sits ahead of the trunk's front. Placeholder: the probe (goal-ai-map fact 25) measured 0.15 to 0.3 m clearing the
/// seated far arm; no pose cost sets it.
/// </summary>
public const float ViaClearance = 0.2f;
/// <summary>Seconds of each of the path's two segments, wrist to via point and via point to goal. Placeholder: a deliberate reach, not measured (fact 25).</summary>
public const float PathSegmentSeconds = 0.3f;
// Swivel search: steps of Pi / SwivelSteps outward from the zero-twist swivel, then bisection to the feasible boundary. When none is
// feasible, the least-violating of LeastSteps steps round the circle, refined by golden section.
private const int SwivelSteps = 90;
private const int SwivelBisections = 16;
private const int LeastSteps = 36;
private const int LeastRefinements = 28;
// Among swivels that violate the limits equally (the arm along the twist axis, where the swivel only twists) the least twist wins.
// Small against the violation's slope of about one, so it barely moves the least-violating swivel.
private const double TwistPreference = 1e-5;
private ArmChain(BodyPlan plan, Side side, double tickSeconds)
{
if (!(double.IsFinite(tickSeconds) && tickSeconds > 0.0))
{
throw new ArgumentException($"the tick length {tickSeconds} s is not finite and positive.");
}
_dt = (float)tickSeconds;
_maxSwivelStep = (float)(SwivelRate * tickSeconds);
_maxStep = (float)(MaxAngularRate * tickSeconds);
_cosHalfMaxStep = MathF.Cos(0.5f * _maxStep);
_sinHalfMaxStep = MathF.Sin(0.5f * _maxStep);
var si = plan.JointIndex("Shoulder", side);
var ei = plan.JointIndex("Elbow", side);
var wi = plan.JointIndex("Wrist", side);
var s = plan.Joints[si];
var e = plan.Joints[ei];
var w = plan.Joints[wi];
if (s.Kind != JointKind.Spherical || e.Kind != JointKind.Revolute || w.Parent != e.Child || e.Parent != s.Child)
{
throw new ArgumentException($"the {side} arm is not a spherical shoulder, a revolute elbow and a wrist on the forearm.");
}
ShoulderJoint = si;
ElbowJoint = ei;
ParentPart = s.Parent;
var shoulder = new IkVec(s.Anchor);
var elbow = new IkVec(e.Anchor);
var wrist = new IkVec(w.Anchor);
_upper = elbow - shoulder;
_lower = wrist - elbow;
L1 = _upper.Length;
L2 = _lower.Length;
_elbowAxis = new IkVec(e.Axis).Unit();
_twistAxis = new IkVec(s.Axis).Unit();
// The closed form needs the creation pose straight and the hinge across both bones.
if (L1 < 1e-4f || L2 < 1e-4f || _upper.Cross(_lower).Length > 1e-3f * L1 * L2 || MathF.Abs(_elbowAxis.Dot(_lower)) > 1e-3f * L2)
{
throw new ArgumentException($"the {side} arm is not straight at its creation pose with the elbow hinge across it.");
}
// The hinge bends to one side of zero; a range straddling zero would make the flex ambiguous.
if (e.Lower < 0f && e.Upper <= 0f) _flexSign = -1f;
else if (e.Lower >= 0f && e.Upper > 0f) _flexSign = 1f;
else throw new ArgumentException($"the {side} elbow range [{e.Lower}, {e.Upper}] does not lie on one side of zero.");
_flexLo = e.Lower;
_flexHi = e.Upper;
_cone = s.Cone;
_twistLo = s.Lower;
_twistHi = s.Upper;
_coneSinHalf = MathF.Sin(0.5f * _cone);
_coneCosHalf = MathF.Cos(0.5f * _cone);
_coneSin2 = _coneSinHalf * _coneSinHalf;
_shoulderAnchor = shoulder;
_frame = Ik.JointFrame(s);
_frameInverse = _frame.Conjugate();
var parent = plan.Parts[ParentPart];
_parentCentre = new IkVec(parent.Position);
_parentRestInverse = parent.Rotation.Conjugate();
ShoulderAnchor = s.Anchor;
ElbowAnchor = e.Anchor;
WristAnchor = w.Anchor;
ForearmPart = e.Child;
// The trunk: the shoulder's parent part and its ancestors, each as its creation-pose axis-aligned bound.
var trunk = 0;
for (var part = s.Parent; part >= 0; part = plan.ParentOf(part)) trunk++;
_trunkCentre = new IkVec[trunk];
_trunkHalf = new IkVec[trunk];
_trunkFront = float.NegativeInfinity;
trunk = 0;
for (var part = s.Parent; part >= 0; part = plan.ParentOf(part))
{
var def = plan.Parts[part];
_trunkCentre[trunk] = new IkVec(def.Position);
_trunkHalf[trunk] = Half(def);
_trunkFront = MathF.Max(_trunkFront, def.Position.Z + _trunkHalf[trunk].Z);
trunk++;
}
var fore = plan.Parts[e.Child];
_forearmRadius = fore.Shape == PartShape.Box ? MathF.Min(fore.Size.X, MathF.Min(fore.Size.Y, fore.Size.Z)) : fore.Size.X;
_newPath = true;
}
// The half extents of a part's creation-pose axis-aligned bound.
private static IkVec Half(in PartDef part)
{
var q = part.Rotation;
var (sx, sy, sz) = part.Size;
q.Rotate(1f, 0f, 0f, out var xx, out var xy, out var xz);
q.Rotate(0f, 1f, 0f, out var yx, out var yy, out var yz);
q.Rotate(0f, 0f, 1f, out var zx, out var zy, out var zz);
switch (part.Shape)
{
case PartShape.Box:
return new IkVec(MathF.Abs(xx) * sx + MathF.Abs(yx) * sy + MathF.Abs(zx) * sz,
MathF.Abs(xy) * sx + MathF.Abs(yy) * sy + MathF.Abs(zy) * sz,
MathF.Abs(xz) * sx + MathF.Abs(yz) * sy + MathF.Abs(zz) * sz);
case PartShape.Capsule:
// Radius sx, half length sy along the part's y.
return new IkVec(MathF.Abs(yx) * sy + sx, MathF.Abs(yy) * sy + sx, MathF.Abs(yz) * sy + sx);
default:
return new IkVec(sx, sx, sx);
}
}
/// <summary>Finds the shoulder, elbow and wrist of <paramref name="side"/> by label; <see cref="ArgumentException"/> if the plan has no such arm.</summary>
/// <remarks>One chain is one arm's solver across ticks of <paramref name="tickSeconds"/>, which sets how far the swivel turns per solve.</remarks>
public static ArmChain Of(BodyPlan plan, Side side, double tickSeconds) => new ArmChain(plan, side, tickSeconds);
/// <summary>
/// Forgets the previous swivel, the returned targets, the hand path and the hand-off: the next <see cref="Solve"/> uses the stateless rule
/// and returns its solution unslewed, and the arm is idle, so <see cref="Release"/> passes the base through and <see cref="Drive"/> engages
/// from it.
/// </summary>
public void Reset()
{
_hasPrevious = false;
_hasOutput = false;
_hand = Hand.Idle;
_newPath = true;
}
/// <summary>The next <see cref="Drive"/> starts a new hand path from the measured wrist, keeping the swivel and the returned targets.</summary>
public void Restart() => _newPath = true;
/// <summary>The last solve's shoulder target before clamping, whose swivel the next solve holds (identity before any solve); tests read it.</summary>
internal Quat Held => _hasPrevious ? _previous : Quat.Identity;
/// <summary>The plan's joint ordinals, where the caller writes the two targets.</summary>
public int ShoulderJoint { get; }
public int ElbowJoint { get; }
/// <summary>The part the shoulder hangs from; Solve takes its world rotation and position.</summary>
public int ParentPart { get; }
/// <summary>The forearm part, which carries the wrist anchor; Drive takes the measured wrist from its pose.</summary>
public int ForearmPart { get; }
/// <summary>Creation-pose anchors. The effector is <see cref="WristAnchor"/>.</summary>
public (float X, float Y, float Z) ShoulderAnchor { get; }
public (float X, float Y, float Z) ElbowAnchor { get; }
public (float X, float Y, float Z) WristAnchor { get; }
/// <summary>Shoulder to elbow anchor, and elbow to wrist anchor, in metres.</summary>
public float L1 { get; }
public float L2 { get; }
/// <summary>
/// Targets that put the wrist anchor on the world point (tx, ty, tz), given the parent part's world rotation and position.
/// Returns false when the point was out of reach or a limit clamped; the targets are then the limits-clamped pose of the swivel that
/// violates the limits least, continuous with the reached targets at the edge of the feasible set, or, while the swivel turns between
/// basins, the clamped pose of the swivel on its way. The returned targets are slewed toward that solution at
/// <see cref="MaxAngularRate"/>; the return value describes the solution. One call is one tick of the arm's history.
/// </summary>
public bool Solve(in Quat parentRotation, float px, float py, float pz, float tx, float ty, float tz, out Quat shoulder, out Quat elbow) =>
SolveCreation(Ik.ToCreationFrame(parentRotation, _parentRestInverse, _parentCentre, px, py, pz, tx, ty, tz), out shoulder, out elbow);
// Solve for a wrist point already in the parent's creation frame.
private bool SolveCreation(IkVec target, out Quat shoulder, out Quat elbow)
{
var reached = true;
var v = target - _shoulderAnchor;
var d = v.Length;
var dMin = MathF.Abs(L1 - L2) + 1e-3f;
var dMax = L1 + L2 - 1e-3f;
var dc = Ik.Clamp(d, dMin, dMax);
if (dc != d) reached = false;
var vHat = d > 1e-6f ? v * (1f / d) : _upper.Unit();
var cosFlex = Ik.Clamp((dc * dc - L1 * L1 - L2 * L2) / (2f * L1 * L2), -1f, 1f);
var flexWant = _flexSign * MathF.Acos(cosFlex);
var flex = Ik.Clamp(flexWant, _flexLo, _flexHi);
if (flex != flexWant) reached = false;
// The hand offset at this flex, in the upper arm's creation frame, and the swing taking it onto the target direction.
var p = _upper + _lower.Rotated(Ik.About(_elbowAxis, flex));
var arc = Ik.Arc(p.Unit(), vHat);
var q = new IkVec(arc.X, arc.Y, arc.Z);
var num = -q.Dot(_twistAxis);
var den = arc.W * vHat.Dot(_twistAxis) + vHat.Cross(q).Dot(_twistAxis);
var zeroTwist = 2f * MathF.Atan2(num, den);
// The target is linear in the half-angle of the swivel: Local(phi) = cos(phi / 2) A + sin(phi / 2) B.
var a = _frameInverse * arc * _frame;
var b = _frameInverse * (new Quat(vHat.X, vHat.Y, vHat.Z, 0f) * arc) * _frame;
var phi = Stateless(a, b, zeroTwist, out var clamp);
if (_hasPrevious)
{
// The previous target's swivel on this goal's swivel circle: a and b are orthonormal, so the nearest point is a projection.
var held = 2f * MathF.Atan2(Dot(_previous, b), Dot(_previous, a));
var basin = BasinOptimum(a, b, zeroTwist, held);
var want = ClearlyBetter(a, b, phi, basin) ? phi : basin;
phi = held + Ik.Clamp(Wrap(want - held), -_maxSwivelStep, _maxSwivelStep);
clamp = !Feasible(Local(a, b, phi));
}
var local = Local(a, b, phi);
var slew = _hasOutput;
_previous = local;
_hasPrevious = true;
_hasOutput = true;
if (clamp)
{
// Infeasible: swing and twist clamped to the limits.
local = ClampToLimits(local);
reached = false;
}
if (slew)
{
_shoulderOut = Toward(_shoulderOut, local);
_flexOut += Ik.Clamp(flex - _flexOut, -_maxStep, _maxStep);
}
else
{
(_shoulderOut, _flexOut) = (local, flex);
}
shoulder = _shoulderOut;
elbow = Quat.FromAxisAngle(0f, 0f, 1f, _flexOut);
return reached;
}
/// <summary>
/// One tick the arm's layer drives: the targets to write for the wrist goal (tx, ty, tz) given the arm parent's world pose, the wrist
/// measured now (mx, my, mz) and the base shoulder and elbow targets, blended toward the solution by <paramref name="weight"/> in [0, 1].
/// An arm that was idle starts slewing from the base targets; one that was releasing, from where its output was. The tick that engages the
/// arm, and every tick after <see cref="Restart"/>, starts a hand path from the measured wrist. Returns whether the goal was reached,
/// as <see cref="Solve"/> does for the point it was given.
/// </summary>
public bool Drive(in Quat parentRotation, float px, float py, float pz, float tx, float ty, float tz, float mx, float my, float mz,
in Quat baseShoulder, in Quat baseElbow, double weight, out Quat shoulder, out Quat elbow)
{
if (_hand != Hand.Driving)
{
if (_hand == Hand.Idle)
{
_shoulderOut = baseShoulder;
_flexOut = Flex(baseElbow);
_hasOutput = true;
}
_hand = Hand.Driving;
_newPath = true;
}
_weight = weight;
var goal = Ik.ToCreationFrame(parentRotation, _parentRestInverse, _parentCentre, px, py, pz, tx, ty, tz);
if (_newPath)
{
_newPath = false;
var wrist = Ik.ToCreationFrame(parentRotation, _parentRestInverse, _parentCentre, px, py, pz, mx, my, mz);
_pathStart = wrist;
_pathBlocked = Blocked(wrist, goal);
_pathVia = new IkVec(wrist.X, 0.5f * (wrist.Y + goal.Y), _trunkFront + ViaClearance);
_pathTicks = 0;
_hasSegGoal = false;
}
var aim = goal;
if (_pathBlocked && _pathTicks * _dt < 2f * PathSegmentSeconds)
{
var t = _pathTicks * _dt;
if (!_hasSegGoal && t >= PathSegmentSeconds)
{
_segGoal = goal;
_hasSegGoal = true;
}
aim = PathPoint(_pathStart, _pathVia, _segGoal, goal, t);
_pathTicks++;
}
_aim = aim;
var reached = SolveCreation(aim, out var s, out var e);
shoulder = Blend(baseShoulder, s, weight);
elbow = Blend(baseElbow, e, weight);
return reached;
}
/// <summary>
/// One tick the arm's layer does not drive: while the arm still holds a driven output, it slews to the base targets at
/// <see cref="MaxAngularRate"/>, written blended toward the base by the weight it was last driven at; when it has arrived, and for an arm
/// that never was driven, the written targets are the base ones, untouched.
/// </summary>
public void Release(in Quat baseShoulder, in Quat baseElbow, out Quat shoulder, out Quat elbow)
{
if (_hand == Hand.Idle)
{
shoulder = baseShoulder;
elbow = baseElbow;
return;
}
_hand = Hand.Releasing;
_shoulderOut = Toward(_shoulderOut, baseShoulder);
var flex = Flex(baseElbow);
var gap = flex - _flexOut;
_flexOut = MathF.Abs(gap) <= _maxStep ? flex : _flexOut + (gap > 0f ? _maxStep : -_maxStep);
if (_flexOut == flex && _shoulderOut.X == baseShoulder.X && _shoulderOut.Y == baseShoulder.Y && _shoulderOut.Z == baseShoulder.Z
&& _shoulderOut.W == baseShoulder.W)
{
_hand = Hand.Idle;
shoulder = baseShoulder;
elbow = baseElbow;
return;
}
shoulder = Blend(baseShoulder, _shoulderOut, _weight);
elbow = Blend(baseElbow, Quat.FromAxisAngle(0f, 0f, 1f, _flexOut), _weight);
}
// The solution itself at weight 1, a blend toward it from the base below that.
private static Quat Blend(in Quat baseTarget, in Quat solution, double weight) =>
weight >= 1.0 ? solution : Quat.Nlerp(baseTarget, solution, (float)weight);
// The flex of an elbow target, a rotation about the hinge's frame z, on the shortest turn.
private static float Flex(in Quat elbow) => 2f * MathF.Atan2(elbow.W < 0f ? -elbow.Z : elbow.Z, MathF.Abs(elbow.W));
// Minimum jerk (Flash and Hogan 1985): 0 to 1 with zero velocity and acceleration at both ends.
internal static float MinimumJerk(float t)
{
t = Ik.Clamp(t, 0f, 1f);
return t * t * t * (10f - 15f * t + 6f * t * t);
}
/// <summary>
/// The hand path in the arm parent's creation frame at <paramref name="t"/> seconds: the start to the via point over
/// <see cref="PathSegmentSeconds"/>, then the goal plus the via point's offset from the goal as it was when the segment began, shrinking
/// to nothing, so a goal that moves is met at the end. <paramref name="segmentGoal"/> is the goal at that moment.
/// </summary>
internal static (float X, float Y, float Z) PathPoint((float X, float Y, float Z) start, (float X, float Y, float Z) via,
(float X, float Y, float Z) segmentGoal, (float X, float Y, float Z) goal, float t)
{
var p = PathPoint(new IkVec(start), new IkVec(via), new IkVec(segmentGoal), new IkVec(goal), t);
return (p.X, p.Y, p.Z);
}
private static IkVec PathPoint(IkVec start, IkVec via, IkVec segmentGoal, IkVec goal, float t)
{
if (t < PathSegmentSeconds) return start + (via - start) * MinimumJerk(t / PathSegmentSeconds);
return goal + (via - segmentGoal) * (1f - MinimumJerk((t - PathSegmentSeconds) / PathSegmentSeconds));
}
/// <summary>Whether the last path start found the trunk in the way (tests read it).</summary>
internal bool PathBlocked => _pathBlocked;
/// <summary>The creation-frame point the last <see cref="Drive"/> solved for: the path point, or the goal (tests read it).</summary>
internal (float X, float Y, float Z) Aim => (_aim.X, _aim.Y, _aim.Z);
// Whether the straight segment from the wrist to the goal passes within the forearm radius of a trunk bound.
private bool Blocked(IkVec wrist, IkVec goal)
{
for (var b = 0; b < _trunkCentre.Length; b++)
{
// The distance to a box is convex along a line, so a ternary search finds its least over the segment.
float lo = 0f, hi = 1f;
for (var i = 0; i < 40; i++)
{
var m1 = lo + (hi - lo) / 3f;
var m2 = hi - (hi - lo) / 3f;
if (BoxDistance(wrist + (goal - wrist) * m1, b) < BoxDistance(wrist + (goal - wrist) * m2, b)) hi = m2;
else lo = m1;
}
if (BoxDistance(wrist + (goal - wrist) * (0.5f * (lo + hi)), b) < _forearmRadius) return true;
}
return false;
}
private float BoxDistance(IkVec p, int box)
{
var d = p - _trunkCentre[box];
var h = _trunkHalf[box];
var x = MathF.Max(0f, MathF.Abs(d.X) - h.X);
var y = MathF.Max(0f, MathF.Abs(d.Y) - h.Y);
var z = MathF.Max(0f, MathF.Abs(d.Z) - h.Z);
return MathF.Sqrt(x * x + y * y + z * z);
}
// The rotation from current toward target, turned by at most the per-solve step: the target itself when it is within the step.
private Quat Toward(in Quat current, in Quat target)
{
var d = current.Conjugate() * target;
var s = d.W < 0f ? -1f : 1f;
var (x, y, z, w) = (s * d.X, s * d.Y, s * d.Z, s * d.W);
var sinHalf = MathF.Sqrt(x * x + y * y + z * z);
if (2f * MathF.Atan2(sinHalf, w) <= _maxStep) return target;
var k = _sinHalfMaxStep / sinHalf;
// Renormalised, so a goal outrunning the rate for many ticks does not drift the target off the unit sphere.
var r = current * new Quat(x * k, y * k, z * k, _cosHalfMaxStep);
var n = 1f / MathF.Sqrt(r.X * r.X + r.Y * r.Y + r.Z * r.Z + r.W * r.W);
return new Quat(r.X * n, r.Y * n, r.Z * n, r.W * n);
}
// The stateless rule: zero twist inside the cone, else the nearest feasible swivel, else the least-violating one (clamp set).
private float Stateless(in Quat a, in Quat b, float zeroTwist, out bool clamp)
{
clamp = false;
if (InsideCone(Local(a, b, zeroTwist))) return zeroTwist;
if (SomeSwivelInsideCone(a, b) && NearestFeasible(a, b, zeroTwist, out var feasible)) return feasible;
clamp = true;
return LeastViolating(a, b, zeroTwist);
}
// The best swivel of the held swivel's basin. When some swivel is feasible: from the held swivel, or the feasible one nearest it,
// toward zero twist while feasible. When none is: the least violation downhill from the held swivel.
private float BasinOptimum(in Quat a, in Quat b, float zeroTwist, float held)
{
if (SomeSwivelInsideCone(a, b))
{
if (Feasible(Local(a, b, held))) return TowardZeroTwist(a, b, zeroTwist, held);
if (NearestFeasible(a, b, held, out var start)) return TowardZeroTwist(a, b, zeroTwist, start);
}
return LocalLeastViolating(a, b, held);
}
// From the feasible swivel start toward the zero-twist swivel, the way twist shrinks: the zero-twist swivel if every step there is
// feasible, else the feasible boundary on the way.
private float TowardZeroTwist(in Quat a, in Quat b, float zeroTwist, float start)
{
var d = Wrap(start - zeroTwist);
if (d == 0f) return zeroTwist;
var dir = d > 0f ? -1f : 1f;
var dist = MathF.Abs(d);
const float step = MathF.PI / SwivelSteps;
var inside = start;
for (var k = 1; k <= SwivelSteps; k++)
{
var t = MathF.Min(k * step, dist);
var phi = start + dir * t;
if (!Feasible(Local(a, b, phi))) return Boundary(a, b, inside, phi);
if (t >= dist) return zeroTwist;
inside = phi;
}
return inside;
}
// Whether swivel x beats swivel y by the margin: less violation, or, both feasible, less twist.
private bool ClearlyBetter(in Quat a, in Quat b, float x, float y)
{
if (Violation(a, b, x) < Violation(a, b, y) - BasinMargin) return true;
var lx = Local(a, b, x);
var ly = Local(a, b, y);
return Feasible(lx) && Feasible(ly) && MathF.Abs(Twist(lx)) < MathF.Abs(Twist(ly)) - (float)BasinMargin;
}
private static float Twist(in Quat local) => 2f * MathF.Atan2(local.Z, local.W);
private static float Dot(in Quat p, in Quat q) => p.X * q.X + p.Y * q.Y + p.Z * q.Z + p.W * q.W;
// An angle difference into [-pi, pi]: the swivel's period is a full turn.
private static float Wrap(float x) => x - 2f * MathF.PI * MathF.Round(x / (2f * MathF.PI));
// The shoulder target in the joint frame for the swivel phi, with w >= 0.
private static Quat Local(in Quat a, in Quat b, float phi)
{
var c = MathF.Cos(0.5f * phi);
var s = MathF.Sin(0.5f * phi);
var local = new Quat(c * a.X + s * b.X, c * a.Y + s * b.Y, c * a.Z + s * b.Z, c * a.W + s * b.W);
return local.W < 0f ? new Quat(-local.X, -local.Y, -local.Z, -local.W) : local;
}
// Swing is the angle between the frame z and its image: inside the cone when sin^2(swing / 2) = x^2 + y^2 <= sin^2(cone / 2).
private bool InsideCone(in Quat local) => local.X * local.X + local.Y * local.Y <= _coneSin2;
// x^2 + y^2 is a quadratic form in (cos(phi / 2), sin(phi / 2)); its least value over the swivel is the form's smaller eigenvalue.
private bool SomeSwivelInsideCone(in Quat a, in Quat b)
{
var maa = a.X * a.X + a.Y * a.Y;
var mbb = b.X * b.X + b.Y * b.Y;
var mab = a.X * b.X + a.Y * b.Y;
var half = 0.5f * (maa - mbb);
return 0.5f * (maa + mbb) - MathF.Sqrt(half * half + mab * mab) <= _coneSin2;
}
private bool Feasible(in Quat local)
{
if (!InsideCone(local)) return false;
var twist = Twist(local);
return twist >= _twistLo && twist <= _twistHi;
}
// Bisection between a feasible and an infeasible swivel to the boundary; the feasible end.
private float Boundary(in Quat a, in Quat b, float inside, float outside)
{
for (var i = 0; i < SwivelBisections; i++)
{
var mid = 0.5f * (inside + outside);
if (Feasible(Local(a, b, mid))) inside = mid;
else outside = mid;
}
return inside;
}
// The feasible swivel nearest phi0: step outward both ways, and at the first step that lands inside, bisect back to the boundary;
// of the two sides, the one with the smaller twist. False when no swivel is feasible.
private bool NearestFeasible(in Quat a, in Quat b, float phi0, out float swivel)
{
swivel = 0f;
const float step = MathF.PI / SwivelSteps;
for (var k = 1; k <= SwivelSteps; k++)
{
var found = false;
var bestTwist = float.MaxValue;
for (var sign = -1; sign <= 1; sign += 2)
{
var phi = phi0 + sign * k * step;
if (!Feasible(Local(a, b, phi))) continue;
var inside = Boundary(a, b, phi, phi0 + sign * (k - 1) * step);
var twist = MathF.Abs(Twist(Local(a, b, inside)));
if (twist < bestTwist)
{
bestTwist = twist;
swivel = inside;
found = true;
}
}
if (found) return true;
}
return false;
}
// Radians past the limits at the swivel phi, swing past the cone plus twist past its range, with the small twist preference. In
// double: the least point of a smooth minimum is found only to the square root of the arithmetic's precision.
private double Violation(in Quat a, in Quat b, double phi)
{
var c = Math.Cos(0.5 * phi);
var s = Math.Sin(0.5 * phi);
var x = c * a.X + s * b.X;
var y = c * a.Y + s * b.Y;
var z = c * a.Z + s * b.Z;
var w = c * a.W + s * b.W;
if (w < 0.0)
{
z = -z;
w = -w;
}
var swing = 2.0 * Math.Atan2(Math.Sqrt(x * x + y * y), Math.Sqrt(z * z + w * w));
var twist = 2.0 * Math.Atan2(z, w);
var over = twist < _twistLo ? _twistLo - twist : (twist > _twistHi ? twist - _twistHi : 0.0);
return Math.Max(0.0, swing - _cone) + over + TwistPreference * Math.Abs(twist);
}
// The least-violating swivel: the least of LeastSteps steps round the circle from phi0, refined by golden section within a step
// either side.
private float LeastViolating(in Quat a, in Quat b, float phi0)
{
const double step = 2.0 * Math.PI / LeastSteps;
var best = (double)phi0;
var least = Violation(a, b, best);
for (var k = 1; k < LeastSteps; k++)
{
var phi = phi0 + k * step;
var v = Violation(a, b, phi);
if (v < least)
{
least = v;
best = phi;
}
}
return Golden(a, b, best - step, best + step);
}
// The least-violating swivel of the held swivel's basin: downhill in steps of a LeastSteps-th of the circle while the violation
// falls, then golden section within a step either side.
private float LocalLeastViolating(in Quat a, in Quat b, float held)
{
const double step = 2.0 * Math.PI / LeastSteps;
var best = (double)held;
var least = Violation(a, b, best);
var up = Violation(a, b, best + step);
var down = Violation(a, b, best - step);
if (up < least || down < least)
{
var dir = up < down ? 1.0 : -1.0;
for (var k = 0; k < LeastSteps; k++)
{
var next = best + dir * step;
var v = Violation(a, b, next);
if (v >= least) break;
best = next;
least = v;
}
}
return Golden(a, b, best - step, best + step);
}
// Golden-section search for the least violation on [lo, hi].
private float Golden(in Quat a, in Quat b, double lo, double hi)
{
const double g = 0.6180339887498949;
var p = hi - g * (hi - lo);
var q = lo + g * (hi - lo);
var fp = Violation(a, b, p);
var fq = Violation(a, b, q);
for (var i = 0; i < LeastRefinements; i++)
{
if (fp <= fq)
{
hi = q;
q = p;
fq = fp;
p = hi - g * (hi - lo);
fp = Violation(a, b, p);
}
else
{
lo = p;
p = q;
fp = fq;
q = lo + g * (hi - lo);
fq = Violation(a, b, q);
}
}
return (float)(fp <= fq ? p : q);
}
// Twist clamped to its range and swing to the cone, the swing direction kept. The target is swing * twist, the twist about the frame
// z and the swing about an axis in its xy plane.
private Quat ClampToLimits(in Quat local)
{
// At a half-turn swing the twist is undefined: read it as none.
var tl = MathF.Sqrt(local.Z * local.Z + local.W * local.W);
var tz = tl > 1e-6f ? local.Z / tl : 0f;
var tw = tl > 1e-6f ? local.W / tl : 1f;
var sx = tw * local.X - tz * local.Y;
var sy = tz * local.X + tw * local.Y;
var sw = tl;
var s2 = sx * sx + sy * sy;
if (s2 > _coneSin2)
{
var k = _coneSinHalf / MathF.Sqrt(s2);
sx *= k;
sy *= k;
sw = _coneCosHalf;
}
var half = 0.5f * Ik.Clamp(2f * MathF.Atan2(tz, tw), _twistLo, _twistHi);
tz = MathF.Sin(half);
tw = MathF.Cos(half);
return new Quat(tw * sx + tz * sy, tw * sy - tz * sx, sw * tz, sw * tw);
}
}
/// <summary>
/// A head that looks: one spherical joint (the neck by default) turned so the child part's creation-pose forward, +z, points at a world
/// point. Yaw about the joint axis is the joint's twist and is clamped to [Lower, Upper]; pitch about the creation-pose left axis is swing and
/// is clamped to Cone.
/// </summary>
public sealed class LookChain
{
private readonly Quat _parentRestInverse, _frame, _frameInverse;
private readonly IkVec _parentCentre, _childCentre, _up, _forward, _left;
private readonly float _lower, _upper, _cone;
private LookChain(BodyPlan plan, string joint)
{
var ji = plan.JointIndex(joint);
var j = plan.Joints[ji];
if (j.Kind != JointKind.Spherical) throw new ArgumentException($"joint '{joint}' is not spherical.");
Joint = ji;
ParentPart = j.Parent;
ChildPart = j.Child;
_up = new IkVec(j.Axis).Unit();
var z = new IkVec(0f, 0f, 1f);
var forward = z - _up * z.Dot(_up);
if (forward.Length < 1e-3f) throw new ArgumentException($"joint '{joint}' has an axis along forward, so it has no yaw.");
_forward = forward.Unit();
_left = _up.Cross(_forward);
_lower = j.Lower;
_upper = j.Upper;
_cone = j.Cone;
_frame = Ik.JointFrame(j);
_frameInverse = _frame.Conjugate();
var parent = plan.Parts[j.Parent];
_parentCentre = new IkVec(parent.Position);
_parentRestInverse = parent.Rotation.Conjugate();
_childCentre = new IkVec(plan.Parts[j.Child].Position);
}
public static LookChain Of(BodyPlan plan, string joint = "Neck") => new LookChain(plan, joint);
/// <summary>The plan's joint ordinal, where the caller writes the target.</summary>
public int Joint { get; }
public int ParentPart { get; }
public int ChildPart { get; }
/// <summary>
/// The target that points the child part at the world point: the direction runs from the child's creation-pose centre to the point,
/// in the parent's frame. Returns false when yaw or pitch was clamped.
/// </summary>
public bool Solve(in Quat parentRotation, float px, float py, float pz, float tx, float ty, float tz, out Quat neck)
{
var reached = true;
var dir = Ik.ToCreationFrame(parentRotation, _parentRestInverse, _parentCentre, px, py, pz, tx, ty, tz) - _childCentre;
var len = dir.Length;
var d = len > 1e-6f ? dir * (1f / len) : _forward;
var yawWant = MathF.Atan2(d.Dot(_left), d.Dot(_forward));
var pitchWant = -MathF.Asin(Ik.Clamp(d.Dot(_up), -1f, 1f));
var yaw = Ik.Clamp(yawWant, _lower, _upper);
var pitch = Ik.Clamp(pitchWant, -_cone, _cone);
if (yaw != yawWant || pitch != pitchWant) reached = false;
neck = _frameInverse * (Ik.About(_up, yaw) * Ik.About(_left, pitch)) * _frame;
return reached;
}
}
}

View file

@ -0,0 +1,7 @@
// Lets C# 9 records use init accessors on netstandard2.1, which does not ship this marker type.
namespace System.Runtime.CompilerServices
{
internal static class IsExternalInit
{
}
}

View file

@ -0,0 +1,15 @@
<Project Sdk="Microsoft.NET.Sdk">
<!-- Engine-free core (invariant core-engine-free): no engine, no physics binding. Unity-consumable. -->
<PropertyGroup>
<TargetFramework>netstandard2.1</TargetFramework>
<LangVersion>12.0</LangVersion>
<RootNamespace>Lodur</RootNamespace>
</PropertyGroup>
<!-- The tests lower the Attention slot through an internal seam; nothing in the core writes it yet. -->
<ItemGroup>
<InternalsVisibleTo Include="Lodur.Core.Tests" />
</ItemGroup>
</Project>

405
src/Lodur.Core/Orient.cs Normal file
View file

@ -0,0 +1,405 @@
using System;
using System.Collections.Generic;
namespace Lodur
{
/// <summary>A part's world rotation and centre, as the caller reads them off the body each tick (one per plan part).</summary>
public readonly record struct PartPose(Quat Rotation, float X, float Y, float Z);
/// <summary>What an arm layer does with the wrists.</summary>
public enum ArmMode
{
/// <summary>The wrist goes to the target.</summary>
Reach,
/// <summary>The wrists go between the head and the target, a hand's breadth either side of the line.</summary>
WardOff,
/// <summary>The wrists go to a fixed point in the arm parent's frame; the target is ignored.</summary>
Present,
}
/// <summary>Which arm or arms a layer drives.</summary>
public enum ArmSide
{
Left,
Right,
Both,
/// <summary>The arm whose shoulder was nearer the target when the (goal, target) pair committed; held until the next commit.</summary>
Nearer,
}
/// <summary>Turns the head toward the committed target: the neck's joint target is blended toward the look solution by <see cref="Weight"/>. Joint targets only, never strength.</summary>
public sealed record LookLayer
{
/// <summary>The blend from the base neck pose to the look solution, in [0, 1].</summary>
public double Weight { get; init; } = 1.0;
internal void Validate(string goal)
{
if (!(double.IsFinite(Weight) && Weight >= 0.0 && Weight <= 1.0))
{
throw new ArgumentException($"Goal {goal}: a Look layer's Weight must be finite and in [0, 1].");
}
}
}
/// <summary>Drives the shoulder and elbow of one or both arms from the arm solver: the base pose is blended toward the solution by <see cref="Weight"/>. Joint targets only, never strength.</summary>
public sealed record ArmLayer
{
public ArmMode Mode { get; init; }
public ArmSide Side { get; init; }
/// <summary>The blend from the base shoulder and elbow poses to the solution, in [0, 1].</summary>
public double Weight { get; init; } = 1.0;
/// <summary>WardOff: metres from the head centre toward the target, where the wrists meet the line. Positive.</summary>
public float Distance { get; init; }
/// <summary>WardOff: metres each wrist sits either side of that line, across the torso (the left wrist toward the actor's left). Not negative.</summary>
public float Spread { get; init; }
/// <summary>Present: the wrists' goal in the arm parent's creation frame, given for the right arm; the left arm takes it mirrored in x.</summary>
public (float X, float Y, float Z) Point { get; init; }
internal void Validate(string goal)
{
if (!(double.IsFinite(Weight) && Weight >= 0.0 && Weight <= 1.0))
{
throw new ArgumentException($"Goal {goal}: an Arms layer's Weight must be finite and in [0, 1].");
}
if (Mode == ArmMode.WardOff && !(float.IsFinite(Distance) && Distance > 0f && float.IsFinite(Spread) && Spread >= 0f))
{
throw new ArgumentException($"Goal {goal}: a WardOff layer needs a finite Distance above 0 and a finite Spread of at least 0.");
}
if (Mode == ArmMode.Present)
{
if (Side == ArmSide.Nearer)
{
throw new ArgumentException($"Goal {goal}: a Present layer ignores the target, so it cannot pick the Nearer arm.");
}
if (!(float.IsFinite(Point.X) && float.IsFinite(Point.Y) && float.IsFinite(Point.Z)))
{
throw new ArgumentException($"Goal {goal}: a Present layer's Point must be finite.");
}
}
if (!Enum.IsDefined(typeof(ArmMode), Mode) || !Enum.IsDefined(typeof(ArmSide), Side))
{
throw new ArgumentException($"Goal {goal}: an Arms layer has a Mode or Side that is not defined.");
}
}
}
/// <summary>
/// Shrinks from a threat: the base pose is blended toward <see cref="AwayLeft"/> or <see cref="AwayRight"/> by the target's bearing and
/// <see cref="Proximity"/> (a Distance consideration, head centre to target, whose response is the blend depth). A frontal threat
/// blends half of each. Joint targets only, never strength.
/// </summary>
public sealed record RecoilLayer
{
private Quat[] _left = Array.Empty<Quat>();
private Quat[] _right = Array.Empty<Quat>();
private IReadOnlyList<Quat> _leftView = Array.AsReadOnly(Array.Empty<Quat>());
private IReadOnlyList<Quat> _rightView = Array.AsReadOnly(Array.Empty<Quat>());
/// <summary>The pose that shrinks from a threat on the actor's left, one rotation per muscle. Copied when set; read back as a read-only view.</summary>
public IReadOnlyList<Quat> AwayLeft
{
get => _leftView;
init
{
_left = Copy(value);
_leftView = Array.AsReadOnly(_left);
}
}
/// <summary>The pose that shrinks from a threat on the actor's right. Copied when set; read back as a read-only view.</summary>
public IReadOnlyList<Quat> AwayRight
{
get => _rightView;
init
{
_right = Copy(value);
_rightView = Array.AsReadOnly(_right);
}
}
/// <summary>Input Distance (the head centre to the target); the response is the blend depth, 0 meaning the base pose.</summary>
public Consideration Proximity { get; init; }
internal Quat[] Left => _left;
internal Quat[] Right => _right;
private static Quat[] Copy(IReadOnlyList<Quat> source)
{
var copy = new Quat[source.Count];
for (var m = 0; m < copy.Length; m++)
{
copy[m] = source[m];
}
return copy;
}
internal void Validate(string goal, int muscles)
{
if (_left.Length != muscles || _right.Length != muscles)
{
throw new ArgumentException($"Goal {goal}: a Recoil layer needs AwayLeft and AwayRight poses of one rotation per muscle.");
}
var k = Proximity;
if (k.Input != ConsiderationInput.Distance)
{
throw new ArgumentException($"Goal {goal}: a Recoil layer's Proximity must read Distance.");
}
if (!double.IsFinite(k.X0) || !double.IsFinite(k.X1) || k.X1 == k.X0
|| !(k.Y0 >= 0.0 && k.Y0 <= 1.0) || !(k.Y1 >= 0.0 && k.Y1 <= 1.0)
|| !(double.IsFinite(k.Exponent) && k.Exponent > 0.0))
{
throw new ArgumentException($"Goal {goal}: a Recoil layer's Proximity needs finite X0 != X1, Y0 and Y1 in [0, 1], and Exponent > 0.");
}
}
}
/// <summary>One tick's inputs to the layers: the rig, the caller's part poses, the committed target (Id 0: none) and the arm the Nearer mode holds.</summary>
internal readonly ref struct OrientInput
{
public readonly OrientRig? Rig;
public readonly ReadOnlySpan<PartPose> Parts;
public readonly Percept Target;
public readonly Side Arm;
public OrientInput(OrientRig rig, ReadOnlySpan<PartPose> parts, Percept target, Side arm)
{
Rig = rig;
Parts = parts;
Target = target;
Arm = arm;
}
}
/// <summary>
/// The solvers an Actor's brain needs, resolved once from the body plan: the look chain when any goal looks, wards off or recoils (they read
/// the head), an arm chain for each side an Arms layer can use. A chain the plan cannot give refuses at construction, naming the goal, so a
/// plan the closed form cannot solve fails at spawn and never mid-tick. The arm chains are the Actor's arms across ticks: each holds its
/// arm's swivel, hand path and written targets from tick to tick, and the rig holds nothing else. The arms are composed on every tick of an
/// Actor with a rig, so an arm its layer does not drive eases back to the base pose (<see cref="ArmChain.Release"/>); solving allocates nothing.
/// </summary>
internal sealed class OrientRig
{
private readonly BodyPlan _plan;
private readonly LookChain? _look;
private readonly ArmChain? _left;
private readonly ArmChain? _right;
public OrientRig(BodyPlan plan, Brain brain, double tickSeconds)
{
_plan = plan;
foreach (var goal in brain.Goals)
{
var b = goal.Behaviour;
if (!b.HasLayers)
{
continue;
}
if (_look == null && (b.Look != null || b.Recoil != null || b.Arms?.Mode == ArmMode.WardOff))
{
try
{
_look = LookChain.Of(plan);
}
catch (ArgumentException e)
{
throw new ArgumentException($"Goal {goal.Id}: the body has no head that can look: {e.Message}", e);
}
}
if (b.Arms is { } arms)
{
if (_left == null && arms.Side != ArmSide.Right)
{
_left = Arm(plan, goal.Id, Side.Left, tickSeconds);
}
if (_right == null && arms.Side != ArmSide.Left)
{
_right = Arm(plan, goal.Id, Side.Right, tickSeconds);
}
}
}
}
private static ArmChain Arm(BodyPlan plan, string goal, Side side, double tickSeconds)
{
try
{
return ArmChain.Of(plan, side, tickSeconds);
}
catch (ArgumentException e)
{
throw new ArgumentException($"Goal {goal}: the {side} arm cannot take an Arms layer: {e.Message}", e);
}
}
/// <summary>Forgets both arms' held swivels, paths and written targets: each arm is idle, and engages from the base pose.</summary>
public void ResetArms()
{
_left?.Reset();
_right?.Reset();
}
/// <summary>The Actor committed a (goal, target) pair: each arm starts a new hand path when next driven.</summary>
public void Commit()
{
_left?.Restart();
_right?.Restart();
}
/// <summary>The arm whose shoulder is nearer the target; ties go to the right.</summary>
public Side NearerArm(ReadOnlySpan<PartPose> parts, in Percept target)
{
if (_left == null || _right == null)
{
return Side.Right;
}
var l = ShoulderDistance(_left, parts, target);
var r = ShoulderDistance(_right, parts, target);
return l < r ? Side.Left : Side.Right;
}
private float ShoulderDistance(ArmChain arm, ReadOnlySpan<PartPose> parts, in Percept target)
{
var s = World(arm.ParentPart, parts, new IkVec(arm.ShoulderAnchor));
return (new IkVec(target.X, target.Y, target.Z) - s).Length;
}
/// <summary>A point given in a part's creation frame, where it is now: the part's centre plus its rotation from creation applied to the offset.</summary>
private IkVec World(int part, ReadOnlySpan<PartPose> parts, IkVec creationPoint)
{
var def = _plan.Parts[part];
var pose = parts[part];
var rel = pose.Rotation * def.Rotation.Conjugate();
return new IkVec(pose.X, pose.Y, pose.Z) + (creationPoint - new IkVec(def.Position)).Rotated(rel);
}
/// <summary>
/// Composes the layers onto the base pose already in <paramref name="targets"/>: recoil, then look, then the arms. An arm the behaviour
/// does not drive this tick is released, which passes the base pose through once it has eased back. The part poses are read only for what is
/// driven.
/// </summary>
public void Compose(PoseBehaviour b, in OrientInput input, Span<Quat> targets)
{
var parts = input.Parts;
var hasTarget = input.Target.Id != 0UL;
var goal = new IkVec(input.Target.X, input.Target.Y, input.Target.Z);
// The head centre, the torso's left axis and the unit direction to the target: read only when a layer needs the target.
var head = default(IkVec);
var left = default(IkVec);
var toward = default(IkVec);
var distance = 0f;
if (hasTarget && _look != null && b.HasLayers)
{
var h = parts[_look.ChildPart];
head = new IkVec(h.X, h.Y, h.Z);
var torso = _look.ParentPart;
left = new IkVec(1f, 0f, 0f).Rotated(parts[torso].Rotation * _plan.Parts[torso].Rotation.Conjugate());
var v = goal - head;
distance = v.Length;
toward = distance > 1e-6f ? v * (1f / distance) : new IkVec(0f, 0f, 1f);
}
if (hasTarget && b.Recoil is { } recoil && _look != null)
{
var s = Ik.Clamp(toward.Dot(left), -1f, 1f);
var depth = (float)recoil.Proximity.Response(distance);
var wl = depth * (1f + s) * 0.5f;
var wr = depth * (1f - s) * 0.5f;
var awayL = recoil.Left;
var awayR = recoil.Right;
for (var m = 0; m < targets.Length; m++)
{
targets[m] = Quat.Nlerp(Quat.Nlerp(targets[m], awayL[m], wl), awayR[m], wr);
}
}
if (hasTarget && b.Look is { } look && _look != null)
{
var t = parts[_look.ParentPart];
_look.Solve(t.Rotation, t.X, t.Y, t.Z, goal.X, goal.Y, goal.Z, out var neck);
targets[_look.Joint] = Toward(targets[_look.Joint], neck, look.Weight);
}
var driveLeft = false;
var driveRight = false;
if (b.Arms is { } arms && (hasTarget || arms.Mode == ArmMode.Present))
{
driveLeft = _left != null && (arms.Side == ArmSide.Left || arms.Side == ArmSide.Both || (arms.Side == ArmSide.Nearer && input.Arm == Side.Left));
driveRight = _right != null && (arms.Side == ArmSide.Right || arms.Side == ArmSide.Both || (arms.Side == ArmSide.Nearer && input.Arm != Side.Left));
if (driveLeft)
{
Drive(_left!, 1f, arms, parts, goal, head, toward, left, targets);
}
if (driveRight)
{
Drive(_right!, -1f, arms, parts, goal, head, toward, left, targets);
}
}
if (!driveLeft && _left != null)
{
Release(_left, targets);
}
if (!driveRight && _right != null)
{
Release(_right, targets);
}
}
private static void Release(ArmChain arm, Span<Quat> targets)
{
arm.Release(targets[arm.ShoulderJoint], targets[arm.ElbowJoint], out var shoulder, out var elbow);
targets[arm.ShoulderJoint] = shoulder;
targets[arm.ElbowJoint] = elbow;
}
// The solution itself at weight 1, a blend toward it below that.
private static Quat Toward(in Quat from, in Quat solution, double weight) => weight >= 1.0 ? solution : Quat.Nlerp(from, solution, (float)weight);
// across: +1 for the left arm (its wrist sits toward the torso's left), -1 for the right.
private void Drive(ArmChain arm, float across, ArmLayer arms, ReadOnlySpan<PartPose> parts, IkVec target, IkVec head, IkVec toward, IkVec left, Span<Quat> targets)
{
IkVec wrist;
switch (arms.Mode)
{
case ArmMode.Reach:
wrist = target;
break;
case ArmMode.WardOff:
wrist = head + toward * arms.Distance + left * (across * arms.Spread);
break;
default:
// Given for the right arm, whose side is -x (forward is +z, left is +x); the left arm mirrors it.
wrist = World(arm.ParentPart, parts, new IkVec(across * -arms.Point.X, arms.Point.Y, arms.Point.Z));
break;
}
var p = parts[arm.ParentPart];
var hand = World(arm.ForearmPart, parts, new IkVec(arm.WristAnchor));
arm.Drive(p.Rotation, p.X, p.Y, p.Z, wrist.X, wrist.Y, wrist.Z, hand.X, hand.Y, hand.Z, targets[arm.ShoulderJoint], targets[arm.ElbowJoint], arms.Weight,
out var shoulder, out var elbow);
targets[arm.ShoulderJoint] = shoulder;
targets[arm.ElbowJoint] = elbow;
}
}
}

134
src/Lodur.Core/PdMuscle.cs Normal file
View file

@ -0,0 +1,134 @@
using System;
namespace Lodur
{
/// <summary>A unit quaternion, x y z w.</summary>
public readonly struct Quat
{
public readonly float X, Y, Z, W;
public Quat(float x, float y, float z, float w)
{
X = x; Y = y; Z = z; W = w;
}
public static Quat Identity => new Quat(0f, 0f, 0f, 1f);
public Quat Conjugate() => new Quat(-X, -Y, -Z, W);
public static Quat operator *(Quat a, Quat b) => new Quat(
a.W * b.X + a.X * b.W + a.Y * b.Z - a.Z * b.Y,
a.W * b.Y - a.X * b.Z + a.Y * b.W + a.Z * b.X,
a.W * b.Z + a.X * b.Y - a.Y * b.X + a.Z * b.W,
a.W * b.W - a.X * b.X - a.Y * b.Y - a.Z * b.Z);
/// <summary>Rotation about <paramref name="x"/>,<paramref name="y"/>,<paramref name="z"/> (a unit axis) by <paramref name="radians"/>.</summary>
public static Quat FromAxisAngle(float x, float y, float z, float radians)
{
var half = 0.5f * radians;
var s = MathF.Sin(half);
return new Quat(x * s, y * s, z * s, MathF.Cos(half));
}
/// <summary>Normalised linear blend from <paramref name="a"/> (t = 0) to <paramref name="b"/> (t = 1), the shorter way round.</summary>
public static Quat Nlerp(in Quat a, in Quat b, float t)
{
var s = a.X * b.X + a.Y * b.Y + a.Z * b.Z + a.W * b.W < 0f ? -1f : 1f;
var x = a.X + t * (s * b.X - a.X);
var y = a.Y + t * (s * b.Y - a.Y);
var z = a.Z + t * (s * b.Z - a.Z);
var w = a.W + t * (s * b.W - a.W);
var inv = 1f / MathF.Sqrt(x * x + y * y + z * z + w * w);
return new Quat(x * inv, y * inv, z * inv, w * inv);
}
/// <summary>Rotates the vector v by this quaternion.</summary>
public void Rotate(float vx, float vy, float vz, out float rx, out float ry, out float rz)
{
// v' = v + 2w(q x v) + 2 q x (q x v)
var tx = 2f * (Y * vz - Z * vy);
var ty = 2f * (Z * vx - X * vz);
var tz = 2f * (X * vy - Y * vx);
rx = vx + W * tx + (Y * tz - Z * ty);
ry = vy + W * ty + (Z * tx - X * tz);
rz = vz + W * tz + (X * ty - Y * tx);
}
}
/// <summary>
/// Gains of one muscle. Swing acts on the joint frame's x and y axes, twist on its z axis (the hinge axis
/// of a hinge, the limb's own axis for a ball joint). They differ because a limb turns about its own axis
/// with a fraction of the inertia it has swinging about its end, and an explicit controller is unstable
/// when damping times the step exceeds that inertia.
/// </summary>
public readonly struct MuscleGains
{
public readonly float SwingStiffness, SwingDamping, TwistStiffness, TwistDamping;
/// <summary>
/// The fraction of damping kept whatever the strength, in [0, 1] (tissue viscosity): a limp joint with Passive 1
/// still resists being swung, with no stiffness. Default 0, where limp is exactly zero torque.
/// </summary>
public readonly float Passive;
public MuscleGains(float swingStiffness, float swingDamping, float twistStiffness, float twistDamping, float passive = 0f)
{
SwingStiffness = swingStiffness; SwingDamping = swingDamping;
TwistStiffness = twistStiffness; TwistDamping = twistDamping;
Passive = passive > 0f ? (passive < 1f ? passive : 1f) : 0f;
}
}
/// <summary>
/// The body layer's muscle: a proportional-derivative law on one joint. It sees only the joint's
/// relative rotation and angular velocity, a target rotation and a strength, and returns a torque;
/// it knows nothing of the physics engine that produced those numbers (invariant body-one-interface).
/// </summary>
public static class PdMuscle
{
/// <summary>
/// Torque on the child, in the parent joint frame, that turns <paramref name="rotation"/> (child frame
/// relative to parent frame) toward <paramref name="target"/> and damps <paramref name="angularVelocity"/>
/// (child minus parent, in the parent frame). Strength scales every gain together, so the
/// damping ratio does not change with it. Damping is scaled by the larger of the strength and
/// <see cref="MuscleGains.Passive"/>, stiffness by the strength alone: strength 0 is a limp joint, exactly zero torque
/// when Passive is 0 and pure damping when it is not.
/// The rotation error takes the shorter way round.
/// </summary>
public static void Torque(
in Quat rotation, float wx, float wy, float wz, in Quat target, in MuscleGains gains, float strength,
out float tx, out float ty, out float tz)
{
var stiff = strength > 0f ? strength : 0f; // negative or NaN strength is limp
var damp = stiff > gains.Passive ? stiff : gains.Passive;
if (damp <= 0f)
{
tx = ty = tz = 0f;
return;
}
// Error rotation in the parent frame that carries the current rotation onto the target.
var e = target * rotation.Conjugate();
if (e.W < 0f)
{
e = new Quat(-e.X, -e.Y, -e.Z, -e.W);
}
var sin = MathF.Sqrt(e.X * e.X + e.Y * e.Y + e.Z * e.Z);
// Rotation vector of the error: angle * axis, with the small-angle limit of 2 * vector part.
var scale = sin < 1e-6f ? 2f : 2f * MathF.Atan2(sin, e.W) / sin;
if (damp == stiff)
{
// The whole law at one strength, in the form every pinned replay was recorded with.
tx = stiff * (gains.SwingStiffness * scale * e.X - gains.SwingDamping * wx);
ty = stiff * (gains.SwingStiffness * scale * e.Y - gains.SwingDamping * wy);
tz = stiff * (gains.TwistStiffness * scale * e.Z - gains.TwistDamping * wz);
return;
}
tx = stiff * gains.SwingStiffness * scale * e.X - damp * gains.SwingDamping * wx;
ty = stiff * gains.SwingStiffness * scale * e.Y - damp * gains.SwingDamping * wy;
tz = stiff * gains.TwistStiffness * scale * e.Z - damp * gains.TwistDamping * wz;
}
}
}

View file

@ -0,0 +1,533 @@
using System;
namespace Lodur
{
/// <summary>
/// A game stimulus: an axis-aligned box volume with an intensity the game writes every tick. Lodur reads
/// it and decides containment and transduction; the box is never a physics body.
/// </summary>
public struct BoxStimulus
{
public float CenterX, CenterY, CenterZ;
public float HalfX, HalfY, HalfZ;
/// <summary>Noxious intensity inside the box, written by the game each tick (0..1 in the slice's scale).</summary>
public double Intensity;
public BoxStimulus(float centerX, float centerY, float centerZ, float halfX, float halfY, float halfZ, double intensity = 0.0)
{
CenterX = centerX; CenterY = centerY; CenterZ = centerZ;
HalfX = halfX; HalfY = halfY; HalfZ = halfZ;
Intensity = intensity;
}
/// <summary>True when the point is inside the box or on one of its faces.</summary>
public bool Contains(float x, float y, float z) =>
MathF.Abs(x - CenterX) <= HalfX && MathF.Abs(y - CenterY) <= HalfY && MathF.Abs(z - CenterZ) <= HalfZ;
}
/// <summary>The sensory channels a point emitter can speak on. Each has its own stimulus, sensitisation and nerve.</summary>
public enum Channel
{
Audio = 0,
Visual = 1,
Interrupt = 2,
}
/// <summary>
/// A game stimulus at a point: sound, flicker, a notification. The game writes its position and intensity every
/// tick; Lodur decides what reaches the sense region. What arrives is the intensity falling off linearly to zero
/// at the radius. With an <see cref="Id"/> it is also a thing the puppet can come to know, remembered as a percept.
/// </summary>
public struct Emitter
{
public Channel Channel;
public float X, Y, Z;
public float Radius;
public double Intensity;
/// <summary>The game's stable id for the thing this emitter belongs to. 0 is anonymous: it loads the nerve and is never a percept. The top bit is reserved (<see cref="Perception.PhantomIdBit"/>); <see cref="Perception.Sense"/> refuses it.</summary>
public ulong Id;
/// <summary>The game's tag for the thing (what kind it is). Lodur carries it and never interprets it; emitters sharing an id must share a kind.</summary>
public uint Kind;
/// <summary>The thing's facts as the game sees them, bit i is fact i. The game owns every bit but <see cref="Perception.InReachFact"/> (63), which <see cref="Perception.Sense"/> refuses; emitters sharing an id must share facts.</summary>
public ulong Facts;
public Emitter(Channel channel, float x, float y, float z, float radius, double intensity = 0.0, ulong id = 0, uint kind = 0, ulong facts = 0)
{
Channel = channel;
X = x; Y = y; Z = z;
Radius = radius;
Intensity = intensity;
Id = id;
Kind = kind;
Facts = facts;
}
/// <summary>Intensity * max(0, 1 - distance / Radius) at the point; zero at and beyond the radius.</summary>
public double Received(float x, float y, float z)
{
double dx = x - X, dy = y - Y, dz = z - Z;
var distance = Math.Sqrt(dx * dx + dy * dy + dz * dz);
return Radius > 0f && distance < Radius ? Intensity * (1.0 - distance / Radius) : 0.0;
}
}
/// <summary>The nerve's tunables, the transduction of any channel, noxious or sensory: threshold, sensitisation under sustained stimulus, conduction delay, and a per-character gain.</summary>
public sealed record NerveParameters
{
public double Threshold { get; init; } = 0.1;
public double SensitisationGrowth { get; init; } = 0.04;
public double SensitisationRecovery { get; init; } = 0.02;
public double SensitisationCap { get; init; } = 2.0;
public double ConductionDelaySeconds { get; init; } = 0.06;
/// <summary>Per-character gain (the consumer draws its trait spread).</summary>
public double Gain { get; init; } = 1.0;
}
/// <summary>The percept memory's tunables.</summary>
public sealed record PerceptParameters
{
/// <summary>How many things can be remembered at once, 1..256.</summary>
public int Capacity { get; init; } = 16;
/// <summary>How long a thing stays remembered after it was last sensed; finite and not negative.</summary>
public double MemorySeconds { get; init; } = 5.0;
public void Validate()
{
if (Capacity < 1 || Capacity > 256)
{
throw new ArgumentException("The percept capacity must be in 1..256.", nameof(Capacity));
}
if (!(MemorySeconds >= 0.0 && MemorySeconds < double.PositiveInfinity))
{
throw new ArgumentException("The percept memory time must be finite and not negative.", nameof(MemorySeconds));
}
}
}
/// <summary>One remembered thing. Id 0 is a free slot. Nothing here says whether the thing is real.</summary>
public readonly struct Percept
{
public ulong Id { get; }
public uint Kind { get; }
/// <summary>The thing's facts as last sensed; a thing changed out of sight keeps its old facts.</summary>
public ulong Facts { get; }
/// <summary>Where the emitter that reached the puppet hardest was, the last tick the thing was sensed.</summary>
public float X { get; }
public float Y { get; }
public float Z { get; }
/// <summary>The largest intensity received among the thing's emitters times the sensory gain; 0 on a tick it is not sensed.</summary>
public double Salience { get; }
/// <summary>0 on a tick the thing is sensed.</summary>
public double SecondsSinceSensed { get; }
public Percept(ulong id, uint kind, float x, float y, float z, double salience, double secondsSinceSensed, ulong facts = 0)
{
Id = id; Kind = kind; Facts = facts; X = x; Y = y; Z = z; Salience = salience; SecondsSinceSensed = secondsSinceSensed;
}
}
/// <summary>
/// Layer 1 for one character, a fixed number of body regions. Each tick it takes one point per region and the
/// game's stimulus sources and produces, per region, the stimulus there and the afferent signal after
/// threshold, sensitisation and conduction delay. With a sensory nerve it also senses point emitters at one
/// region on three channels and combines the channels into one load and remembers the identified things it senses in a bounded slot table. Everything is allocated in the constructor.
/// </summary>
public sealed class Perception
{
private readonly NerveParameters _p;
private readonly double _dt;
private readonly int _regions;
private readonly int _slots;
private readonly double[] _ring; // afferent signal in flight along the nerve, region-major
private readonly double[] _sens;
private readonly double[] _stimulus;
private readonly double[] _afferent;
private readonly NerveParameters? _senses;
private readonly int _senseRegion;
private readonly int _senseSlots;
private readonly double[] _senseRing; // afferent in flight per channel, channel-major
private readonly double[] _senseSens = new double[ChannelCount];
private readonly double[] _senseStimulus = new double[ChannelCount];
private readonly double[] _senseAfferent = new double[ChannelCount];
private readonly double _memorySeconds;
private readonly ulong[] _pId; // percept slots; id 0 is free
private readonly uint[] _pKind;
private readonly ulong[] _pFacts;
private readonly float[] _pX, _pY, _pZ;
private readonly double[] _pSalience;
private readonly double[] _pSince;
private readonly bool[] _pSensed; // sensed this tick
private long _tick;
private const int ChannelCount = 3;
/// <summary>The top bit of an emitter id, reserved to Lodur's phantoms; <see cref="Sense"/> refuses a caller emitter that sets it.</summary>
public const ulong PhantomIdBit = 1UL << 63;
/// <summary>The top fact bit, Lodur's own: whether the thing is within reach. The planner is its only writer, deriving it per call from distance; <see cref="Sense"/> refuses an emitter that sets it.</summary>
public const ulong InReachFact = 1UL << 63;
/// <param name="senses">The nerve of the sensory channels; null for a body with no senses (the load stays zero).</param>
/// <param name="senseRegion">The region whose point the emitters are sensed at.</param>
public Perception(NerveParameters parameters, double tickSeconds, int regionCount, NerveParameters? senses = null, int senseRegion = 0, PerceptParameters? percepts = null)
{
_p = parameters;
_dt = tickSeconds;
_regions = regionCount;
var delayTicks = (int)Math.Round(parameters.ConductionDelaySeconds / tickSeconds);
_slots = Math.Max(1, delayTicks);
_ring = new double[regionCount * _slots];
_sens = new double[regionCount];
Array.Fill(_sens, 1.0);
_stimulus = new double[regionCount];
_afferent = new double[regionCount];
_senses = senses;
_senseRegion = senseRegion;
if (senses != null)
{
if ((uint)senseRegion >= (uint)regionCount)
{
throw new ArgumentOutOfRangeException(nameof(senseRegion), $"The sense region must be one of {regionCount} regions.");
}
_senseSlots = Math.Max(1, (int)Math.Round(senses.ConductionDelaySeconds / tickSeconds));
_senseRing = new double[ChannelCount * _senseSlots];
Array.Fill(_senseSens, 1.0);
var pp = percepts ?? new PerceptParameters();
pp.Validate();
_memorySeconds = pp.MemorySeconds;
_pId = new ulong[pp.Capacity];
_pKind = new uint[pp.Capacity];
_pFacts = new ulong[pp.Capacity];
_pX = new float[pp.Capacity];
_pY = new float[pp.Capacity];
_pZ = new float[pp.Capacity];
_pSalience = new double[pp.Capacity];
_pSince = new double[pp.Capacity];
_pSensed = new bool[pp.Capacity];
}
else
{
_senseRing = Array.Empty<double>();
_pId = Array.Empty<ulong>();
_pKind = Array.Empty<uint>();
_pFacts = Array.Empty<ulong>();
_pX = _pY = _pZ = Array.Empty<float>();
_pSalience = _pSince = Array.Empty<double>();
_pSensed = Array.Empty<bool>();
}
}
public int RegionCount => _regions;
/// <summary>The stimulus at the region's point this tick: the largest intensity among the boxes containing it.</summary>
public double Stimulus(int region) => _stimulus[region];
/// <summary>The afferent signal arriving this tick: what the nerve took in a conduction delay ago.</summary>
public double Afferent(int region) => _afferent[region];
/// <summary>The sensory signals combined: 1 - the product over channels of (1 - afferent, capped at 1), the afferents being the gated ones (see <see cref="ChannelAfferent"/>). Zero with no senses or no emitters.</summary>
public double Load { get; private set; }
/// <summary>The largest intensity of the channel's emitters at the sense region's point this tick.</summary>
public double ChannelStimulus(Channel channel) => _senseStimulus[(int)channel];
/// <summary>
/// The channel's afferent arriving this tick, after threshold, sensitisation and conduction delay, times the sensory gain
/// <see cref="Sense"/> was given (lodur:ruling:stress-bar-shows-arousal-calm-silences). <see cref="ChannelStimulus"/> stays the world's.
/// </summary>
public double ChannelAfferent(Channel channel) => _senseAfferent[(int)channel];
/// <summary>The region whose point the senses are sensed at.</summary>
public int SenseRegion => _senseRegion;
/// <summary>The number of percept slots: the capacity, or 0 with no senses. A slot is free when its percept's id is 0.</summary>
public int PerceptCount => _pId.Length;
/// <summary>The percept in the slot. A thing keeps its slot while it is remembered; a free slot reads as Id 0.</summary>
public Percept Percept(int slot) =>
new Percept(_pId[slot], _pKind[slot], _pX[slot], _pY[slot], _pZ[slot], _pSalience[slot], _pSince[slot], _pFacts[slot]);
// The planner reads every slot each call; a Percept per slot would copy fields it never looks at.
internal ReadOnlySpan<ulong> PerceptIds => _pId;
internal ReadOnlySpan<uint> PerceptKinds => _pKind;
internal ReadOnlySpan<ulong> PerceptFacts => _pFacts;
internal ReadOnlySpan<float> PerceptX => _pX;
internal ReadOnlySpan<float> PerceptY => _pY;
internal ReadOnlySpan<float> PerceptZ => _pZ;
/// <summary>
/// Senses once per physics step. The spans are the caller's, one point per region. The sensory gain (default 1, the identity) multiplies the sense
/// channels' afferents as they leave the conduction delay, so a change of gain reaches <see cref="Load"/> on the next call it is passed to; the nociceptive region
/// afferents are never gated. A gain outside [0, 1] (NaN and infinity included) is refused,
/// as is an emitter that sets <see cref="PhantomIdBit"/> or <see cref="InReachFact"/> and two emitters of one id with different kinds or facts.
/// </summary>
public void Sense(ReadOnlySpan<float> x, ReadOnlySpan<float> y, ReadOnlySpan<float> z, ReadOnlySpan<BoxStimulus> sources,
ReadOnlySpan<Emitter> emitters = default, double sensoryGain = 1.0)
{
if (x.Length != _regions || y.Length != _regions || z.Length != _regions)
{
throw new ArgumentException($"x, y and z need {_regions} entries, one per region.");
}
if (!(sensoryGain >= 0.0 && sensoryGain <= 1.0))
{
throw new ArgumentException("The sensory gain must be in [0, 1].", nameof(sensoryGain));
}
if (_senses != null)
{
// Refused before any state steps, so a bad emitter leaves the tick unrun.
for (var i = 0; i < emitters.Length; i++)
{
if ((uint)emitters[i].Channel >= ChannelCount)
{
throw new ArgumentException($"Emitter {i} has channel {(int)emitters[i].Channel}; the channels are Audio, Visual and Interrupt.", nameof(emitters));
}
var id = emitters[i].Id;
if ((id & PhantomIdBit) != 0)
{
throw new ArgumentException($"Emitter {i} sets the phantom id bit, which is reserved to Lodur.", nameof(emitters));
}
if ((emitters[i].Facts & InReachFact) != 0)
{
throw new ArgumentException($"Emitter {i} sets the in-reach fact bit, which is reserved to Lodur.", nameof(emitters));
}
if (id != 0)
{
for (var j = 0; j < i; j++)
{
if (emitters[j].Id == id && emitters[j].Kind != emitters[i].Kind)
{
throw new ArgumentException($"Emitters {j} and {i} share id {id} with different kinds.", nameof(emitters));
}
if (emitters[j].Id == id && emitters[j].Facts != emitters[i].Facts)
{
throw new ArgumentException($"Emitters {j} and {i} share id {id} with different facts.", nameof(emitters));
}
}
}
}
}
var slot = (int)(_tick % _slots);
for (var r = 0; r < _regions; r++)
{
var stimulus = 0.0;
for (var i = 0; i < sources.Length; i++)
{
if (sources[i].Intensity > stimulus && sources[i].Contains(x[r], y[r], z[r]))
{
stimulus = sources[i].Intensity;
}
}
// Nociceptor: threshold, then sensitisation, then conduction delay.
var above = Math.Max(0.0, stimulus - _p.Threshold);
var sens = _sens[r] + _dt * (_p.SensitisationGrowth * above - _p.SensitisationRecovery * (_sens[r] - 1.0));
sens = Math.Min(Math.Max(sens, 1.0), _p.SensitisationCap);
_sens[r] = sens;
var ring = r * _slots + slot;
_afferent[r] = _ring[ring]; // written one conduction delay ago
_ring[ring] = above * sens * _p.Gain;
_stimulus[r] = stimulus;
}
if (_senses != null)
{
SenseEmitters(x[_senseRegion], y[_senseRegion], z[_senseRegion], emitters, sensoryGain);
}
_tick++;
}
private void SenseEmitters(float x, float y, float z, ReadOnlySpan<Emitter> emitters, double gain)
{
var senses = _senses!;
var slot = (int)(_tick % _senseSlots);
Array.Clear(_senseStimulus, 0, ChannelCount);
for (var i = 0; i < emitters.Length; i++)
{
var c = (int)emitters[i].Channel;
var received = emitters[i].Received(x, y, z);
if (received > _senseStimulus[c])
{
_senseStimulus[c] = received;
}
}
var quiet = 1.0;
for (var c = 0; c < ChannelCount; c++)
{
var above = Math.Max(0.0, _senseStimulus[c] - senses.Threshold);
var sens = _senseSens[c] + _dt * (senses.SensitisationGrowth * above - senses.SensitisationRecovery * (_senseSens[c] - 1.0));
sens = Math.Min(Math.Max(sens, 1.0), senses.SensitisationCap);
_senseSens[c] = sens;
var ring = c * _senseSlots + slot;
// Written one conduction delay ago; the gate sits after the ring, so sensitisation still follows the world.
_senseAfferent[c] = _senseRing[ring] * gain;
_senseRing[ring] = above * sens * senses.Gain;
quiet *= 1.0 - Math.Min(1.0, _senseAfferent[c]);
}
Load = 1.0 - quiet;
SensePercepts(x, y, z, emitters, gain);
}
// A thing is sensed when it has an id, the gain is above zero and the sense point is strictly inside the emitter's radius.
private void SensePercepts(float x, float y, float z, ReadOnlySpan<Emitter> emitters, double gain)
{
for (var s = 0; s < _pId.Length; s++)
{
if (_pId[s] == 0)
{
continue;
}
_pSensed[s] = false;
_pSalience[s] = 0.0;
_pSince[s] += _dt;
}
if (gain > 0.0)
{
// Things already remembered first, so a newcomer can never evict one that is sensed this tick.
for (var i = 0; i < emitters.Length; i++)
{
var slot = Reaches(emitters[i], x, y, z) ? SlotOf(emitters[i].Id) : -1;
if (slot >= 0)
{
Touch(slot, emitters[i], x, y, z, gain);
}
}
}
for (var s = 0; s < _pId.Length; s++)
{
if (_pId[s] != 0 && !_pSensed[s] && _pSince[s] > _memorySeconds)
{
_pId[s] = 0;
_pKind[s] = 0;
_pFacts[s] = 0;
_pX[s] = 0f; _pY[s] = 0f; _pZ[s] = 0f;
_pSalience[s] = 0.0;
_pSince[s] = 0.0;
}
}
if (gain > 0.0)
{
for (var i = 0; i < emitters.Length; i++)
{
if (!Reaches(emitters[i], x, y, z))
{
continue;
}
var slot = SlotOf(emitters[i].Id);
if (slot < 0)
{
slot = Admit(emitters[i].Id, emitters[i].Kind);
}
if (slot >= 0)
{
Touch(slot, emitters[i], x, y, z, gain);
}
}
}
}
private static bool Reaches(in Emitter e, float x, float y, float z)
{
if (e.Id == 0 || !(e.Radius > 0f))
{
return false;
}
double dx = x - e.X, dy = y - e.Y, dz = z - e.Z;
return Math.Sqrt(dx * dx + dy * dy + dz * dz) < e.Radius;
}
private int SlotOf(ulong id)
{
for (var s = 0; s < _pId.Length; s++)
{
if (_pId[s] == id)
{
return s;
}
}
return -1;
}
// The lowest free slot, else the unsensed slot longest unsensed (ties lowest slot); -1 when every slot was sensed this tick.
private int Admit(ulong id, uint kind)
{
var slot = -1;
for (var s = 0; s < _pId.Length; s++)
{
if (_pId[s] == 0)
{
slot = s;
break;
}
}
if (slot < 0)
{
for (var s = 0; s < _pId.Length; s++)
{
if (!_pSensed[s] && (slot < 0 || _pSince[s] > _pSince[slot]))
{
slot = s;
}
}
}
if (slot >= 0)
{
_pId[slot] = id;
_pKind[slot] = kind;
_pFacts[slot] = 0;
_pSensed[slot] = false;
_pSalience[slot] = 0.0;
_pSince[slot] = 0.0;
}
return slot;
}
// The first emitter of the tick fills the slot; a later one replaces it only by reaching him strictly harder.
private void Touch(int slot, in Emitter e, float x, float y, float z, double gain)
{
var salience = e.Received(x, y, z) * gain;
if (!_pSensed[slot] || salience > _pSalience[slot])
{
_pX[slot] = e.X; _pY[slot] = e.Y; _pZ[slot] = e.Z;
_pSalience[slot] = salience;
}
_pKind[slot] = e.Kind;
_pFacts[slot] = e.Facts;
_pSensed[slot] = true;
_pSince[slot] = 0.0;
}
}
}

View file

@ -0,0 +1,543 @@
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
namespace Lodur
{
/// <summary>Why a body died; the first rule that held at the end of the step that killed it (ruling bds-death).</summary>
public enum DeathCause { None, VitalTissue, BloodLoss, Consciousness }
/// <summary>
/// The liquid at a body's airway openings this step, as the caller measures it: the live liquid and the pooled liquid, each a non-negative amount
/// summed over the openings, and Drop in m, at least 0: how far the lowest opening's rim lies below the deepest point liquid pools at inside the airway, 0 when none lies below.
/// The default is nothing at the airway.
/// </summary>
public readonly record struct AirwaySample(double Live, double Pooled, double Drop)
{
/// <summary>One entry per opening: Live and Pooled summed, Drop the largest of the openings' signed drops, floored at 0 (0 with no opening).</summary>
public static AirwaySample Of(ReadOnlySpan<float> live, ReadOnlySpan<float> pooled, ReadOnlySpan<float> drop)
{
double l = 0.0, p = 0.0, f = 0.0;
for (var i = 0; i < live.Length; i++) l += live[i];
for (var i = 0; i < pooled.Length; i++) p += pooled[i];
for (var i = 0; i < drop.Length; i++) f = Math.Max(f, drop[i]);
return new AirwaySample(l, p, f);
}
}
/// <summary>
/// What the stepping Actor reports each step. Arousal is the sensory load carried over time and Effort the mean strength the muscles actually applied last tick,
/// after each joint's motor ceiling (the Actor reports it so, not what the behaviour asked), each in [0, 1]. BreathHeld is whether the breath is held this step
/// (decided by the Actor on the tick before); Airway is what the caller finds at the airway. The default is rest, breathing freely, nothing at the airway.
/// </summary>
public readonly record struct PhysiologyInput(double Arousal, double Effort, bool BreathHeld = false, AirwaySample Airway = default);
/// <summary>
/// The body's physiology: tissue integrity, bound afflictions, blood and its oxygen, the capacities they fold into, the motor ceiling and death.
/// Harm enters only through <see cref="Afflict"/>; time through <see cref="Step"/>. Integrity is derived from the severities of the
/// Injures afflictions bound to a tissue (part HP is never stored), and capacities, bleed and the motor ceiling are recomputed each step;
/// nobody writes them. A bleed leaves the circulation once, through the part's surface (<see cref="Bleed"/>) or into the airway (<see cref="AirwayBleed"/>), split by each tissue's <see cref="TissueDef.AirwayShare"/>; the gases are integrated by Step and nobody writes those either. Content owns every label and number (<see cref="PhysiologyPlan"/>). Everything is allocated in the constructor.
/// </summary>
public sealed class Physiology
{
private readonly BodyPlan _body;
private readonly double _slowScale;
private readonly double _nominal;
private readonly double _lethalLoss;
private readonly double _regen;
private readonly AfflictionDef[] _defs;
private readonly Effect[] _organism;
private readonly int[] _partStart; // first tissue of each part in the flattened tissues; one past the last at [parts]
private readonly TissueDef[] _tissues;
private readonly double[] _injury;
private readonly double[] _integrity;
private readonly double[] _capacityWeight; // per capacity, indexed by EffectTarget (Consciousness, BloodPumping, Breathing)
private readonly RespirationDef _respiration;
private readonly AirwayDef _airway;
private readonly double[] _drivers; // the organism's driver values as the step began, indexed by EffectDriver
private readonly double[] _motorWeight; // per part
private readonly int[] _slotDef; // -1: free
private readonly int[] _slotPart;
private readonly int[] _slotTissue; // flattened
private readonly double[] _slotSeverity;
private readonly double[] _slotAge;
private readonly double[] _bleed; // per part, m^3/s, through the surface
private readonly double _bloodGain;
private double _airwayBleed; // m^3/s into the airway
private readonly double[] _motor; // per joint
private double _volume;
private double _consciousness;
private double _pumping = 1.0;
private double _breathing = 1.0;
private double _bloodOxygen = 1.0;
private double _brainOxygen = 1.0;
private double _airwayLiquid;
private double _occlusion;
private double _carbonDioxide;
private double _urge;
private double _coughed;
private double _drained;
private double _drawnLive;
private double _drawnPooled;
private bool _atAirway;
private long _steps;
private bool _bound;
/// <param name="bloodGain">The world's liquid volume per m^3 of blood, owned by the caller: blood bled into the airway enters it at this multiple of its real volume. Finite and above 0.</param>
public Physiology(BodyPlan body, PhysiologyPlan plan, double slowScale, double bloodGain = 1.0)
{
if (!(slowScale > 0.0 && !double.IsInfinity(slowScale))) throw new ArgumentException("the slow scale must be finite and above 0.");
if (!(bloodGain > 0.0 && !double.IsInfinity(bloodGain))) throw new ArgumentException("the blood gain must be finite and above 0.");
_bloodGain = bloodGain;
_body = body;
_slowScale = slowScale;
_nominal = plan.Blood.NominalVolume;
_lethalLoss = plan.Blood.LethalLossFraction;
_regen = plan.Blood.RegenPerSecond;
_respiration = plan.Respiration;
_airway = plan.Airway;
_volume = _nominal;
_capacityWeight = new double[CapacityCount];
_drivers = new double[Enum.GetValues(typeof(EffectDriver)).Length];
_defs = new AfflictionDef[plan.Afflictions.Count];
for (var i = 0; i < _defs.Length; i++) _defs[i] = plan.Afflictions[i];
_organism = new Effect[plan.OrganismEffects.Count];
for (var i = 0; i < _organism.Length; i++) _organism[i] = plan.OrganismEffects[i];
var parts = body.Parts.Count;
var stackOf = plan.Resolve(body);
_partStart = new int[parts + 1];
var total = 0;
for (var p = 0; p < parts; p++)
{
_partStart[p] = total;
total += plan.Parts[stackOf[p]].Tissues.Count;
}
_partStart[parts] = total;
_tissues = new TissueDef[total];
_injury = new double[total];
_integrity = new double[total];
_motorWeight = new double[parts];
for (var p = 0; p < parts; p++)
{
var stack = plan.Parts[stackOf[p]].Tissues;
for (var l = 0; l < stack.Count; l++)
{
var t = stack[l];
_tissues[_partStart[p] + l] = t;
_integrity[_partStart[p] + l] = 1.0;
_capacityWeight[(int)EffectTarget.Consciousness] += t.Consciousness;
_capacityWeight[(int)EffectTarget.BloodPumping] += t.BloodPumping;
_capacityWeight[(int)EffectTarget.Breathing] += t.Breathing;
_motorWeight[p] += t.Motor;
}
}
if (!(_capacityWeight[(int)EffectTarget.Consciousness] > 0.0)) throw new ArgumentException("no tissue carries consciousness.");
_motor = new double[body.Joints.Count];
for (var j = 0; j < _motor.Length; j++)
{
if (!(_motorWeight[body.Joints[j].Child] > 0.0))
{
throw new ArgumentException($"the part below joint '{body.Joints[j].Label}' {body.Joints[j].Side} has no motor tissue.");
}
_motor[j] = 1.0;
}
_consciousness = 1.0;
_bleed = new double[parts];
var slots = plan.AfflictionSlots;
_slotDef = new int[slots];
_slotPart = new int[slots];
_slotTissue = new int[slots];
_slotSeverity = new double[slots];
_slotAge = new double[slots];
for (var s = 0; s < slots; s++) _slotDef[s] = -1;
}
public int JointCount => _motor.Length;
/// <summary>Blood volume in m^3; starts at the nominal volume.</summary>
public double BloodVolume => _volume;
/// <summary>The fraction of the lethal loss lost so far: 0 at nominal volume, 1 where the blood kills. Derived from the volume.</summary>
public double BloodLoss => (1.0 - _volume / _nominal) / _lethalLoss;
public bool Dead { get; private set; }
public DeathCause Cause { get; private set; }
/// <summary>The ordinal (from 0) of the <see cref="Step"/> that killed, -1 while alive.</summary>
public long DiedAtStep { get; private set; } = -1;
/// <summary>Afflictions refused because the table lacked room; a span call refused counts once.</summary>
public int Refused { get; private set; }
/// <summary>Wakefulness, 0..1; 0 once dead.</summary>
public double Consciousness => Dead ? 0.0 : _consciousness;
/// <summary>The heart's capacity to drive what bleeds, 0..1; 0 once dead.</summary>
public double BloodPumping => Dead ? 0.0 : _pumping;
/// <summary>The lungs' capacity to ventilate, 0..1; 0 once dead. An empty Breathing weight reads 1, as BloodPumping does.</summary>
public double Breathing => Dead ? 0.0 : _breathing;
/// <summary>The blood's oxygen store, 0..1, starting full; integrated by <see cref="Step"/>.</summary>
public double BloodOxygen => _bloodOxygen;
/// <summary>The brain's oxygen, 0..1, starting full: it relaxes toward what the pumping delivers from the blood store. Content turns it into consciousness.</summary>
public double BrainOxygen => _brainOxygen;
/// <summary>The liquid in the airway in m^3, 0 to the airway's capacity; integrated by <see cref="Step"/>.</summary>
public double AirwayLiquid => _airwayLiquid;
/// <summary>The fraction of the airway the liquid fills, 0..1; it takes that share of the ventilation. Derived from the liquid each step.</summary>
public double Occlusion => _occlusion;
/// <summary>Carbon dioxide, 0 at rest and about 1 at the break point; it rises with the load that uses oxygen and is blown off by ventilation.</summary>
public double CarbonDioxide => _carbonDioxide;
/// <summary>Air hunger, 0..1: the larger of the carbon dioxide urge and the ventilation deficit urge as the last step computed them; 0 once dead. The Actor carries it to the drive.</summary>
public double BreathUrge => Dead ? 0.0 : _urge;
/// <summary>True when the liquid at the airway the last step was sampled was at least the airway's HoldAt: the Actor holds the breath while it is.</summary>
public bool LiquidAtAirway => _atAirway;
/// <summary>The liquid in world m^3 the last step coughed out of the airway.</summary>
public double Coughed => _coughed;
/// <summary>The liquid in world m^3 the last step drained out of the airway (by gravity through the mouth), including what a full airway spilled.</summary>
public double Drained => _drained;
/// <summary>The liquid in world m^3 the last step drew into the airway from the live liquid at the openings, after the room-left clip; 0 for a held breath, and after a Step on a dead physiology.</summary>
public double DrawnLive => _drawnLive;
/// <summary>The liquid in world m^3 the last step drew into the airway from the pooled liquid at the openings, after the room-left clip; 0 for a held breath, and after a Step on a dead physiology.</summary>
public double DrawnPooled => _drawnPooled;
/// <summary>The tissue's remaining fraction, 0..1, as of the last step.</summary>
public double Integrity(int part, int layer) => _integrity[Flat(part, layer)];
/// <summary>The blood lost through the part's surface in real m^3/s over the last Step that ran, the dying step included; 0 after a Step on a dead physiology.</summary>
public double Bleed(int part) => _bleed[part];
/// <summary>The blood bled into the airway in real m^3/s over the last Step that ran (same lifetime as <see cref="Bleed"/>); it enters the airway at the blood gain.</summary>
public double AirwayBleed => _airwayBleed;
/// <summary>The ceiling on a joint's muscle strength, 0..1: its capacity times consciousness; 0 once dead.</summary>
public double MotorCeiling(int joint) => Dead ? 0.0 : _motor[joint];
/// <summary>The layer of the part's stack with this label (the layer index <see cref="Afflict"/> and <see cref="Integrity"/> take).</summary>
public int TissueIndex(int part, string label)
{
for (var i = _partStart[part]; i < _partStart[part + 1]; i++)
{
if (_tissues[i].Label == label) return i - _partStart[part];
}
throw new ArgumentException($"part {part} has no tissue labelled '{label}'.");
}
internal int SlotCount => _slotDef.Length;
internal int SlotDef(int slot) => _slotDef[slot];
internal double SlotSeverity(int slot) => _slotSeverity[slot];
internal double SlotAge(int slot) => _slotAge[slot];
/// <summary>Set by the Actor that steps this physiology; one Actor steps one physiology until lodur-grafting moves stepping to the organism.</summary>
internal bool TryBind()
{
if (_bound) return false;
_bound = true;
return true;
}
private int Flat(int part, int layer)
{
if ((uint)part >= (uint)_bleed.Length) throw new ArgumentException("not a part.");
var i = _partStart[part] + layer;
if (layer < 0 || i >= _partStart[part + 1]) throw new ArgumentException("not a layer of the part.");
return i;
}
/// <summary>
/// Binds a new instance of the affliction to a tissue, never merged with another. Returns false, counting a refusal and
/// overwriting nothing, when the table is full. Allowed while dead: it records the wound and nothing steps.
/// </summary>
public bool Afflict(int affliction, int part, int layer, double severity) =>
Afflict(affliction, part, MemoryMarshal.CreateReadOnlySpan(ref layer, 1), severity);
/// <summary>
/// A wound of several layers of one part, all or none: binds one new instance of the affliction per layer, in span order into
/// the lowest free slots, and returns true; with fewer free slots than layers it writes nothing, counts one refusal and returns
/// false. The affliction, severity and every layer are validated before anything is written; an empty span or a layer named
/// twice throws. Allowed while dead, as the single-layer call.
/// </summary>
public bool Afflict(int affliction, int part, ReadOnlySpan<int> layers, double severity)
{
if ((uint)affliction >= (uint)_defs.Length) throw new ArgumentException("not an affliction.");
if (layers.Length == 0) throw new ArgumentException("a wound needs at least one layer.");
if (!(severity > 0.0 && !double.IsInfinity(severity))) throw new ArgumentException("severity must be finite and above 0.");
for (var i = 0; i < layers.Length; i++)
{
Flat(part, layers[i]);
for (var j = 0; j < i; j++)
if (layers[j] == layers[i]) throw new ArgumentException("a layer is named twice.");
}
var free = 0;
for (var s = 0; s < _slotDef.Length; s++)
if (_slotDef[s] < 0) free++;
if (free < layers.Length)
{
Refused++;
return false;
}
var slot = 0;
for (var i = 0; i < layers.Length; i++)
{
while (_slotDef[slot] >= 0) slot++;
_slotDef[slot] = affliction;
_slotPart[slot] = part;
_slotTissue[slot] = Flat(part, layers[i]);
_slotSeverity[slot] = severity;
_slotAge[slot] = 0.0;
}
return true;
}
/// <summary>
/// Advances by dt seconds of the caller's clock: afflictions age and change severity (healed ones free their slot), integrity,
/// capacities, bleeding and regrowth follow, then the airway and the gases on the Acute clock, the motor ceilings, and death is judged once. Bleeding is computed before the airway.
/// A dead physiology does not change, except that its flows (Bleed, AirwayBleed, Coughed, Drained, DrawnLive, DrawnPooled) read 0 after a Step on it. A non-finite input, or one outside [0, 1], is refused before anything changes.
/// </summary>
public void Step(double dt, in PhysiologyInput input = default)
{
if (!(input.Arousal >= 0.0 && input.Arousal <= 1.0 && input.Effort >= 0.0 && input.Effort <= 1.0))
{
throw new ArgumentException("the input's arousal and effort must be finite and in [0, 1].");
}
var air = input.Airway;
if (!(air.Live >= 0.0 && air.Live < double.PositiveInfinity && air.Pooled >= 0.0 && air.Pooled < double.PositiveInfinity && air.Drop >= 0.0 && air.Drop < double.PositiveInfinity))
{
throw new ArgumentException("the airway sample's liquid must be finite and not negative and its drop finite and not negative.");
}
if (Dead)
{
Array.Clear(_bleed, 0, _bleed.Length);
_airwayBleed = 0.0;
_coughed = 0.0;
_drained = 0.0;
_drawnLive = 0.0;
_drawnPooled = 0.0;
return;
}
var slowDt = dt * _slowScale;
// 1. Each live affliction on its own clock.
for (var s = 0; s < _slotDef.Length; s++)
{
if (_slotDef[s] < 0) continue;
var def = _defs[_slotDef[s]];
var c = def.Clock == PhysiologyClock.Acute ? dt : slowDt;
_slotAge[s] += c;
_slotSeverity[s] += def.SeverityRate * c;
if (_slotSeverity[s] <= 0.0) _slotDef[s] = -1;
}
// 2. Integrity from the severities of the Injures afflictions.
Array.Clear(_injury, 0, _injury.Length);
for (var s = 0; s < _slotDef.Length; s++)
{
if (_slotDef[s] >= 0 && _defs[_slotDef[s]].Injures) _injury[_slotTissue[s]] += _slotSeverity[s];
}
for (var i = 0; i < _integrity.Length; i++) _integrity[i] = Clamp01(1.0 - _injury[i] / _tissues[i].Hp);
// 3. Capacities: the weighted mean integrity, then every effect's offsets, then its factors. The blood loss and brain oxygen they read are the values the step began with.
_drivers[(int)EffectDriver.BloodLoss] = BloodLoss;
_drivers[(int)EffectDriver.BrainOxygen] = _brainOxygen;
_consciousness = Capacity(EffectTarget.Consciousness);
_pumping = Capacity(EffectTarget.BloodPumping);
_breathing = Capacity(EffectTarget.Breathing);
// 4. Bleeding: each affliction's bleed effects, through its tissue's vascularity and the pumping; the tissue's airway share enters the airway, the rest leaves through the part's surface.
Array.Clear(_bleed, 0, _bleed.Length);
var totalBleed = 0.0;
var internalBleed = 0.0;
for (var s = 0; s < _slotDef.Length; s++)
{
if (_slotDef[s] < 0) continue;
double offset = 0.0, factor = 1.0;
Fold(_defs[_slotDef[s]].Effects, EffectTarget.Bleed, _slotSeverity[s], _slotAge[s], ref offset, ref factor);
var tissue = _tissues[_slotTissue[s]];
var rate = Math.Max(0.0, offset * factor) * tissue.Vascularity * _pumping;
_bleed[_slotPart[s]] += rate * (1.0 - tissue.AirwayShare);
internalBleed += rate * tissue.AirwayShare;
totalBleed += rate;
}
_airwayBleed = internalBleed;
_volume -= totalBleed * dt;
// 4b. The airway, a quantity (not particles): liquid at the openings is drawn in by a free breath, never by a held one, and only into the room left; blood bled into it enters at the
// blood gain whether or not the breath is held; a cough clears it by this step's consciousness, and it drains by gravity through the mouth. What a full airway cannot hold of the bled blood
// spills through the mouth. What a step removes is reported as Coughed and Drained, and what a breath drew as DrawnLive and DrawnPooled; occlusion takes its share of the ventilation below.
var held = input.BreathHeld;
var aw = _airway;
var at = aw.LiveWeight * air.Live + aw.PooledWeight * air.Pooled;
_atAirway = at > 0.0 && at >= aw.HoldAt;
var inflow = held ? 0.0 : aw.DrawPerSecond * _breathing * at;
var cough = aw.CoughPerSecond * Effect.EvalCurve(aw.CoughByConsciousness, _consciousness);
var drain = aw.DrainPerSecond * Clamp01(air.Drop / aw.DrainDrop);
var total = cough + drain;
var bled = dt * _bloodGain * _airwayBleed;
var drawRaw = dt * inflow;
var avail = _airwayLiquid + bled + drawRaw;
var want = dt * total * _airwayLiquid;
var removed = want < avail ? want : avail;
var after = avail - removed;
// Only bled blood overflows: a breath draws into the room left, so the spill is what the airway held plus what bled in, less what left, above capacity (after - capacity - drawRaw, ordered so a full airway with no bleed spills exactly 0).
var spill = Math.Max(0.0, _airwayLiquid + bled - removed - aw.Capacity);
// Coughed is capped at removed: for a cough that is not a power of two removed x cough / total can exceed removed by an ulp, and Drained (removed - Coughed + spill) would read a negative, which no consumer can take.
_coughed = total > 0.0 ? Math.Min(removed, removed * cough / total) : 0.0;
_drained = removed - _coughed + spill;
// What the breath really drew: the draw clipped to the room left after what the airway held, bled in and lost (a full airway with nothing removed leaves exactly 0), split by the sample's weighted shares.
var drawn = Math.Max(0.0, Math.Min(drawRaw, aw.Capacity - (_airwayLiquid + bled - removed)));
_drawnLive = at > 0.0 ? drawn * (aw.LiveWeight * air.Live / at) : 0.0;
_drawnPooled = at > 0.0 ? drawn * (aw.PooledWeight * air.Pooled / at) : 0.0;
_airwayLiquid = Math.Min(aw.Capacity, after);
_occlusion = Clamp01(_airwayLiquid / aw.Capacity);
// 5. Regrowth, on the slow clock, only while nothing bleeds.
if (totalBleed == 0.0)
{
_volume = Math.Min(_nominal, _volume + _regen * _nominal * slowDt);
}
// 6. The gases, on the Acute clock (ruling bds-asphyxia-real-time): the blood store refills by ventilation and is used by exertion;
// the brain relaxes toward what the pumping delivers. Placeholder constants live in content (RespirationDef).
var r = _respiration;
var load = 1.0 + r.ArousalUse * input.Arousal + r.EffortUse * input.Effort;
var use = r.BasalUsePerSecond * load;
var ventilation = held ? 0.0 : _breathing * (1.0 - _occlusion);
_bloodOxygen = Clamp01(_bloodOxygen + dt * (r.UptakePerSecond * ventilation * (1.0 - _bloodOxygen) - use));
_carbonDioxide = Math.Max(0.0, _carbonDioxide + dt * (r.CarbonDioxideRise * load - r.CarbonDioxideClear * ventilation * _carbonDioxide));
// Air hunger: carbon dioxide, or a breath tried and not got (neuroventilatory dissociation, felt at once); a held breath is not tried, so its urge is carbon dioxide alone.
var deficit = held ? 0.0 : 1.0 - _breathing * (1.0 - _occlusion);
_urge = Math.Max(Effect.EvalCurve(r.UrgeByCarbonDioxide, _carbonDioxide), Effect.EvalCurve(r.UrgeByVentilationDeficit, deficit));
_brainOxygen = Clamp01(_brainOxygen + (_pumping * _bloodOxygen - _brainOxygen) * (1.0 - Math.Exp(-dt / r.BrainSeconds)));
// 7. Motor ceilings: the child part's motor-weighted integrity, folded with its live afflictions' motor effects, times consciousness.
for (var j = 0; j < _motor.Length; j++)
{
var part = _body.Joints[j].Child;
var mean = 0.0;
for (var i = _partStart[part]; i < _partStart[part + 1]; i++)
{
var w = _tissues[i].Motor;
if (w > 0.0) mean += w * _integrity[i];
}
double offset = 0.0, factor = 1.0;
for (var s = 0; s < _slotDef.Length; s++)
{
if (_slotDef[s] >= 0 && _slotPart[s] == part)
{
Fold(_defs[_slotDef[s]].Effects, EffectTarget.Motor, _slotSeverity[s], _slotAge[s], ref offset, ref factor);
}
}
_motor[j] = Clamp01((mean / _motorWeight[part] + offset) * factor) * _consciousness;
}
// 8. Death, once, for every cause; the first rule that holds names it.
var cause = DeathCause.None;
for (var i = 0; i < _tissues.Length && cause == DeathCause.None; i++)
{
if (_tissues[i].Vital && _integrity[i] <= 0.0) cause = DeathCause.VitalTissue;
}
if (cause == DeathCause.None && BloodLoss >= 1.0) cause = DeathCause.BloodLoss;
if (cause == DeathCause.None && _consciousness <= 0.0) cause = DeathCause.Consciousness;
if (cause != DeathCause.None)
{
Dead = true;
Cause = cause;
DiedAtStep = _steps;
}
_steps++;
}
private const int CapacityCount = 3;
private static double Weight(in TissueDef t, EffectTarget target) => target switch
{
EffectTarget.Consciousness => t.Consciousness,
EffectTarget.BloodPumping => t.BloodPumping,
_ => t.Breathing,
};
private double Capacity(EffectTarget target)
{
var weightSum = _capacityWeight[(int)target];
var mean = 1.0;
if (weightSum > 0.0)
{
var acc = 0.0;
for (var i = 0; i < _tissues.Length; i++)
{
var w = Weight(_tissues[i], target);
if (w > 0.0) acc += w * _integrity[i];
}
mean = acc / weightSum;
}
double offset = 0.0, factor = 1.0;
for (var i = 0; i < _organism.Length; i++)
{
Fold(_organism[i], target, 0.0, 0.0, ref offset, ref factor);
}
for (var s = 0; s < _slotDef.Length; s++)
{
if (_slotDef[s] >= 0) Fold(_defs[_slotDef[s]].Effects, target, _slotSeverity[s], _slotAge[s], ref offset, ref factor);
}
return Clamp01((mean + offset) * factor);
}
private void Fold(IReadOnlyList<Effect> effects, EffectTarget target, double severity, double age, ref double offset, ref double factor)
{
for (var i = 0; i < effects.Count; i++)
{
Fold(effects[i], target, severity, age, ref offset, ref factor);
}
}
private void Fold(Effect e, EffectTarget target, double severity, double age, ref double offset, ref double factor)
{
if (e.Target != target) return;
var x = e.Driver switch
{
EffectDriver.Severity => severity,
EffectDriver.Age => age,
_ => _drivers[(int)e.Driver],
};
var v = e.Eval(x);
if (e.Op == EffectOp.Offset) offset += v;
else factor *= v;
}
private static double Clamp01(double x) => x < 0.0 ? 0.0 : x > 1.0 ? 1.0 : x;
}
}

View file

@ -0,0 +1,398 @@
using System;
using System.Collections.Generic;
namespace Lodur
{
/// <summary>The clock a process runs on: Acute on the caller's seconds, Slow on those times the session's slow scale (ruling bds-physiology-clock).</summary>
public enum PhysiologyClock { Acute, Slow }
/// <summary>
/// What an effect shapes. One mechanism reads each: capacities (Consciousness, BloodPumping, Breathing, the last read by gas exchange as
/// ventilation), an affliction's bleed rate, a part's motor ceiling. The three capacities come first and their order is the capacity index.
/// </summary>
public enum EffectTarget { Consciousness, BloodPumping, Breathing, Bleed, Motor }
/// <summary>How an effect's value joins its target: summed into the offsets, or multiplied into the factors.</summary>
public enum EffectOp { Offset, Factor }
/// <summary>
/// What an effect's curve is read at: its affliction's severity or age (in its clock's seconds), or an organism value as the step began:
/// the blood loss or the brain oxygen. Severity and Age belong to an affliction alone; BloodLoss and BrainOxygen index the organism's driver array.
/// </summary>
public enum EffectDriver { Severity, Age, BloodLoss, BrainOxygen }
/// <summary>
/// The material of a layer simulated as a particle sheet. <paramref name="Spacing"/> is the particle spacing in m. The compliances are
/// XPBD compliances in m/N: along the sheet's edges (also its joint stitches) and to the bone. <paramref name="TensileStrength"/> is
/// ultimate stress in Pa; the sheet builder derives an edge's break force as TensileStrength x Thickness x Spacing.
/// </summary>
public readonly record struct SheetDef(double Spacing, double EdgeCompliance, double AttachCompliance, double TensileStrength);
/// <summary>A sphere in the part's frame (origin at the part's Position, axes by its Rotation) that a sited core occupies: <paramref name="Radius"/> in m about <paramref name="Centre"/>.</summary>
public readonly record struct TissueSite((float X, float Y, float Z) Centre, float Radius);
/// <summary>
/// One tissue layer of a part. <paramref name="Consciousness"/>, <paramref name="BloodPumping"/> and <paramref name="Motor"/> are
/// function weights, a closed set with one reader each (<paramref name="Breathing"/> is the lungs' share of ventilation): a capacity is the weighted mean integrity of the tissues that carry its weight.
/// A Vital tissue at integrity 0 kills. A stack is shells (<see cref="Thickness"/> above 0, in m) outside-in, then cores (Thickness 0:
/// bone, organs, a muscle with no sheet); a core with a <see cref="Site"/> occupies that sphere of the part, one with none fills what the shells leave of the part's shape. Stack order is depth order: a sited tissue may sit among the shells (a vessel between fat and a muscle sheet), at the depth the shells listed before it give; an unsited core fills past all the shells and may not precede one. <see cref="Sheet"/> is the
/// material of a shell simulated as a particle sheet; null means it is not.
/// </summary>
public readonly record struct TissueDef(
string Label, double Hp, double Vascularity, bool Vital = false, double Consciousness = 0.0, double BloodPumping = 0.0, double Motor = 0.0, double Breathing = 0.0)
{
public double Thickness { get; init; }
public SheetDef? Sheet { get; init; }
/// <summary>Where a core sits in the part's frame; null fills the part past its shells. A shell takes none. A sited tissue's depth is the summed thickness of the shells listed before it.</summary>
public TissueSite? Site { get; init; }
/// <summary>The fraction, 0..1, of a wound's bleed in this tissue that enters the airway instead of leaving through the part's surface (the larynx, trachea and lungs' mucosa); 0 for every other tissue.</summary>
public double AirwayShare { get; init; }
}
/// <summary>The one tissue stack of a part, outside-in, owned by <see cref="PhysiologyPlan.Parts"/> and joined to a <see cref="BodyPlan"/> only through <see cref="PhysiologyPlan.Resolve"/>.</summary>
public readonly record struct PartTissuesDef(string PartLabel, Side Side, IReadOnlyList<TissueDef> Tissues)
{
/// <summary>
/// The layers a wound of <paramref name="depth"/> (m, finite and above 0) at <paramref name="point"/> (the part's frame) reaches, written into <paramref name="layers"/> as stack indices in stack order; returns the count.
/// Stack order is depth order: with B the summed Thickness of the shells listed before a tissue, a shell is reached iff depth exceeds B, and a core iff depth exceeds B and (it has no Site, or depth exceeds the distance from point to the Site's centre less its radius).
/// The validator refuses a shell after an unsited core, so an unsited core's B is every shell's total. Strict: a depth equal to a boundary does not reach past it. Allocates nothing.
/// </summary>
public int Reach((float X, float Y, float Z) point, double depth, Span<int> layers)
{
if (!(double.IsFinite(depth) && depth > 0.0)) throw new ArgumentException("depth is not finite and above 0.");
if (!(float.IsFinite(point.X) && float.IsFinite(point.Y) && float.IsFinite(point.Z))) throw new ArgumentException("the point is not finite.");
if (layers.Length < Tissues.Count) throw new ArgumentException("layers is shorter than the stack.");
var n = 0;
var before = 0.0;
for (var i = 0; i < Tissues.Count; i++)
{
var t = Tissues[i];
if (t.Thickness > 0.0)
{
if (depth > before) layers[n++] = i;
before += t.Thickness;
}
else
{
if (!(depth > before)) continue;
if (t.Site is not TissueSite site) layers[n++] = i;
else
{
double dx = point.X - site.Centre.X, dy = point.Y - site.Centre.Y, dz = point.Z - site.Centre.Z;
if (depth > Math.Sqrt(dx * dx + dy * dy + dz * dz) - site.Radius) layers[n++] = i;
}
}
}
return n;
}
}
/// <summary>The blood: nominal volume in m^3, the lost fraction that kills, and the regrowth per slow second as a fraction of nominal.</summary>
public readonly record struct BloodDef(double NominalVolume, double LethalLossFraction, double RegenPerSecond);
/// <summary>
/// The gases, all on the Acute clock (ruling bds-asphyxia-real-time): the blood oxygen store S refills at
/// <paramref name="UptakePerSecond"/> x ventilation x (1 - S) per second and is used at <paramref name="BasalUsePerSecond"/> x
/// (1 + <paramref name="ArousalUse"/> x arousal + <paramref name="EffortUse"/> x effort); the brain oxygen relaxes toward BloodPumping x S
/// with time constant <paramref name="BrainSeconds"/>. Both stores run 0..1. Carbon dioxide C (0 at rest, about 1 at the break point) rises at
/// <paramref name="CarbonDioxideRise"/> x (1 + ArousalUse x arousal + EffortUse x effort) per second, the load that uses oxygen, and is blown off at
/// <paramref name="CarbonDioxideClear"/> x ventilation x C. Air hunger is the larger of two curves: <paramref name="UrgeByCarbonDioxide"/> read at C and
/// <paramref name="UrgeByVentilationDeficit"/> read at the deficit, 1 - Breathing x (1 - occlusion), a breath tried and not got (zero while the breath is held).
/// </summary>
public readonly record struct RespirationDef(
double UptakePerSecond, double BasalUsePerSecond, double ArousalUse, double EffortUse, double BrainSeconds,
double CarbonDioxideRise, double CarbonDioxideClear,
IReadOnlyList<(double X, double Y)> UrgeByCarbonDioxide, IReadOnlyList<(double X, double Y)> UrgeByVentilationDeficit);
/// <summary>
/// The airway as a quantity, not as particles: it holds <paramref name="Capacity"/> m^3 of liquid at most. Liquid at the airway is
/// <paramref name="LiveWeight"/> x the live liquid plus <paramref name="PooledWeight"/> x the pooled; at <paramref name="HoldAt"/> or more it is "at the airway"
/// and the Actor holds the breath. A free breath draws <paramref name="DrawPerSecond"/> x Breathing x (liquid at the airway) per second into it; a cough
/// removes <paramref name="CoughPerSecond"/> x <paramref name="CoughByConsciousness"/>(consciousness) x contents per second; and it drains at
/// <paramref name="DrainPerSecond"/> x clamp01(drop / <paramref name="DrainDrop"/>) x contents, drop being how far (m) the lowest opening's rim lies below the deepest airway sump along
/// gravity: <paramref name="DrainDrop"/> m of drop drains at the full rate. The airway holds liquid in the world's units (what the openings sample); blood bled into it
/// (<see cref="TissueDef.AirwayShare"/>) enters at the physiology's blood gain; a breath draws only into the room left, and what bleeds into a full airway spills through the mouth and is reported as drained.
/// </summary>
public readonly record struct AirwayDef(
double Capacity, double DrawPerSecond, double LiveWeight, double PooledWeight, double HoldAt, double CoughPerSecond,
IReadOnlyList<(double X, double Y)> CoughByConsciousness, double DrainPerSecond, double DrainDrop);
/// <summary>
/// A piecewise-linear curve in its driver, clamped at the ends. An equal-x pair is a step: at that x the later value holds
/// (a stage begins at its threshold). Effects only shape values a mechanism reads; they never write state.
/// </summary>
public readonly record struct Effect(EffectTarget Target, EffectOp Op, EffectDriver Driver, IReadOnlyList<(double X, double Y)> Curve)
{
public double Eval(double x) => EvalCurve(Curve, x);
/// <summary>The evaluation every curve of the plan shares: clamped at the ends, an equal-x pair a step.</summary>
internal static double EvalCurve(IReadOnlyList<(double X, double Y)> c, double x)
{
if (x < c[0].X)
{
return c[0].Y;
}
for (var i = 1; i < c.Count; i++)
{
if (x < c[i].X)
{
var a = c[i - 1];
var b = c[i];
return a.Y + (b.Y - a.Y) * ((x - a.X) / (b.X - a.X));
}
}
return c[c.Count - 1].Y;
}
}
/// <summary>
/// A kind of harm or condition. <paramref name="SeverityRate"/> is per second of its clock (negative heals); an Injures
/// affliction's severity is HP lost from its tissue; a live affliction's effects apply while it lives.
/// </summary>
public readonly record struct AfflictionDef(string Label, PhysiologyClock Clock, double SeverityRate, bool Injures, IReadOnlyList<Effect> Effects);
/// <summary>
/// Physiology as content: tissue stacks per body part, the afflictions that can be bound, the organism-wide effects of the organism's blood
/// loss and brain oxygen, the blood, the respiration and the size of the affliction table. Validated at construction; resolved against a <see cref="BodyPlan"/> by <see cref="Resolve"/>, the one (label, side) join, which <see cref="Physiology"/> and the sheet builder both call.
/// </summary>
public sealed class PhysiologyPlan
{
private readonly Dictionary<string, int> _afflictionIndex = new Dictionary<string, int>();
public PhysiologyPlan(
IReadOnlyList<PartTissuesDef> parts, IReadOnlyList<AfflictionDef> afflictions, IReadOnlyList<Effect> organismEffects,
BloodDef blood, RespirationDef respiration, AirwayDef airway, int afflictionSlots)
{
var ownedParts = new List<PartTissuesDef>(parts.Count);
foreach (var p in parts)
{
ownedParts.Add(p with { Tissues = new List<TissueDef>(p.Tissues).AsReadOnly() });
}
var ownedAfflictions = new List<AfflictionDef>(afflictions.Count);
foreach (var a in afflictions)
{
ownedAfflictions.Add(a with { Effects = Own(a.Effects) });
}
Parts = ownedParts.AsReadOnly();
Afflictions = ownedAfflictions.AsReadOnly();
OrganismEffects = Own(organismEffects);
Blood = blood;
Respiration = respiration with { UrgeByCarbonDioxide = OwnCurve(respiration.UrgeByCarbonDioxide), UrgeByVentilationDeficit = OwnCurve(respiration.UrgeByVentilationDeficit) };
Airway = airway with { CoughByConsciousness = OwnCurve(airway.CoughByConsciousness) };
AfflictionSlots = afflictionSlots;
Validate();
}
public IReadOnlyList<PartTissuesDef> Parts { get; }
public IReadOnlyList<AfflictionDef> Afflictions { get; }
public IReadOnlyList<Effect> OrganismEffects { get; }
public BloodDef Blood { get; }
public RespirationDef Respiration { get; }
public AirwayDef Airway { get; }
public int AfflictionSlots { get; }
public int AfflictionIndex(string label) =>
_afflictionIndex.TryGetValue(label, out var i) ? i : throw new ArgumentException($"no affliction labelled '{label}'.");
/// <summary>
/// The one (label, side) join of stacks to a body: element p is the index in <see cref="Parts"/> of body part p's stack. Refuses a
/// stack naming no part, a part with two stacks, a part with no stack, and shells that do not fit (a stack's summed Thickness must be
/// below the part's inscribed half extent, compared at the shape's float precision), and a sited core whose site centre is not strictly inside its part's shape. Physiology and the sheet builder call it; it allocates, at construction only.
/// </summary>
public int[] Resolve(BodyPlan body)
{
var parts = body.Parts.Count;
var stackOf = new int[parts];
for (var p = 0; p < parts; p++) stackOf[p] = -1;
for (var s = 0; s < Parts.Count; s++)
{
var def = Parts[s];
var part = -1;
for (var p = 0; p < parts; p++)
{
if (body.Parts[p].Label == def.PartLabel && body.Parts[p].Side == def.Side) part = p;
}
if (part < 0) throw new ArgumentException($"a tissue stack names no body part: '{def.PartLabel}' {def.Side}.");
if (stackOf[part] >= 0) throw new ArgumentException($"body part '{def.PartLabel}' {def.Side} has two tissue stacks.");
stackOf[part] = s;
}
for (var p = 0; p < parts; p++)
{
var d = body.Parts[p];
if (stackOf[p] < 0) throw new ArgumentException($"body part '{d.Label}' {d.Side} has no tissue stack.");
var shells = 0.0;
foreach (var t in Parts[stackOf[p]].Tissues) shells += t.Thickness;
var half = d.Shape == PartShape.Box ? Math.Min(d.Size.X, Math.Min(d.Size.Y, d.Size.Z)) : d.Size.X;
if (!((float)shells < half)) throw new ArgumentException($"body part '{d.Label}' {d.Side}: the shells ({shells} m) do not fit inside its inscribed half extent ({half} m).");
foreach (var t in Parts[stackOf[p]].Tissues)
{
if (t.Site is TissueSite site && !Inside(d, site.Centre)) throw new ArgumentException($"body part '{d.Label}' {d.Side}: the site of tissue '{t.Label}' is not inside the part's shape.");
}
}
return stackOf;
}
private static bool Inside(PartDef d, (float X, float Y, float Z) c)
{
double x = c.X, y = c.Y, z = c.Z;
switch (d.Shape)
{
case PartShape.Box: return Math.Abs(x) < d.Size.X && Math.Abs(y) < d.Size.Y && Math.Abs(z) < d.Size.Z;
case PartShape.Capsule:
double along = Math.Max(-d.Size.Y, Math.Min(d.Size.Y, y));
return Math.Sqrt(x * x + (y - along) * (y - along) + z * z) < d.Size.X;
default: return Math.Sqrt(x * x + y * y + z * z) < d.Size.X;
}
}
private static IReadOnlyList<(double X, double Y)> OwnCurve(IReadOnlyList<(double X, double Y)>? curve) =>
curve == null ? null! : new List<(double X, double Y)>(curve).AsReadOnly();
private static IReadOnlyList<Effect> Own(IReadOnlyList<Effect> effects)
{
var list = new List<Effect>(effects.Count);
foreach (var e in effects)
{
list.Add(e with { Curve = new List<(double X, double Y)>(e.Curve).AsReadOnly() });
}
return list.AsReadOnly();
}
private static bool IsFinite(double d) => !double.IsNaN(d) && !double.IsInfinity(d);
private void Validate()
{
foreach (var p in Parts)
{
var seen = new HashSet<string>();
var core = false;
foreach (var t in p.Tissues)
{
var where = $"tissue '{t.Label}' of part '{p.PartLabel}' {p.Side}";
if (string.IsNullOrEmpty(t.Label)) throw new ArgumentException($"a tissue of part '{p.PartLabel}' {p.Side} has an empty label.");
if (!seen.Add(t.Label)) throw new ArgumentException($"{where}: the label is not unique within the part.");
if (!(IsFinite(t.Hp) && t.Hp > 0.0)) throw new ArgumentException($"{where}: Hp is not finite and above 0.");
if (!(IsFinite(t.Vascularity) && t.Vascularity >= 0.0)) throw new ArgumentException($"{where}: vascularity is not finite and at least 0.");
if (!(IsFinite(t.AirwayShare) && t.AirwayShare >= 0.0 && t.AirwayShare <= 1.0)) throw new ArgumentException($"{where}: the airway share is not finite and in [0, 1].");
if (!(IsFinite(t.Consciousness) && t.Consciousness >= 0.0 && IsFinite(t.BloodPumping) && t.BloodPumping >= 0.0 && IsFinite(t.Motor) && t.Motor >= 0.0 && IsFinite(t.Breathing) && t.Breathing >= 0.0))
{
throw new ArgumentException($"{where}: a function weight is not finite and at least 0.");
}
if (!(IsFinite(t.Thickness) && t.Thickness >= 0.0)) throw new ArgumentException($"{where}: thickness is not finite and at least 0.");
if (t.Site is TissueSite site)
{
if (t.Thickness > 0.0) throw new ArgumentException($"{where}: a shell takes no site.");
if (!(float.IsFinite(site.Centre.X) && float.IsFinite(site.Centre.Y) && float.IsFinite(site.Centre.Z))) throw new ArgumentException($"{where}: the site centre is not finite.");
if (!(float.IsFinite(site.Radius) && site.Radius > 0f)) throw new ArgumentException($"{where}: the site radius is not finite and above 0.");
}
if (t.Thickness == 0.0 && t.Site is null) core = true;
else if (t.Thickness > 0.0 && core) throw new ArgumentException($"{where}: a shell follows a core.");
if (t.Sheet is SheetDef sh)
{
if (!(t.Thickness > 0.0)) throw new ArgumentException($"{where}: a sheet needs a thickness above 0.");
if (!(IsFinite(sh.Spacing) && sh.Spacing > 0.0)) throw new ArgumentException($"{where}: sheet spacing is not finite and above 0.");
if (!(IsFinite(sh.EdgeCompliance) && sh.EdgeCompliance >= 0.0 && IsFinite(sh.AttachCompliance) && sh.AttachCompliance >= 0.0))
{
throw new ArgumentException($"{where}: a sheet compliance is not finite and at least 0.");
}
if (!(IsFinite(sh.TensileStrength) && sh.TensileStrength > 0.0)) throw new ArgumentException($"{where}: sheet tensile strength is not finite and above 0.");
}
}
}
var labels = new HashSet<string>();
for (var i = 0; i < Afflictions.Count; i++)
{
var a = Afflictions[i];
if (string.IsNullOrEmpty(a.Label)) throw new ArgumentException("an affliction has an empty label.");
if (!labels.Add(a.Label)) throw new ArgumentException($"affliction '{a.Label}': the label is not unique.");
_afflictionIndex.Add(a.Label, i);
if (!Enum.IsDefined(typeof(PhysiologyClock), a.Clock)) throw new ArgumentException($"affliction '{a.Label}': the clock is not defined.");
if (!IsFinite(a.SeverityRate)) throw new ArgumentException($"affliction '{a.Label}': the severity rate is not finite.");
foreach (var e in a.Effects)
{
ValidateEffect(e, $"affliction '{a.Label}'");
}
}
foreach (var e in OrganismEffects)
{
ValidateEffect(e, "an organism effect");
if (e.Target != EffectTarget.Consciousness && e.Target != EffectTarget.BloodPumping && e.Target != EffectTarget.Breathing)
{
throw new ArgumentException("an organism effect targets only a capacity: Consciousness, BloodPumping or Breathing.");
}
if (e.Driver == EffectDriver.Severity || e.Driver == EffectDriver.Age)
{
throw new ArgumentException("an organism effect is not driven by Severity or Age: those belong to an affliction.");
}
}
if (!(IsFinite(Blood.NominalVolume) && Blood.NominalVolume > 0.0)) throw new ArgumentException("blood: the nominal volume is not finite and above 0.");
if (!(Blood.LethalLossFraction > 0.0 && Blood.LethalLossFraction <= 1.0)) throw new ArgumentException("blood: the lethal loss fraction is not in (0, 1].");
if (!(IsFinite(Blood.RegenPerSecond) && Blood.RegenPerSecond >= 0.0)) throw new ArgumentException("blood: the regrowth is not finite and at least 0.");
var r = Respiration;
if (!(IsFinite(r.UptakePerSecond) && r.UptakePerSecond >= 0.0 && IsFinite(r.BasalUsePerSecond) && r.BasalUsePerSecond >= 0.0
&& IsFinite(r.ArousalUse) && r.ArousalUse >= 0.0 && IsFinite(r.EffortUse) && r.EffortUse >= 0.0))
{
throw new ArgumentException("respiration: a rate is not finite and at least 0.");
}
if (!(IsFinite(r.BrainSeconds) && r.BrainSeconds > 0.0)) throw new ArgumentException("respiration: BrainSeconds is not finite and above 0.");
if (!(IsFinite(r.CarbonDioxideRise) && r.CarbonDioxideRise >= 0.0 && IsFinite(r.CarbonDioxideClear) && r.CarbonDioxideClear >= 0.0))
{
throw new ArgumentException("respiration: a carbon dioxide rate is not finite and at least 0.");
}
ValidateCurve(r.UrgeByCarbonDioxide, "respiration: the carbon dioxide urge curve");
ValidateCurve(r.UrgeByVentilationDeficit, "respiration: the ventilation deficit urge curve");
var w = Airway;
if (!(IsFinite(w.Capacity) && w.Capacity > 0.0)) throw new ArgumentException("airway: the capacity is not finite and above 0.");
if (!(IsFinite(w.DrawPerSecond) && w.DrawPerSecond >= 0.0 && IsFinite(w.LiveWeight) && w.LiveWeight >= 0.0 && IsFinite(w.PooledWeight) && w.PooledWeight >= 0.0
&& IsFinite(w.HoldAt) && w.HoldAt >= 0.0 && IsFinite(w.CoughPerSecond) && w.CoughPerSecond >= 0.0 && IsFinite(w.DrainPerSecond) && w.DrainPerSecond >= 0.0))
{
throw new ArgumentException("airway: a number is not finite and at least 0.");
}
if (!(w.DrainDrop > 0.0 && w.DrainDrop < double.PositiveInfinity)) throw new ArgumentException("airway: DrainDrop is not finite and above 0.");
ValidateCurve(w.CoughByConsciousness, "airway: the cough curve");
if (AfflictionSlots < 1) throw new ArgumentException("the affliction table needs at least one slot.");
}
private static void ValidateEffect(Effect e, string where)
{
if (!Enum.IsDefined(typeof(EffectTarget), e.Target) || !Enum.IsDefined(typeof(EffectOp), e.Op) || !Enum.IsDefined(typeof(EffectDriver), e.Driver))
{
throw new ArgumentException($"{where}: an effect has an undefined target, op or driver.");
}
ValidateCurve(e.Curve, $"{where}: an effect curve");
}
private static void ValidateCurve(IReadOnlyList<(double X, double Y)> curve, string where)
{
if (curve == null || curve.Count == 0) throw new ArgumentException($"{where} is empty.");
for (var i = 0; i < curve.Count; i++)
{
var (x, y) = curve[i];
if (!IsFinite(x) || !IsFinite(y)) throw new ArgumentException($"{where} has a non-finite point.");
if (i > 0 && x < curve[i - 1].X) throw new ArgumentException($"{where}'s x decreases.");
}
}
}
}

View file

@ -0,0 +1,122 @@
using System;
using System.Collections.Generic;
namespace Lodur
{
/// <summary>Physiology content in code, until it lives in a store; the only place tissue, organ and affliction labels are spelled.</summary>
public static class PhysiologyPlans
{
private const double Day = 86400.0;
// Vascularity is the blood a wound in the tissue loses relative to muscle (play-tuned placeholders): skin and bone are thin, organs rich.
private const double SkinV = 0.2, MuscleV = 1.0, BoneV = 0.3, BrainV = 1.0, HeartV = 4.0, LungV = 2.0, LiverV = 3.0, KidneyV = 2.0, GutV = 1.0;
// Airway tissues: mucosa as perfused as muscle (placeholders). AirwayShare is the fraction of a wound's bleed that enters the airway: all of the larynx's and trachea's, half a lung's (half coughed up, half stays in the chest).
private const double LarynxV = 0.7, TracheaV = 1.0, MucosaShare = 1.0, LungShare = 0.5;
// Major vessels: a sited tissue placed among the shells at its depth (ruling bds-bleed-by-vessels), so a knife at the side of the neck or the inner thigh reaches one and the front of the throat does not.
// VesselV is play-tuned (probe: at the BDS knife's severity 20 and blood gain 10 either dies of blood loss at about 30 s; 3.0 gave 33.9 s, 4.0 gave 26.5 s). A vessel is no airway tissue (AirwayShare 0).
// LarynxV 1.0 -> 0.7: at 1.0 the front of the throat bled him out before it drowned him (grid in the cut report); 0.7 with the cough at 0.3 drowns him first (ruling bds-drown-in-own-blood-first).
private const double VesselV = 3.5;
// Fat is thickness in the stack, not particles; its vascularity is a placeholder.
private const double FatV = 0.1;
// Shell thickness in m. Skin: mean dermis thickness of excised back skin (research tissue-tensile-strength.ts-skin-annaidh-2012). Fat and muscle sheet: (placeholder).
private const double SkinT = 0.00256, FatT = 0.005, MuscleSheetT = 0.015;
// Sheet material: spacing m, edge and attach compliance m/N, tensile strength Pa. Skin strength is the same study's ultimate stress (21.6 MPa);
// spacing and compliances are (placeholder) values the fella.c and sieve.c probes ran with (flesh-map P1, P2, P6). Muscle strength is (placeholder): no human failure value.
private static readonly SheetDef SkinSheet = new SheetDef(0.10, 2e-4, 1e-3, 21.6e6);
private static readonly SheetDef MuscleSheetMaterial = new SheetDef(0.14, 1e-4, 1e-4, 0.5e6);
private static TissueDef Skin(double hp) => new TissueDef("Skin", hp, SkinV) { Thickness = SkinT, Sheet = SkinSheet };
private static TissueDef Fat(double hp) => new TissueDef("Fat", hp, FatV) { Thickness = FatT };
private static TissueDef Muscle(double hp) => new TissueDef("Muscle", hp, MuscleV, Motor: 1.0);
private static TissueDef MuscleSheet(double hp) => Muscle(hp) with { Thickness = MuscleSheetT, Sheet = MuscleSheetMaterial };
private static TissueDef Bone(string label, double hp) => new TissueDef(label, hp, BoneV);
private static Effect Curve(EffectTarget target, EffectOp op, EffectDriver driver, params (double X, double Y)[] curve) => new Effect(target, op, driver, curve);
/// <summary>
/// The 19-part humanoid of <see cref="BodyPlans.Humanoid"/>: tissue stacks outside-in with RimWorld's human part HP (fat and bone are stack thickness and core, not particles), the
/// blood, the stages of blood loss, the hypoxia curve and the respiration, and the Cut and Bruise afflictions. Numbers not cited are play-tuned placeholders; the respiration constants (uptake, basal and exertion use, brain lag) are literature-shaped placeholders.
/// </summary>
public static PhysiologyPlan Humanoid()
{
var parts = new List<PartTissuesDef>();
void Stack(string part, Side side, params TissueDef[] tissues) => parts.Add(new PartTissuesDef(part, side, tissues));
Stack("Pelvis", Side.Center, Skin(10), Fat(10), MuscleSheet(30), Bone("Pelvis", 25), new TissueDef("Gut", 20, GutV));
Stack("Torso", Side.Center,
Skin(10), Fat(10), MuscleSheet(40), Bone("Ribcage", 25),
// Organ sites (placeholders in the part's frame, left is +x, probed against PartTissuesDef.Reach); the ribcage stays unsited and fills the torso.
new TissueDef("Heart", 15, HeartV, BloodPumping: 1.0) { Site = new TissueSite((0.02f, 0.05f, 0.03f), 0.05f) },
new TissueDef("LungLeft", 15, LungV, Breathing: 1.0) { AirwayShare = LungShare, Site = new TissueSite((0.08f, 0.07f, 0f), 0.06f) },
new TissueDef("LungRight", 15, LungV, Breathing: 1.0) { AirwayShare = LungShare, Site = new TissueSite((-0.08f, 0.07f, 0f), 0.06f) },
new TissueDef("Liver", 20, LiverV) { Site = new TissueSite((-0.06f, -0.1f, 0.01f), 0.06f) },
new TissueDef("KidneyLeft", 15, KidneyV) { Site = new TissueSite((0.06f, -0.15f, -0.05f), 0.03f) },
new TissueDef("KidneyRight", 15, KidneyV) { Site = new TissueSite((-0.06f, -0.15f, -0.05f), 0.03f) },
new TissueDef("Trachea", 10, TracheaV) { AirwayShare = MucosaShare, Site = new TissueSite((0f, 0.2f, 0.06f), 0.015f) });
// The neck's muscle carries the Neck joint's motor weight: the head has to be a joint child with a muscle (spec discrepancy, report deviation).
// Head sites are placeholders in the part's frame (+z face, -y chin), probed against PartTissuesDef.Reach: the neck muscle low at the chin, skull and brain about the crown, the larynx at the throat.
// The carotids lie at the side of the neck, 0.055 m either side of the midline (placeholders), after the fat and before the muscle: a depth-2 cm wound at the side reaches one, the front of the throat does not.
Stack("Head", Side.Center, Skin(5), Fat(5),
new TissueDef("CarotidLeft", 10, VesselV) { Site = new TissueSite((0.055f, -0.07f, 0.01f), 0.012f) },
new TissueDef("CarotidRight", 10, VesselV) { Site = new TissueSite((-0.055f, -0.07f, 0.01f), 0.012f) },
Muscle(25) with { Site = new TissueSite((0f, -0.085f, -0.01f), 0.06f) }, Bone("Skull", 25) with { Site = new TissueSite((0f, 0.02f, -0.005f), 0.09f) },
new TissueDef("Brain", 10, BrainV, Vital: true, Consciousness: 1.0) { Site = new TissueSite((0f, 0.02f, -0.005f), 0.07f) },
new TissueDef("Larynx", 10, LarynxV) { AirwayShare = MucosaShare, Site = new TissueSite((0f, -0.075f, 0.06f), 0.015f) });
foreach (var side in new[] { Side.Left, Side.Right })
{
Stack("UpperArm", side, Skin(8), Fat(8), MuscleSheet(30), Bone("Humerus", 25));
Stack("LowerArm", side, Skin(8), Fat(8), MuscleSheet(25), Bone("Radius", 20));
// The femoral vessel runs at the inner thigh (sx +1 Left, -1 Right: the inner side is toward the midline), between the fat and the muscle sheet (placeholder site in the part's frame).
var sx = side == Side.Left ? 1f : -1f;
Stack("Thigh", side, Skin(10), Fat(10), new TissueDef("Femoral", 10, VesselV) { Site = new TissueSite((-sx * 0.032f, 0.12f, 0.032f), 0.012f) }, MuscleSheet(30), Bone("Femur", 25));
Stack("Shin", side, Skin(8), Fat(8), MuscleSheet(25), Bone("Tibia", 25));
Stack("Foot", side, Skin(5), Muscle(20), Bone("Bones", 25));
Stack("Palm", side, Skin(5), Muscle(20), Bone("Metacarpals", 15));
Stack("Thumb", side, Skin(3), Muscle(8), Bone("Bone", 8));
Stack("Fingers", side, Skin(3), Muscle(8), Bone("Bone", 8));
}
// RimWorld's blood-loss stages (research rw-blood-bleeding) as step offsets on consciousness, by fraction of the lethal loss.
var bloodLoss = Curve(EffectTarget.Consciousness, EffectOp.Offset, EffectDriver.BloodLoss,
(0.0, 0.0), (0.15, 0.0), (0.15, -0.1), (0.30, -0.1), (0.30, -0.2), (0.45, -0.2), (0.45, -0.4), (0.60, -0.4), (0.60, -0.9), (1.0, -0.9));
// Brain oxygen to consciousness: flat 1 above 0.70 so a healthy body reads exactly 1, falling to 0 at 0.10. A stopped heart or a smothering
// reaches it through the stores. (placeholder, fitted to ~75 s unconscious while struggling and death at 134-360 s, PMC8928428 and Szpilman NEJM 2012;
// 6-10 s after cerebral circulation stops, Rossen, Kabat and Anderson 1943; rulings bds-asphyxia-real-time, bds-heart-stop-stagger)
var hypoxia = Curve(EffectTarget.Consciousness, EffectOp.Factor, EffectDriver.BrainOxygen, (0.10, 0.0), (0.35, 0.1), (0.70, 1.0));
var afflictions = new[]
{
// Acute: a wound (Cut, Bruise) bleeds, clots and heals in real seconds whatever the slow scale (ruling bds-physiology-clock); Slow is for toxins, radiation and osmosis only. 1 mL/s per HP of severity
// (play-tuned), clotting with age (play-tuned); heals 10 HP per day of real seconds (RimWorld's rate).
new AfflictionDef("Cut", PhysiologyClock.Acute, -10.0 / Day, true, new[]
{
Curve(EffectTarget.Bleed, EffectOp.Offset, EffectDriver.Severity, (0.0, 0.0), (100.0, 1e-4)),
Curve(EffectTarget.Bleed, EffectOp.Factor, EffectDriver.Age, (0.0, 1.0), (60.0, 0.5), (300.0, 0.1)),
}),
new AfflictionDef("Bruise", PhysiologyClock.Acute, -20.0 / Day, true, Array.Empty<Effect>()),
};
// ATLS class IV past 40% loss (research df-and-atls) puts the lethal fraction at 0.5 (play-tuned); regrowth is RimWorld's 0.333 per slow day.
return new PhysiologyPlan(parts, afflictions, new[] { bloodLoss, hypoxia }, new BloodDef(0.005, 0.5, 0.333 / Day),
new RespirationDef(
1.0, 0.002, 0.5, 4.0, 9.5,
// CO2 (placeholders, the readings are the real Actor smothered: struggle takes over at 0.1 s, out 81.6 s, dead 154.3 s; calm breath-hold gasps at 60.1 s). Rise 1/300 per second of
// basal load: carbon dioxide reaches its urge threshold in tens of seconds of exertion with no ventilation (breath-hold breaking point, PMC8511405; Frontiers Physiol 2021, 10.3389/fphys.2021.731633).
// Clear 0.5 per ventilated second keeps a healthy body at 0.01-0.07, below the curves' floor of 0.5.
1.0 / 300.0, 0.5,
// Urge by CO2 (placeholder): nothing up to 0.5, full at 1.3. Urge by ventilation deficit (placeholder): nothing up to a deficit of 0.5 (a lung lost), 0.6 at no breath at all;
// a breath tried and not got is felt at once (Banzett, Lansing and Schwartzstein, Air hunger, Respir Physiol Neurobiol 2008).
new[] { (0.5, 0.0), (1.3, 1.0) }, new[] { (0.5, 0.0), (1.0, 0.6) }),
// The airway (placeholders). Capacity 150 mL is 2 mL/kg at 75 kg (an upper-airway and bronchial volume, the lung's own is far larger: the airway fills before the lung); it holds the breath from 15.6 mL
// of liquid at the openings (a mouthful, a tenth of the capacity). A free breath draws the liquid at the airway in at 1 per second, an awake cough clears 0.3 per second of what is there (a continuous airway bleed at the knife's severity must beat the cough, or the front of the throat bleeds him out instead of drowning him) and fails below 0.3
// consciousness, and the airway drains at 0.1 per second once the lowest rim of an opening lies 5 cm below the deepest sump (a true side pose, drop 0.025 m the mouth's half-width, halves it; side-lying falls measure a median 0.043 m, upright -0.047 m, so he drains nothing standing). Liquid and pooled liquid count alike.
new AirwayDef(150e-6, 1.0, 1.0, 1.0, 15.6e-6, 0.3, new[] { (0.3, 0.0), (0.6, 1.0) }, 0.1, 0.05), 64);
}
}
}

629
src/Lodur.Core/Planner.cs Normal file
View file

@ -0,0 +1,629 @@
using System;
using System.Collections.Generic;
namespace Lodur
{
/// <summary>Whom a fact is about, in a verb: the actor, the verb's target, or the verb's second thing.</summary>
public enum FactSubject
{
Self,
This,
Tool,
}
/// <summary>One literal: bit <see cref="Bit"/> (0..63) of the subject's facts is <see cref="Value"/>. Lodur never interprets a bit except <see cref="Perception.InReachFact"/>.</summary>
public readonly record struct Fact(FactSubject Subject, int Bit, bool Value);
/// <summary>
/// A thing the game lets the puppet do, as the planner sees it: what must hold before and what holds after.
/// Content, authored by the consumer; the planner never reads <see cref="Id"/>.
/// </summary>
public sealed record Verb
{
private IReadOnlyList<Fact> _needsView = Array.AsReadOnly(Array.Empty<Fact>());
private IReadOnlyList<Fact> _givesView = Array.AsReadOnly(Array.Empty<Fact>());
/// <summary>The consumer's name for the verb; never read.</summary>
public string Id { get; init; } = "";
/// <summary>The kinds the verb's target may be; null accepts any kind.</summary>
public TargetFilter? This { get; init; }
/// <summary>The kinds the verb's second thing may be; null means the verb takes no second thing.</summary>
public TargetFilter? Tool { get; init; }
/// <summary>What must hold before the verb. Copied when set; read back as a read-only view.</summary>
public IReadOnlyList<Fact> Needs
{
get => _needsView;
init => _needsView = Array.AsReadOnly(Planner.Copy(value));
}
/// <summary>What holds after the verb. Copied when set; read back as a read-only view.</summary>
public IReadOnlyList<Fact> Gives
{
get => _givesView;
init => _givesView = Array.AsReadOnly(Planner.Copy(value));
}
}
/// <summary>One step of a plan: the verb's index in the planner's list and the percept ids it is grounded on (Tool 0: none). Ids, not slots, because slots are reused.</summary>
public readonly record struct PlanStep(int Verb, ulong This, ulong Tool);
/// <summary>
/// A bounded regressive planner over the percepts' facts. Given a want it finds the shallowest sequence of at most
/// <c>depth</c> verbs that would make it hold, working back from the want through what each verb gives and needs.
/// It reads percepts and keeps nothing: the plan is the caller's, derived per call. Everything it allocates is allocated here.
/// Not thread-safe: the search works in the planner's own buffers.
/// </summary>
public sealed class Planner
{
private const int MaxNeeds = 8;
/// <summary>
/// The default budget of a <see cref="Plan"/> call: the most groundings it may regress, counted across all its depths. A counter, not a clock, so the cut-off is the same on every machine.
/// A call that spends its budget returns -1 and sets <see cref="LastExhausted"/>.
/// </summary>
public const int NodeBudget = 4096;
private readonly Verb[] _verbs;
private readonly Fact[][] _needs;
private readonly Fact[][] _gives;
private readonly uint[]?[] _thisKinds; // the kinds a verb's target may be; null accepts any
private readonly uint[]?[] _toolKinds; // the kinds a verb's second thing may be; null when it takes none
private readonly ulong[] _givenBits; // per verb, bit i set when one of its gives is on bit i of any subject
private readonly bool[] _moves; // per verb, a This give of bit 63 true: the step brings its This into reach
private readonly float[] _px; // the slots' remembered positions, copied per call
private readonly float[] _py;
private readonly float[] _pz;
private readonly int _words;
private readonly int _capacity;
private readonly double _reach;
private readonly int _stride;
private readonly ulong[] _facts; // thing 0 is self, thing 1 + s is percept slot s
private readonly ulong[] _slotId;
private readonly uint[] _slotKind;
private readonly int[] _set; // the needed literals with r steps left, at r * _stride
private readonly int[] _setCount;
private readonly int[] _stepVerb; // the step chosen with r steps left, at r - 1
private readonly int[] _stepThis;
private readonly int[] _stepTool;
private readonly ulong[] _meetsThis; // per level, the slots whose literal a This give of the verb in hand meets, _words per level
private readonly ulong[] _meetsTool;
private int _nodes;
private int _budget;
private bool _exhausted;
public Planner(IReadOnlyList<Verb> verbs, int capacity, int maxDepth, double reachMeters)
{
if (verbs is null)
{
throw new ArgumentNullException(nameof(verbs));
}
if (maxDepth < 0 || maxDepth > 8)
{
throw new ArgumentOutOfRangeException(nameof(maxDepth), "The planner's depth must be in 0..8.");
}
if (!(reachMeters > 0.0 && reachMeters < double.PositiveInfinity))
{
throw new ArgumentException("The reach must be finite and above zero.", nameof(reachMeters));
}
if (capacity < 1 || capacity > 256)
{
throw new ArgumentOutOfRangeException(nameof(capacity), "The planner's capacity must be in 1..256.");
}
_verbs = new Verb[verbs.Count];
_needs = new Fact[verbs.Count][];
_gives = new Fact[verbs.Count][];
_thisKinds = new uint[verbs.Count][];
_toolKinds = new uint[verbs.Count][];
_givenBits = new ulong[verbs.Count];
_moves = new bool[verbs.Count];
for (var v = 0; v < _verbs.Length; v++)
{
var verb = verbs[v] ?? throw new ArgumentException($"Verb {v} is null.", nameof(verbs));
Validate(v, verb);
_verbs[v] = verb;
_needs[v] = Copy(verb.Needs);
_gives[v] = Copy(verb.Gives);
_thisKinds[v] = Kinds(verb.This);
_toolKinds[v] = Kinds(verb.Tool);
foreach (var g in _gives[v])
{
_givenBits[v] |= 1UL << g.Bit;
_moves[v] |= g.Subject == FactSubject.This && g.Bit == 63 && g.Value;
}
}
MaxDepth = maxDepth;
_capacity = capacity;
_reach = reachMeters;
_stride = 1 + maxDepth * MaxNeeds;
_facts = new ulong[capacity + 1];
_slotId = new ulong[capacity];
_slotKind = new uint[capacity];
_px = new float[capacity];
_py = new float[capacity];
_pz = new float[capacity];
_set = new int[(maxDepth + 1) * _stride];
_setCount = new int[maxDepth + 1];
_stepVerb = new int[Math.Max(1, maxDepth)];
_stepThis = new int[Math.Max(1, maxDepth)];
_stepTool = new int[Math.Max(1, maxDepth)];
_words = (capacity + 63) >> 6;
_meetsThis = new ulong[(maxDepth + 1) * _words];
_meetsTool = new ulong[(maxDepth + 1) * _words];
}
/// <summary>The deepest plan this planner can be asked for.</summary>
public int MaxDepth { get; }
/// <summary>The groundings the last <see cref="Plan"/> call regressed; above the call budget means it ran out and returned -1.</summary>
public int LastNodes => _nodes;
/// <summary>True when the last <see cref="Plan"/> call returned -1 because it spent its budget, not because no plan within the depth exists.</summary>
public bool LastExhausted => _exhausted;
/// <summary>
/// 0 when the want already holds, else the length of the shallowest plan of at most <paramref name="depth"/> steps, written into
/// <paramref name="plan"/> in execution order, else -1. The want is about self or about the percept in <paramref name="targetSlot"/>.
/// A thing's facts are those it was last sensed with, bit 63 replaced by whether it is within reach of the point.
/// A step that gives its This reach (bit 63 true) is a move: after it, another thing is in reach exactly when it is within reach of that This.
/// <paramref name="budget"/> is the most groundings the call may regress, at least 1; a call that spends it returns -1 and sets <see cref="LastExhausted"/>.
/// <paramref name="fromDepth"/> (1..max(depth, 1)) is where the deepening starts: a call with depth k and fromDepth k searches for a plan of exactly k steps and returns none shallower
/// (0 still means the want holds).
/// </summary>
public int Plan(Perception perception, ulong selfFacts, float ox, float oy, float oz, int targetSlot, Fact want, int depth, Span<PlanStep> plan, int budget = NodeBudget, int fromDepth = 1)
{
Check(perception, targetSlot, want, depth, plan.Length, budget, fromDepth);
_nodes = 0;
_budget = budget;
_exhausted = false;
_facts[0] = selfFacts & ~Perception.InReachFact;
var ids = perception.PerceptIds;
var kinds = perception.PerceptKinds;
var facts = perception.PerceptFacts;
var xs = perception.PerceptX;
var ys = perception.PerceptY;
var zs = perception.PerceptZ;
var reachSquared = _reach * _reach;
ids.CopyTo(_slotId);
kinds.CopyTo(_slotKind);
xs.CopyTo(_px);
ys.CopyTo(_py);
zs.CopyTo(_pz);
for (var s = 0; s < _capacity; s++)
{
double dx = xs[s] - ox, dy = ys[s] - oy, dz = zs[s] - oz;
_facts[s + 1] = (facts[s] & ~Perception.InReachFact) | (dx * dx + dy * dy + dz * dz <= reachSquared ? Perception.InReachFact : 0UL);
}
var wantLit = Lit(want.Subject == FactSubject.Self ? 0 : targetSlot + 1, want.Bit, want.Value);
if (Holds(wantLit))
{
return 0;
}
for (var d = fromDepth; d <= depth; d++)
{
_set[d * _stride] = wantLit;
_setCount[d] = 1;
if (Search(d))
{
for (var i = 0; i < d; i++)
{
plan[i] = Step(_stepVerb[i], _slotId[_stepThis[i]], _stepTool[i] < 0 ? 0UL : _slotId[_stepTool[i]]);
}
return d;
}
if (_nodes > _budget)
{
break;
}
}
_exhausted = _nodes > _budget;
return -1;
}
// Can the set at r be reached in exactly r steps from the state? The last step is chosen here, in ascending (verb, This slot, Tool slot).
private bool Search(int r)
{
var cur = r * _stride;
var n = _setCount[r];
if (r == 0)
{
for (var i = 0; i < n; i++)
{
if (!Holds(_set[i]))
{
return false;
}
}
return true;
}
var open = 0UL;
for (var i = 0; i < n; i++)
{
open |= 1UL << ((_set[cur + i] >> 1) & 63);
}
for (var v = 0; v < _verbs.Length; v++)
{
// Relevance, before any grounding: a step is only worth taking if it gives a literal still open.
if ((_givenBits[v] & open) == 0UL || !Meets(v, r, cur, n, out var meetsSelf))
{
continue;
}
var thisKinds = _thisKinds[v];
var toolKinds = _toolKinds[v];
var m = r * _words;
for (var a = 0; a < _capacity; a++)
{
if (_slotId[a] == 0 || (thisKinds is not null && !Has(thisKinds, _slotKind[a])))
{
continue;
}
var meetsA = meetsSelf || ((_meetsThis[m + (a >> 6)] >> (a & 63)) & 1UL) != 0UL;
if (toolKinds is null)
{
if (meetsA && Try(r, v, a, -1, cur, n))
{
return true;
}
if (_nodes > _budget)
{
return false;
}
continue;
}
for (var b = 0; b < _capacity; b++)
{
if (b == a || _slotId[b] == 0 || !Has(toolKinds, _slotKind[b]) || !(meetsA || ((_meetsTool[m + (b >> 6)] >> (b & 63)) & 1UL) != 0UL))
{
continue;
}
if (Try(r, v, a, b, cur, n))
{
return true;
}
if (_nodes > _budget)
{
return false;
}
}
}
}
return false;
}
// Takes the step v on (a, b) as the last of r: regress through it and search the rest.
private bool Try(int r, int v, int a, int b, int cur, int n)
{
_nodes++;
if (_nodes > _budget || !Regress(v, a, b, cur, n, (r - 1) * _stride, out var count))
{
return false;
}
_setCount[r - 1] = count;
_stepVerb[r - 1] = v;
_stepThis[r - 1] = a;
_stepTool[r - 1] = b;
return Search(r - 1);
}
// Which groundings of the verb give a literal the set at r still needs: a Self give meets one whatever the grounding (meetsSelf),
// a This give meets the one on the slot it is grounded on, a Tool give likewise; those slots are left in the level's masks.
// False when no grounding of the verb meets anything.
private bool Meets(int v, int r, int cur, int n, out bool meetsSelf)
{
meetsSelf = false;
var m = r * _words;
for (var w = 0; w < _words; w++)
{
_meetsThis[m + w] = 0UL;
_meetsTool[m + w] = 0UL;
}
var any = false;
var gives = _gives[v];
for (var g = 0; g < gives.Length; g++)
{
var gf = gives[g];
for (var i = 0; i < n; i++)
{
var l = _set[cur + i];
if (_moves[v] && gf.Subject == FactSubject.This && gf.Bit == 63 && gf.Value && ((l >> 1) & 63) == 63 && (l >> 7) > 0)
{
// A move: the literal on slot o holds after it for every This slot a with o near a exactly as the literal says (a == o is near).
var o = (l >> 7) - 1;
for (var a = 0; a < _capacity; a++)
{
if (_slotId[a] != 0 && Near(o, a) == ((l & 1) != 0))
{
_meetsThis[m + (a >> 6)] |= 1UL << (a & 63);
any = true;
}
}
continue;
}
if (((l >> 1) & 63) != gf.Bit || (l & 1) != (gf.Value ? 1 : 0))
{
continue;
}
var thing = l >> 7;
if (gf.Subject == FactSubject.Self)
{
if (thing == 0)
{
meetsSelf = true;
any = true;
}
}
else if (thing > 0)
{
var mask = gf.Subject == FactSubject.This ? _meetsThis : _meetsTool;
mask[m + ((thing - 1) >> 6)] |= 1UL << ((thing - 1) & 63);
any = true;
}
}
}
return any;
}
private static bool Has(uint[] kinds, uint kind)
{
for (var i = 0; i < kinds.Length; i++)
{
if (kinds[i] == kind)
{
return true;
}
}
return false;
}
private static uint[]? Kinds(TargetFilter? filter)
{
if (filter is null)
{
return null;
}
var kinds = new uint[filter.Kinds.Count];
for (var i = 0; i < kinds.Length; i++)
{
kinds[i] = filter.Kinds[i];
}
return kinds;
}
// The set before the step: what the step gives that is needed is met, what it needs is added. False when the
// step undoes something needed or leaves a literal and its negation. That it meets something is Search's relevance check.
private bool Regress(int v, int a, int b, int cur, int n, int next, out int count)
{
count = 0;
var gives = _gives[v];
for (var g = 0; g < gives.Length; g++)
{
var lit = Ground(gives[g], a, b);
for (var i = 0; i < n; i++)
{
var l = _set[cur + i];
if ((l >> 1) != (lit >> 1))
{
continue;
}
if (l != lit)
{
return false;
}
}
}
for (var i = 0; i < n; i++)
{
var l = _set[cur + i];
var given = false;
for (var g = 0; g < gives.Length && !given; g++)
{
given = Ground(gives[g], a, b) == l;
}
if (!given && _moves[v] && ((l >> 1) & 63) == 63 && (l >> 7) > 0 && (l >> 7) - 1 != a)
{
// After a move to a, every other thing is in reach exactly when it is near a: that literal is met or the step is refused.
if (Near((l >> 7) - 1, a) != ((l & 1) != 0))
{
return false;
}
given = true;
}
if (!given)
{
_set[next + count++] = l;
}
}
var needs = _needs[v];
for (var k = 0; k < needs.Length; k++)
{
var lit = Ground(needs[k], a, b);
var present = false;
for (var i = 0; i < count; i++)
{
var l = _set[next + i];
if (l == lit)
{
present = true;
}
else if (l == (lit ^ 1))
{
return false;
}
}
if (!present)
{
_set[next + count++] = lit;
}
}
return true;
}
// The one reach test: squared distance of remembered positions against reach squared. The start state applies it to the observer point.
private bool Near(int o, int a)
{
double dx = _px[o] - _px[a], dy = _py[o] - _py[a], dz = _pz[o] - _pz[a];
return dx * dx + dy * dy + dz * dz <= _reach * _reach;
}
private bool Holds(int lit) => (int)((_facts[lit >> 7] >> ((lit >> 1) & 63)) & 1UL) == (lit & 1);
private static int Lit(int thing, int bit, bool value) => (thing << 7) | (bit << 1) | (value ? 1 : 0);
private static int Ground(Fact f, int thisSlot, int toolSlot) =>
Lit(f.Subject == FactSubject.Self ? 0 : (f.Subject == FactSubject.This ? thisSlot : toolSlot) + 1, f.Bit, f.Value);
private static PlanStep Step(int verb, ulong thisId, ulong toolId) => new PlanStep(verb, thisId, toolId);
private void Check(Perception perception, int targetSlot, Fact want, int depth, int planLength, int budget, int fromDepth)
{
if (budget < 1)
{
throw new ArgumentOutOfRangeException(nameof(budget), "The budget must be at least 1.");
}
if (perception is null)
{
throw new ArgumentNullException(nameof(perception));
}
if (perception.PerceptCount != _capacity)
{
throw new ArgumentException($"The planner holds {_capacity} percept slots; the perception has {perception.PerceptCount}.", nameof(perception));
}
if (depth < 0 || depth > MaxDepth)
{
throw new ArgumentOutOfRangeException(nameof(depth), $"The depth must be in 0..{MaxDepth}.");
}
if (fromDepth < 1 || fromDepth > Math.Max(depth, 1))
{
throw new ArgumentOutOfRangeException(nameof(fromDepth), "The first depth must be in 1..max(depth, 1).");
}
if (planLength < depth)
{
throw new ArgumentException("The plan span is shorter than the depth.", "plan");
}
if (want.Subject == FactSubject.Tool || (uint)want.Subject > 2u || (uint)want.Bit > 63u)
{
throw new ArgumentException("The want is about self or the target, on a bit in 0..63.", nameof(want));
}
if (want.Subject == FactSubject.Self && want.Bit == 63)
{
throw new ArgumentException("Bit 63 is Lodur's reach; self has none.", nameof(want));
}
if (want.Subject == FactSubject.This && ((uint)targetSlot >= (uint)_capacity || perception.Percept(targetSlot).Id == 0))
{
throw new ArgumentException("A want on the target needs an occupied target slot.", nameof(targetSlot));
}
}
internal static Fact[] Copy(IReadOnlyList<Fact> facts)
{
var copy = new Fact[facts.Count];
for (var i = 0; i < copy.Length; i++)
{
copy[i] = facts[i];
}
return copy;
}
private static void Validate(int index, Verb verb)
{
var name = $"Verb {index} ({verb.Id})";
if ((verb.This is not null && verb.This.Kinds.Count == 0) || (verb.Tool is not null && verb.Tool.Kinds.Count == 0))
{
throw new ArgumentException($"{name} has a filter with no kinds.");
}
if (verb.Gives.Count == 0)
{
throw new ArgumentException($"{name} gives nothing.");
}
if (verb.Needs.Count > MaxNeeds || verb.Gives.Count > MaxNeeds)
{
throw new ArgumentException($"{name} has more than {MaxNeeds} needs or gives.");
}
ValidateFacts(name, verb, verb.Needs);
ValidateFacts(name, verb, verb.Gives);
}
private static void ValidateFacts(string name, Verb verb, IReadOnlyList<Fact> facts)
{
for (var i = 0; i < facts.Count; i++)
{
var f = facts[i];
if ((uint)f.Bit > 63u || (uint)f.Subject > 2u)
{
throw new ArgumentException($"{name} has a fact on bit {f.Bit} of subject {f.Subject}; bits are 0..63.");
}
if (f.Subject == FactSubject.Tool && verb.Tool is null)
{
throw new ArgumentException($"{name} has a Tool fact but takes no second thing.");
}
if (f.Subject == FactSubject.Self && f.Bit == 63)
{
throw new ArgumentException($"{name} has a Self fact on bit 63, which is Lodur's reach.");
}
for (var j = 0; j < i; j++)
{
if (facts[j].Subject == f.Subject && facts[j].Bit == f.Bit && facts[j].Value != f.Value)
{
throw new ArgumentException($"{name} lists {f.Subject} bit {f.Bit} both ways.");
}
}
}
}
}
}

View file

@ -0,0 +1,208 @@
using System;
using System.Collections.Generic;
namespace Lodur
{
/// <summary>The pose behaviour's tunables.</summary>
public sealed record HoldParameters
{
/// <summary>Muscle strength written for every muscle, in [0, 1] (above 1 an explicit PD arm sags and drifts).</summary>
public float HoldStrength { get; init; } = 1f;
/// <summary>How far the reflex leak pulls the pose from its base toward the flinch pose, per unit of leak.</summary>
public double FlinchGain { get; init; } = 0.3;
/// <summary>Strain shake amplitude (blend fraction) per unit of strain. Zero strain, no shake. Measured at the palm of the ragdoll with hands (hand mass damps the arm's response), where it makes the 3-7 cm shake in hand height the strain rule describes.</summary>
public double StrainShake { get; init; } = 0.08;
/// <summary>Shake frequency. A few Hz: the arm's PD filters anything faster to nothing.</summary>
public double ShakeHz { get; init; } = 3.5;
}
/// <summary>
/// The one behaviour a goal can have: a pose held, or a loop through pose keys, with the reflex leak and a
/// strain-scaled shake blending the base pose toward the flinch pose. One key is held as it is; k keys are
/// walked in a loop, <see cref="SecondsPerKey"/> from each to the next and the last back to the first.
/// It writes per-muscle strength and target rotation into the caller's spans and nothing else (invariant
/// body-one-interface). The poses are the consumer's data, one rotation per muscle. A release is the same
/// behaviour with a key and a flinch pose equal and the gains zero.
/// </summary>
public sealed record PoseBehaviour
{
private Quat[][] _keys = Array.Empty<Quat[]>();
private Quat[] _flinch = Array.Empty<Quat>();
private IReadOnlyList<IReadOnlyList<Quat>> _keysView = Array.AsReadOnly(Array.Empty<IReadOnlyList<Quat>>());
private IReadOnlyList<Quat> _flinchView = Array.AsReadOnly(Array.Empty<Quat>());
/// <summary>k keys of one rotation per muscle each. Copied when set; read back as a read-only view.</summary>
public IReadOnlyList<IReadOnlyList<Quat>> Keys
{
get => _keysView;
init
{
var copy = new Quat[value.Count][];
var views = new IReadOnlyList<Quat>[copy.Length];
for (var k = 0; k < copy.Length; k++)
{
copy[k] = new Quat[value[k].Count];
for (var m = 0; m < copy[k].Length; m++)
{
copy[k][m] = value[k][m];
}
views[k] = Array.AsReadOnly(copy[k]);
}
_keys = copy;
_keysView = Array.AsReadOnly(views);
}
}
/// <summary>Seconds from one key to the next when there is more than one key.</summary>
public double SecondsPerKey { get; init; } = 1.0;
/// <summary>The pose the leak and the shake pull toward, one rotation per muscle. Copied when set; read back as a read-only view.</summary>
public IReadOnlyList<Quat> FlinchPose
{
get => _flinchView;
init
{
_flinch = new Quat[value.Count];
for (var m = 0; m < _flinch.Length; m++)
{
_flinch[m] = value[m];
}
_flinchView = Array.AsReadOnly(_flinch);
}
}
public HoldParameters Hold { get; init; } = new HoldParameters();
/// <summary>Aims the neck at the committed target. Null: no layer. Layers need a BodyPlan on the Actor.</summary>
public LookLayer? Look { get; init; }
/// <summary>Drives one or both arms by the arm solver: reach the target, ward it off, or present the wrists. Null: no layer.</summary>
public ArmLayer? Arms { get; init; }
/// <summary>Shrinks the pose from the target by its bearing and proximity. Null: no layer.</summary>
public RecoilLayer? Recoil { get; init; }
/// <summary>Whether any orient layer is present. Such a behaviour needs the Actor to hold a <see cref="BodyPlan"/> and be given part poses each tick.</summary>
public bool HasLayers => Look != null || Arms != null || Recoil != null;
public int MuscleCount => _keys.Length == 0 ? 0 : _keys[0].Length;
internal void Validate(string goal)
{
if (_keys.Length == 0 || _keys[0].Length == 0)
{
throw new ArgumentException($"Goal {goal}: a pose behaviour needs at least one key of at least one muscle.");
}
foreach (var key in _keys)
{
if (key.Length != _keys[0].Length)
{
throw new ArgumentException($"Goal {goal}: every key needs one rotation per muscle.");
}
}
if (_flinch.Length != _keys[0].Length)
{
throw new ArgumentException($"Goal {goal}: the flinch pose needs one rotation per muscle.");
}
if (_keys.Length > 1 && !(SecondsPerKey > 0.0 && double.IsFinite(SecondsPerKey)))
{
throw new ArgumentException($"Goal {goal}: SecondsPerKey must be positive and finite.");
}
Look?.Validate(goal);
Arms?.Validate(goal);
Recoil?.Validate(goal, _keys[0].Length);
}
/// <summary>The blend toward the flinch pose: the leak and the shake, clamped to [0, 1]. <paramref name="seconds"/> is the Actor's absolute time.</summary>
public double Blend(double leak, double strain, double seconds)
{
var w = leak * Hold.FlinchGain + Hold.StrainShake * strain * Math.Sin(2.0 * Math.PI * Hold.ShakeHz * seconds);
return Math.Min(Math.Max(w, 0.0), 1.0);
}
/// <summary>
/// Writes one tick's strengths and targets. The strength is <see cref="HoldParameters.HoldStrength"/> scaled by the
/// <paramref name="weight"/> in [0, 1] (the will that powers the layer, or 1 while it is involuntary) plus the leaked
/// reflex, capped at 1: a reflex that gets past a failing will still moves the muscle. The target rule is
/// <see cref="Blend"/>, unchanged. A behaviour with orient layers needs the Actor's part poses and refuses this overload.
/// </summary>
public void Write(double weight, double leak, double strain, double seconds, double secondsInGoal, Span<float> strengths, Span<Quat> targets)
{
Write(weight, leak, strain, seconds, secondsInGoal, strengths, targets, default);
}
/// <summary>
/// The same, with the orient layers composed between the keys and the flinch: the base key pose, then recoil, look and the arms (each a
/// blend toward its solution), then the flinch blend over every muscle. With a rig, the arms are composed on every call, driven or
/// released, so an arm the goal stopped driving eases back to the base pose. Layers write joint targets only; the strength line is the pose rule's.
/// With no layers, the arithmetic is the key loop's, operation for operation.
/// </summary>
internal void Write(double weight, double leak, double strain, double seconds, double secondsInGoal, Span<float> strengths, Span<Quat> targets, in OrientInput orient)
{
var count = MuscleCount;
if (strengths.Length != count || targets.Length != count)
{
throw new ArgumentException($"strengths and targets need {count} entries, one per muscle.");
}
if (!(weight >= 0.0 && weight <= 1.0))
{
throw new ArgumentOutOfRangeException(nameof(weight), "The weight must be in [0, 1].");
}
var layered = HasLayers;
if (layered && orient.Rig == null)
{
throw new ArgumentException("A behaviour with orient layers needs the Actor's orient input.");
}
var w = (float)Blend(leak, strain, seconds);
var strength = Hold.HoldStrength * (float)Math.Min(1.0, weight + leak * Hold.FlinchGain);
var k = _keys.Length;
var from = 0;
var to = 0;
var phase = 0f;
if (k > 1)
{
var p = secondsInGoal / SecondsPerKey;
var whole = Math.Floor(p);
from = (int)(whole % k);
to = (from + 1) % k;
phase = (float)(p - whole);
}
for (var m = 0; m < count; m++)
{
var a = _keys[from][m];
if (phase > 0f)
{
a = Quat.Nlerp(_keys[from][m], _keys[to][m], phase);
}
strengths[m] = strength;
targets[m] = a;
}
if (orient.Rig != null)
{
orient.Rig.Compose(this, orient, targets);
}
for (var m = 0; m < count; m++)
{
targets[m] = Quat.Nlerp(targets[m], _flinch[m], w);
}
}
}
}

View file

@ -0,0 +1,54 @@
using System;
namespace Lodur
{
/// <summary>The withdrawal reflex's tunables.</summary>
public sealed record WithdrawalParameters
{
/// <summary>How much of the reflex a fully resolved will can hold down (0..1).</summary>
public double MaxSuppression { get; init; } = 0.95;
public double FlinchLeakThreshold { get; init; } = 0.3;
public double FlinchRefractorySeconds { get; init; } = 0.5;
}
/// <summary>
/// Layer 2 for one body region. Its gain is set ahead of time by the drive: it reads the drive state the
/// previous tick left, before the drive steps (invariant reflex-gain-from-drive). What the suppression holds
/// down is the strain load; what leaks past is the reflex command and, over the threshold, a flinch.
/// </summary>
public sealed class WithdrawalReflex
{
private readonly WithdrawalParameters _p;
private readonly long _refractory;
private long _tick;
private long _lastFlinch = long.MinValue / 2;
public WithdrawalReflex(WithdrawalParameters parameters, double tickSeconds)
{
_p = parameters;
_refractory = (long)Math.Round(parameters.FlinchRefractorySeconds / tickSeconds);
}
/// <summary>The part of the afferent signal that gets past the will this tick.</summary>
public double Leak { get; private set; }
/// <summary>The part the will holds down this tick: the strain the drive accumulates.</summary>
public double StrainLoad { get; private set; }
/// <summary>Steps once; returns true on a flinch (leak over the threshold, outside the refractory window).</summary>
public bool Step(double afferent, in DriveState drive)
{
var suppression = _p.MaxSuppression * drive.Will;
Leak = afferent * (1.0 - suppression);
StrainLoad = afferent * suppression;
var flinch = Leak > _p.FlinchLeakThreshold && _tick - _lastFlinch >= _refractory;
if (flinch)
{
_lastFlinch = _tick;
}
_tick++;
return flinch;
}
}
}

View file

@ -0,0 +1,272 @@
using Lodur;
using static Lodur.Core.Tests.PhysioFixtures;
namespace Lodur.Core.Tests;
/// <summary>The Actor steps its Physiology first, writes the Consciousness slot from it, scales strengths by the motor ceiling, and goes limp when it dies.</summary>
public sealed class ActorPhysiologyTests
{
private static readonly float[] NoPoint = { 0f };
private static Brain HoldBrain() => new()
{
Goals = new[] { new GoalSpec { Id = "g", Behaviour = new PoseBehaviour { Keys = new[] { PainBoxBrain.Hold }, FlinchPose = PainBoxBrain.Withdraw, Hold = new HoldParameters { HoldStrength = 0.7f } } } },
};
private static Actor Make(Physiology? physiology, DriveParameters? drive = null) =>
new(0.01, 1, new NerveParameters(), new WithdrawalParameters(), drive ?? new DriveParameters(), HoldBrain(), physiology: physiology);
private static TickEvents Tick(Actor a, double intensity, float[] strengths, Quat[] targets)
{
var box = new[] { new BoxStimulus(0f, 0f, 0f, 1f, 1f, 1f) { Intensity = intensity } };
return a.Tick(NoPoint, NoPoint, NoPoint, box, strengths, targets);
}
[Fact]
public void The_slot_is_the_physiologys_consciousness_every_tick_and_strengths_are_held_to_each_joints_ceiling()
{
var p = Make3();
Assert.True(p.Afflict(Af("Lesion"), 0, BrainLayer, 4)); // consciousness 0.6
Assert.True(p.Afflict(Af("MotorHalf"), 1, 0, 1)); // joint 0 at half
var a = Make(p, new DriveParameters { WillCurve = 0.5 });
var s = new float[2];
var q = new Quat[2];
for (var i = 0; i < 50; i++)
{
Tick(a, 0.0, s, q);
Assert.Equal(p.Consciousness, a.Drive.Consciousness);
Assert.Equal(0.6, p.Consciousness, 12);
var raw = 0.7f * (float)Math.Sqrt(a.Drive.Will);
Assert.Equal(raw * (float)p.MotorCeiling(0), s[0]);
Assert.Equal(raw * (float)p.MotorCeiling(1), s[1]);
Assert.Equal(0.3, p.MotorCeiling(0), 12);
Assert.Equal(0.6, p.MotorCeiling(1), 12);
}
}
private static Physiology Make3() => PhysioFixtures.Make();
[Fact]
public void An_actor_with_no_physiology_keeps_the_slot_at_one_and_scales_nothing()
{
var a = Make(null);
var s = new float[2];
var q = new Quat[2];
for (var i = 0; i < 20; i++) Tick(a, 0.0, s, q);
Assert.Equal(1.0, a.Drive.Consciousness);
Assert.Equal(0.7f, s[0]);
Assert.Null(a.Physiology);
}
[Fact]
public void A_physiology_bound_to_one_actor_is_refused_by_a_second_and_strengths_of_the_wrong_length_throw()
{
var p = Make3();
var a = Make(p);
Assert.Same(p, a.Physiology);
Assert.Throws<ArgumentException>(() => Make(p));
Assert.True(p.Afflict(Af("Bleeder"), 1, 0, 1));
var q = new Quat[2];
Assert.Throws<ArgumentException>(() => Tick(a, 0.0, new float[1], q));
Assert.Throws<ArgumentException>(() => Tick(a, 0.0, new float[3], q));
Assert.Equal(0, a.TickCount); // a refused call changes nothing, the physiology included
Assert.Equal(0.0, p.SlotAge(0));
Assert.Equal(0.005, p.BloodVolume);
}
[Fact]
public void Death_is_reported_once_and_is_limp_and_the_actor_never_changes_again()
{
var p = Make3();
var a = Make(p);
var s = new float[2];
var q = new Quat[2] { Quat.FromAxisAngle(1f, 0f, 0f, 0.5f), Quat.FromAxisAngle(0f, 1f, 0f, 0.5f) };
for (var i = 0; i < 100; i++) Assert.Equal(TickEvents.None, Tick(a, 0.8, s, q) & TickEvents.Died);
Assert.True(s[0] > 0f && a.Drive.Pain > 0.0);
q[0] = Quat.FromAxisAngle(0f, 0f, 1f, 0.3f); // a value no behaviour writes: a dead actor leaves targets as they are
q[1] = Quat.FromAxisAngle(0f, 1f, 0f, 0.4f);
var sentinel = q.ToArray();
Assert.True(p.Afflict(Af("Lesion"), 0, Heart, 10));
var died = Tick(a, 0.8, s, q);
Assert.Equal(TickEvents.Died, died);
Assert.Equal(DeathCause.VitalTissue, p.Cause);
Assert.Equal(new float[2], s);
Assert.Equal(sentinel, q); // targets are left as they were
var frozen = a.Drive;
var goal = a.GoalIndex;
var ticks = a.TickCount;
for (var i = 0; i < 200; i++)
{
s[0] = s[1] = 0.5f;
Assert.Equal(TickEvents.None, Tick(a, 0.8, s, q));
Assert.Equal(new float[2], s);
Assert.Equal(frozen, a.Drive);
Assert.Equal(goal, a.GoalIndex);
}
Assert.Equal(ticks + 200, a.TickCount);
Assert.Equal(sentinel, q);
Assert.Equal(0.0, frozen.Consciousness);
Assert.Equal(0.0, frozen.Will);
}
[Fact]
public void A_dead_physiologys_flows_stand_on_the_tick_it_died_and_read_zero_after()
{
var airway = InertAirway with { CoughByConsciousness = new[] { (0.0, 1.0), (1.0, 1.0) } }; // a cough that does not need consciousness, so it still runs on the step the brain lesion kills
var p = Bleeding(0.5, 1.0, airway, new BloodDef(1000.0, 0.5, 1e-4)); // bleeds into the airway, which coughs and drains; the blood is too deep to run out
var a = Make(p);
var s = new float[2];
var q = new Quat[2];
var box = new[] { new BoxStimulus(0f, 0f, 0f, 1f, 1f, 1f) { Intensity = 0.0 } };
var air = new AirwaySample(1e-6, 1e-6, airway.DrainDrop);
for (var i = 0; i < 10; i++) Assert.Equal(TickEvents.None, a.Tick(NoPoint, NoPoint, NoPoint, box, s, q, airway: air) & TickEvents.Died);
Assert.True(p.Bleed(0) > 0.0 && p.AirwayBleed > 0.0 && p.DrawnLive > 0.0 && p.DrawnPooled > 0.0 && p.Coughed > 0.0 && p.Drained > 0.0);
Assert.True(p.Afflict(Af("Lesion"), 0, BrainLayer, 10)); // not the heart: a stopped heart would stop the bleed on the dying step
Assert.Equal(TickEvents.Died, a.Tick(NoPoint, NoPoint, NoPoint, box, s, q, airway: air));
Assert.True(p.Dead);
Assert.True(p.Bleed(0) > 0.0, "the dying step's bleed was not reported"); // Lodur reports the step it died on
Assert.True(p.AirwayBleed > 0.0 && p.DrawnLive > 0.0 && p.DrawnPooled > 0.0 && p.Coughed > 0.0 && p.Drained > 0.0, "a flow of the dying step was not reported");
Assert.Equal(TickEvents.None, a.Tick(NoPoint, NoPoint, NoPoint, box, s, q, airway: air));
Assert.Equal(0.0, p.Bleed(0));
Assert.Equal(0.0, p.AirwayBleed);
Assert.Equal(0.0, p.DrawnLive);
Assert.Equal(0.0, p.DrawnPooled);
Assert.Equal(0.0, p.Coughed);
Assert.Equal(0.0, p.Drained);
}
[Fact]
public void A_physiology_that_died_before_it_was_bound_reports_the_death_on_the_first_tick()
{
var p = Make3();
Assert.True(p.Afflict(Af("Lesion"), 0, Heart, 10));
p.Step(0.01);
Assert.True(p.Dead);
var a = Make(p);
var s = new float[2] { 1f, 1f };
Assert.Equal(TickEvents.Died, Tick(a, 0.0, s, new Quat[2]));
Assert.Equal(new float[2], s);
Assert.Equal(TickEvents.None, Tick(a, 0.0, s, new Quat[2]));
}
[Fact]
public void The_actor_reports_its_last_ticks_strength_as_effort()
{
double Oxygen(float hold)
{
var brain = new Brain
{
Goals = new[] { new GoalSpec { Id = "g", Behaviour = new PoseBehaviour { Keys = new[] { PainBoxBrain.Hold }, FlinchPose = PainBoxBrain.Withdraw, Hold = new HoldParameters { HoldStrength = hold } } } },
};
var p = Make3();
Assert.True(p.Afflict(Af("Choke"), 0, 0, 1e9));
var a = new Actor(0.01, 1, new NerveParameters(), new WithdrawalParameters(), new DriveParameters(), brain, physiology: p);
var s = new float[2];
var q = new Quat[2];
for (var i = 0; i < 3000; i++) Tick(a, 0.0, s, q);
Assert.False(p.Dead);
return p.BloodOxygen;
}
var strong = Oxygen(0.7f);
var idle = Oxygen(0.0f);
Assert.True(strong < idle, $"strong {strong}, idle {idle}");
}
[Fact]
public void The_actor_steps_its_physiology_on_the_drives_arousal_and_the_strength_it_applied_after_the_ceiling()
{
Physiology Body()
{
var q = Make3();
Assert.True(q.Afflict(Af("Choke"), 0, 0, 1e9)); // the stores move every tick
Assert.True(q.Afflict(Af("MotorHalf"), 1, 0, 1)); // joint 0 at half: the ceiling makes the applied strength differ from the asked one
return q;
}
var p = Body();
var twin = Body();
var a = new Actor(0.01, 1, new NerveParameters(), new WithdrawalParameters(), new DriveParameters(), HoldBrain(),
new NerveParameters { Threshold = 0.05, SensitisationGrowth = 0.0 }, 0, physiology: p);
var loud = SensoryRig.One(0.55);
var s = new float[2];
var q = new Quat[2];
double arousalBefore = 0.0, effortBefore = 0.0, peakArousal = 0.0;
var peakEffort = 0.0;
for (var i = 0; i < 1500; i++)
{
twin.Step(0.01, new PhysiologyInput(arousalBefore, effortBefore));
a.Tick(NoPoint, NoPoint, NoPoint, ReadOnlySpan<BoxStimulus>.Empty, s, q, loud);
Assert.Equal(twin.BloodOxygen, p.BloodOxygen);
Assert.Equal(twin.BrainOxygen, p.BrainOxygen);
arousalBefore = a.Drive.Arousal;
effortBefore = ((double)s[0] + s[1]) / 2.0;
peakArousal = Math.Max(peakArousal, arousalBefore);
peakEffort = Math.Max(peakEffort, effortBefore);
}
Assert.True(peakArousal > 0.1, $"arousal never rose: {peakArousal}");
Assert.True(peakEffort > 0.1, $"no strength was applied: {peakEffort}");
}
[Fact]
public void A_healthy_physiology_changes_nothing_bit_for_bit()
{
foreach (var seed in new ulong[] { 1, 2, 3 })
{
var plain = new PainBoxReplay(seed);
var with = new PainBoxReplay(seed, physiology: Make3());
for (var i = 0; i < 4000; i++)
{
var on = i < 2500;
Assert.Equal(plain.Tick(on), with.Tick(on));
var a = plain.Actor.Drive;
var b = with.Actor.Drive;
Assert.Equal(BitConverter.DoubleToInt64Bits(a.Pain), BitConverter.DoubleToInt64Bits(b.Pain));
Assert.Equal(BitConverter.DoubleToInt64Bits(a.Strain), BitConverter.DoubleToInt64Bits(b.Strain));
Assert.Equal(BitConverter.DoubleToInt64Bits(a.Resolve), BitConverter.DoubleToInt64Bits(b.Resolve));
Assert.Equal(a.Consciousness, b.Consciousness);
Assert.Equal(plain.Actor.GoalIndex, with.Actor.GoalIndex);
Assert.Equal(plain.Strengths, with.Strengths);
}
Assert.True(plain.Actor.Drive.Breaks > 0 && plain.Actor.GoalIndex == 1, "the replay never reached the withdraw goal");
}
}
/// <summary>The measuring loop lives here, fully optimised from its first call, so the tier-up and its first-tier instrumentation cannot allocate inside the measurement; only Actor.Tick's own bytes are counted.</summary>
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining | System.Runtime.CompilerServices.MethodImplOptions.AggressiveOptimization)]
private static long AllocatedByTicking(Actor a, BoxStimulus[] box, float[] s, Quat[] q, int n)
{
var before = GC.GetAllocatedBytesForCurrentThread();
for (var i = 0; i < n; i++) a.Tick(NoPoint, NoPoint, NoPoint, box, s, q);
return GC.GetAllocatedBytesForCurrentThread() - before;
}
[Fact]
public void A_tick_with_a_physiology_and_eight_bleeding_afflictions_allocates_nothing()
{
var p = new Physiology(Body3(), Plan3(blood: new BloodDef(1000.0, 0.5, 1e-4), slots: 9, organism: new[] { Hypoxia }), 20);
for (var i = 0; i < 4; i++)
{
Assert.True(p.Afflict(Af("Bleeder"), 1 + i % 2, 0, 0.5 + 0.1 * i));
Assert.True(p.Afflict(Af("Clot"), 0, RootMuscle, 1.0));
}
Assert.True(p.Afflict(Af("Choke"), 0, 0, 0.8)); // the gases run and the hypoxia curve reads, through the warm-up and into the measured ticks
var a = Make(p);
var s = new float[2];
var q = new Quat[2];
var box = new[] { new BoxStimulus(0f, 0f, 0f, 1f, 1f, 1f) { Intensity = 0.5 } };
for (var i = 0; i < 2000; i++) a.Tick(NoPoint, NoPoint, NoPoint, box, s, q); // warm the JIT and the first-use paths
Assert.Equal(0L, AllocatedByTicking(a, box, s, q, 10000));
Assert.False(p.Dead);
Assert.Equal(8, Live(p));
Assert.True(p.Bleed(0) > 0.0 && p.Bleed(1) > 0.0);
}
}

View file

@ -0,0 +1,189 @@
using Lodur;
namespace Lodur.Core.Tests;
public sealed class ActorTests
{
[Fact]
public void Parity_seed_1_breaks_at_14730_ms_switches_goal_at_14830_ms_with_16_flinches()
{
var (broke, withdrew, flinches) = new PainBoxReplay(1).Run(120.0);
Assert.Equal(1473, broke);
Assert.Equal(1483, withdrew);
Assert.Equal(16, flinches);
}
[Fact]
public void Reflex_gain_is_set_ahead_of_time_suppression_uses_the_previous_resolve()
{
// Drain hard so resolve moves a lot on every tick; then the previous and the current resolve differ visibly.
var drive = new DriveParameters { ResolveDrainPain = 8.0, ResolveDrainStrain = 8.0 };
var w = new WithdrawalParameters();
var r = new PainBoxReplay(1, drive: drive);
var checkedTicks = 0;
while (r.Actor.TickCount < 3000 && !r.Actor.Drive.WillBroken)
{
var before = r.Actor.Drive;
r.Tick();
var after = r.Actor.Drive;
var afferent = r.Actor.Afferent(0);
if (before.Resolve < 0.9 && afferent > 0.2 && before.Resolve - after.Resolve > 1e-4 && !after.WillBroken)
{
var load = afferent * (w.MaxSuppression * before.Resolve);
var viaPrevious = before.Strain + PainBoxReplay.Dt * (load - 0.1 * before.Strain);
var viaCurrent = before.Strain + PainBoxReplay.Dt * (afferent * (w.MaxSuppression * after.Resolve) - 0.1 * before.Strain);
Assert.Equal(viaPrevious, after.Strain, 12);
Assert.True(Math.Abs(viaCurrent - after.Strain) > 1e-7);
checkedTicks++;
}
}
Assert.True(checkedTicks > 10);
}
[Fact]
public void Suppression_is_never_free_pain_is_identical_and_only_the_suppressed_run_accumulates_strain()
{
var held = new PainBoxReplay(2);
var free = new PainBoxReplay(2, withdrawal: new WithdrawalParameters { MaxSuppression = 0.0 });
for (var i = 0; i < 1000; i++)
{
held.Tick();
free.Tick();
Assert.Equal(free.Actor.Drive.Pain, held.Actor.Drive.Pain);
Assert.Equal(0.0, free.Actor.Drive.Strain);
}
Assert.True(held.Actor.Drive.Strain > 0.5);
Assert.True(held.Actor.Drive.Pain > 0.1);
}
[Fact]
public void A_broken_will_releases_suppression_and_the_deliberate_goal_switch_follows_its_latency()
{
var r = new PainBoxReplay(1);
long broke = -1, withdrew = -1;
var strain = 0.0;
for (long i = 0; i < 1600; i++)
{
var e = r.Tick();
if (broke >= 0)
{
// Nothing is held down any more: strain only decays, and a broken will stays broken.
Assert.True(r.Actor.Drive.WillBroken);
Assert.True(r.Actor.Drive.Strain < strain);
}
if ((e & TickEvents.WillBroke) != 0) broke = i;
if ((e & TickEvents.GoalChanged) != 0) withdrew = i;
Assert.Equal(withdrew >= 0 ? 1 : 0, r.Actor.GoalIndex); // 0 until GoalChanged, 1 from it
strain = r.Actor.Drive.Strain;
if (withdrew >= 0) break;
}
Assert.Equal(broke + 10, withdrew); // round(0.1 s / 10 ms)
// From GoalChanged the behaviour is the release behaviour's: the withdraw pose whatever the leak.
Assert.Equal(PainBoxReplay.Withdraw[0].X, r.Targets[0].X, 5);
Assert.Equal(PainBoxReplay.Withdraw[1].Z, r.Targets[1].Z, 5);
Assert.Equal(PainBoxReplay.Withdraw[0].W, r.Targets[0].W, 5);
}
[Fact]
public void Resolve_recovers_when_the_box_goes_quiet_and_not_when_recovery_is_off()
{
static double Resolve(double recovery)
{
var r = new PainBoxReplay(1, drive: new DriveParameters { ResolveRecovery = recovery });
for (var i = 0; i < 400; i++) r.Tick(); // 4 s in the box: resolve is down a little, will intact
var low = r.Actor.Drive.Resolve;
Assert.InRange(low, 0.85, 0.97);
for (var i = 0; i < 20000; i++) r.Tick(boxOn: false); // 200 s quiet: pain falls under the recovery line
Assert.False(r.Actor.Drive.WillBroken);
return r.Actor.Drive.Resolve - low;
}
Assert.True(Resolve(0.02) > 0.04); // recovers what it lost
Assert.True(Resolve(0.0) <= 0.0); // with recovery off it never rises (lingering pain still drains it)
}
[Fact]
public void A_flinch_is_a_suppressed_reflex_leaking_so_none_is_reported_after_the_will_breaks()
{
// Across seeds, some runs have a leak over the threshold, outside the refractory window, in the ticks
// between WillBroke and Withdrew (BDS counts none there). The golden table pins the totals; this pins the rule.
var sawLeakAfterBreak = 0;
for (ulong seed = 1; seed <= 60; seed++)
{
var r = new PainBoxReplay(seed);
var broke = false;
for (var i = 0; i < 4000; i++)
{
var e = r.Tick();
if (broke) Assert.Equal(0, (int)(e & TickEvents.Flinch));
broke |= (e & TickEvents.WillBroke) != 0;
if ((e & TickEvents.GoalChanged) != 0) break;
}
sawLeakAfterBreak += broke ? 1 : 0;
}
Assert.Equal(60, sawLeakAfterBreak);
}
private static long BreakTick(double intensity, double pull)
{
var (broke, _, _) = new PainBoxReplay(1, intensity, pull).Run(3000.0);
return broke;
}
[Fact]
public void Break_time_is_ordered_by_intensity_and_by_pull_and_no_stimulus_never_breaks()
{
long a = BreakTick(1.0, 0.5), b = BreakTick(0.8, 0.5), c = BreakTick(0.6, 0.5);
Assert.True(a > 0 && a < b && b < c, $"intensity: {a} {b} {c}");
long p0 = BreakTick(0.8, 0.0), p5 = BreakTick(0.8, 0.5), p8 = BreakTick(0.8, 0.8);
Assert.True(p0 > 0 && p0 < p5 && p5 < p8, $"pull: {p0} {p5} {p8}");
var quiet = new PainBoxReplay(1, intensity: 0.0);
for (var i = 0; i < 60000; i++) Assert.Equal(TickEvents.None, quiet.Tick());
Assert.Equal(0.0, quiet.Actor.Drive.Pain);
Assert.Equal(0.0, quiet.Actor.Drive.Strain);
Assert.Equal(1.0, quiet.Actor.Drive.Resolve);
Assert.False(quiet.Actor.Drive.WillBroken);
}
[Fact]
public void Tick_allocates_nothing_in_steady_state()
{
var r = new PainBoxReplay(1);
r.Tick(); // warm
var before = GC.GetAllocatedBytesForCurrentThread();
for (var i = 0; i < 10000; i++) r.Tick();
Assert.Equal(0L, GC.GetAllocatedBytesForCurrentThread() - before);
}
[Fact]
public void Two_actors_ticked_interleaved_equal_the_same_actors_ticked_alone()
{
const int n = 2500;
var a1 = new PainBoxReplay(1);
var b1 = new PainBoxReplay(7, intensity: 0.6, pull: 0.2);
var a2 = new PainBoxReplay(1);
var b2 = new PainBoxReplay(7, intensity: 0.6, pull: 0.2);
var ea = new TickEvents[n];
var eb = new TickEvents[n];
for (var i = 0; i < n; i++) { ea[i] = a1.Tick(); eb[i] = b1.Tick(); }
for (var i = 0; i < n; i++) Assert.Equal(ea[i], a2.Tick());
for (var i = 0; i < n; i++) Assert.Equal(eb[i], b2.Tick());
static void Same(PainBoxReplay x, PainBoxReplay y)
{
Assert.Equal(x.Actor.Drive.Pain, y.Actor.Drive.Pain);
Assert.Equal(x.Actor.Drive.Strain, y.Actor.Drive.Strain);
Assert.Equal(x.Actor.Drive.Resolve, y.Actor.Drive.Resolve);
Assert.Equal(x.Actor.Drive.WillBroken, y.Actor.Drive.WillBroken);
Assert.Equal(x.Actor.Afferent(0), y.Actor.Afferent(0));
Assert.Equal(x.Actor.Stimulus(0), y.Actor.Stimulus(0));
Assert.Equal(x.Actor.GoalIndex, y.Actor.GoalIndex);
Assert.Equal(x.Actor.TickCount, y.Actor.TickCount);
Assert.Equal(x.Strengths, y.Strengths);
Assert.Equal(x.Targets, y.Targets);
}
Same(a1, a2);
Same(b1, b2);
}
}

View file

@ -0,0 +1,344 @@
using Lodur;
using static Lodur.Core.Tests.PhysioFixtures;
namespace Lodur.Core.Tests;
/// <summary>
/// A wound in an airway tissue bleeds into the airway: the bleed splits at the tissue by its AirwayShare, the airway share enters at the caller's blood gain, and a full airway spills
/// through the mouth (idea bds-slice-map.gain-at-circulation-boundary; rulings bds-drown-in-own-blood-first, bds-blood-gain-simulated, bds-airway-cough-hold-drain).
/// The rule tests run on Body3 / Plan3 with a root muscle given an AirwayShare and a Bleeder (1e-3 m^3/s at severity 1, vascularity 1) on it.
/// </summary>
public sealed class AirwayBleedTests
{
private const double Dt = 0.01;
private const double Rate = 1e-3;
private static void Near(double expected, double actual) => Assert.InRange(Math.Abs(expected - actual), 0.0, 1e-12 * Math.Abs(expected));
[Theory]
[InlineData(0.25)]
[InlineData(0.0)]
[InlineData(1.0)]
public void A_tissues_bleed_splits_by_its_airway_share_and_the_blood_falls_by_both(double share)
{
var p = Bleeding(share, 1.0);
p.Step(Dt);
Assert.Equal(Rate * (1.0 - share), p.Bleed(0), 15);
Assert.Equal(Rate * share, p.AirwayBleed, 15);
Assert.Equal(0.0, p.Bleed(1));
Assert.Equal(0.0, p.Bleed(2));
var drop = 0.005 - p.BloodVolume;
Assert.Equal(Dt * (p.Bleed(0) + p.Bleed(1) + p.Bleed(2) + p.AirwayBleed), drop, 15);
Assert.Equal(Dt * Rate, drop, 15);
}
[Theory]
[InlineData(1.0, false)]
[InlineData(10.0, false)]
[InlineData(1.0, true)]
[InlineData(10.0, true)]
public void Blood_enters_the_airway_at_the_gain_held_breath_or_not(double gain, bool held)
{
var p = Bleeding(1.0, gain);
p.Step(Dt, new PhysiologyInput(0.0, 0.0, held));
Near(Dt * gain * p.AirwayBleed, p.AirwayLiquid);
Near(Dt * gain * Rate, p.AirwayLiquid);
Assert.Equal(0.0, p.Coughed);
Assert.Equal(0.0, p.Drained);
}
[Theory]
[InlineData(1.0)]
[InlineData(10.0)]
[InlineData(0.1)]
public void The_gain_is_applied_once_at_airway_entry_and_not_to_the_circulation_or_the_readouts(double gain)
{
const double share = 0.25;
var p = Bleeding(share, gain);
p.Step(Dt);
// Real m^3/s and real blood volume are ungained at any gain; only the airway's intake is.
Assert.Equal(Rate * (1.0 - share), p.Bleed(0), 15);
Assert.Equal(Rate * share, p.AirwayBleed, 15);
Near(Dt * Rate, 0.005 - p.BloodVolume);
Near(gain * Dt * Rate * share, p.AirwayLiquid);
}
[Fact]
public void A_breath_into_a_full_airway_spills_exactly_nothing_whatever_the_draw()
{
// The spill is only what bled in: a draw into a full airway must leave Drained exactly 0, not a rounding residue (after - Capacity - drawRaw leaves up to ~1e-20).
for (var k = 0; k < 400; k++)
{
var p = new Physiology(Body3(), Plan3(airway: Quiet), 20.0);
var wet = new AirwaySample(1e-4 * (1.0 + 0.0371 * k), 0.0, 0.0);
for (var i = 0; i < 200; i++)
{
p.Step(Dt * (1.0 + 0.013 * k), new PhysiologyInput(0.0, 0.0, false, wet));
Assert.Equal(0.0, p.Drained);
}
Assert.Equal(Quiet.Capacity, p.AirwayLiquid);
}
}
[Fact]
public void A_full_airway_spills_what_bleeds_into_it_through_the_mouth()
{
// Share 1, gain 10, a drain the sample opens (Drop at DrainDrop): fill, then 600 more steps.
var air = Quiet with { DrainPerSecond = 0.1 };
var p = Bleeding(1.0, 10.0, air, new BloodDef(1.0, 0.5, 0.0));
var drop = new AirwaySample(0.0, 0.0, air.DrainDrop);
double bledIn = 0.0, out_ = 0.0;
var steps = 0;
for (; p.AirwayLiquid < air.Capacity && steps < 100000; steps++) Step();
Assert.Equal(air.Capacity, p.AirwayLiquid);
for (var i = 0; i < 600; i++) Step();
Assert.Equal(air.Capacity, p.AirwayLiquid);
Assert.True(out_ > 0.0);
Near(10.0 * bledIn, out_ + p.AirwayLiquid);
void Step()
{
p.Step(Dt, new PhysiologyInput(0.0, 0.0, false, drop));
bledIn += p.AirwayBleed * Dt;
out_ += p.Coughed + p.Drained;
}
}
[Fact]
public void Every_airway_flow_is_at_least_zero_at_any_cough_rate()
{
// Drained was removed - Coughed + spill, with Coughed = removed x cough / total: for a cough that is not a power of two the product can exceed removed by an ulp and Drained read -5e-23 (BDS refuses a negative drain).
// Fill the airway, then clear it with drain on and off, and read every flow every step.
var humanoid = PhysiologyPlans.Humanoid().Airway;
var rates = new List<double> { 0.3, 0.36, 0.24, 2.0, humanoid.CoughPerSecond };
for (var k = 1; k <= 300; k++) rates.Add(0.01 * k);
foreach (var rate in rates)
{
foreach (var drop in new[] { 0.0, 0.5 * humanoid.DrainDrop, humanoid.DrainDrop })
{
var air = humanoid with { CoughPerSecond = rate };
var p = new Physiology(Body3(), Plan3(airway: air), 20.0);
var flood = new AirwaySample(100.0 * air.HoldAt, 0.0, drop);
var clear = new AirwaySample(0.0, 0.0, drop);
for (var i = 0; i < 1500; i++)
{
p.Step(Dt, new PhysiologyInput(0.0, 0.0, false, i < 100 ? flood : clear));
var at = $"cough {rate} drop {drop} step {i}";
Assert.True(p.Coughed >= 0.0, $"{at}: Coughed {p.Coughed:R}");
Assert.True(p.Drained >= 0.0, $"{at}: Drained {p.Drained:R}");
Assert.True(p.AirwayBleed >= 0.0 && p.DrawnLive >= 0.0 && p.DrawnPooled >= 0.0, $"{at}: a flow is negative");
Assert.True(p.AirwayLiquid >= 0.0, $"{at}: liquid {p.AirwayLiquid:R}");
}
}
}
}
[Fact]
public void A_breath_draws_only_into_the_room_left()
{
var p = Make(); // no wound: nothing bleeds
var pp = new Physiology(Body3(), Plan3(airway: Quiet), 20.0);
var wet = new AirwaySample(1e-3, 0.0, 0.0);
for (var i = 0; i < 100 && pp.AirwayLiquid < Quiet.Capacity; i++) pp.Step(Dt, new PhysiologyInput(0.0, 0.0, false, wet));
Assert.Equal(Quiet.Capacity, pp.AirwayLiquid);
for (var i = 0; i < 100; i++)
{
pp.Step(Dt, new PhysiologyInput(0.0, 0.0, false, wet));
Assert.Equal(Quiet.Capacity, pp.AirwayLiquid);
Assert.Equal(0.0, pp.Drained);
Assert.Equal(0.0, pp.Coughed);
Assert.Equal(0.0, pp.DrawnLive);
Assert.Equal(0.0, pp.DrawnPooled);
}
Assert.Equal(0.0, p.AirwayBleed);
}
[Fact]
public void A_breath_reports_what_it_drew_split_by_the_airways_weights()
{
var p = new Physiology(Body3(), Plan3(airway: Quiet), 20.0);
p.Step(Dt, new PhysiologyInput(0.0, 0.0, false, new AirwaySample(2e-5, 6e-5, 0.0)));
Near(Dt * 2e-5, p.DrawnLive);
Near(Dt * 6e-5, p.DrawnPooled);
var half = new Physiology(Body3(), Plan3(airway: Quiet with { PooledWeight = 0.5 }), 20.0);
half.Step(Dt, new PhysiologyInput(0.0, 0.0, false, new AirwaySample(2e-5, 6e-5, 0.0)));
Near(Dt * 2e-5, half.DrawnLive);
Near(Dt * 3e-5, half.DrawnPooled);
}
[Fact]
public void A_nearly_full_airway_draws_only_the_room_left()
{
var p = new Physiology(Body3(), Plan3(airway: Quiet), 20.0);
var wet = new AirwaySample(1e-3, 3e-3, 0.0);
for (var i = 0; i < 100 && p.AirwayLiquid < Quiet.Capacity; i++)
{
var room = Quiet.Capacity - p.AirwayLiquid;
p.Step(Dt, new PhysiologyInput(0.0, 0.0, false, wet));
if (Dt * 4e-3 > room)
{
Near(room, p.DrawnLive + p.DrawnPooled);
Near(0.25, p.DrawnLive / (p.DrawnLive + p.DrawnPooled));
Assert.Equal(Quiet.Capacity, p.AirwayLiquid);
}
}
Assert.Equal(Quiet.Capacity, p.AirwayLiquid);
}
[Fact]
public void A_held_breath_draws_nothing_while_the_airway_bleeds()
{
var p = Bleeding(1.0, 10.0);
p.Step(Dt, new PhysiologyInput(0.0, 0.0, true, new AirwaySample(1e-4, 1e-4, 0.0)));
Assert.Equal(0.0, p.DrawnLive);
Assert.Equal(0.0, p.DrawnPooled);
Near(Dt * 10.0 * Rate, p.AirwayLiquid);
}
[Fact]
public void The_airways_liquid_is_conserved_with_the_draw()
{
var p = Bleeding(0.5, 10.0, InertAirway, new BloodDef(1.0, 0.5, 0.0));
var rng = new Random(7);
var drew = 0.0;
for (var i = 0; i < 2000; i++)
{
var before = p.AirwayLiquid;
var sample = new AirwaySample(rng.NextDouble() * 1e-4, rng.NextDouble() * 1e-4, rng.NextDouble() * InertAirway.DrainDrop);
p.Step(Dt, new PhysiologyInput(0.0, 0.0, rng.NextDouble() < 0.2, sample));
Assert.True(p.DrawnLive >= 0.0 && p.DrawnPooled >= 0.0);
var expected = Dt * 10.0 * p.AirwayBleed + p.DrawnLive + p.DrawnPooled - p.Coughed - p.Drained;
Assert.InRange(Math.Abs(p.AirwayLiquid - before - expected), 0.0, 1e-18);
drew += p.DrawnLive + p.DrawnPooled;
}
Assert.True(drew > 0.0);
}
[Fact]
public void A_dry_sample_draws_exactly_zero_not_nan()
{
var p = new Physiology(Body3(), Plan3(airway: Quiet), 20.0);
for (var i = 0; i < 10; i++)
{
p.Step(Dt, new PhysiologyInput(0.0, 0.0, false, new AirwaySample(0.0, 0.0, 0.0)));
Assert.Equal(0.0, p.DrawnLive);
Assert.Equal(0.0, p.DrawnPooled);
}
var b = Bleeding(1.0, 10.0);
b.Step(Dt, new PhysiologyInput(0.0, 0.0, false));
Assert.Equal(0.0, b.DrawnLive);
Assert.Equal(0.0, b.DrawnPooled);
}
[Theory]
[InlineData(1.0)]
[InlineData(10.0)]
public void The_dying_step_into_a_full_airway_draws_nothing(double gain)
{
var p = Bleeding(0.5, gain, Quiet, new BloodDef(0.005, 0.5, 0.0));
var wet = new AirwaySample(1e-5, 1e-5, 0.0);
for (var i = 0; i < 100000 && !p.Dead; i++) p.Step(Dt, new PhysiologyInput(0.0, 0.0, false, wet));
Assert.True(p.Dead);
Assert.Equal(Quiet.Capacity, p.AirwayLiquid);
Assert.Equal(0.0, p.DrawnLive);
Assert.Equal(0.0, p.DrawnPooled);
}
[Fact]
public void The_dying_step_reports_its_draw_and_the_next_step_none()
{
var p = Bleeding(0.5, 0.1, InertAirway);
var pooled = new AirwaySample(1e-6, 1e-6, InertAirway.DrainDrop);
for (var i = 0; i < 100000 && !p.Dead; i++) p.Step(Dt, new PhysiologyInput(0.0, 0.0, false, pooled));
Assert.True(p.Dead);
Assert.True(p.DrawnPooled > 0.0);
Assert.True(p.DrawnLive > 0.0);
p.Step(Dt, new PhysiologyInput(0.0, 0.0, false, pooled));
Assert.Equal(0.0, p.DrawnLive);
Assert.Equal(0.0, p.DrawnPooled);
}
[Fact]
public void The_dying_step_reports_its_flows_and_the_next_step_none()
{
var p = Bleeding(0.5, 1.0, InertAirway); // cough 2/s and a drain, so Coughed and Drained read above 0 while it bleeds into the airway
var drop = new AirwaySample(0.0, 0.0, InertAirway.DrainDrop);
double lost = 0.0;
for (var i = 0; i < 100000 && !p.Dead; i++)
{
p.Step(Dt, new PhysiologyInput(0.0, 0.0, false, drop));
lost += Dt * (p.Bleed(0) + p.Bleed(1) + p.Bleed(2) + p.AirwayBleed);
}
Assert.True(p.Dead);
Assert.Equal(DeathCause.BloodLoss, p.Cause);
Assert.True(p.Bleed(0) > 0.0 && p.AirwayBleed > 0.0);
Near(0.005 - p.BloodVolume, lost);
Assert.True(p.Coughed > 0.0 && p.Drained > 0.0);
p.Step(Dt, new PhysiologyInput(0.0, 0.0, false, drop));
Assert.Equal(0.0, p.Bleed(0));
Assert.Equal(0.0, p.AirwayBleed);
Assert.Equal(0.0, p.Coughed);
Assert.Equal(0.0, p.Drained);
}
[Fact]
public void A_cut_larynx_fills_the_humanoids_airway_at_the_gain()
{
var body = BodyPlans.Humanoid();
var plan = PhysiologyPlans.Humanoid();
var head = body.PartIndex("Head");
var cut = plan.AfflictionIndex("Cut");
double Seconds(double gain)
{
var p = new Physiology(body, plan, 20.0, gain);
Assert.True(p.Afflict(cut, head, p.TissueIndex(head, "Larynx"), 60));
var input = new PhysiologyInput(0.5, 0.5);
for (var i = 0; i < 3.05 * 120; i++)
{
p.Step(1.0 / 120.0, input);
if (p.Occlusion >= 0.99) return (i + 1) / 120.0;
}
return double.PositiveInfinity;
}
Assert.True(Seconds(10.0) <= 3.05);
Assert.True(double.IsPositiveInfinity(Seconds(1.0))); // at gain 1 it takes 31 s (probe): a dropped gain misses the bound
// Larynx and Trachea are cores with share 1, the lungs 0.5, every other tissue 0.
foreach (var part in plan.Parts)
{
foreach (var t in part.Tissues)
{
if (t.Label is "Larynx" or "Trachea") { Assert.Equal(0.0, t.Thickness); Assert.Equal(1.0, t.AirwayShare); }
else if (t.Label is "LungLeft" or "LungRight") Assert.Equal(0.5, t.AirwayShare);
else Assert.Equal(0.0, t.AirwayShare);
}
}
}
[Fact]
public void Shares_and_gains_the_physiology_cannot_run_on_are_refused()
{
foreach (var bad in new[] { -0.1, 1.1, double.NaN, double.PositiveInfinity })
{
var root = new[] { new TissueDef("brain", 10, 1, Consciousness: 1) { AirwayShare = bad } };
Assert.Throws<ArgumentException>(() => Plan3(root: root));
}
foreach (var bad in new[] { 0.0, -1.0, double.PositiveInfinity, double.NaN })
{
Assert.Throws<ArgumentException>(() => new Physiology(Body3(), Plan3(), 20.0, bad));
}
}
}

View file

@ -0,0 +1,459 @@
using Lodur;
using static Lodur.Core.Tests.PhysioFixtures;
namespace Lodur.Core.Tests;
/// <summary>
/// Air hunger, the struggle it drives, the breath held on will and ended by a gasp, cough and drainage (rulings bds-airway-cough-hold-drain, bds-asphyxia-real-time).
/// The timed tests run on the real Actor over a Body3 with a lung and the humanoid's respiration and airway, at 120 Hz and slow scale 1 and 20 (the gases are on the Acute clock, so the
/// readings are identical). Every bound is a deterministic one (ruling deterministic-bound-margin): the geometric midpoint of the shipped worst and the least claimed mutant, or the
/// ruled literature window where that is tighter; a zero reading counts as half a unit for the shipped side and a whole unit for a mutant (ruling deterministic-bound-zero-reading).
/// </summary>
public sealed class AirwayPhysiologyTests
{
private const double Dt = 1.0 / 120.0;
private static readonly float[] NoPoint = { 0f };
/// <summary>The humanoid's HoldAt: the liquid at the openings at which the breath is held.</summary>
private static readonly double HoldAt = PhysiologyPlans.Humanoid().Airway.HoldAt;
private static readonly double Capacity = PhysiologyPlans.Humanoid().Airway.Capacity;
/// <summary>The humanoid's DrawPerSecond, a placeholder: the tests that read what a free breath draws read it from here.</summary>
private static readonly double Draw = PhysiologyPlans.Humanoid().Airway.DrawPerSecond;
private static Brain RestOnly() => new()
{
Goals = new[]
{
new GoalSpec
{
Id = "rest", Priority = 0.0,
Behaviour = new PoseBehaviour { Keys = new[] { PainBoxBrain.Hold }, FlinchPose = PainBoxBrain.Withdraw, Hold = new HoldParameters { HoldStrength = 0.7f } },
},
},
};
private static Actor Real(Physiology p, Brain brain, WithdrawalParameters? breath = null) =>
new(Dt, 1, new NerveParameters(), new WithdrawalParameters(), new DriveParameters(), brain, physiology: p, breath: breath);
private static Physiology Smothered(double slowScale)
{
var p = Breather(slowScale);
Assert.True(p.Afflict(Af("Choke"), 0, 0, 1e9));
return p;
}
private readonly record struct Smother(double Struggle, double Out, double Dead, double Effort, double Arousal30, DeathCause Cause);
/// <summary>Smothers (Breathing 0 for good) a real Actor with no stimulus: when the struggle goal took over, when consciousness first fell to 0.1, when it died, the mean strength written while awake, and the arousal at 30 s.</summary>
private static Smother Suffocate(double slowScale, Brain brain)
{
var p = Smothered(slowScale);
var a = Real(p, brain);
var s = new float[2];
var q = new Quat[2];
double struggle = -1, outAt = -1, deadAt = -1, arousal = -1, effort = 0;
long awake = 0;
for (long i = 0; i < (long)(500.0 / Dt) && !p.Dead; i++)
{
var e = a.Tick(NoPoint, NoPoint, NoPoint, default, s, q);
var t = (i + 1) * Dt;
if (struggle < 0 && a.GoalIndex == 1) struggle = t;
if (outAt < 0 && p.Consciousness <= 0.1) outAt = t;
if (outAt < 0)
{
effort += (s[0] + s[1]) / 2.0;
awake++;
}
if (arousal < 0 && t >= 30.0) arousal = a.Drive.Arousal;
if ((e & TickEvents.Died) != 0) deadAt = t;
}
return new Smother(struggle, outAt, deadAt, effort / awake, arousal, p.Cause);
}
[Theory]
[InlineData(1.0)]
[InlineData(20.0)]
public void Smothered_the_real_Actor_struggles_and_is_out_in_the_ruled_window(double slowScale)
{
// Shipped (placeholder content, probe and real Actor agree): struggle at 0.11 s, out 81.6 s, dead 154.3 s, mean awake effort 0.72. The fading-effort finding: the same Actor with only the rest goal
// (the will broken by arousal, the goal limp) is out at 219.8 s and dead at 308.4 s; with no deficit term the smothering is out at 100.0 and dead at 188.5 (2.0 and 1.22 times shipped: claimed).
// Bounds: out 60 (ruling) to 90 (the ruled 90 s, tighter than the midpoint 90.3), dead 134 (ruling) to 170.6 (midpoint of 154.3 and 188.5), effort 0.6 (shipped 0.72 is 1.2 above it; the rest-only reading 0.04 is 17 below).
var r = Suffocate(slowScale, StruggleBrain());
Assert.InRange(r.Struggle, 0.0, 2.0);
Assert.InRange(r.Out, 60.0, 90.0);
Assert.InRange(r.Dead, 134.0, 170.6);
Assert.Equal(DeathCause.Consciousness, r.Cause);
Assert.True(r.Effort > 0.6, $"mean awake effort {r.Effort}");
}
[Fact]
public void Without_a_struggle_goal_the_broken_will_goes_limp_and_the_window_is_missed()
{
// The finding, kept as a claim of the content: the rest goal alone is the will-weighted goal that the oxygen tests assumed fades only with consciousness.
var r = Suffocate(1.0, RestOnly());
Assert.True(r.Out > 150.0, $"out {r.Out}");
Assert.True(r.Effort < 0.2, $"effort {r.Effort}");
}
[Fact]
public void Air_hunger_raises_arousal_with_no_sensory_load()
{
// Shipped 0.75 at 30 s; with hunger kept out of the drive 0.0, which counts as one unit (0.01): the bound is sqrt(0.75 x 0.01) = 0.0866 (ruling deterministic-bound-zero-reading).
var r = Suffocate(1.0, RestOnly());
Assert.True(r.Arousal30 > 0.0866, $"arousal at 30 s {r.Arousal30}");
}
private readonly record struct Hold(double FirstLiquid, double MaxBeforeGasp, double Gasp, double WillAtGasp, double After, double Window);
/// <summary>A real Actor, calm and awake, with liquid at the airway openings from the first tick on, no opening below the sump.</summary>
private static Hold HoldUnderLiquid(double slowScale, WithdrawalParameters? breath = null, double attention = 1.0)
{
var p = Breather(slowScale);
var a = Real(p, StruggleBrain(), breath);
a.SetAttention(attention);
var s = new float[2];
var q = new Quat[2];
var liquid = new AirwaySample(2.0 * HoldAt, 0.0, 0.0);
double first = -1, max = 0, gasp = -1, will = -1, after = -1, window = -1;
for (long i = 0; i < (long)(200.0 / Dt); i++)
{
var e = a.Tick(NoPoint, NoPoint, NoPoint, default, s, q, default, liquid);
var t = (i + 1) * Dt;
if (i == 0) first = p.AirwayLiquid;
if (gasp < 0)
{
if ((e & TickEvents.Gasp) != 0)
{
gasp = t;
will = a.Drive.Will;
}
else
{
max = Math.Max(max, p.AirwayLiquid);
}
}
else
{
if (window < 0 && t >= gasp + 0.25) window = p.AirwayLiquid;
if (t >= gasp + 1.0)
{
after = p.AirwayLiquid;
break;
}
}
}
return new Hold(first, max, gasp, will, after, window);
}
[Theory]
[InlineData(1.0)]
[InlineData(20.0)]
public void A_calm_awake_Fella_holds_his_breath_under_liquid_and_gasps_in_45_to_90_s(double slowScale)
{
// Shipped gasp 60.06 s (the will gives out first, at urge 0.30); inside the ruled 45-90 s with 1.34 and 1.5 to spare. The first tick draws one tick's inflow (the Actor decides the hold from what
// the step found), 2.6e-7 m^3; held, nothing more enters and the cough clears it, so the airway never holds more than that until the gasp. With inflow while held it climbs to the cough's balance, 1.6e-5 (60 times).
var h = HoldUnderLiquid(slowScale);
Assert.InRange(h.Gasp, 45.0, 90.0);
// Draw is a placeholder and decides this reading (the first tick's inflow is Draw x Breathing x liquid x dt): it is read from the content, not written here.
Assert.Equal(Draw * 1.0 * 2.0 * HoldAt * Dt, h.FirstLiquid, 12);
Assert.True(h.MaxBeforeGasp <= h.FirstLiquid * 1.0000001, $"airway liquid {h.MaxBeforeGasp} while held");
Assert.Equal(0.0, h.WillAtGasp);
// Placeholders deciding this test: Draw (the first-tick inflow, and the 1.35e-5 after the gasp); Cough (the airway never holds more than a tick's inflow while held, since it clears at once); HoldAt is
// content the test reads. The gasp draws the liquid in: a second later the airway holds 1.35e-5 (the held mutant 2.6e-7); the bound is their geometric mean.
Assert.True(h.After > 1.8e-6, $"airway liquid a second after the gasp {h.After}");
}
[Fact]
public void The_breath_gasps_when_the_hunger_leaks_past_a_will_that_still_holds()
{
// Suppression 0 and a low leak threshold: the urge itself crosses the threshold (carbon dioxide 0.54) long before the will gives out.
var h = HoldUnderLiquid(1.0, new WithdrawalParameters { MaxSuppression = 0.0, FlinchLeakThreshold = 0.05 });
var shipped = HoldUnderLiquid(1.0);
Assert.True(h.Gasp > 0.0 && h.Gasp < shipped.Gasp / 1.2, $"leak gasp {h.Gasp}, will gasp {shipped.Gasp}");
Assert.True(h.WillAtGasp > 0.0, "the will had not given out");
}
[Fact]
public void With_no_will_there_is_no_hold()
{
// The will is 0 (attention is the seam): the breath is never held, liquid is drawn at once and no gasp is ever reported. Shipped the airway fills to the cough's balance (1.56e-5) within 5 s;
// a hold not gated by will stays at one tick's inflow (2.6e-7): the bound is the geometric midpoint, sqrt(1.56e-5 x 2.6e-7) = 2.0e-6.
var p = Breather(20.0);
var a = Real(p, StruggleBrain());
a.SetAttention(0.0);
var s = new float[2];
var q = new Quat[2];
var liquid = new AirwaySample(2.0 * HoldAt, 0.0, 0.0);
for (long i = 0; i < (long)(5.0 / Dt); i++)
{
Assert.Equal(TickEvents.None, a.Tick(NoPoint, NoPoint, NoPoint, default, s, q, default, liquid) & TickEvents.Gasp);
}
Assert.True(p.AirwayLiquid > 2.0e-6, $"airway liquid {p.AirwayLiquid}");
}
/// <summary>
/// Fills the airway with a flood (awake, the cough cannot keep up) until it is full, then smothers calmly with no liquid left at it until consciousness first falls to 0.1; returns that physiology,
/// the airway full. Calm and unventilated the blood store falls by its basal use alone (0.002 per second), so the fall to 0.1 takes 334.5 s; a Fella left face up dies 125 s later.
/// </summary>
private static Physiology Drowned()
{
var p = Breather(20.0);
var flood = new PhysiologyInput(0.0, 0.0, false, new AirwaySample(100.0 * HoldAt, 0.0, 0.0));
for (long i = 0; i < (long)(600.0 / Dt) && p.Consciousness > 0.1; i++) p.Step(Dt, flood);
Assert.True(p.Consciousness <= 0.1 && !p.Dead, $"consciousness {p.Consciousness}");
Assert.Equal(Capacity, p.AirwayLiquid);
return p;
}
/// <summary>The unconscious Fella, liquid no longer at the airway, with his lowest opening rim this far (m) below the deepest sump; steps for the given seconds.</summary>
private static Physiology Rolled(double drop, double seconds)
{
var p = Drowned();
var rolled = new PhysiologyInput(0.0, 0.0, false, new AirwaySample(0.0, 0.0, drop));
for (long i = 0; i < (long)(seconds / Dt) && !p.Dead; i++) p.Step(Dt, rolled);
return p;
}
[Theory]
[InlineData(0.05)]
[InlineData(0.025)]
public void Face_down_or_on_his_side_the_airway_drains_and_he_lives(double drop)
{
// Placeholders: Drain decides nothing here but whether it is above zero (a tiny drain restarts ventilation and the awake cough then clears the airway: probed at 0.1, 0.01, 0.001); Cough decides the recovery once he wakes.
// Out at 0.1 with the airway full, then drained at 0.1 (drop 0.05, face down) or 0.05 (drop 0.025, on his side) per second: back above 0.5 in 7.0 and 8.5 s (the bound is the 200 s simulated; a drain that waits on consciousness never comes). Face up it never drains and he dies (below).
var p = Rolled(drop, 200.0);
Assert.False(p.Dead);
Assert.True(p.Consciousness > 0.5, $"consciousness {p.Consciousness}");
Assert.True(p.AirwayLiquid < 1e-6, $"airway liquid {p.AirwayLiquid}");
}
[Theory]
[InlineData(0.0, 0.0)]
[InlineData(0.0125, 0.25)]
[InlineData(0.025, 0.5)]
[InlineData(0.05, 1.0)]
[InlineData(0.1, 1.0)]
public void The_drain_is_linear_in_drop_up_to_DrainDrop(double drop, double fraction)
{
// One step on the full airway with nothing at the openings: the cough is zero below 0.3 consciousness (he is out at 0.1), so what drained is dt x DrainPerSecond x clamp01(drop / DrainDrop) x Capacity,
// exact arithmetic (1e-12), not a measured bound. Half the rate at a pure side pose (drop 0.025, the mouth's half-width); the binary-drain and doubled-slope mutants read 1 at 0.025, and the quarter
// point (0.0125) kills a step at half.
var p = Drowned();
p.Step(Dt, new PhysiologyInput(0.0, 0.0, false, new AirwaySample(0.0, 0.0, drop)));
Assert.Equal(0.0, p.Coughed);
Assert.Equal(fraction, p.Drained / (Dt * PhysiologyPlans.Humanoid().Airway.DrainPerSecond * Capacity), 12);
}
[Fact]
public void Face_up_the_airway_stays_full_and_he_dies_through_consciousness()
{
// Decided by the Cough curve (zero below 0.3 consciousness) and by drop (0 face up: no opening rim lies below the sump); Drain and Draw decide nothing here (nothing drains face up, nothing is drawn, none at the openings).
var p = Rolled(0.0, 600.0);
Assert.True(p.Dead);
Assert.Equal(DeathCause.Consciousness, p.Cause);
Assert.Equal(Capacity, p.AirwayLiquid);
Assert.Equal(0.0, p.Drained);
}
private static Physiology Flooded(int dims)
{
var p = Breather(20.0);
for (var d = 0; d < dims; d++) Assert.True(p.Afflict(Af("Dim"), 0, BrainLayer, 1.0));
var flood = new PhysiologyInput(0.0, 0.0, false, new AirwaySample(100.0 * HoldAt, 0.0, 0.0));
for (long i = 0; i < (long)(2.0 / Dt); i++) p.Step(Dt, flood);
Assert.Equal(Capacity, p.AirwayLiquid);
return p;
}
[Fact]
public void An_awake_Fella_coughs_his_airway_clear()
{
// Placeholders deciding this: Cough (0.3 per second, a continuous airway bleed must beat it: ruling bds-drown-in-own-blood-first) and every bound below; Draw only fills the half airway first and decides no outcome; Drain is 0 face up and decides nothing.
// Half the airway, awake, face up, nothing at the openings, 20 s. Readings (deterministic, ruling deterministic-bound-margin): the time for the liquid to fall to a quarter of the capacity (half of what it held)
// shipped 2.425 s, a cough at half the rate 4.867 s, cough 2.0 0.417 s; the liquid left after 20 s shipped 1.9e-7 m^3, half-rate 3.864e-6, no cough 7.8e-5; the total coughed (fraction of the capacity) shipped 0.515, no cough 0.
// Time bound (1.005, 3.436) = sqrt(2.425 x 0.417) and sqrt(2.425 x 4.867), separation 5.8 and 2.0: it claims cough 2.0 and the half-rate cough (a cough of 0.36 or 0.24 is not claimed). Liquid bound 8.6e-7 = sqrt(1.9e-7 x 3.864e-6),
// separation 20: it claims the half-rate and the missing cough. Coughed bound 0.0718 = sqrt(0.515 x 0.01), the zero reading's mutant counted as one unit of 0.01 (ruling deterministic-bound-zero-reading), separation 7.2.
var p = Breather(20.0);
var flood = new PhysiologyInput(0.0, 0.0, false, new AirwaySample(100.0 * HoldAt, 0.0, 0.0));
while (p.AirwayLiquid < 0.5 * Capacity) p.Step(Dt, flood);
var clear = new PhysiologyInput(0.0, 0.0, false, new AirwaySample(0.0, 0.0, 0.0));
double coughed = 0.0, quarter = -1.0;
for (long i = 0; i < (long)(20.0 / Dt); i++)
{
p.Step(Dt, clear);
coughed += p.Coughed;
if (quarter < 0.0 && p.AirwayLiquid < 0.25 * Capacity) quarter = (i + 1) * Dt;
}
Assert.True(quarter > 1.005 && quarter < 3.436, $"quarter at {quarter} s");
Assert.True(p.AirwayLiquid < 8.6e-7, $"airway liquid {p.AirwayLiquid}");
Assert.True(coughed > 0.0718 * Capacity, $"coughed {coughed}");
Assert.Equal(0.0, p.Drained);
}
[Fact]
public void A_stuporous_Fella_cannot_cough()
{
// Consciousness held at 0.2 by eight Dim afflictions, below the cough's 0.3: the Cough curve's knee (a placeholder) decides this; Drain decides nothing (face up).
var p = Flooded(8);
Assert.Equal(0.2, p.Consciousness, 9);
var clear = new PhysiologyInput(0.0, 0.0, false, new AirwaySample(0.0, 0.0, 0.0));
for (long i = 0; i < (long)(10.0 / Dt); i++)
{
p.Step(Dt, clear);
Assert.Equal(0.0, p.Coughed);
}
Assert.Equal(Capacity, p.AirwayLiquid);
}
[Theory]
[InlineData(1.0)]
[InlineData(20.0)]
public void Healthy_and_one_lung_bodies_feel_no_air_hunger_at_rest(double slowScale)
{
foreach (var lungLost in new[] { false, true })
{
var p = Breather(slowScale);
if (lungLost) Assert.True(p.Afflict(Af("Lesion"), 0, 2, 5.0)); // half the lung layer: Breathing 0.5
var a = Real(p, StruggleBrain());
var s = new float[2];
var q = new Quat[2];
for (long i = 0; i < (long)(600.0 / Dt); i++)
{
a.Tick(NoPoint, NoPoint, NoPoint, default, s, q);
Assert.Equal(0.0, p.BreathUrge);
Assert.Equal(0.0, a.Drive.AirHunger);
}
Assert.Equal(lungLost ? 0.5 : 1.0, p.Breathing);
Assert.True(p.CarbonDioxide < 0.5, $"carbon dioxide {p.CarbonDioxide}");
}
}
[Fact]
public void After_a_gasp_the_breath_is_free_for_its_window_before_it_is_held_again()
{
// The leak gasp (the will still holds): a quarter second later the breath is still free and the airway holds 6.2e-6 (Draw and Cough, placeholders, decide it); with no window (_held = willing) the
// breath is held the very next tick and the airway holds a tick's inflow, 2.6e-7 or less: the bound is their geometric mean, 1.3e-6.
var h = HoldUnderLiquid(1.0, new WithdrawalParameters { MaxSuppression = 0.0, FlinchLeakThreshold = 0.05 });
Assert.True(h.WillAtGasp > 0.0, "the will had not given out");
Assert.True(h.Window > 1.3e-6, $"airway liquid a quarter second after the gasp {h.Window}");
}
[Fact]
public void Liquid_below_the_hold_threshold_is_breathed_in_and_not_held()
{
// Liquid at the openings under HoldAt: the breath is not held, so the airway draws it in and never gasps. With the hold at any liquid the breath is held from the second tick and the airway keeps a tick's draw (6.5e-8). Shipped it holds 3.9e-6 after 5 s (Draw and Cough, placeholders); the bound is the geometric mean, 5.0e-7.
var p = Breather(20.0);
var a = Real(p, StruggleBrain());
var s = new float[2];
var q = new Quat[2];
var low = new AirwaySample(0.5 * HoldAt, 0.0, 0.0);
for (long i = 0; i < (long)(5.0 / Dt); i++)
{
Assert.Equal(TickEvents.None, a.Tick(NoPoint, NoPoint, NoPoint, default, s, q, default, low) & TickEvents.Gasp);
}
Assert.True(p.AirwayLiquid > 5.0e-7, $"airway liquid {p.AirwayLiquid}");
}
[Fact]
public void A_breath_draws_in_what_the_lung_ventilates()
{
// One step from empty (nothing to cough or drain yet): the inflow is Draw x Breathing x liquid x dt, and a lung half lost draws half. An inflow that ignores Breathing draws the same in both.
double Drawn(bool lungLost)
{
var p = Breather(20.0);
if (lungLost) Assert.True(p.Afflict(Af("Lesion"), 0, 2, 5.0));
p.Step(Dt, new PhysiologyInput(0.0, 0.0, false, new AirwaySample(0.5 * HoldAt, 0.0, 0.0)));
Assert.Equal(lungLost ? 0.5 : 1.0, p.Breathing);
return p.AirwayLiquid;
}
Assert.Equal(Draw * 1.0 * 0.5 * HoldAt * Dt, Drawn(false), 14);
Assert.Equal(Draw * 0.5 * 0.5 * HoldAt * Dt, Drawn(true), 14);
}
[Fact]
public void A_dead_body_feels_no_urge()
{
var p = Smothered(20.0);
double last = 0.0;
for (long i = 0; i < (long)(500.0 / Dt) && !p.Dead; i++)
{
p.Step(Dt, new PhysiologyInput(0.0, 0.0, false, default));
if (!p.Dead) last = p.BreathUrge;
}
Assert.True(p.Dead);
Assert.True(last > 0.5, $"urge the step before he died {last}");
Assert.Equal(0.0, p.BreathUrge);
}
[Fact]
public void An_airway_sample_is_the_sum_of_what_is_live_and_pooled_and_the_greatest_drop()
{
var s = AirwaySample.Of(new[] { 1f, 2f }, new[] { 0.5f }, new[] { -0.5f, 0.25f, -1f });
Assert.Equal(new AirwaySample(3.0, 0.5, 0.25), s);
Assert.Equal(new AirwaySample(1.0, 1.0, 0.0), AirwaySample.Of(new[] { 1f }, new[] { 1f }, new[] { -0.5f, -1f }));
Assert.Equal(new AirwaySample(0.0, 0.0, 0.0), AirwaySample.Of(default, default, default));
}
[Fact]
public void A_sample_outside_its_range_is_refused_before_anything_changes()
{
var p = Breather(20.0);
foreach (var bad in new[] { new AirwaySample(-1e-9, 0, 0), new AirwaySample(0, double.NaN, 0), new AirwaySample(double.PositiveInfinity, 0, 0), new AirwaySample(0, 0, -1e-9), new AirwaySample(0, 0, double.NaN), new AirwaySample(0, 0, double.PositiveInfinity) })
{
Assert.Throws<ArgumentException>(() => p.Step(Dt, new PhysiologyInput(0.0, 0.0, false, bad)));
}
Assert.Equal(1.0, p.BloodOxygen);
Assert.Equal(0.0, p.AirwayLiquid);
p.Step(Dt, new PhysiologyInput(0.0, 0.0, false, new AirwaySample(1.0, 1.0, 0.05)));
}
[Fact]
public void An_airway_or_urge_curve_the_physiology_cannot_run_on_is_refused()
{
var h = PhysiologyPlans.Humanoid();
PhysiologyPlan With(RespirationDef? r = null, AirwayDef? w = null) =>
new(h.Parts, h.Afflictions, h.OrganismEffects, h.Blood, r ?? h.Respiration, w ?? h.Airway, h.AfflictionSlots);
With();
var ok = h.Airway;
foreach (var bad in new[]
{
ok with { Capacity = 0.0 }, ok with { Capacity = double.NaN }, ok with { DrawPerSecond = -1.0 }, ok with { HoldAt = double.PositiveInfinity },
ok with { CoughPerSecond = -0.1 }, ok with { DrainPerSecond = double.NaN }, ok with { DrainDrop = 0.0 }, ok with { DrainDrop = -0.01 }, ok with { DrainDrop = double.NaN },
ok with { CoughByConsciousness = Array.Empty<(double X, double Y)>() }, ok with { CoughByConsciousness = new[] { (1.0, 0.0), (0.0, 1.0) } },
ok with { LiveWeight = -1.0 }, ok with { PooledWeight = double.NaN },
})
{
Assert.Throws<ArgumentException>(() => With(w: bad));
}
var r = h.Respiration;
foreach (var bad in new[]
{
r with { CarbonDioxideRise = -1.0 }, r with { CarbonDioxideClear = double.NaN },
r with { UrgeByCarbonDioxide = Array.Empty<(double X, double Y)>() }, r with { UrgeByVentilationDeficit = new[] { (1.0, 0.0), (0.5, 1.0) } },
})
{
Assert.Throws<ArgumentException>(() => With(r: bad));
}
// The plan owns its curves: a caller editing the array it passed changes nothing.
var mine = new[] { (0.0, 0.0), (1.0, 1.0) };
var plan = With(r: r with { UrgeByCarbonDioxide = mine });
mine[1] = (1.0, 5.0);
Assert.Equal(1.0, plan.Respiration.UrgeByCarbonDioxide[1].Y);
}
}

View file

@ -0,0 +1,465 @@
using System;
using Lodur;
using Xunit.Abstractions;
namespace Lodur.Core.Tests;
/// <summary>
/// An arm's motion across ticks, owned by <see cref="ArmChain"/>: the minimum-jerk hand path through a via point ahead of the trunk, taken only
/// when the trunk is in the way (rulings reach-clears-body-by-via-point, reach-path-blocked-only), and the hand-off into and out of the arm layer,
/// slewed at the output rate both ways (ruling ik-output-slew-limit, follow-up orient-s4-lows).
/// </summary>
public sealed class ArmPathTests
{
private const double Dt = 0.01;
private const uint Thing = 7;
private const float Step = (float)(ArmChain.MaxAngularRate * Dt);
private static readonly BodyPlan Plan = BodyPlans.Humanoid();
private static readonly int Joints = Plan.Joints.Count;
private static readonly BoxStimulus[] NoBoxes = Array.Empty<BoxStimulus>();
private static readonly float[] Origin = { 0f };
private readonly ITestOutputHelper _output;
public ArmPathTests(ITestOutputHelper output) => _output = output;
private static (float X, float Y, float Z) Mirror((float X, float Y, float Z) p, Side side) => side == Side.Right ? p : (-p.X, p.Y, p.Z);
private static float Gap((float X, float Y, float Z) a, (float X, float Y, float Z) b) =>
MathF.Sqrt((a.X - b.X) * (a.X - b.X) + (a.Y - b.Y) * (a.Y - b.Y) + (a.Z - b.Z) * (a.Z - b.Z));
private static float Turn(Quat a, Quat b) => 2f * MathF.Acos(MathF.Min(1f, MathF.Abs(a.X * b.X + a.Y * b.Y + a.Z * b.Z + a.W * b.W)));
/// <summary>Drives the arm with the body at its creation pose and the wrist where it hangs, or at <paramref name="wrist"/>.</summary>
private static bool Drive(ArmChain arm, (float X, float Y, float Z) goal, Quat baseShoulder, Quat baseElbow, double weight, out Quat shoulder, out Quat elbow,
(float X, float Y, float Z)? wrist = null)
{
var parent = Plan.Parts[arm.ParentPart];
var w = wrist ?? arm.WristAnchor;
return arm.Drive(parent.Rotation, parent.Position.X, parent.Position.Y, parent.Position.Z, goal.X, goal.Y, goal.Z, w.X, w.Y, w.Z,
baseShoulder, baseElbow, weight, out shoulder, out elbow);
}
[Theory]
[InlineData(Side.Right)]
[InlineData(Side.Left)]
public void Blocked_is_decided_by_the_trunk_once_per_path_start(Side side)
{
// The hanging wrist to a goal across the chest and level with the torso: the straight segment touches the trunk. To a goal out to the
// arm's own side it stays clear of the trunk by more than the forearm radius.
var arm = ArmChain.Of(Plan, side, Dt);
var across = Mirror((-0.04f, 1.60f, 0.24f), side);
var aside = Mirror((-0.30f, 1.74f, 0.26f), side);
Drive(arm, across, Quat.Identity, Quat.Identity, 1.0, out _, out _);
Assert.True(arm.PathBlocked);
Assert.True(Gap(arm.Aim, arm.WristAnchor) < 1e-4f, $"the path starts at the wrist, not {arm.Aim}");
// Decided once: the goal moving clear of the trunk does not unblock the path.
Drive(arm, aside, Quat.Identity, Quat.Identity, 1.0, out _, out _);
Assert.True(arm.PathBlocked);
arm.Restart();
Drive(arm, aside, Quat.Identity, Quat.Identity, 1.0, out _, out _);
Assert.False(arm.PathBlocked);
Assert.True(Gap(arm.Aim, aside) < 1e-4f, $"an unblocked reach solves the goal itself, not {arm.Aim}");
}
[Fact]
public void The_hand_path_is_minimum_jerk_through_the_via_point_and_meets_a_moving_goal()
{
var start = (0f, 1f, 0f);
var via = (0.1f, 1.2f, 0.3f);
var seg = ArmChain.PathSegmentSeconds;
var g0 = (0.5f, 1.5f, 0.4f);
Assert.True(Gap(ArmChain.PathPoint(start, via, g0, g0, 0f), start) < 1e-4f);
Assert.True(Gap(ArmChain.PathPoint(start, via, g0, g0, seg), via) < 1e-4f);
Assert.True(Gap(ArmChain.PathPoint(start, via, g0, g0, 2f * seg), g0) < 1e-4f);
var mid = ((start.Item1 + via.Item1) / 2f, (start.Item2 + via.Item2) / 2f, (start.Item3 + via.Item3) / 2f);
Assert.True(Gap(ArmChain.PathPoint(start, via, g0, g0, 0.5f * seg), mid) < 1e-4f, "midway in the first segment is the midpoint");
// Zero velocity at both ends of a segment: a tick in is far less than a linear tick in.
Assert.True(Gap(ArmChain.PathPoint(start, via, g0, g0, 0.01f * seg), start) < 1e-3f * Gap(start, via));
// A goal that has moved on during the second segment is met at its end, and the via point's offset shrinks to nothing on the way.
var g1 = (0.7f, 1.4f, 0.5f);
Assert.True(Gap(ArmChain.PathPoint(start, via, g0, g1, 2f * seg), g1) < 1e-4f);
var half = ArmChain.PathPoint(start, via, g0, g1, 1.5f * seg);
var want = (g1.Item1 + 0.5f * (via.Item1 - g0.Item1), g1.Item2 + 0.5f * (via.Item2 - g0.Item2), g1.Item3 + 0.5f * (via.Item3 - g0.Item3));
Assert.True(Gap(half, want) < 1e-4f);
// The chain follows it from the measured wrist: the via point is (wrist x, mid y, trunk front + clearance), the trunk front 0.09 m on the humanoid.
var arm = ArmChain.Of(Plan, Side.Right, Dt);
var wrist = arm.WristAnchor;
(float X, float Y, float Z) goal = (-0.04f, 1.60f, 0.24f);
(float X, float Y, float Z) viaWant = (wrist.X, 0.5f * (wrist.Y + goal.Y), 0.09f + ArmChain.ViaClearance);
var ticks = (int)Math.Round(2.0 * ArmChain.PathSegmentSeconds / Dt);
for (var i = 0; i <= ticks + 5; i++)
{
// The goal drifts 0.1 m forward over the path.
(float X, float Y, float Z) g = (goal.X, goal.Y, goal.Z + 0.1f * Math.Min(1f, i / (float)ticks));
Drive(arm, g, Quat.Identity, Quat.Identity, 1.0, out _, out _);
var t = i * (float)Dt;
if (i == 0) Assert.True(Gap(arm.Aim, wrist) < 1e-4f);
if (i == (int)Math.Round(0.5 * ArmChain.PathSegmentSeconds / Dt))
{
var half1 = ((wrist.X + viaWant.X) / 2f, (wrist.Y + viaWant.Y) / 2f, (wrist.Z + viaWant.Z) / 2f);
Assert.True(Gap(arm.Aim, half1) < 2e-3f, $"midway to the via point at {t} s: {arm.Aim}");
}
if (i == (int)Math.Round(ArmChain.PathSegmentSeconds / Dt))
{
Assert.True(Gap(arm.Aim, viaWant) < 2e-3f, $"at the via point at {t} s: {arm.Aim}");
}
if (i >= ticks)
{
Assert.True(Gap(arm.Aim, g) < 1e-4f, $"after the path the goal itself is solved for, not {arm.Aim}");
}
}
}
[Fact]
public void Slewed_by_the_actor_the_hand_off_moves_the_written_arm_targets_at_most_the_rate_both_ways_and_ends_in_the_base()
{
// A pose goal and a ward-off goal alternate as a sound comes and goes. Every tick, the shoulder and elbow targets of both arms move at most
// the rate times the tick, across engaging and disengaging; and once the arms have eased back they write exactly what the pose goal does.
var key = new Quat[Joints];
for (var m = 0; m < Joints; m++) key[m] = Quat.FromAxisAngle(0f, 0f, 1f, 0.02f * (m + 1));
var idle = Pose(key, null);
var ward = Pose(key, new ArmLayer { Mode = ArmMode.WardOff, Side = ArmSide.Both, Distance = 0.3f, Spread = 0.15f });
var brain = new Brain
{
Goals = new[]
{
new GoalSpec { Id = "idle", Priority = 0.0, Behaviour = idle },
new GoalSpec
{
Id = "ward", Priority = 1.0, Target = new TargetFilter { Kinds = new[] { Thing } },
Considerations = new[] { new Consideration(ConsiderationInput.Distance, 0.0, 60.0, 1.0, 0.0) },
Behaviour = ward,
},
},
};
var actor = new Actor(Dt, 1, new NerveParameters(), new WithdrawalParameters(), new DriveParameters(), brain,
new NerveParameters { Threshold = 0.05, SensitisationGrowth = 0.0, ConductionDelaySeconds = 0.0 }, 0,
new PerceptParameters { Capacity = 4, MemorySeconds = 0.2 }, body: Plan);
var parts = Rest();
var targets = new Quat[Joints];
var previous = new Quat[Joints];
var strengths = new float[Joints];
var armJoints = new[] { Plan.JointIndex("Shoulder", Side.Left), Plan.JointIndex("Elbow", Side.Left), Plan.JointIndex("Shoulder", Side.Right), Plan.JointIndex("Elbow", Side.Right) };
var sound = new[] { new Emitter { Channel = Channel.Audio, X = 0.3f, Y = 1.5f, Z = 0.7f, Radius = 40f, Intensity = 1.0, Id = 1, Kind = Thing } };
var reference = new Quat[Joints];
idle.Write(1.0, 0.0, 0.0, 0.0, 0.0, new float[Joints], reference);
var (worst, engaged, released, restored) = (0f, 0, 0, 0);
var wasWard = false;
for (var i = 0; i < 1800; i++)
{
var on = (i / 150) % 2 == 0;
actor.Tick(Origin, Origin, Origin, NoBoxes, strengths, targets, on ? sound : Array.Empty<Emitter>(), parts: parts);
var ward1 = actor.GoalIndex == 1;
if (ward1 && !wasWard) engaged++;
if (!ward1 && wasWard) released++;
wasWard = ward1;
if (i > 0)
{
foreach (var m in armJoints) worst = MathF.Max(worst, Turn(previous[m], targets[m]));
}
if (!ward1 && i % 150 == 149 && !on)
{
// The arms have had the rest of the off-phase to ease back.
var same = true;
for (var m = 0; m < Joints; m++) same &= targets[m].Equals(reference[m]);
if (same) restored++;
}
Array.Copy(targets, previous, Joints);
}
_output.WriteLine($"worst per-tick change {worst:F5} rad against {Step}; engaged {engaged}, released {released}, written the base bit for bit at {restored} phase ends");
Assert.True(engaged >= 5 && released >= 5, $"the goals alternated too little to test the hand-off: {engaged}, {released}");
Assert.True(worst <= Step + 1e-5f, $"an arm target moved {worst} rad in one tick, the bound is {Step}");
Assert.True(worst > 0.5f * Step, $"the arms moved at most {worst} rad a tick, so the hand-off was not slewed at the rate");
Assert.True(restored >= 5, $"the arms wrote the base pose bit for bit at only {restored} of the off-phases");
static PoseBehaviour Pose(Quat[] key, ArmLayer? arms) => new()
{
Keys = new[] { key }, FlinchPose = Array.ConvertAll(key, _ => Quat.Identity), Arms = arms,
};
}
[Fact]
public void A_released_arm_stays_the_base_and_reset_and_restart_forget_the_path_and_the_hand_off()
{
var arm = ArmChain.Of(Plan, Side.Right, Dt);
var baseShoulder = Quat.FromAxisAngle(0f, 0f, 1f, 0.2f);
var baseElbow = Quat.FromAxisAngle(0f, 0f, 1f, -0.3f);
var goal = (-0.04f, 1.60f, 0.24f);
// An arm never driven writes the base untouched.
arm.Release(baseShoulder, baseElbow, out var s0, out var e0);
Assert.Equal(baseShoulder, s0);
Assert.Equal(baseElbow, e0);
for (var i = 0; i < 100; i++) Drive(arm, goal, baseShoulder, baseElbow, 1.0, out _, out _);
var held = Quat.Identity;
var converged = -1;
for (var i = 0; i < 100; i++)
{
arm.Release(baseShoulder, baseElbow, out var s, out var e);
if (i > 0) Assert.True(Turn(held, s) <= Step + 1e-5f, "the release moved the shoulder faster than the rate");
held = s;
if (converged < 0 && s.Equals(baseShoulder) && e.Equals(baseElbow)) converged = i;
if (converged >= 0) Assert.True(s.Equals(baseShoulder) && e.Equals(baseElbow), "a released arm left the base after arriving");
}
Assert.True(converged > 3, $"the arm was back on the base after {converged} ticks: it was not slewed");
// Reset forgets the hand-off: the arm is idle, so the base passes through at once.
for (var i = 0; i < 20; i++) Drive(arm, goal, baseShoulder, baseElbow, 1.0, out _, out _);
arm.Reset();
arm.Release(baseShoulder, baseElbow, out var s1, out var e1);
Assert.Equal(baseShoulder, s1);
Assert.Equal(baseElbow, e1);
// At half weight the written targets are the base blended toward the output, and the hand-off is continuous in them, not in the output.
var half = ArmChain.Of(Plan, Side.Right, Dt);
var writtenHalf = Quat.Identity;
for (var i = 0; i < 100; i++) Drive(half, goal, baseShoulder, baseElbow, 0.5, out writtenHalf, out _);
var released = 0f;
for (var i = 0; i < 20; i++)
{
half.Release(baseShoulder, baseElbow, out var sh, out _);
released = MathF.Max(released, Turn(writtenHalf, sh));
writtenHalf = sh;
}
Assert.True(released <= Step + 1e-5f, $"releasing at half weight moved the written shoulder {released} rad in a tick");
// Restart starts the path again at the measured wrist, keeping the output: the aim goes back to the wrist.
for (var i = 0; i < 100; i++) Drive(arm, goal, baseShoulder, baseElbow, 1.0, out _, out _);
Assert.True(Gap(arm.Aim, goal) < 1e-4f);
arm.Restart();
Drive(arm, goal, baseShoulder, baseElbow, 1.0, out _, out _);
Assert.True(Gap(arm.Aim, arm.WristAnchor) < 1e-4f, $"a restarted path begins at the measured wrist, not {arm.Aim}");
}
[Fact]
public void A_commit_restarts_both_arms_paths_from_the_measured_wrist()
{
// Reach across the body with the right arm, settled; the parts do not follow, so the measured wrist stays hanging. A tick after
// the rig is told of a commit, the arm is on a new path from that wrist and its output turns back toward it by a step; without
// the commit the settled output does not move.
var key = new Quat[Joints];
Array.Fill(key, Quat.Identity);
var b = new PoseBehaviour { Keys = new[] { key }, FlinchPose = key, Arms = new ArmLayer { Mode = ArmMode.Reach, Side = ArmSide.Right } };
var brain = new Brain { Goals = new[] { new GoalSpec { Id = "g", Behaviour = b } } };
var parts = Rest();
var target = new Percept(1, Thing, 0.3f, 1.45f, 0.5f, 1.0, 0.0);
var shoulder = Plan.JointIndex("Shoulder", Side.Right);
foreach (var commit in new[] { false, true })
{
var rig = new OrientRig(Plan, brain, Dt);
var targets = new Quat[Joints];
for (var i = 0; i < 100; i++) b.Write(1.0, 0.0, 0.0, 0.0, 0.0, new float[Joints], targets, new OrientInput(rig, parts, target, Side.Right));
var settled = targets[shoulder];
if (commit) rig.Commit();
b.Write(1.0, 0.0, 0.0, 0.0, 0.0, new float[Joints], targets, new OrientInput(rig, parts, target, Side.Right));
var moved = Turn(settled, targets[shoulder]);
if (commit) Assert.True(moved > 0.5f * Step, $"after a commit the arm moved only {moved} rad");
else Assert.True(moved < 1e-4f, $"a settled arm moved {moved} rad without a commit");
}
}
[Fact]
public void The_actor_restarts_the_hand_path_when_it_commits_another_target()
{
// The right arm reaches across the body to a sound, settled. The parts do not follow, so the measured wrist stays hanging. A second,
// sound, a millimetre nearer, is committed a latency later and the arm starts a new path from that wrist, turning back by steps; with no second sound the
// settled arm does not move.
var key = new Quat[Joints];
Array.Fill(key, Quat.Identity);
PoseBehaviour Pose(ArmLayer? arms) => new() { Keys = new[] { key }, FlinchPose = key, Arms = arms };
var brain = new Brain
{
Goals = new[]
{
new GoalSpec { Id = "idle", Priority = 0.0, Behaviour = Pose(null) },
new GoalSpec
{
Id = "reach", Priority = 1.0, Target = new TargetFilter { Kinds = new[] { Thing } },
Considerations = new[] { new Consideration(ConsiderationInput.Distance, 0.0, 60.0, 1.0, 0.0) },
Behaviour = Pose(new ArmLayer { Mode = ArmMode.Reach, Side = ArmSide.Right }),
},
},
};
Emitter Sound(ulong id, float x, float y, float z) => new() { Channel = Channel.Audio, X = x, Y = y, Z = z, Radius = 40f, Intensity = 1.0, Id = id, Kind = Thing };
var shoulder = Plan.JointIndex("Shoulder", Side.Right);
foreach (var retarget in new[] { false, true })
{
var actor = new Actor(Dt, 1, new NerveParameters(), new WithdrawalParameters(), new DriveParameters(), brain,
new NerveParameters { Threshold = 0.05, SensitisationGrowth = 0.0, ConductionDelaySeconds = 0.0 }, 0,
new PerceptParameters { Capacity = 4, MemorySeconds = 5.0 }, body: Plan);
var parts = Rest();
var targets = new Quat[Joints];
var first = new[] { Sound(1, 0.3f, 1.45f, 0.5f) };
var both = new[] { Sound(1, 0.3f, 1.45f, 0.5f), Sound(2, 0.3f, 1.45f, 0.499f) };
for (var i = 0; i < 150; i++) actor.Tick(Origin, Origin, Origin, NoBoxes, new float[Joints], targets, first, parts: parts);
Assert.Equal(1UL, actor.TargetId);
var last = targets[shoulder];
var worst = 0f;
for (var i = 0; i < 100; i++)
{
actor.Tick(Origin, Origin, Origin, NoBoxes, new float[Joints], targets, retarget ? both : first, parts: parts);
worst = MathF.Max(worst, Turn(last, targets[shoulder]));
last = targets[shoulder];
}
if (retarget)
{
Assert.Equal(2UL, actor.TargetId);
Assert.True(worst > 0.5f * Step, $"a committed retarget moved the arm at most {worst} rad in a tick");
}
else
{
Assert.True(worst < 1e-3f, $"a settled arm moved {worst} rad in a tick with nothing new");
}
}
}
[Fact]
public void The_hand_path_has_no_break_at_the_via_point_and_ends_on_the_goal()
{
// A static blocked goal: the aim moves no more than a minimum-jerk tick all the way (peak speed 1.875 D / T), through the hand-off between
// the two segments, and a segment that began on the via point instead of the goal would jump 0.3 m at the segment time.
var arm = ArmChain.Of(Plan, Side.Right, Dt);
var goal = (-0.04f, 1.60f, 0.24f);
var previous = arm.WristAnchor;
var worst = 0f;
for (var i = 0; i < 80; i++)
{
Drive(arm, goal, Quat.Identity, Quat.Identity, 1.0, out _, out _);
if (i > 0) worst = MathF.Max(worst, Gap(arm.Aim, previous));
previous = arm.Aim;
}
Assert.True(arm.PathBlocked);
Assert.True(worst < 0.05f, $"the aim moved {worst} m in one tick");
Assert.True(Gap(arm.Aim, goal) < 1e-4f);
}
[Fact]
public void An_arm_engaged_again_from_releasing_starts_a_new_path_from_the_measured_wrist()
{
var arm = ArmChain.Of(Plan, Side.Right, Dt);
var goal = (-0.04f, 1.60f, 0.24f);
for (var i = 0; i < 100; i++) Drive(arm, goal, Quat.Identity, Quat.Identity, 1.0, out _, out _);
Assert.True(Gap(arm.Aim, goal) < 1e-4f);
// Still releasing, not yet back on the base (the slew takes more than three ticks).
for (var i = 0; i < 3; i++) arm.Release(Quat.Identity, Quat.Identity, out _, out _);
Drive(arm, goal, Quat.Identity, Quat.Identity, 1.0, out _, out _);
Assert.True(arm.PathBlocked);
Assert.True(Gap(arm.Aim, arm.WristAnchor) < 1e-4f, $"an arm engaged again from releasing starts its path at the measured wrist, not {arm.Aim}");
}
[Fact]
public void Restart_keeps_the_held_swivel()
{
var arm = ArmChain.Of(Plan, Side.Right, Dt);
var goal = (-0.04f, 1.60f, 0.24f);
for (var i = 0; i < 100; i++) Drive(arm, goal, Quat.Identity, Quat.Identity, 1.0, out _, out _);
var held = arm.Held;
Assert.False(held.Equals(Quat.Identity), "the arm holds no swivel to keep");
arm.Restart();
Assert.Equal(held, arm.Held);
}
[Fact]
public void The_minimum_jerk_profile_is_the_quintic()
{
// Flash and Hogan: 10 t^3 - 15 t^4 + 6 t^5. Smoothstep shares the ends, the midpoint and the zero first velocity but not these.
Assert.Equal(0.103515625f, ArmChain.MinimumJerk(0.25f), 6);
Assert.Equal(0.896484375f, ArmChain.MinimumJerk(0.75f), 6);
Assert.Equal(0.00856f, ArmChain.MinimumJerk(0.1f), 5);
Assert.Equal(0f, ArmChain.MinimumJerk(-1f));
Assert.Equal(1f, ArmChain.MinimumJerk(2f));
}
[Theory]
[InlineData(Side.Right)]
[InlineData(Side.Left)]
public void Blocked_means_within_the_forearm_radius_of_the_trunk(Side side)
{
// A vertical segment in front of the trunk's front face at a distance d from it: blocked within the radius and not beyond, to a tenth.
var arm = ArmChain.Of(Plan, side, Dt);
var fore = Plan.Parts[arm.ForearmPart];
var radius = fore.Shape == PartShape.Box ? MathF.Min(fore.Size.X, MathF.Min(fore.Size.Y, fore.Size.Z)) : fore.Size.X;
const float front = 0.09f;
foreach (var (factor, blocked) in new[] { (0.5f, true), (0.95f, true), (1.05f, false), (1.5f, false) })
{
var z = front + factor * radius;
arm.Reset();
Drive(arm, (0f, 1.45f, z), Quat.Identity, Quat.Identity, 1.0, out _, out _, wrist: (0f, 1.25f, z));
Assert.Equal(blocked, arm.PathBlocked);
}
}
[Fact]
public void An_engaging_arm_takes_the_short_way_from_a_base_given_with_the_opposite_sign()
{
// The same rotation as q and as -q: engaging from -q must not turn the long way round to the solution q.
var arm = ArmChain.Of(Plan, Side.Right, Dt);
var fresh = ArmChain.Of(Plan, Side.Right, Dt);
var goal = (-0.2f, 1.4f, 0.35f);
var parent = Plan.Parts[arm.ParentPart];
fresh.Solve(parent.Rotation, parent.Position.X, parent.Position.Y, parent.Position.Z, goal.Item1, goal.Item2, goal.Item3, out var solution, out _);
// A base a few steps short of the solution, negated: engaging turns the step toward it, not away.
var toward = Quat.Nlerp(solution, Quat.Identity, 0.05f);
var negated = new Quat(-toward.X, -toward.Y, -toward.Z, -toward.W);
Drive(arm, goal, negated, Quat.Identity, 1.0, out var written, out _);
Assert.True(Turn(negated, written) <= Step + 1e-5f, $"engaging turned {Turn(negated, written)} rad from the base in one tick");
Assert.True(Turn(written, solution) < Turn(negated, solution) + 1e-4f, "engaging turned away from the solution");
Assert.True(Turn(negated, solution) > 0f);
}
[Theory]
[InlineData(Side.Right)]
[InlineData(Side.Left)]
public void A_goal_outrunning_the_rate_keeps_the_shoulder_target_a_unit_rotation(Side side)
{
// The goal circles the shoulder so fast that the target is always behind it: ten thousand slewed steps compose without drift.
var arm = ArmChain.Of(Plan, side, Dt);
var s = arm.ShoulderAnchor;
var worst = 0f;
var chasing = 0;
var last = Quat.Identity;
for (var i = 0; i < 10000; i++)
{
var th = 0.9f * i;
arm.Solve(Plan.Parts[arm.ParentPart].Rotation, Plan.Parts[arm.ParentPart].Position.X, Plan.Parts[arm.ParentPart].Position.Y, Plan.Parts[arm.ParentPart].Position.Z,
s.X + 0.4f * MathF.Sin(th), s.Y - 0.1f, s.Z + 0.4f * MathF.Cos(th), out var q, out _);
worst = MathF.Max(worst, MathF.Abs(MathF.Sqrt(q.X * q.X + q.Y * q.Y + q.Z * q.Z + q.W * q.W) - 1f));
if (i > 0 && Turn(last, q) > 0.99f * Step) chasing++;
last = q;
}
_output.WriteLine($"{side}: norm error {worst:E2}, {chasing} of 10000 ticks at the rate");
Assert.True(chasing > 5000, $"the target was at the rate on only {chasing} ticks, so it was not outrun");
Assert.True(worst < 1e-5f, $"the shoulder target left the unit sphere by {worst}");
}
// A pose with the arms at rest, to look at the written targets of.
private static PartPose[] Rest()
{
var poses = new PartPose[Plan.Parts.Count];
for (var p = 0; p < poses.Length; p++)
{
var d = Plan.Parts[p];
poses[p] = new PartPose(d.Rotation, d.Position.X, d.Position.Y, d.Position.Z);
}
return poses;
}
}

View file

@ -0,0 +1,204 @@
using Lodur;
namespace Lodur.Core.Tests;
/// <summary>An Actor with one region at the origin, a sensory nerve with sensitisation off, and a settable emitter list.</summary>
internal sealed class SensoryRig
{
public const double Dt = 0.01;
public readonly Actor Actor;
public readonly Emitter[] Emitters;
public readonly float[] Strengths = new float[2];
public readonly Quat[] Targets = new Quat[2];
private readonly float[] _p = { 0f };
/// <param name="heard">False builds the Actor without senses, so the emitters have no one to reach.</param>
public SensoryRig(Emitter[] emitters, double pull = 0.5, double drainTrait = 1.0, DriveParameters? drive = null, bool heard = true, Brain? brain = null)
{
Emitters = emitters;
Actor = new Actor(Dt, 1, new NerveParameters(), new WithdrawalParameters(),
(drive ?? new DriveParameters()) with { DrainTrait = drainTrait }, brain ?? PainBoxBrain.Make(pull),
heard ? new NerveParameters { Threshold = 0.05, SensitisationGrowth = 0.0 } : null, 0);
}
/// <summary>One audio emitter on the sense region whose afferent settles at (intensity - 0.05).</summary>
public static Emitter[] One(double intensity) => new[] { new Emitter(Channel.Audio, 0f, 0f, 0f, 1f, intensity) };
public TickEvents Tick() => Actor.Tick(_p, _p, _p, ReadOnlySpan<BoxStimulus>.Empty, Strengths, Targets, Emitters);
public long TicksToBreak(double maxSeconds)
{
var max = (long)Math.Round(maxSeconds / Dt);
for (long i = 0; i < max; i++)
{
if ((Tick() & TickEvents.WillBroke) != 0) return i;
}
return -1;
}
}
public sealed class ArousalTests
{
private const double Load = 0.5; // an emitter of 0.55 through a 0.05 threshold, no sensitisation, gain 1
[Fact]
public void Arousal_rises_under_constant_load_toward_its_equilibrium_and_decays_at_the_decay_rate_after_it_stops()
{
var p = new DriveParameters();
var rig = new SensoryRig(SensoryRig.One(0.55), pull: 1.0); // pull 1: no drain, so only arousal is watched
double last = 0;
for (var i = 0; i < 20000; i++)
{
rig.Tick();
Assert.True(rig.Actor.Drive.Arousal >= last - 1e-15, "arousal never falls under constant load");
last = rig.Actor.Drive.Arousal;
}
Assert.Equal(Load, rig.Actor.Load, 12);
var equilibrium = p.ArousalRise * Load / (p.ArousalRise * Load + p.ArousalDecay);
Assert.Equal(equilibrium, rig.Actor.Drive.Arousal, 9);
rig.Emitters[0].Intensity = 0.0;
while (rig.Actor.Load > 0.0) rig.Tick(); // the last of the signal in flight arrives
var a0 = rig.Actor.Drive.Arousal;
Assert.True(a0 > 0.5 * equilibrium);
for (var i = 0; i < 1000; i++) rig.Tick();
Assert.Equal(a0 * Math.Pow(1.0 - SensoryRig.Dt * p.ArousalDecay, 1000), rig.Actor.Drive.Arousal, 12);
}
[Fact]
public void Under_the_same_load_a_weaker_pull_breaks_first_pull_one_never_drains_and_the_trait_scales_the_drain()
{
long Break(double pull, double trait = 1.0) => new SensoryRig(SensoryRig.One(0.55), pull, trait).TicksToBreak(3000.0);
long p3 = Break(0.3), p6 = Break(0.6);
Assert.True(p3 > 0 && p3 < p6, $"pull: {p3} {p6}");
var held = new SensoryRig(SensoryRig.One(0.55), pull: 1.0);
Assert.Equal(-1, held.TicksToBreak(3000.0));
Assert.Equal(1.0, held.Actor.Drive.Resolve);
long t2 = Break(0.6, 2.0);
Assert.True(t2 > 0 && t2 < p6, $"trait: {t2} {p6}");
Assert.InRange((double)t2 / p6, 0.35, 0.6); // double the drain, about half the time (arousal needs a moment to rise)
}
[Fact]
public void Resolve_does_not_recover_while_arousal_is_at_the_recovery_ceiling_or_above_and_does_after()
{
var drive = new DriveParameters { ResolveRecovery = 0.5 }; // strong enough that a gate on pain alone would show at once
var ceiling = drive.ResolveRecoversBelowArousal;
var rig = new SensoryRig(SensoryRig.One(0.55), pull: 0.5, drive: drive);
double minResolve = 1.0;
for (var i = 0; i < 2000; i++) { rig.Tick(); minResolve = Math.Min(minResolve, rig.Actor.Drive.Resolve); }
Assert.True(minResolve < 0.95 && !rig.Actor.Drive.WillBroken);
rig.Emitters[0].Intensity = 0.0;
var rosePastCeiling = false;
var settled = false;
var last = rig.Actor.Drive.Resolve;
for (var i = 0; i < 20000; i++)
{
rig.Tick();
var a = rig.Actor.Drive.Arousal;
var r = rig.Actor.Drive.Resolve;
if (a >= ceiling)
{
Assert.True(r <= last, $"resolve rose at arousal {a}");
settled = true;
}
else if (settled && r > last)
{
rosePastCeiling = true;
}
last = r;
}
Assert.True(settled && rosePastCeiling, "resolve recovers once arousal is below the ceiling");
Assert.True(rig.Actor.Drive.Resolve > minResolve);
}
[Fact]
public void Arousal_updates_before_it_drains_resolve_on_the_same_tick()
{
var rig = new SensoryRig(SensoryRig.One(0.55), pull: 0.5);
for (var i = 0; i < 100; i++)
{
rig.Tick();
if (rig.Actor.Load > 0.0) break;
Assert.Equal(0.0, rig.Actor.Drive.Arousal);
Assert.Equal(1.0, rig.Actor.Drive.Resolve);
}
Assert.True(rig.Actor.Load > 0.0, "the load arrives within the conduction delay");
// On the tick the load first arrives, arousal has already risen and already drained: read a tick late, resolve would still be 1.
Assert.True(rig.Actor.Drive.Arousal > 0.0);
Assert.True(rig.Actor.Drive.Resolve < 1.0);
}
[Fact]
public void Without_emitters_or_without_senses_arousal_and_load_stay_exactly_zero()
{
var silent = new SensoryRig(Array.Empty<Emitter>());
var deaf = new SensoryRig(SensoryRig.One(1.0), heard: false);
for (var i = 0; i < 10000; i++)
{
Assert.Equal(TickEvents.None, silent.Tick());
Assert.Equal(TickEvents.None, deaf.Tick());
Assert.Equal(0.0, silent.Actor.Drive.Arousal);
Assert.Equal(0.0, deaf.Actor.Drive.Arousal);
Assert.Equal(0.0, silent.Actor.Load);
Assert.Equal(0.0, deaf.Actor.Load);
}
Assert.Equal(1.0, silent.Actor.Drive.Resolve);
Assert.Equal(1.0, deaf.Actor.Drive.Resolve);
}
private static Emitter[] Three() => new[]
{
new Emitter(Channel.Audio, 0.2f, 0f, 0f, 1f, 0.5),
new Emitter(Channel.Visual, 0f, 0.3f, 0f, 1f, 0.4),
new Emitter(Channel.Interrupt, 0f, 0f, 0f, 1f, 0.6),
};
[Fact]
public void Tick_with_three_emitters_allocates_nothing_in_steady_state_and_actors_do_not_share_state()
{
var r = new SensoryRig(Three());
r.Tick();
var before = GC.GetAllocatedBytesForCurrentThread();
for (var i = 0; i < 10000; i++) r.Tick();
Assert.Equal(0L, GC.GetAllocatedBytesForCurrentThread() - before);
const int n = 2500;
var a1 = new SensoryRig(Three());
var b1 = new SensoryRig(SensoryRig.One(0.4), pull: 0.2, drainTrait: 1.3);
var a2 = new SensoryRig(Three());
var b2 = new SensoryRig(SensoryRig.One(0.4), pull: 0.2, drainTrait: 1.3);
var ea = new TickEvents[n];
var eb = new TickEvents[n];
for (var i = 0; i < n; i++) { ea[i] = a1.Tick(); eb[i] = b1.Tick(); }
for (var i = 0; i < n; i++) Assert.Equal(ea[i], a2.Tick());
for (var i = 0; i < n; i++) Assert.Equal(eb[i], b2.Tick());
static void Same(SensoryRig x, SensoryRig y)
{
Assert.Equal(x.Actor.Drive.Arousal, y.Actor.Drive.Arousal);
Assert.Equal(x.Actor.Drive.Resolve, y.Actor.Drive.Resolve);
Assert.Equal(x.Actor.Load, y.Actor.Load);
foreach (var c in new[] { Channel.Audio, Channel.Visual, Channel.Interrupt })
{
Assert.Equal(x.Actor.ChannelStimulus(c), y.Actor.ChannelStimulus(c));
Assert.Equal(x.Actor.ChannelAfferent(c), y.Actor.ChannelAfferent(c));
}
}
Same(a1, a2);
Same(b1, b2);
Assert.True(a1.Actor.Drive.Arousal > 0.0);
}
}

View file

@ -0,0 +1,360 @@
using Lodur;
namespace Lodur.Core.Tests;
public sealed class BodyPlanTests
{
private static PartDef Box(string label, Side side = Side.Center) =>
new(label, side, PartShape.Box, (0.1f, 0.1f, 0.1f), (0f, 0f, 0f), Quat.Identity, 1000f, 0.8f, 0f);
private static JointDef Joint(string label, int parent, int child, Side side = Side.Center) =>
new(label, side, JointKind.Spherical, parent, child, (0f, 0f, 0f), (0f, 1f, 0f), -1f, 1f, 0.5f, new MuscleGains(1f, 1f, 1f, 1f));
private static BodyPlan Plan(PartDef[] parts, JointDef[] joints, SensePointDef[]? senses = null) =>
new(parts, joints, senses ?? Array.Empty<SensePointDef>());
private static BodyPlan Valid() => Plan(new[] { Box("A"), Box("B") }, new[] { Joint("J", 0, 1) });
private static void Refuses(Action build, string saying)
{
var e = Assert.Throws<ArgumentException>(build);
Assert.Contains(saying, e.Message);
}
[Fact]
public void A_valid_plan_resolves_labels_and_derives_the_tree_from_its_joints()
{
var plan = Valid();
Assert.Equal(1, plan.PartIndex("B"));
Assert.Equal(0, plan.JointIndex("J"));
Assert.Equal(new[] { -1, 0 }, new[] { plan.ParentOf(0), plan.ParentOf(1) });
}
// Rule 1: (label, side) unique per list, labels non-empty.
[Fact]
public void Rule1_a_repeated_label_and_side_is_refused_in_each_list_and_another_side_is_not()
{
Refuses(() => Plan(new[] { Box("A"), Box("A") }, new[] { Joint("J", 0, 1) }), "two parts are labelled 'A'");
Refuses(() => Plan(new[] { Box("A"), Box("B"), Box("C") }, new[] { Joint("J", 0, 1), Joint("J", 0, 2) }), "two joints are labelled 'J'");
Refuses(() => Plan(new[] { Box("A"), Box("B") }, new[] { Joint("J", 0, 1) },
new[] { new SensePointDef("S", Side.Left, 0, default), new SensePointDef("S", Side.Left, 1, default) }), "two sense points are labelled 'S'");
var plan = Plan(new[] { Box("A"), Box("L", Side.Left), Box("L", Side.Right) }, new[] { Joint("J", 0, 1, Side.Left), Joint("J", 0, 2, Side.Right) });
Assert.Equal(2, plan.PartIndex("L", Side.Right));
}
[Fact]
public void Rule1_an_empty_label_is_refused()
{
Refuses(() => Plan(new[] { Box("A"), Box("") }, new[] { Joint("J", 0, 1) }), "empty label");
}
// Rule 2: joint ends in range, parent before child.
[Theory]
[InlineData(0, 2)]
[InlineData(-1, 1)]
[InlineData(5, 1)]
public void Rule2_a_joint_end_that_is_not_a_part_is_refused(int parent, int child)
{
Refuses(() => Plan(new[] { Box("A"), Box("B") }, new[] { Joint("J", parent, child) }), "is not a part");
}
[Fact]
public void Rule2_a_parent_that_does_not_precede_its_child_is_refused()
{
Refuses(() => Plan(new[] { Box("A"), Box("B") }, new[] { Joint("J", 1, 0) }), "must precede");
Refuses(() => Plan(new[] { Box("A"), Box("B") }, new[] { Joint("J", 1, 1) }), "must precede");
}
// Rule 3: part 0 the root, every other part the child of exactly one joint.
[Fact]
public void Rule3_a_part_with_no_joint_is_refused()
{
Refuses(() => Plan(new[] { Box("A"), Box("B"), Box("C") }, new[] { Joint("J", 0, 1) }), "child of 0 joints");
}
[Fact]
public void Rule3_a_part_with_two_joints_is_refused()
{
Refuses(() => Plan(new[] { Box("A"), Box("B"), Box("C") }, new[] { Joint("J", 0, 1), Joint("K", 0, 2), Joint("M", 1, 2) }), "child of 2 joints");
}
[Fact]
public void Rule3_a_plan_without_parts_is_refused()
{
Refuses(() => Plan(Array.Empty<PartDef>(), Array.Empty<JointDef>()), "needs a root");
}
// Rule 4: sense points name parts.
[Theory]
[InlineData(2)]
[InlineData(-1)]
public void Rule4_a_sense_point_on_no_part_is_refused(int part)
{
Refuses(() => Plan(new[] { Box("A"), Box("B") }, new[] { Joint("J", 0, 1) }, new[] { new SensePointDef("S", Side.Center, part, default) }), "is not a part");
}
// Rule 5: numbers a physics world can take.
[Fact]
public void Rule5_a_non_finite_part_number_is_refused()
{
var nan = Box("B") with { Position = (float.NaN, 0f, 0f) };
Refuses(() => Plan(new[] { Box("A"), nan }, new[] { Joint("J", 0, 1) }), "non-finite");
var inf = Box("B") with { Friction = float.PositiveInfinity };
Refuses(() => Plan(new[] { Box("A"), inf }, new[] { Joint("J", 0, 1) }), "non-finite");
}
[Fact]
public void Rule5_a_size_the_shape_uses_must_be_positive_and_one_it_does_not_use_may_be_zero()
{
Refuses(() => Plan(new[] { Box("A"), Box("B") with { Size = (0.1f, 0f, 0.1f) } }, new[] { Joint("J", 0, 1) }), "size its shape uses");
Refuses(() => Plan(new[] { Box("A"), Box("B") with { Shape = PartShape.Capsule, Size = (0.1f, 0f, 0f) } }, new[] { Joint("J", 0, 1) }), "size its shape uses");
Refuses(() => Plan(new[] { Box("A"), Box("B") with { Shape = PartShape.Sphere, Size = (-0.1f, 0f, 0f) } }, new[] { Joint("J", 0, 1) }), "size its shape uses");
var capsule = Plan(new[] { Box("A"), Box("B") with { Shape = PartShape.Capsule, Size = (0.1f, 0.2f, 0f) } }, new[] { Joint("J", 0, 1) });
Assert.Equal(2, capsule.Parts.Count);
}
[Fact]
public void Rule5_a_box_depth_that_is_not_positive_is_refused()
{
Refuses(() => Plan(new[] { Box("A"), Box("B") with { Size = (0.1f, 0.1f, 0f) } }, new[] { Joint("J", 0, 1) }), "size its shape uses");
Refuses(() => Plan(new[] { Box("A"), Box("B") with { Size = (0.1f, 0.1f, -0.1f) } }, new[] { Joint("J", 0, 1) }), "size its shape uses");
}
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(2)]
[InlineData(3)]
public void Rule5_a_non_finite_rotation_component_is_refused(int component)
{
var q = new[] { 0f, 0f, 0f, 1f };
q[component] = float.NaN;
Refuses(() => Plan(new[] { Box("A"), Box("B") with { Rotation = new Quat(q[0], q[1], q[2], q[3]) } }, new[] { Joint("J", 0, 1) }), "non-finite");
q[component] = float.PositiveInfinity;
Refuses(() => Plan(new[] { Box("A"), Box("B") with { Rotation = new Quat(q[0], q[1], q[2], q[3]) } }, new[] { Joint("J", 0, 1) }), "non-finite");
}
[Fact]
public void Rule5_a_field_the_shape_cannot_carry_is_refused()
{
var turned = Quat.FromAxisAngle(0f, 0f, 1f, 0.5f);
Refuses(() => Plan(new[] { Box("A"), Box("B") with { Shape = PartShape.Sphere, Size = (0.1f, 0f, 0f), Rotation = turned } }, new[] { Joint("J", 0, 1) }), "sphere carries no rotation");
Refuses(() => Plan(new[] { Box("A"), Box("B") with { RollingResistance = 0.1f } }, new[] { Joint("J", 0, 1) }), "box carries no rolling resistance");
Refuses(() => Plan(new[] { Box("A"), Box("B") with { Shape = PartShape.Capsule, Size = (0.1f, 0.2f, 0.3f) } }, new[] { Joint("J", 0, 1) }), "does not use is not zero");
Refuses(() => Plan(new[] { Box("A"), Box("B") with { Shape = PartShape.Sphere, Size = (0.1f, 0.2f, 0f) } }, new[] { Joint("J", 0, 1) }), "does not use is not zero");
Refuses(() => Plan(new[] { Box("A"), Box("B") with { Shape = PartShape.Sphere, Size = (0.1f, 0f, 0.3f) } }, new[] { Joint("J", 0, 1) }), "does not use is not zero");
// what each shape does carry is accepted
var ok = Plan(new[] { Box("A") with { Rotation = turned }, Box("B") with { Shape = PartShape.Capsule, Size = (0.1f, 0.2f, 0f), Rotation = turned, RollingResistance = 0.1f },
Box("C") with { Shape = PartShape.Sphere, Size = (0.1f, 0f, 0f), RollingResistance = 0.1f } }, new[] { Joint("J", 0, 1), Joint("K", 0, 2) });
Assert.Equal(3, ok.Parts.Count);
}
[Fact]
public void Rule5_a_density_that_is_not_positive_is_refused()
{
Refuses(() => Plan(new[] { Box("A"), Box("B") with { Density = 0f } }, new[] { Joint("J", 0, 1) }), "density");
}
[Fact]
public void Rule5_a_joint_with_a_non_finite_number_is_refused()
{
Refuses(() => Plan(new[] { Box("A"), Box("B") }, new[] { Joint("J", 0, 1) with { Axis = (0f, float.NaN, 0f) } }), "non-finite");
Refuses(() => Plan(new[] { Box("A"), Box("B") }, new[] { Joint("J", 0, 1) with { Gains = new MuscleGains(float.PositiveInfinity, 1f, 1f, 1f) } }), "non-finite");
}
[Fact]
public void Rule5_a_lower_limit_above_the_upper_is_refused()
{
Refuses(() => Plan(new[] { Box("A"), Box("B") }, new[] { Joint("J", 0, 1) with { Lower = 0.5f, Upper = 0.4f } }), "lower limit");
}
[Fact]
public void Rule5_a_negative_cone_is_refused()
{
Refuses(() => Plan(new[] { Box("A"), Box("B") }, new[] { Joint("J", 0, 1) with { Cone = -0.1f } }), "cone");
}
[Fact]
public void Rule5_a_non_finite_sense_offset_is_refused()
{
Refuses(() => Plan(new[] { Box("A"), Box("B") }, new[] { Joint("J", 0, 1) }, new[] { new SensePointDef("S", Side.Center, 0, (0f, float.NaN, 0f)) }), "non-finite");
}
[Fact]
public void The_plan_copies_its_lists()
{
var parts = new List<PartDef> { Box("A"), Box("B") };
var plan = Plan(parts.ToArray(), new[] { Joint("J", 0, 1) });
var viaList = new BodyPlan(parts, new[] { Joint("J", 0, 1) }, Array.Empty<SensePointDef>());
parts.Add(Box("C"));
Assert.Equal(2, viaList.Parts.Count);
Assert.Equal(2, plan.Parts.Count);
}
// Airway openings: rules 1, 4, 5, 6.
private static BodyPlan WithAirway(PartDef part, params AirwayOpeningDef[] openings) =>
new(new[] { part }, Array.Empty<JointDef>(), Array.Empty<SensePointDef>(), openings, new[] { new AirwaySumpDef("S", 0, (0f, 0f, 0f)) });
private static BodyPlan WithSumps(PartDef part, params AirwaySumpDef[] sumps) =>
new(new[] { part }, Array.Empty<JointDef>(), Array.Empty<SensePointDef>(), new[] { Opening((0f, 0f, 0.11f)) }, sumps);
private static PartDef Shaped(PartShape shape, (float, float, float) size) =>
new("P", Side.Center, shape, size, (0f, 0f, 0f), Quat.Identity, 1000f, 0.8f, 0f);
private static AirwayOpeningDef Opening((float, float, float) offset, float radius = 0.025f, string label = "O") =>
new(label, Side.Center, 0, offset, radius);
[Fact]
public void Rule1_a_repeated_airway_label_and_side_is_refused_and_another_side_is_not()
{
var part = Shaped(PartShape.Sphere, (0.11f, 0f, 0f));
Refuses(() => WithAirway(part, Opening((0f, 0f, 0.11f)), Opening((0f, 0.05f, 0.1f))), "two airway openings are labelled 'O'");
var plan = WithAirway(part, Opening((0f, 0f, 0.11f)), Opening((0f, 0.05f, 0.1f), label: "O") with { Side = Side.Left });
Assert.Equal(1, plan.AirwayIndex("O", Side.Left));
Refuses(() => plan.AirwayIndex("O", Side.Right), "no airway opening labelled 'O' on side Right");
}
[Fact]
public void Rule4_an_airway_opening_on_no_part_is_refused()
{
var part = Shaped(PartShape.Sphere, (0.11f, 0f, 0f));
Refuses(() => WithAirway(part, Opening((0f, 0f, 0.11f)) with { Part = 1 }), "part 1 is not a part");
Refuses(() => WithAirway(part, Opening((0f, 0f, 0.11f)) with { Part = -1 }), "part -1 is not a part");
}
[Fact]
public void Rule5_a_non_finite_offset_or_radius_and_a_radius_not_above_zero_are_refused()
{
var part = Shaped(PartShape.Sphere, (0.11f, 0f, 0f));
Refuses(() => WithAirway(part, Opening((0f, float.NaN, 0.11f))), "non-finite");
Refuses(() => WithAirway(part, Opening((float.PositiveInfinity, 0f, 0.11f))), "non-finite");
Refuses(() => WithAirway(part, Opening((0f, 0f, 0.11f), float.NaN)), "non-finite");
Refuses(() => WithAirway(part, Opening((0f, 0f, 0.11f), 0f)), "radius is not positive");
Refuses(() => WithAirway(part, Opening((0f, 0f, 0.11f), -0.01f)), "radius is not positive");
}
[Fact]
public void Rule6_an_opening_wholly_inside_its_part_is_refused_and_one_straddling_the_surface_is_accepted_for_each_shape()
{
// sphere r 0.11: centre at 0.05 with radius 0.025 is wholly inside (distance -0.06); at the surface it straddles.
var sphere = Shaped(PartShape.Sphere, (0.11f, 0f, 0f));
Refuses(() => WithAirway(sphere, Opening((0f, 0f, 0.05f))), "lies inside its part");
WithAirway(sphere, Opening((0f, 0f, 0.11f)));
WithAirway(sphere, Opening((0f, 0f, 0.12f)));
// capsule r 0.05, half length 0.2 along y: past the cap is measured from the end of the segment, beside the side from the axis.
var capsule = Shaped(PartShape.Capsule, (0.05f, 0.2f, 0f));
Refuses(() => WithAirway(capsule, Opening((0f, 0.1f, 0.01f))), "lies inside its part");
Refuses(() => WithAirway(capsule, Opening((0f, 0.2f, 0f))), "lies inside its part");
Refuses(() => WithAirway(capsule, Opening((0f, 0.22f, 0f))), "lies inside its part"); // 0.02 past the segment end, r 0.05: inside by 0.03, more than the radius 0.025
WithAirway(capsule, Opening((0.05f, 0.1f, 0f)));
WithAirway(capsule, Opening((0f, 0.25f, 0f)));
WithAirway(capsule, Opening((0f, 0.3f, 0f)));
// box half extents (0.1, 0.05, 0.2): the signed distance is the box's, so a point deep in one axis is not rescued by another.
var box = Shaped(PartShape.Box, (0.1f, 0.05f, 0.2f));
Refuses(() => WithAirway(box, Opening((0f, 0f, 0f))), "lies inside its part");
Refuses(() => WithAirway(box, Opening((0.05f, 0.01f, 0.1f))), "lies inside its part");
WithAirway(box, Opening((0.1f, 0f, 0f)));
WithAirway(box, Opening((0f, 0.05f, 0f)));
WithAirway(box, Opening((0.11f, 0.06f, 0.21f)));
}
[Fact]
public void Airway_openings_need_a_sump_on_a_part_with_a_finite_offset()
{
var part = Shaped(PartShape.Sphere, (0.11f, 0f, 0f));
Refuses(() => WithSumps(part), "need at least one airway sump");
Refuses(() => WithSumps(part, new AirwaySumpDef("S", 1, (0f, 0f, 0f))), "part 1 is not a part");
Refuses(() => WithSumps(part, new AirwaySumpDef("S", -1, (0f, 0f, 0f))), "part -1 is not a part");
Refuses(() => WithSumps(part, new AirwaySumpDef("S", 0, (0f, float.NaN, 0f))), "non-finite");
Refuses(() => WithSumps(part, new AirwaySumpDef("S", 0, (float.PositiveInfinity, 0f, 0f))), "non-finite");
Assert.Single(WithSumps(part, new AirwaySumpDef("S", 0, (0f, 0f, 0f))).AirwaySumps);
Assert.Empty(Valid().AirwaySumps);
}
[Fact]
public void The_airway_opening_list_is_copied_and_null_means_none()
{
var part = Shaped(PartShape.Sphere, (0.11f, 0f, 0f));
var list = new List<AirwayOpeningDef> { Opening((0f, 0f, 0.11f)) };
var plan = new BodyPlan(new[] { part }, Array.Empty<JointDef>(), Array.Empty<SensePointDef>(), list, new[] { new AirwaySumpDef("S", 0, (0f, 0f, 0f)) });
list.Add(Opening((0f, 0f, 0.12f), label: "P"));
Assert.Single(plan.AirwayOpenings);
Assert.Empty(Valid().AirwayOpenings);
}
// The humanoid.
[Fact]
public void The_humanoid_has_19_parts_18_joints_and_3_sense_points_labelled_in_build_order()
{
var plan = BodyPlans.Humanoid();
string Name(string label, Side side) => side == Side.Center ? label : label + side;
Assert.Equal(new[]
{
"Pelvis", "Torso", "Head",
"UpperArmLeft", "LowerArmLeft", "ThighLeft", "ShinLeft", "FootLeft",
"UpperArmRight", "LowerArmRight", "ThighRight", "ShinRight", "FootRight",
"PalmLeft", "ThumbLeft", "FingersLeft", "PalmRight", "ThumbRight", "FingersRight",
}, plan.Parts.Select(p => Name(p.Label, p.Side)).ToArray());
Assert.Equal(new[]
{
"Spine", "Neck",
"ShoulderLeft", "ElbowLeft", "HipLeft", "KneeLeft", "AnkleLeft",
"ShoulderRight", "ElbowRight", "HipRight", "KneeRight", "AnkleRight",
"WristLeft", "ThumbLeft", "FingersLeft", "WristRight", "ThumbRight", "FingersRight",
}, plan.Joints.Select(j => Name(j.Label, j.Side)).ToArray());
Assert.Equal(new[] { "HandLeft", "HandRight", "Head" }, plan.SensePoints.Select(s => Name(s.Label, s.Side)).ToArray());
Assert.Equal(new[] { plan.PartIndex("Palm", Side.Left), plan.PartIndex("Palm", Side.Right), plan.PartIndex("Head") }, plan.SensePoints.Select(s => s.Part).ToArray());
}
[Fact]
public void The_humanoid_has_a_mouth_and_a_nose_on_the_head_each_on_its_surface()
{
var plan = BodyPlans.Humanoid();
Assert.Equal(new[] { "Mouth", "Nose" }, plan.AirwayOpenings.Select(a => a.Label).ToArray());
Assert.Equal(new[] { "Pharynx", "Glottis" }, plan.AirwaySumps.Select(a => a.Label).ToArray());
Assert.All(plan.AirwaySumps, s => Assert.Equal(plan.PartIndex("Head"), s.Part));
foreach (var a in plan.AirwayOpenings)
{
Assert.Equal(plan.PartIndex("Head"), a.Part);
var o = a.Offset;
Assert.InRange(MathF.Sqrt(o.X * o.X + o.Y * o.Y + o.Z * o.Z), 0.109f, 0.111f);
}
}
[Fact]
public void The_humanoid_parent_tree_is_the_old_one()
{
var plan = BodyPlans.Humanoid();
// pelvis torso head uaL laL thL shL ftL uaR laR thR shR ftR plL thL fiL plR thR fiR
var old = new[] { -1, 0, 1, 1, 3, 0, 5, 6, 1, 8, 0, 10, 11, 4, 13, 13, 9, 16, 16 };
Assert.Equal(old, Enumerable.Range(0, plan.Parts.Count).Select(plan.ParentOf).ToArray());
}
[Fact]
public void The_humanoid_hand_joints_hang_palm_thumb_fingers_off_the_lower_arm_per_side()
{
var plan = BodyPlans.Humanoid();
foreach (var side in new[] { Side.Left, Side.Right })
{
Assert.Equal((plan.PartIndex("LowerArm", side), plan.PartIndex("Palm", side)),
(plan.Joints[plan.JointIndex("Wrist", side)].Parent, plan.Joints[plan.JointIndex("Wrist", side)].Child));
Assert.Equal((plan.PartIndex("Palm", side), plan.PartIndex("Thumb", side)),
(plan.Joints[plan.JointIndex("Thumb", side)].Parent, plan.Joints[plan.JointIndex("Thumb", side)].Child));
Assert.Equal((plan.PartIndex("Palm", side), plan.PartIndex("Fingers", side)),
(plan.Joints[plan.JointIndex("Fingers", side)].Parent, plan.Joints[plan.JointIndex("Fingers", side)].Child));
}
}
[Fact]
public void A_lookup_with_the_wrong_side_refuses_and_names_label_and_side()
{
var plan = BodyPlans.Humanoid();
Refuses(() => plan.PartIndex("Palm"), "'Palm' on side Center");
Refuses(() => plan.PartIndex("Pelvis", Side.Left), "'Pelvis' on side Left");
Refuses(() => plan.JointIndex("Knee"), "'Knee' on side Center");
Refuses(() => plan.SenseIndex("Head", Side.Right), "'Head' on side Right");
Refuses(() => plan.PartIndex("Tail"), "'Tail'");
}
}

View file

@ -0,0 +1,639 @@
using Lodur;
namespace Lodur.Core.Tests;
public sealed class BrainTests
{
private const long Latency = 10; // round(0.1 s / 10 ms)
private static GoalSpec Goal(string id, double priority, double pull = 0.5, params Condition[] when) => new()
{
Id = id, Priority = priority, Pull = pull, When = when,
Behaviour = new PoseBehaviour { Keys = new[] { PainBoxBrain.Hold }, FlinchPose = PainBoxBrain.Withdraw },
};
private static readonly Perception Deaf = new(new NerveParameters(), 0.01, 1);
private static int Pick(Brain brain, DriveState drive, int current) => brain.Select(drive, Deaf, 0f, 0f, 0f, new Choice(current, 0)).Goal;
private static Condition Pain(ConditionOp op, double t) => new(DriveQuantity.Pain, op, t);
private sealed record Run(List<long> Changes, List<int> Goals, long Broke, long[] Held);
/// <summary>Ticks the pain box; reports the GoalChanged ticks and goals, the WillBroke tick, and per probe the first tick its predicate held after the tick.</summary>
private static Run Go(PainBoxReplay r, long ticks, params Func<DriveState, bool>[] probes)
{
var run = new Run(new List<long>(), new List<int>(), -1, Enumerable.Repeat(-1L, probes.Length).ToArray());
for (long i = 0; i < ticks; i++)
{
var e = r.Tick();
if ((e & TickEvents.GoalChanged) != 0) { run.Changes.Add(i); run.Goals.Add(r.Actor.GoalIndex); }
if ((e & TickEvents.WillBroke) != 0 && run.Broke < 0) run = run with { Broke = i };
for (var p = 0; p < probes.Length; p++)
{
if (run.Held[p] < 0 && probes[p](r.Actor.Drive)) run.Held[p] = i;
}
}
return run;
}
[Fact]
public void A_brain_with_no_rule_about_the_will_never_changes_goal_when_the_will_breaks()
{
var one = new Brain { Goals = new[] { Goal("only", 0.0) } };
var r = new PainBoxReplay(1, brain: one);
var run = Go(r, 2500);
Assert.True(run.Broke > 0, "the will never broke");
Assert.Empty(run.Changes);
Assert.Equal(0, r.Actor.GoalIndex);
}
[Fact]
public void A_release_that_enters_on_pain_switches_long_before_the_will_breaks_exactly_the_latency_after_pain_first_reached_it()
{
var brain = new Brain
{
Goals = new[] { Goal("objective", 0.0), Goal("release", 1.0, 0.5, Pain(ConditionOp.AtLeast, 0.6)) },
};
var r = new PainBoxReplay(1, brain: brain);
var run = Go(r, 2500, d => d.Pain >= 0.6);
Assert.True(run.Held[0] > 0);
Assert.Equal(new[] { run.Held[0] + Latency }, run.Changes);
Assert.Equal(new[] { 1 }, run.Goals);
Assert.True(run.Broke > run.Changes[0] + 500, $"will broke at {run.Broke}, the switch was at {run.Changes[0]}");
}
[Fact]
public void Of_several_eligible_goals_the_highest_priority_is_taken_ties_stay_put_or_go_to_the_lowest_index()
{
var calm = default(DriveState); // all zero, will intact
Condition Always = Pain(ConditionOp.Below, 1.0);
var brain = new Brain
{
Goals = new[]
{
Goal("a", 2.0, 0.5, Always), Goal("b", 5.0, 0.5, Always), Goal("c", 5.0, 0.5, Always),
Goal("d", 9.0, 0.5, Pain(ConditionOp.AtLeast, 0.5)),
},
};
Assert.Equal(1, Pick(brain, calm, 0)); // b and c tie at the top: the lowest index
Assert.Equal(2, Pick(brain, calm, 2)); // the current goal wins a tie
Assert.Equal(1, Pick(brain, calm, 3)); // d is ineligible: current is not kept for its own sake
var none = new Brain { Goals = new[] { Goal("x", 1.0, 0.5, Pain(ConditionOp.AtLeast, 0.5)), Goal("y", 0.0, 0.5, Pain(ConditionOp.AtLeast, 0.5)) } };
Assert.Equal(1, Pick(none, calm, 1)); // nothing eligible: the current goal
Assert.Equal(0, Pick(none, calm, 0));
}
[Fact]
public void A_three_goal_brain_passes_through_the_goals_as_their_conditions_come_true_each_a_latency_after_its_own()
{
var brain = new Brain
{
Goals = new[]
{
Goal("calm", 0.0),
Goal("wary", 3.0, 0.5, Pain(ConditionOp.AtLeast, 0.3)),
Goal("hurt", 5.0, 0.5, Pain(ConditionOp.AtLeast, 0.6)),
},
};
var r = new PainBoxReplay(1, brain: brain);
var run = Go(r, 2500, d => d.Pain >= 0.3, d => d.Pain >= 0.6);
Assert.Equal(new[] { 1, 2 }, run.Goals);
Assert.Equal(new[] { run.Held[0] + Latency, run.Held[1] + Latency }, run.Changes);
}
[Fact]
public void A_revert_brain_switches_back_when_the_arousal_that_chose_the_rage_falls_and_each_switch_fires_once()
{
var brain = new Brain
{
Goals = new[] { Goal("calm", 1.0, 1.0), Goal("rage", 2.0, 1.0, new Condition(DriveQuantity.Arousal, ConditionOp.AtLeast, 0.5)) },
};
var rig = new SensoryRig(SensoryRig.One(0.55), brain: brain);
long rose = -1, fell = -1;
var changes = new List<(long Tick, int Goal)>();
for (long i = 0; i < 20000; i++)
{
if (i == 6000) rig.Emitters[0].Intensity = 0.0;
var e = rig.Tick();
if ((e & TickEvents.GoalChanged) != 0) changes.Add((i, rig.Actor.GoalIndex));
if (rose < 0 && rig.Actor.Drive.Arousal >= 0.5) rose = i;
if (rose >= 0 && fell < 0 && i >= 6000 && rig.Actor.Drive.Arousal < 0.5) fell = i;
}
Assert.True(rose > 0 && fell > rose);
Assert.Equal(new[] { (rose + Latency, 1), (fell + Latency, 0) }, changes);
}
[Fact]
public void Resolve_drain_follows_the_pull_of_the_goal_in_force_slower_after_a_switch_to_a_goal_that_pulls_harder()
{
Brain Of(double secondPull) => new()
{
Goals = new[] { Goal("a", 0.0, 0.0), Goal("b", 1.0, secondPull, Pain(ConditionOp.AtLeast, 0.3)) },
};
var plain = new PainBoxReplay(1, brain: Of(0.0));
var pulled = new PainBoxReplay(1, brain: Of(0.9));
long switched = -1;
double before = 0.0, plainLoss = 0.0, pulledLoss = 0.0;
for (long i = 0; i < 1200; i++)
{
var ea = plain.Tick();
var eb = pulled.Tick();
if (switched < 0) Assert.Equal(ea, eb);
if ((eb & TickEvents.GoalChanged) != 0) { switched = i; before = plain.Actor.Drive.Resolve - pulled.Actor.Drive.Resolve; }
if (switched < 0) Assert.Equal(plain.Actor.Drive.Resolve, pulled.Actor.Drive.Resolve); // same pull until the switch
if (switched >= 0 && i == switched + 600)
{
plainLoss = 1.0 - plain.Actor.Drive.Resolve;
pulledLoss = 1.0 - pulled.Actor.Drive.Resolve;
}
}
Assert.True(switched > 0);
Assert.Equal(0.0, before);
Assert.True(pulled.Actor.Drive.Resolve > plain.Actor.Drive.Resolve);
Assert.True(pulledLoss < 0.25 * plainLoss, $"pull 0.9 lost {pulledLoss}, pull 0 lost {plainLoss}");
}
[Fact]
public void A_decision_in_flight_commits_at_its_tick_even_if_its_condition_has_lapsed()
{
// The band is a tick or two wide while pain rises through it; the latency is ten.
var brain = new Brain
{
Goals = new[] { Goal("a", 0.0), Goal("b", 1.0, 0.5, Pain(ConditionOp.AtLeast, 0.3), Pain(ConditionOp.Below, 0.305)) },
};
var r = new PainBoxReplay(1, brain: brain);
long inBand = -1, lapsed = -1;
var changes = new List<(long Tick, int Goal)>();
for (long i = 0; i < 600; i++)
{
var e = r.Tick();
if ((e & TickEvents.GoalChanged) != 0) changes.Add((i, r.Actor.GoalIndex));
var p = r.Actor.Drive.Pain;
if (inBand < 0 && p >= 0.3) inBand = i;
if (inBand >= 0 && lapsed < 0 && p >= 0.305) lapsed = i;
}
Assert.True(inBand > 0 && lapsed > inBand && lapsed < inBand + Latency, $"band {inBand}..{lapsed}");
Assert.Equal(new[] { (inBand + Latency, 1), (inBand + Latency + 1 + Latency, 0) }, changes); // committed, then the lapse is acted on once
}
[Fact]
public void While_a_decision_is_in_flight_no_second_one_is_made_the_later_goal_waits_for_the_first_to_commit()
{
var brain = new Brain
{
Goals = new[]
{
Goal("a", 0.0), Goal("b", 1.0, 0.5, Pain(ConditionOp.AtLeast, 0.3)), Goal("c", 2.0, 0.5, Pain(ConditionOp.AtLeast, 0.31)),
},
};
var r = new PainBoxReplay(1, brain: brain);
var run = Go(r, 600, d => d.Pain >= 0.3, d => d.Pain >= 0.31);
Assert.True(run.Held[1] > run.Held[0] && run.Held[1] < run.Held[0] + Latency, $"{run.Held[0]} {run.Held[1]}");
Assert.Equal(new[] { 1, 2 }, run.Goals);
Assert.Equal(new[] { run.Held[0] + Latency, run.Held[0] + Latency + 1 + Latency }, run.Changes);
}
[Fact]
public void The_brain_is_checked_when_the_actor_is_built()
{
Actor Build(Brain b) => new(0.01, 1, new NerveParameters(), new WithdrawalParameters(), new DriveParameters(), b);
var g = Goal("g", 0.0);
Assert.Throws<ArgumentException>(() => Build(new Brain()));
Assert.Throws<ArgumentException>(() => Build(new Brain { Goals = new[] { g }, Start = 1 }));
Assert.Throws<ArgumentException>(() => Build(new Brain { Goals = new[] { g }, DeliberateLatencySeconds = double.NaN }));
Assert.Throws<ArgumentException>(() => Build(new Brain { Goals = new[] { g with { Pull = 1.5 } } }));
Assert.Throws<ArgumentException>(() => Build(new Brain { Goals = new[] { g with { When = new[] { Pain(ConditionOp.AtLeast, double.NaN) } } } }));
Assert.Throws<ArgumentException>(() => Build(new Brain
{
Goals = new[] { g, g with { Behaviour = g.Behaviour with { Keys = new[] { new[] { Quat.Identity } }, FlinchPose = new[] { Quat.Identity } } } },
}));
Assert.Equal(1, Build(new Brain { Goals = new[] { g, g }, Start = 1 }).GoalIndex);
}
[Fact]
public void A_goal_in_force_writes_its_behaviour_and_seconds_in_goal_count_from_the_tick_it_took_over()
{
var spin = new[]
{
new[] { Quat.Identity, Quat.Identity },
new[] { Quat.FromAxisAngle(0f, 0f, 1f, 0.8f), Quat.Identity },
};
var brain = new Brain
{
Goals = new[]
{
Goal("a", 0.0),
Goal("loop", 1.0, 0.5, Pain(ConditionOp.AtLeast, 0.3)) with
{
Behaviour = new PoseBehaviour
{
Keys = spin, SecondsPerKey = 0.2, FlinchPose = spin[0],
Hold = new HoldParameters { FlinchGain = 0.0, StrainShake = 0.0 },
},
},
},
};
var r = new PainBoxReplay(1, brain: brain);
long changed = -1;
for (long i = 0; i < 600 && changed < 0; i++)
{
if ((r.Tick() & TickEvents.GoalChanged) != 0) changed = i;
}
Assert.True(changed > 0);
Assert.Equal(0.01, r.Actor.SecondsInGoal, 12); // the next tick sees one tick in the goal
for (var k = 0; k < 10; k++) r.Tick();
Assert.Equal(0.11, r.Actor.SecondsInGoal, 9);
Assert.NotEqual(0f, r.Targets[0].Z); // partway from key 0 to key 1: the loop is walking
}
[Fact]
public void Tick_with_a_three_goal_brain_and_a_four_key_behaviour_allocates_nothing_and_interleaved_actors_equal_each_alone()
{
Brain Make()
{
var keys = Enumerable.Range(0, 4).Select(k => new[] { Quat.FromAxisAngle(0f, 0f, 1f, 0.3f * k), Quat.Identity }).ToArray();
return new Brain
{
Goals = new[]
{
Goal("calm", 0.0),
Goal("wary", 1.0, 0.4, Pain(ConditionOp.AtLeast, 0.3)) with
{
Behaviour = new PoseBehaviour { Keys = keys, SecondsPerKey = 0.1, FlinchPose = PainBoxBrain.Withdraw },
},
Goal("hurt", 2.0, 0.8, Pain(ConditionOp.AtLeast, 0.6)),
},
};
}
var solo = new PainBoxReplay(1, brain: Make());
for (var i = 0; i < 300; i++) solo.Tick(); // warm, and through the first switches
var before = GC.GetAllocatedBytesForCurrentThread();
for (var i = 0; i < 10000; i++) solo.Tick();
Assert.Equal(0L, GC.GetAllocatedBytesForCurrentThread() - before);
const int n = 2500;
var a1 = new PainBoxReplay(1, brain: Make());
var b1 = new PainBoxReplay(7, intensity: 0.6, brain: Make());
var a2 = new PainBoxReplay(1, brain: Make());
var b2 = new PainBoxReplay(7, intensity: 0.6, brain: Make());
var ea = new TickEvents[n];
var eb = new TickEvents[n];
for (var i = 0; i < n; i++) { ea[i] = a1.Tick(); eb[i] = b1.Tick(); }
for (var i = 0; i < n; i++) Assert.Equal(ea[i], a2.Tick());
for (var i = 0; i < n; i++) Assert.Equal(eb[i], b2.Tick());
Assert.Equal(a1.Actor.GoalIndex, a2.Actor.GoalIndex);
Assert.Equal(b1.Actor.GoalIndex, b2.Actor.GoalIndex);
Assert.Equal(a1.Targets, a2.Targets);
Assert.Equal(b1.Targets, b2.Targets);
Assert.Contains(ea, e => (e & TickEvents.GoalChanged) != 0);
}
private static double Read(DriveState d, DriveQuantity q) => q switch
{
DriveQuantity.Pain => d.Pain,
DriveQuantity.Strain => d.Strain,
DriveQuantity.Arousal => d.Arousal,
DriveQuantity.Resolve => d.Resolve,
DriveQuantity.Breaks => d.Breaks,
DriveQuantity.AirHunger => d.AirHunger,
_ => d.WillBroken ? 1.0 : 0.0,
};
private static Brain Gated(Condition when, double dwell = 0.0, double pull = 0.5) => new()
{
Goals = new[] { Goal("calm", 0.0, pull), Goal("gated", 1.0, pull, when) with { MinDwellSeconds = dwell } },
};
/// <summary>
/// Runs a rig whose Brain has one goal gated on the condition; the switch must land the latency after the tick the
/// quantity itself first crossed, and no other quantity read the same way may cross on that tick (or the scenario
/// could not tell a misread from the right read).
/// </summary>
private static void GateFollowsOnly(Func<Brain, (Func<TickEvents> Tick, Func<DriveState> Drive)> rig, DriveQuantity q, ConditionOp op, double threshold, long ticks, DriveQuantity? sameTickOk = null)
{
var (tick, drive) = rig(Gated(new Condition(q, op, threshold)));
bool Crossed(DriveState d, DriveQuantity of) => op == ConditionOp.AtLeast ? Read(d, of) >= threshold : Read(d, of) < threshold;
var firstOf = new Dictionary<DriveQuantity, long>();
long changed = -1;
for (long i = 0; i < ticks; i++)
{
var e = tick();
if ((e & TickEvents.GoalChanged) != 0 && changed < 0) changed = i;
foreach (var of in Enum.GetValues<DriveQuantity>())
{
if (!firstOf.ContainsKey(of) && Crossed(drive(), of)) firstOf[of] = i;
}
}
Assert.True(firstOf.TryGetValue(q, out var own), $"{q} never crossed {threshold}");
Assert.Equal(own + Latency, changed);
foreach (var of in Enum.GetValues<DriveQuantity>())
{
if (of != q && of != sameTickOk) Assert.False(firstOf.TryGetValue(of, out var other) && other == own, $"{of} crosses on the same tick as {q}: the scenario cannot tell them apart");
}
}
private static (Func<TickEvents>, Func<DriveState>) PainRig(Brain b) { var r = new PainBoxReplay(1, brain: b); return (() => r.Tick(), () => r.Actor.Drive); }
private static (Func<TickEvents>, Func<DriveState>) SenseRig(Brain b)
{
var r = new SensoryRig(SensoryRig.One(0.55), brain: b);
return (() => r.Tick(), () => r.Actor.Drive);
}
[Theory]
[InlineData(DriveQuantity.Pain, ConditionOp.AtLeast, 0.5)]
[InlineData(DriveQuantity.Strain, ConditionOp.AtLeast, 1.0)]
[InlineData(DriveQuantity.Resolve, ConditionOp.Below, 0.9)]
[InlineData(DriveQuantity.WillBroken, ConditionOp.AtLeast, 1.0)]
public void Each_drive_quantity_a_condition_reads_is_that_quantity_in_the_pain_box(DriveQuantity q, ConditionOp op, double threshold) =>
// The first break moves Breaks and WillBroken on one tick; WillTests reads Breaks at its second break, where they part.
GateFollowsOnly(PainRig, q, op, threshold, 1700, DriveQuantity.Breaks);
[Fact]
public void Arousal_a_condition_reads_is_arousal_where_pain_strain_and_resolve_do_not_move_with_it()
{
GateFollowsOnly(SenseRig, DriveQuantity.Arousal, ConditionOp.AtLeast, 0.5, 3000);
}
[Fact]
public void Below_is_strict_and_at_least_is_inclusive_at_the_threshold()
{
var zero = default(DriveState); // pain exactly 0
Assert.True(new Condition(DriveQuantity.Pain, ConditionOp.AtLeast, 0.0).Holds(zero));
Assert.False(new Condition(DriveQuantity.Pain, ConditionOp.Below, 0.0).Holds(zero));
Assert.True(new Condition(DriveQuantity.Pain, ConditionOp.Below, 1e-300).Holds(zero));
Assert.False(new Condition(DriveQuantity.Pain, ConditionOp.AtLeast, 1e-300).Holds(zero));
Assert.False(new Condition(DriveQuantity.WillBroken, ConditionOp.Below, 0.0).Holds(zero)); // unbroken reads 0
Assert.True(new Condition(DriveQuantity.WillBroken, ConditionOp.Below, 1.0).Holds(zero));
}
private static long ChangeTickAfterPain(double latencySeconds)
{
var brain = Gated(Pain(ConditionOp.AtLeast, 0.3)) with { DeliberateLatencySeconds = latencySeconds };
var run = Go(new PainBoxReplay(1, brain: brain), 600, d => d.Pain >= 0.3);
Assert.Single(run.Changes);
return run.Changes[0] - run.Held[0];
}
[Fact]
public void The_deliberate_latency_is_rounded_to_ticks_never_less_than_one_and_a_negative_latency_is_refused()
{
Assert.Equal(1, ChangeTickAfterPain(0.0)); // a switch never lands on the tick it was decided
Assert.Equal(1, ChangeTickAfterPain(0.001));
Assert.Equal(1, ChangeTickAfterPain(0.014));
Assert.Equal(2, ChangeTickAfterPain(0.016));
Assert.Equal(10, ChangeTickAfterPain(0.1));
var g = Goal("g", 0.0);
Assert.Throws<ArgumentException>(() => new Actor(0.01, 1, new NerveParameters(), new WithdrawalParameters(), new DriveParameters(),
new Brain { Goals = new[] { g }, DeliberateLatencySeconds = -0.01 }));
}
[Fact]
public void The_pending_goals_behaviour_is_not_written_during_the_latency_only_from_the_tick_it_takes_over()
{
var loud = Goal("b", 1.0, 0.5, Pain(ConditionOp.AtLeast, 0.3)) with
{
Behaviour = new PoseBehaviour { Keys = new[] { PainBoxBrain.Hold }, FlinchPose = PainBoxBrain.Withdraw, Hold = new HoldParameters { HoldStrength = 0.25f } },
};
var r = new PainBoxReplay(1, brain: new Brain { Goals = new[] { Goal("a", 0.0), loud } });
long decided = -1;
var landed = false;
for (long i = 0; i < 600 && !landed; i++)
{
var e = r.Tick();
if (decided < 0 && r.Actor.Drive.Pain >= 0.3) decided = i;
if (decided < 0) continue;
if (i < decided + Latency)
{
Assert.Equal(1f, r.Strengths[0]);
Assert.Equal((i + 1) * 0.01, r.Actor.SecondsInGoal, 9); // the goal in force keeps its own clock through the decision and the latency
Assert.Equal(0, (int)(e & TickEvents.GoalChanged));
}
else
{
Assert.Equal(TickEvents.GoalChanged, e & TickEvents.GoalChanged);
Assert.Equal(0.25f, r.Strengths[0]);
landed = true;
}
}
Assert.True(landed);
}
[Fact]
public void A_behaviours_phase_restarts_from_the_time_in_the_goal_not_the_clock()
{
var keys = Enumerable.Range(0, 4).Select(k => new[] { Quat.FromAxisAngle(0f, 0f, 1f, 0.3f * k), Quat.Identity }).ToArray();
var loop = Goal("loop", 1.0, 0.5, Pain(ConditionOp.AtLeast, 0.3)) with
{
Behaviour = new PoseBehaviour { Keys = keys, SecondsPerKey = 0.1, FlinchPose = keys[0], Hold = new HoldParameters { FlinchGain = 0.0, StrainShake = 0.0 } },
};
var r = new PainBoxReplay(1, brain: new Brain { Goals = new[] { Goal("a", 0.0), loop } });
long changed = -1;
for (long i = 0; i < 600 && changed < 0; i++)
{
if ((r.Tick() & TickEvents.GoalChanged) != 0) changed = i;
}
Assert.True(changed > 0 && changed % 40 != 0, $"changed at {changed}: the loop is 40 ticks, a clock-driven phase would be hidden");
Assert.Equal(Quat.Nlerp(keys[0][0], keys[0][0], 0f).Z, r.Targets[0].Z); // key 0 exactly, the tick it takes over
for (var k = 0; k < 5; k++) r.Tick();
Assert.Equal(Quat.Nlerp(keys[0][0], keys[1][0], 0.5f).Z, r.Targets[0].Z, 5); // half way to key 1 after half a key
}
private static List<(long Tick, int Goal)> Hover(double dwell, double threshold)
{
var rage = Goal("rage", 2.0, 1.0, new Condition(DriveQuantity.Arousal, ConditionOp.AtLeast, threshold)) with { MinDwellSeconds = dwell };
var brain = new Brain { Goals = new[] { Goal("calm", 1.0, 1.0) with { MinDwellSeconds = dwell }, rage } };
var rig = new SensoryRig(SensoryRig.One(0.55), brain: brain);
var changes = new List<(long, int)>();
for (long i = 0; i < 6000; i++)
{
rig.Emitters[0].Intensity = (i / 100) % 2 == 0 ? 0.55 : 0.0; // on 1 s, off 1 s: arousal saws around its middle
if ((rig.Tick() & TickEvents.GoalChanged) != 0) changes.Add((i, rig.Actor.GoalIndex));
}
return changes;
}
[Fact]
public void A_condition_hovering_at_its_threshold_chatters_without_a_dwell_and_with_one_the_entered_goal_is_not_left_for_a_lower_one_inside_its_window()
{
double lo = 1, hi = 0;
var probe = new SensoryRig(SensoryRig.One(0.55), brain: new Brain { Goals = new[] { Goal("only", 0.0, 1.0) } });
for (long i = 0; i < 6000; i++)
{
probe.Emitters[0].Intensity = (i / 100) % 2 == 0 ? 0.55 : 0.0;
probe.Tick();
if (i >= 3000) { lo = Math.Min(lo, probe.Actor.Drive.Arousal); hi = Math.Max(hi, probe.Actor.Drive.Arousal); }
}
var mid = 0.5 * (lo + hi);
var free = Hover(0.0, mid);
Assert.True(free.Count >= 15, $"{free.Count} changes with no dwell: the scenario does not chatter");
const double dwell = 3.0;
const long dwellTicks = 300;
var held = Hover(dwell, mid);
Assert.True(held.Count >= 2 && held.Count * 2 <= free.Count, $"{held.Count} changes with a dwell of {dwell} s against {free.Count}");
var leaves = 0;
for (var i = 1; i < held.Count; i++)
{
if (held[i].Goal != 0) continue; // only the return trip (rage to the lower calm) is gated by rage's dwell
leaves++;
Assert.True(held[i].Tick - held[i - 1].Tick >= dwellTicks + Latency, $"rage taken at {held[i - 1].Tick} and left at {held[i].Tick}");
}
Assert.True(leaves >= 2);
Assert.Throws<ArgumentException>(() => new Actor(0.01, 1, new NerveParameters(), new WithdrawalParameters(), new DriveParameters(),
new Brain { Goals = new[] { Goal("g", 0.0) with { MinDwellSeconds = -1.0 } } }));
foreach (var bad in new[] { double.PositiveInfinity, double.NaN })
{
Assert.Throws<ArgumentException>(() => new Actor(0.01, 1, new NerveParameters(), new WithdrawalParameters(), new DriveParameters(),
new Brain { Goals = new[] { Goal("g", 0.0) with { MinDwellSeconds = bad } } }));
}
}
/// <summary>
/// Goal 1 is the start goal, eligible while pain is below 0.3, with the dwell; goal 0 (no dwell) is the lower-priority
/// goal always eligible. Pain passes 0.3 early, so the decision to leave goal 1 is held to its dwell and lands exactly then.
/// </summary>
private static (long Dwell, long Changed, long PainLapsed) LeaveHeldGoal(double dwellSeconds, double priorityOfTarget = 1.0)
{
var brain = new Brain
{
Goals = new[]
{
Goal("target", priorityOfTarget, 0.5, Pain(ConditionOp.AtLeast, 0.3)),
Goal("held", 2.0, 0.5, Pain(ConditionOp.Below, 0.3)) with { MinDwellSeconds = dwellSeconds },
},
Start = 1,
};
var r = new PainBoxReplay(1, brain: brain);
long lapsed = -1, changed = -1;
for (long i = 0; i < 800 && changed < 0; i++)
{
if ((r.Tick() & TickEvents.GoalChanged) != 0) changed = i;
if (lapsed < 0 && r.Actor.Drive.Pain >= 0.3) lapsed = i;
}
return (0, changed, lapsed);
}
[Fact]
public void A_goal_not_outranked_is_left_exactly_a_dwell_after_it_took_over_the_decision_held_on_the_dwells_last_tick()
{
// 3.0 s is 300 ticks from tick 0 (the start goal is active from there): the decision is taken on tick 300 and lands 10 later.
var (_, changed, lapsed) = LeaveHeldGoal(3.0);
Assert.True(lapsed > 0 && lapsed < 290, $"pain lapsed the condition on tick {lapsed}");
Assert.Equal(300 + Latency, changed);
// The dwell is the held goal's own (goal 1), not goal 0's, which has none.
var free = LeaveHeldGoal(0.0);
Assert.Equal(free.PainLapsed + Latency, free.Changed);
}
[Fact]
public void A_dwell_is_rounded_to_the_nearest_tick_as_the_latency_is()
{
Assert.Equal(300 + Latency, LeaveHeldGoal(3.004).Changed); // 300.4 ticks: a ceiling would make it 301
Assert.Equal(301 + Latency, LeaveHeldGoal(3.006).Changed); // 300.6 ticks: a floor would make it 300
}
[Fact]
public void A_strictly_higher_priority_goal_preempts_during_the_dwell_after_the_latency_and_a_goal_that_ties_or_ranks_below_is_held()
{
// Same scene, but the goal it would move to outranks the held one: no wait for the dwell.
var (_, preempted, lapsed) = LeaveHeldGoal(3.0, priorityOfTarget: 3.0);
Assert.Equal(lapsed + Latency, preempted);
Assert.Equal(300 + Latency, LeaveHeldGoal(3.0, priorityOfTarget: 2.0).Changed); // a tie is not strictly higher
Assert.Equal(300 + Latency, LeaveHeldGoal(3.0, priorityOfTarget: 1.99).Changed);
}
[Fact]
public void The_dwell_of_an_entered_goal_counts_from_the_tick_it_took_over_not_from_the_decision()
{
// Held goal b is entered on pain at least 0.3 and its condition lapses at once (a band); its dwell of 2 s runs from the takeover.
var band = Goal("b", 2.0, 0.5, Pain(ConditionOp.AtLeast, 0.3), Pain(ConditionOp.Below, 0.305)) with { MinDwellSeconds = 2.0 };
var r = new PainBoxReplay(1, brain: new Brain { Goals = new[] { Goal("a", 1.0), band } });
long decided = -1, entered = -1, left = -1;
for (long i = 0; i < 800 && left < 0; i++)
{
var e = r.Tick();
if (decided < 0 && r.Actor.Drive.Pain >= 0.3) decided = i;
if ((e & TickEvents.GoalChanged) != 0) { if (entered < 0) entered = i; else left = i; }
}
Assert.Equal(decided + Latency, entered);
Assert.Equal(entered + 200 + Latency, left);
}
[Fact]
public void A_built_brains_getters_hand_out_read_only_views_and_writing_through_them_changes_nothing()
{
var keys = new[] { new[] { Quat.Identity, Quat.Identity } };
var brain = new Brain
{
Goals = new[]
{
Goal("a", 0.0),
Goal("b", 1.0, 0.5, Pain(ConditionOp.AtLeast, 0.3)) with
{
Behaviour = new PoseBehaviour { Keys = keys, FlinchPose = PainBoxBrain.Withdraw },
},
},
};
static void Sealed<T>(IReadOnlyList<T> view, T poison)
{
Assert.False(view is T[]);
if (view is IList<T> list)
{
Assert.True(list.IsReadOnly);
Assert.Throws<NotSupportedException>(() => list[0] = poison);
}
}
Sealed(brain.Goals, Goal("poison", 9.0));
Sealed(brain.Goals[1].When, Pain(ConditionOp.AtLeast, double.NaN));
Sealed(brain.Goals[1].Behaviour.Keys, (IReadOnlyList<Quat>)new Quat[1]);
Sealed(brain.Goals[1].Behaviour.Keys[0], new Quat(7f, 7f, 7f, 7f));
Sealed(brain.Goals[1].Behaviour.FlinchPose, new Quat(7f, 7f, 7f, 7f));
var a = new PainBoxReplay(1, brain: brain);
var b = new PainBoxReplay(1, brain: new Brain { Goals = new[] { Goal("a", 0.0), Goal("b", 1.0, 0.5, Pain(ConditionOp.AtLeast, 0.3)) with { Behaviour = new PoseBehaviour { Keys = keys, FlinchPose = PainBoxBrain.Withdraw } } } });
for (var i = 0; i < 1000; i++)
{
Assert.Equal(b.Tick(), a.Tick());
Assert.Equal(b.Targets, a.Targets);
}
}
[Fact]
public void A_validated_brain_does_not_follow_later_changes_to_the_lists_and_arrays_it_was_built_from()
{
Brain Build(out List<GoalSpec> goals, out Condition[] when, out Quat[][] keys, out Quat[] flinch)
{
when = new[] { Pain(ConditionOp.AtLeast, 0.3) };
keys = new[] { (Quat[])PainBoxBrain.Hold.Clone() };
flinch = (Quat[])PainBoxBrain.Withdraw.Clone();
goals = new List<GoalSpec>
{
Goal("a", 0.0),
Goal("b", 1.0, 0.5) with { When = when, Behaviour = new PoseBehaviour { Keys = keys, FlinchPose = flinch } },
};
return new Brain { Goals = goals };
}
var brain = Build(out var goals, out var when, out var keys, out var flinch);
var twin = Build(out _, out _, out _, out _);
goals.Clear();
when[0] = Pain(ConditionOp.AtLeast, double.NaN);
keys[0][0] = new Quat(9f, 9f, 9f, 9f);
keys[0] = new Quat[1];
flinch[0] = new Quat(5f, 5f, 5f, 5f);
var a = new PainBoxReplay(1, brain: brain);
var b = new PainBoxReplay(1, brain: twin);
for (var i = 0; i < 1500; i++)
{
Assert.Equal(b.Tick(), a.Tick());
Assert.Equal(b.Targets, a.Targets);
}
Assert.Equal(2, brain.Goals.Count);
Assert.Equal(1, a.Actor.GoalIndex);
}
}

View file

@ -0,0 +1,202 @@
using Lodur;
namespace Lodur.Core.Tests;
/// <summary>
/// A goal's sensory gain (lodur:ruling:stress-bar-shows-arousal-calm-silences) gates the sense channels' afferents after the conduction delay,
/// builds Load from the gated values, and never touches the world's stimulus or the nociceptive region afferents.
/// </summary>
public sealed class SensoryGainTests
{
private const double Dt = 0.01;
private static readonly float[] Zero = { 0f };
private static readonly BoxStimulus[] NoBoxes = System.Array.Empty<BoxStimulus>();
private static readonly Emitter[] Loud = { new Emitter(Channel.Audio, 0f, 0f, 0f, 1f, 0.6), new Emitter(Channel.Visual, 0f, 0f, 0f, 1f, 0.4) };
private static Perception Senses(NerveParameters senses, double delay = 0.0) =>
new Perception(new NerveParameters(), Dt, 1, senses with { ConductionDelaySeconds = delay }, 0);
[Fact]
public void Gain_one_leaves_every_afferent_and_the_load_bit_identical_to_no_gain()
{
var a = Senses(new NerveParameters { Threshold = 0.05, SensitisationGrowth = 2.0 }, 0.03);
var b = Senses(new NerveParameters { Threshold = 0.05, SensitisationGrowth = 2.0 }, 0.03);
for (var i = 0; i < 300; i++)
{
a.Sense(Zero, Zero, Zero, NoBoxes, Loud);
b.Sense(Zero, Zero, Zero, NoBoxes, Loud, 1.0);
Assert.Equal(a.Load, b.Load);
Assert.Equal(a.ChannelAfferent(Channel.Audio), b.ChannelAfferent(Channel.Audio));
Assert.Equal(a.ChannelAfferent(Channel.Visual), b.ChannelAfferent(Channel.Visual));
}
Assert.True(a.Load > 0.0);
}
[Fact]
public void Gain_scales_each_channels_afferent_and_builds_the_load_from_the_scaled_afferents_while_the_stimulus_is_the_worlds()
{
var p = Senses(new NerveParameters { Threshold = 0.05, SensitisationGrowth = 0.0 });
p.Sense(Zero, Zero, Zero, NoBoxes, Loud, 0.5);
p.Sense(Zero, Zero, Zero, NoBoxes, Loud, 0.5);
double audio = (0.6 - 0.05) * 0.5, visual = (0.4 - 0.05) * 0.5;
Assert.Equal(audio, p.ChannelAfferent(Channel.Audio), 12);
Assert.Equal(visual, p.ChannelAfferent(Channel.Visual), 12);
Assert.Equal(1.0 - (1.0 - audio) * (1.0 - visual), p.Load, 12);
Assert.Equal(0.6, p.ChannelStimulus(Channel.Audio), 12);
p.Sense(Zero, Zero, Zero, NoBoxes, Loud, 0.0);
Assert.Equal(0.0, p.ChannelAfferent(Channel.Audio));
Assert.Equal(0.0, p.ChannelAfferent(Channel.Visual));
Assert.Equal(0.0, p.Load);
Assert.Equal(0.6, p.ChannelStimulus(Channel.Audio), 12);
Assert.Equal(0.4, p.ChannelStimulus(Channel.Visual), 12);
}
[Fact]
public void The_gain_in_force_when_the_afferent_leaves_the_delay_applies_not_the_gain_when_the_stimulus_entered()
{
var p = Senses(new NerveParameters { Threshold = 0.05, SensitisationGrowth = 0.0 }, 0.05); // 5 ticks in flight
for (var i = 0; i < 20; i++) p.Sense(Zero, Zero, Zero, NoBoxes, Loud, 1.0);
Assert.True(p.ChannelAfferent(Channel.Audio) > 0.5);
p.Sense(Zero, Zero, Zero, NoBoxes, Loud, 0.0); // the same signal, gated as it arrives
Assert.Equal(0.0, p.ChannelAfferent(Channel.Audio));
p.Sense(Zero, Zero, Zero, NoBoxes, Loud, 1.0);
Assert.Equal(0.55, p.ChannelAfferent(Channel.Audio), 12);
}
[Fact]
public void Sensitisation_follows_the_world_not_the_gain()
{
var nerve = new NerveParameters { Threshold = 0.05, SensitisationGrowth = 2.0, SensitisationCap = 4.0 };
var deaf = Senses(nerve);
var hearing = Senses(nerve);
for (var i = 0; i < 200; i++)
{
deaf.Sense(Zero, Zero, Zero, NoBoxes, Loud, 0.0);
hearing.Sense(Zero, Zero, Zero, NoBoxes, Loud, 1.0);
}
deaf.Sense(Zero, Zero, Zero, NoBoxes, Loud, 1.0);
hearing.Sense(Zero, Zero, Zero, NoBoxes, Loud, 1.0);
Assert.Equal(hearing.ChannelAfferent(Channel.Audio), deaf.ChannelAfferent(Channel.Audio));
Assert.True(deaf.ChannelAfferent(Channel.Audio) > 0.55, "the channel sensitised while it was gated");
}
[Fact]
public void Sense_refuses_a_gain_outside_zero_to_one_and_leaves_its_state_alone()
{
var p = Senses(new NerveParameters { Threshold = 0.05, SensitisationGrowth = 0.0 });
p.Sense(Zero, Zero, Zero, NoBoxes, Loud, 1.0);
foreach (var bad in new[] { double.NaN, -0.01, 1.01, double.PositiveInfinity, double.NegativeInfinity })
{
var ex = Assert.Throws<ArgumentException>(() => p.Sense(Zero, Zero, Zero, NoBoxes, Loud, bad));
Assert.Contains("gain", ex.Message);
}
p.Sense(Zero, Zero, Zero, NoBoxes, Loud, 0.0);
p.Sense(Zero, Zero, Zero, NoBoxes, Loud, 1.0);
Assert.Equal(0.55, p.ChannelAfferent(Channel.Audio), 12);
}
private static Brain GainGoal(double gain, string id = "g") => new()
{
Goals = new[] { new GoalSpec { Id = id, SensoryGain = gain, Behaviour = new PoseBehaviour { Keys = new[] { PainBoxBrain.Hold }, FlinchPose = PainBoxBrain.Withdraw } } },
};
[Fact]
public void A_goal_with_gain_zero_silences_load_and_channel_afferents_but_not_the_pain_path_or_the_world_stimulus()
{
var events = new List<TickEvents>[2] { new(), new() };
var afferent = new List<double>[2] { new(), new() };
var flinches = new int[2];
var gains = new[] { 1.0, 0.0 };
var p = new[] { 0f };
for (var k = 0; k < 2; k++)
{
var actor = new Actor(Dt, 1, new NerveParameters(), new WithdrawalParameters(), new DriveParameters() with { ResolveDrainPain = 0.0, ResolveDrainStrain = 0.0, ResolveDrainArousal = 0.0 },
GainGoal(gains[k]), new NerveParameters { Threshold = 0.05, SensitisationGrowth = 0.0 }, 0);
actor.SetAttention(0.4); // a will that holds only part of the reflex down, so flinches leak
Assert.Equal(gains[k], actor.Drive.SensoryGain);
var strengths = new float[2];
var targets = new Quat[2];
var box = new[] { new BoxStimulus(0f, 0f, 0f, 1f, 1f, 1f) { Intensity = 0.8 } };
for (var i = 0; i < 600; i++)
{
var e = actor.Tick(p, p, p, box, strengths, targets, Loud);
events[k].Add(e);
afferent[k].Add(actor.Afferent(0));
if ((e & TickEvents.Flinch) != 0) flinches[k]++;
if (i >= 10)
{
Assert.Equal(0.6, actor.ChannelStimulus(Channel.Audio), 12);
if (k == 1)
{
Assert.Equal(0.0, actor.Load);
Assert.Equal(0.0, actor.ChannelAfferent(Channel.Audio));
}
else
{
Assert.True(actor.Load > 0.0);
}
}
}
}
Assert.True(flinches[1] > 0, "the fixture flinches");
Assert.Equal(events[0], events[1]);
Assert.Equal(afferent[0], afferent[1]);
}
[Fact]
public void The_start_goals_gain_holds_at_construction_and_a_later_goal_sets_it_the_tick_it_takes_over()
{
var pose = new PoseBehaviour { Keys = new[] { PainBoxBrain.Hold }, FlinchPose = PainBoxBrain.Withdraw };
var brain = new Brain
{
Start = 0,
Goals = new[]
{
new GoalSpec { Id = "a", SensoryGain = 0.25, Behaviour = pose },
new GoalSpec { Id = "b", Priority = 1.0, SensoryGain = 0.75, When = new[] { new Condition(DriveQuantity.Pain, ConditionOp.AtLeast, 0.05) }, Behaviour = pose },
},
};
var actor = new Actor(Dt, 1, new NerveParameters(), new WithdrawalParameters(), new DriveParameters(), brain);
Assert.Equal(0.25, actor.Drive.SensoryGain);
var p = new[] { 0f };
var box = new[] { new BoxStimulus(0f, 0f, 0f, 1f, 1f, 1f) { Intensity = 0.9 } };
var strengths = new float[2];
var targets = new Quat[2];
for (var i = 0; i < 2000; i++)
{
var e = actor.Tick(p, p, p, box, strengths, targets);
if ((e & TickEvents.GoalChanged) != 0)
{
Assert.Equal(1, actor.GoalIndex);
Assert.Equal(0.75, actor.Drive.SensoryGain);
return;
}
Assert.Equal(0.25, actor.Drive.SensoryGain);
}
Assert.Fail("the second goal never took over");
}
[Fact]
public void SensoryGain_outside_zero_to_one_or_not_a_number_is_refused_naming_the_goal()
{
void Refused(double gain)
{
var ex = Assert.Throws<ArgumentException>(() => new Actor(Dt, 1, new NerveParameters(), new WithdrawalParameters(), new DriveParameters(), GainGoal(gain, "bad")));
Assert.Contains("bad", ex.Message);
}
Refused(-0.01);
Refused(1.01);
Refused(double.NaN);
Refused(double.PositiveInfinity);
_ = new Actor(Dt, 1, new NerveParameters(), new WithdrawalParameters(), new DriveParameters(), GainGoal(0.0));
_ = new Actor(Dt, 1, new NerveParameters(), new WithdrawalParameters(), new DriveParameters(), GainGoal(1.0));
}
}

View file

@ -0,0 +1,249 @@
using Lodur;
namespace Lodur.Core.Tests;
/// <summary>
/// The entry ramp (lodur:ruling:flinch-tail-after-stimulus): a goal's arousal and sensory-gain targets are reached linearly over EntrySeconds from
/// their values at takeover, so the stress bar and the flinch drive tail off rather than cut; after it the drive owns arousal.
/// </summary>
public sealed class EntryRampTests
{
private const double Dt = 0.01;
private const double Afferent = 0.5; // an emitter of 0.55 through a 0.05 threshold, no sensitisation, gain 1
private static readonly PoseBehaviour Pose = new() { Keys = new[] { PainBoxBrain.Hold }, FlinchPose = PainBoxBrain.Withdraw };
/// <summary>Stress is the Start goal; calm takes over once arousal reaches 0.2 and holds (its dwell outlasts every test).</summary>
private static Brain StressThenCalm(double entrySeconds, double gain = 0.0, double? arousal = 0.0) => new()
{
Goals = new[]
{
new GoalSpec { Id = "stress", Behaviour = Pose },
new GoalSpec
{
Id = "calm", Priority = 1.0, MinDwellSeconds = 1000.0, SensoryGain = gain, EntryArousal = arousal, EntrySeconds = entrySeconds,
When = new[] { new Condition(DriveQuantity.Arousal, ConditionOp.AtLeast, 0.2) }, Behaviour = Pose,
},
},
};
private sealed class Rig
{
public readonly Actor Actor;
private readonly Emitter[] _emitters = { new Emitter(Channel.Audio, 0f, 0f, 0f, 1f, 0.55) };
private readonly BoxStimulus[] _box = { new BoxStimulus(0f, 0f, 0f, 1f, 1f, 1f) };
private readonly float[] _p = { 0f };
private readonly float[] _strengths = new float[2];
private readonly Quat[] _targets = new Quat[2];
public Rig(Brain brain) =>
Actor = new Actor(Dt, 1, new NerveParameters(), new WithdrawalParameters(), new DriveParameters(), brain,
new NerveParameters { Threshold = 0.05, SensitisationGrowth = 0.0 }, 0);
public double Pain { set => _box[0].Intensity = value; }
public TickEvents Tick() => Actor.Tick(_p, _p, _p, _box, _strengths, _targets, _emitters);
/// <summary>Ticks until the goal at <paramref name="goal"/> takes over; the takeover tick has just run.</summary>
public void UntilTakeover(int goal)
{
for (var i = 0; i < 20000; i++)
{
if ((Tick() & TickEvents.GoalChanged) != 0 && Actor.GoalIndex == goal) return;
}
Assert.Fail("the goal never took over");
}
}
[Fact]
public void A_three_second_ramp_takes_arousal_and_load_linearly_to_exactly_zero_on_its_last_tick_and_not_before_and_they_stay_zero_under_steady_emitters()
{
var rig = new Rig(StressThenCalm(3.0));
rig.UntilTakeover(1);
var a0 = rig.Actor.Drive.Arousal;
Assert.True(a0 >= 0.2);
Assert.Equal(1.0, rig.Actor.Drive.SensoryGain);
const int ticks = 300;
for (var k = 1; k <= ticks + 500; k++)
{
rig.Tick();
var ramp = Math.Max(0.0, 1.0 - (double)k / ticks);
// Sense reads the gain the ramp left at the end of the previous tick.
var senseGain = Math.Max(0.0, 1.0 - (double)(k - 1) / ticks);
Assert.Equal(a0 * ramp, rig.Actor.Drive.Arousal, 12);
Assert.Equal(ramp, rig.Actor.Drive.SensoryGain, 12);
Assert.Equal(Afferent * senseGain, rig.Actor.Load, 12);
Assert.Equal(0.55, rig.Actor.ChannelStimulus(Channel.Audio), 12); // the world keeps sounding
if (k < ticks) Assert.True(rig.Actor.Drive.Arousal > 0.0 && rig.Actor.Drive.SensoryGain > 0.0, $"still above zero at {k * Dt:0.00} s");
if (k >= ticks)
{
Assert.Equal(0.0, rig.Actor.Drive.Arousal);
Assert.Equal(0.0, rig.Actor.Drive.SensoryGain);
}
if (k > ticks) Assert.Equal(0.0, rig.Actor.Load);
}
}
[Fact]
public void A_ramp_of_zero_seconds_reaches_the_targets_on_the_takeover_tick()
{
var rig = new Rig(StressThenCalm(0.0));
rig.UntilTakeover(1);
Assert.Equal(0.0, rig.Actor.Drive.Arousal);
Assert.Equal(0.0, rig.Actor.Drive.SensoryGain);
for (var i = 0; i < 300; i++)
{
rig.Tick();
Assert.Equal(0.0, rig.Actor.Load);
Assert.Equal(0.0, rig.Actor.Drive.Arousal);
}
}
[Fact]
public void A_ramp_ends_exactly_on_a_nonzero_target_not_a_float_step_away_from_it()
{
var brain = new Brain
{
Goals = new[]
{
new GoalSpec { Id = "a", SensoryGain = 0.8, Behaviour = Pose },
new GoalSpec
{
Id = "b", Priority = 1.0, MinDwellSeconds = 1000.0, SensoryGain = 0.15, EntryArousal = 0.05, EntrySeconds = 0.5,
When = new[] { new Condition(DriveQuantity.Arousal, ConditionOp.AtLeast, 0.2) }, Behaviour = Pose,
},
},
};
var rig = new Rig(brain);
Assert.Equal(0.8, rig.Actor.Drive.SensoryGain);
rig.UntilTakeover(1);
for (var k = 1; k < 50; k++) rig.Tick();
Assert.NotEqual(0.15, rig.Actor.Drive.SensoryGain);
rig.Tick(); // the ramp's last tick
Assert.Equal(0.15, rig.Actor.Drive.SensoryGain); // 0.8 + (0.15 - 0.8) * 1 is not 0.15 in a double
Assert.Equal(0.05, rig.Actor.Drive.Arousal); // from the arousal at takeover, 0.2142..., a lerp lands a step off 0.05 too
}
[Fact]
public void A_huge_finite_EntrySeconds_is_an_unending_ramp_not_a_snap_or_a_wrap()
{
// 1e300 / 0.01 is past the long range. On .NET 10 the cast of such a double saturates, so the guard in the Actor is not observable here
// (its mutant is equivalent on this runtime); the behaviour it protects on runtimes where the cast is undefined is pinned.
var rig = new Rig(StressThenCalm(1e300));
rig.UntilTakeover(1);
for (var i = 0; i < 2000; i++) rig.Tick();
Assert.Equal(1.0, rig.Actor.Drive.SensoryGain, 12);
Assert.True(rig.Actor.Drive.Arousal > 0.0);
Assert.True(rig.Actor.Load > 0.0);
}
[Fact]
public void The_ramp_length_is_rounded_to_whole_ticks_so_a_quotient_just_under_an_integer_gets_that_integer()
{
var rig = new Rig(StressThenCalm(0.29)); // 0.29 / 0.01 is 28.999999999999996 ticks, not 28
rig.UntilTakeover(1);
for (var k = 1; k <= 29; k++)
{
rig.Tick();
if (k < 29) Assert.True(rig.Actor.Drive.SensoryGain > 0.0, $"still ramping at tick {k}");
}
Assert.Equal(0.0, rig.Actor.Drive.SensoryGain);
Assert.Equal(0.0, rig.Actor.Drive.Arousal);
}
[Fact]
public void A_goal_without_an_entry_arousal_ramps_only_the_gain_and_the_drive_keeps_arousal()
{
var rig = new Rig(StressThenCalm(2.0, gain: 0.0, arousal: null));
rig.UntilTakeover(1);
var before = rig.Actor.Drive.Arousal;
rig.Tick();
// One tick of the drive's own law under the gate (the sense still reads gain 1 on the first tick after takeover): arousal moves by it, not by any ramp.
var p = new DriveParameters();
var expected = Math.Min(Math.Max(before + Dt * (p.ArousalRise * Afferent * (1.0 - before) - p.ArousalDecay * before), 0.0), 1.0);
Assert.Equal(expected, rig.Actor.Drive.Arousal, 12);
for (var i = 0; i < 6000; i++) rig.Tick();
Assert.Equal(0.0, rig.Actor.Drive.SensoryGain);
Assert.True(rig.Actor.Drive.Arousal < 0.01, "with the gain at zero the drive decays arousal on its own");
}
[Fact]
public void A_goal_that_takes_over_mid_ramp_ramps_from_where_the_last_ramp_had_got_to()
{
var brain = new Brain
{
Goals = new[]
{
new GoalSpec { Id = "stress", Behaviour = Pose },
new GoalSpec
{
Id = "calm", Priority = 1.0, MinDwellSeconds = 1000.0, SensoryGain = 0.0, EntryArousal = 0.0, EntrySeconds = 3.0,
When = new[] { new Condition(DriveQuantity.Arousal, ConditionOp.AtLeast, 0.2) }, Behaviour = Pose,
},
new GoalSpec
{
Id = "alert", Priority = 2.0, SensoryGain = 1.0, EntryArousal = 0.9, EntrySeconds = 2.0,
When = new[] { new Condition(DriveQuantity.Pain, ConditionOp.AtLeast, 0.05) }, Behaviour = Pose,
},
},
};
var rig = new Rig(brain);
rig.UntilTakeover(1);
for (var i = 0; i < 100; i++) rig.Tick(); // 1 s into the 3 s ramp
Assert.True(rig.Actor.Drive.SensoryGain is > 0.0 and < 1.0);
rig.Pain = 0.8;
rig.UntilTakeover(2);
var g0 = rig.Actor.Drive.SensoryGain;
var a0 = rig.Actor.Drive.Arousal;
Assert.True(g0 is > 0.0 and < 0.7, "alert took over partway down calm's ramp");
for (var k = 1; k <= 200; k++)
{
rig.Tick();
var f = k / 200.0;
Assert.Equal(g0 + (1.0 - g0) * f, rig.Actor.Drive.SensoryGain, 12);
Assert.Equal(a0 + (0.9 - a0) * f, rig.Actor.Drive.Arousal, 12);
}
Assert.Equal(1.0, rig.Actor.Drive.SensoryGain);
}
[Fact]
public void The_start_goals_targets_hold_from_construction_and_under_steady_emitters()
{
var brain = new Brain { Goals = new[] { new GoalSpec { Id = "calm", SensoryGain = 0.0, EntryArousal = 0.0, EntrySeconds = 3.0, Behaviour = Pose } } };
var rig = new Rig(brain);
Assert.Equal(0.0, rig.Actor.Drive.SensoryGain);
Assert.Equal(0.0, rig.Actor.Drive.Arousal);
for (var i = 0; i < 600; i++)
{
rig.Tick();
Assert.Equal(0.0, rig.Actor.Load);
Assert.Equal(0.0, rig.Actor.Drive.Arousal);
}
var warm = new Rig(new Brain { Goals = new[] { new GoalSpec { Id = "wound", EntryArousal = 0.6, Behaviour = Pose } } });
Assert.Equal(0.6, warm.Actor.Drive.Arousal);
}
[Fact]
public void EntryArousal_outside_zero_to_one_and_a_negative_NaN_or_infinite_EntrySeconds_are_refused_naming_the_goal()
{
void Refused(GoalSpec g)
{
var ex = Assert.Throws<ArgumentException>(() => new Actor(Dt, 1, new NerveParameters(), new WithdrawalParameters(), new DriveParameters(), new Brain { Goals = new[] { g } }));
Assert.Contains("bad", ex.Message);
}
GoalSpec Base() => new() { Id = "bad", Behaviour = Pose };
Refused(Base() with { EntryArousal = -0.01 });
Refused(Base() with { EntryArousal = 1.01 });
Refused(Base() with { EntryArousal = double.NaN });
Refused(Base() with { EntrySeconds = -0.01 });
Refused(Base() with { EntrySeconds = double.NaN });
Refused(Base() with { EntrySeconds = double.PositiveInfinity });
_ = new Actor(Dt, 1, new NerveParameters(), new WithdrawalParameters(), new DriveParameters(), new Brain { Goals = new[] { Base() with { EntryArousal = 0.0, EntrySeconds = 5.0 } } });
_ = new Actor(Dt, 1, new NerveParameters(), new WithdrawalParameters(), new DriveParameters(), new Brain { Goals = new[] { Base() with { EntryArousal = 1.0 } } });
}
}

View file

@ -0,0 +1,475 @@
using System;
using Lodur;
namespace Lodur.Core.Tests;
public sealed class GoalTargetTests
{
private const double Dt = 0.01;
private const uint Thing = 7;
private const uint Other = 9;
private static readonly float[] Zero = { 0f };
private static readonly BoxStimulus[] NoBoxes = Array.Empty<BoxStimulus>();
private static GoalSpec Goal(string id, double priority, TargetFilter? target = null, Consideration[]? considerations = null, params Condition[] when) => new()
{
Id = id, Priority = priority, When = when, Target = target, Considerations = considerations ?? Array.Empty<Consideration>(),
Behaviour = new PoseBehaviour { Keys = new[] { PainBoxBrain.Hold }, FlinchPose = PainBoxBrain.Withdraw },
};
private static TargetFilter Kinds(params uint[] kinds) => new() { Kinds = kinds };
private static Consideration Nearer(double far) => new(ConsiderationInput.Distance, 0.0, far, 1.0, 0.0);
private static Emitter At(ulong id, float x, uint kind = Thing, double intensity = 1.0, float radius = 20f) =>
new(Channel.Audio, x, 0f, 0f, radius, intensity, id, kind);
private static Perception Ears(int capacity = 4, double memory = 5.0) =>
new(new NerveParameters(), Dt, 1, new NerveParameters { Threshold = 0.05, SensitisationGrowth = 0.0, ConductionDelaySeconds = 0.0 },
0, new PerceptParameters { Capacity = capacity, MemorySeconds = memory });
private static Perception Hearing(params Emitter[] emitters)
{
var p = Ears();
p.Sense(Zero, Zero, Zero, NoBoxes, emitters, 1.0);
return p;
}
private static Choice Pick(Brain brain, Perception p, Choice current, DriveState drive = default) => brain.Select(drive, p, 0f, 0f, 0f, current);
private static int SlotOf(Perception p, ulong id)
{
for (var s = 0; s < p.PerceptCount; s++)
{
if (p.Percept(s).Id == id) return s;
}
return -1;
}
[Fact]
public void An_untargeted_brain_selects_as_before()
{
var calm = default(DriveState);
var always = new Condition(DriveQuantity.Pain, ConditionOp.Below, 1.0);
var hears = Hearing(At(1, 1f));
var brain = new Brain
{
Goals = new[]
{
Goal("a", 2.0, when: always), Goal("b", 5.0, when: always), Goal("c", 5.0, when: always),
Goal("d", 9.0, when: new Condition(DriveQuantity.Pain, ConditionOp.AtLeast, 0.5)),
},
};
// Percepts in the room change nothing for goals that name no target.
Assert.Equal(new Choice(1, 0), Pick(brain, hears, new Choice(0, 0), calm));
Assert.Equal(new Choice(2, 0), Pick(brain, hears, new Choice(2, 0), calm));
Assert.Equal(new Choice(1, 0), Pick(brain, hears, new Choice(3, 0), calm));
var none = new Brain { Goals = new[] { Goal("x", 1.0, when: new Condition(DriveQuantity.Pain, ConditionOp.AtLeast, 0.5)) } };
// Nothing eligible: the goal in force stays and lets go of its target.
Assert.Equal(new Choice(0, 0), Pick(none, hears, new Choice(0, 77), calm));
}
[Fact]
public void A_targeted_goal_with_no_percept_of_its_kinds_is_not_chosen()
{
var brain = new Brain { Goals = new[] { Goal("idle", 1.0), Goal("chase", 5.0, Kinds(Other)) } };
// A percept of another kind, and free slots (Id 0), make no pair.
var wrongKind = Hearing(At(1, 1f, Thing));
Assert.Equal(new Choice(0, 0), Pick(brain, wrongKind, new Choice(0, 0)));
Assert.Equal(new Choice(0, 0), Pick(brain, Ears(), new Choice(0, 0)));
var rightKind = Hearing(At(1, 1f, Thing), At(2, 3f, Other));
Assert.Equal(new Choice(1, 2), Pick(brain, rightKind, new Choice(0, 0)));
// Only targeted goals, none with a percept: the goal in force stays and lets go of its target (finding stale-target-without-pair).
var only = new Brain { Goals = new[] { Goal("chase", 5.0, Kinds(Other)) } };
Assert.Equal(new Choice(0, 0), Pick(only, wrongKind, new Choice(0, 0)));
Assert.Equal(new Choice(0, 0), Pick(only, wrongKind, new Choice(0, 55)));
}
[Fact]
public void Considerations_multiply_priority_and_the_best_pair_wins()
{
// Distance: the nearer of two things.
var near = Hearing(At(1, 6f), At(2, 2f));
var go = new Brain { Goals = new[] { Goal("go", 1.0, Kinds(Thing), new[] { Nearer(10.0) }) } };
Assert.Equal(new Choice(0, 2), Pick(go, near, default));
// Salience: the louder thing wins when the curve rises; the quieter when it falls.
var loud = Hearing(At(1, 1f, intensity: 0.2), At(2, 1f, intensity: 0.9));
var rising = new Brain { Goals = new[] { Goal("go", 1.0, Kinds(Thing), new[] { new Consideration(ConsiderationInput.Salience, 0.0, 1.0, 0.0, 1.0) }) } };
var falling = new Brain { Goals = new[] { Goal("go", 1.0, Kinds(Thing), new[] { new Consideration(ConsiderationInput.Salience, 0.0, 1.0, 1.0, 0.0) }) } };
Assert.Equal(2UL, Pick(rising, loud, default).Target);
Assert.Equal(1UL, Pick(falling, loud, default).Target);
// Priority times the Drive curve: a goal at priority 4 whose Arousal curve zeroes it loses to priority 1.
var drained = new DriveState { Arousal = 0.0 };
var duel = new Brain
{
Goals = new[]
{
Goal("brave", 4.0, Kinds(Thing), new[] { new Consideration(ConsiderationInput.Drive, 0.0, 1.0, 0.0, 1.0, 1.0, DriveQuantity.Arousal) }),
Goal("plain", 1.0, Kinds(Thing)),
},
};
Assert.Equal(1, Pick(duel, near, default, drained).Goal);
Assert.Equal(0, Pick(duel, near, default, new DriveState { Arousal = 1.0 }).Goal);
Assert.Equal(0, Pick(duel, near, default, new DriveState { Arousal = 0.5 }).Goal); // 2.0 > 1.0
// The curve itself: clamped, shaped by the exponent, inverted by Y0 > Y1.
var c = new Consideration(ConsiderationInput.Salience, 2.0, 4.0, 0.0, 1.0, 2.0);
Assert.Equal(0.0, c.Response(1.0));
Assert.Equal(0.25, c.Response(3.0));
Assert.Equal(1.0, c.Response(9.0));
}
[Fact]
public void Ties_go_to_the_current_pair_then_lowest_goal_then_lowest_slot()
{
// Equal distance on either side of the observer: two equal scores in slots 0 and 1.
var twins = Hearing(At(10, 3f), At(20, -3f));
Assert.True(SlotOf(twins, 10) < SlotOf(twins, 20));
var one = new Brain { Goals = new[] { Goal("go", 1.0, Kinds(Thing), new[] { Nearer(10.0) }) } };
Assert.Equal(new Choice(0, 10), Pick(one, twins, default)); // lowest slot
Assert.Equal(new Choice(0, 20), Pick(one, twins, new Choice(0, 20))); // the current pair
Assert.Equal(new Choice(0, 10), Pick(one, twins, new Choice(0, 10)));
var two = new Brain { Goals = new[] { Goal("a", 1.0, Kinds(Thing), new[] { Nearer(10.0) }), Goal("b", 1.0, Kinds(Thing), new[] { Nearer(10.0) }) } };
Assert.Equal(new Choice(0, 10), Pick(two, twins, new Choice(1, 99))); // lowest goal, then slot
Assert.Equal(new Choice(1, 20), Pick(two, twins, new Choice(1, 20))); // current beats the lower goal
}
[Fact]
public void Commitment_holds_the_current_target_until_a_challenger_beats_it_by_the_multiplier()
{
// Distance 2 scores 0.75, distance 4 scores 0.5 on a curve over 8.
var hears = Hearing(At(1, 4f), At(2, 2f));
Brain With(double commitment) => new() { TargetCommitment = commitment, Goals = new[] { Goal("go", 1.0, Kinds(Thing), new[] { Nearer(8.0) }) } };
Assert.Equal(2UL, Pick(With(1.0), hears, new Choice(0, 1)).Target); // no commitment: the nearer wins
Assert.Equal(2UL, Pick(With(1.4), hears, new Choice(0, 1)).Target); // 0.5 * 1.4 = 0.70 < 0.75
Assert.Equal(1UL, Pick(With(1.5), hears, new Choice(0, 1)).Target); // 0.75 tie goes to the current pair
Assert.Equal(1UL, Pick(With(2.0), hears, new Choice(0, 1)).Target);
Assert.Equal(2UL, Pick(With(2.0), hears, default).Target); // the multiplier is for the current pair only
// It does not carry over to another goal's pair on the same target.
var rival = new Brain
{
TargetCommitment = 2.0,
Goals = new[] { Goal("go", 1.0, Kinds(Thing), new[] { Nearer(8.0) }), Goal("flee", 1.2, Kinds(Thing), new[] { Nearer(8.0) }) },
};
Assert.Equal(new Choice(0, 1), Pick(rival, hears, new Choice(0, 1))); // 0.5 * 2.0 = 1.0 beats flee's 1.2 * 0.75 = 0.9, on the same thing or the nearer
Assert.Equal(new Choice(1, 2), Pick(rival, hears, default)); // uncommitted, flee on the nearer wins
}
private static Actor Hunter(Brain brain, int capacity = 4, double memory = 5.0) =>
new(Dt, 1, new NerveParameters(), new WithdrawalParameters(), new DriveParameters(), brain,
new NerveParameters { Threshold = 0.05, SensitisationGrowth = 0.0, ConductionDelaySeconds = 0.0 }, 0,
new PerceptParameters { Capacity = capacity, MemorySeconds = memory });
private static TickEvents Tick(Actor a, params Emitter[] emitters) =>
a.Tick(Zero, Zero, Zero, NoBoxes, new float[2], new Quat[2], emitters);
[Fact]
public void A_retarget_waits_the_latency_and_fires_no_goal_change_or_entry_effect()
{
var brain = new Brain
{
Goals = new[]
{
Goal("idle", 0.0),
new GoalSpec
{
Id = "chase", Priority = 1.0, EntryResolve = 0.9, Effort = 0.1, Target = Kinds(Thing), Considerations = new[] { Nearer(30.0) },
When = new[] { new Condition(DriveQuantity.Pain, ConditionOp.Below, 1.0) },
Behaviour = new PoseBehaviour { Keys = new[] { PainBoxBrain.Hold }, FlinchPose = PainBoxBrain.Withdraw },
},
},
};
var a = Hunter(brain);
// Takes over the goal and the nearer thing, a latency after it is first heard.
var changes = 0;
for (var i = 0; i < 40; i++) changes += (Tick(a, At(1, 5f), At(2, 9f)) & TickEvents.GoalChanged) != 0 ? 1 : 0;
Assert.Equal(1, changes);
Assert.Equal(1, a.GoalIndex);
Assert.Equal(1UL, a.TargetId);
Assert.Equal(1UL, a.Target.Id);
for (var i = 0; i < 50; i++) Tick(a, At(1, 5f), At(2, 9f));
var inGoal = a.SecondsInGoal;
var resolve = a.Drive.Resolve;
Assert.True(resolve < 0.89, "the goal's effort should have drained resolve below its entry value by now");
// Thing 2 comes closer than thing 1: the pair changes a latency later, and nothing else does.
long first = -1;
for (var i = 0; i < 30; i++)
{
var e = Tick(a, At(1, 5f), At(2, 1f));
Assert.Equal(TickEvents.None, e & TickEvents.GoalChanged);
if (first < 0 && a.TargetId == 2) first = i;
if (first < 0)
{
Assert.Equal(1UL, a.TargetId);
Assert.Equal(1, a.GoalIndex);
}
}
Assert.Equal(10, first); // Latency: round(0.1 s / 10 ms)
Assert.Equal(2UL, a.Target.Id);
Assert.Equal(inGoal + 30 * Dt, a.SecondsInGoal, 9);
Assert.True(a.Drive.Resolve < resolve, "EntryResolve must not be applied again by a retarget: resolve keeps draining");
}
private static Emitter AtXyz(ulong id, float x, float y, float z, double intensity = 1.0) =>
new(Channel.Audio, x, y, z, 40f, intensity, id, Thing);
private static Perception HearingAt(params Emitter[] emitters)
{
var p = Ears(8);
p.Sense(Zero, Zero, Zero, NoBoxes, emitters, 1.0);
return p;
}
private static ulong Nearest(Perception p, float ox, float oy, float oz)
{
var brain = new Brain { Goals = new[] { Goal("go", 1.0, Kinds(Thing), new[] { Nearer(60.0) }) } };
return brain.Select(default, p, ox, oy, oz, default).Target;
}
[Fact]
public void Distance_is_euclidean_over_all_three_axes_from_the_observer_point()
{
// Each pair ranks differently under a dropped axis, a Manhattan sum, or a mixed-up observer coordinate.
Assert.Equal(1UL, Nearest(HearingAt(AtXyz(1, 2f, 0f, 0f), AtXyz(2, 1f, 5f, 0f)), 0f, 0f, 0f)); // dy matters
Assert.Equal(1UL, Nearest(HearingAt(AtXyz(1, 2f, 0f, 0f), AtXyz(2, 1f, 0f, 5f)), 0f, 0f, 0f)); // dz matters
Assert.Equal(1UL, Nearest(HearingAt(AtXyz(1, 0f, 2f, 0f), AtXyz(2, 5f, 1f, 0f)), 0f, 0f, 0f)); // dx matters
Assert.Equal(1UL, Nearest(HearingAt(AtXyz(1, 3f, 3f, 0f), AtXyz(2, 5f, 0f, 0f)), 0f, 0f, 0f)); // 4.24 < 5, though 6 > 5
// The observer is a point, each coordinate its own: swapping any two moves the answer.
Assert.Equal(1UL, Nearest(HearingAt(AtXyz(1, 6f, 3f, 0f), AtXyz(2, 3f, 1f, 0f)), 6f, 1f, 0f)); // x with y
Assert.Equal(1UL, Nearest(HearingAt(AtXyz(1, 6f, 0f, 3f), AtXyz(2, 3f, 0f, 1f)), 6f, 0f, 1f)); // x with z
Assert.Equal(1UL, Nearest(HearingAt(AtXyz(1, 0f, 6f, 3f), AtXyz(2, 0f, 3f, 1f)), 0f, 6f, 1f)); // y with z
}
[Fact]
public void A_percept_is_scored_by_its_age_and_by_every_consideration()
{
// Thing 1 (slot 0) falls silent while thing 2 keeps sounding: the fresher thing wins on a falling age curve.
var p = Ears(4, 5.0);
p.Sense(Zero, Zero, Zero, NoBoxes, new[] { At(1, 3f), At(2, 3f) }, 1.0);
for (var i = 0; i < 100; i++) p.Sense(Zero, Zero, Zero, NoBoxes, new[] { At(2, 3f) }, 1.0);
Assert.True(p.Percept(SlotOf(p, 1)).SecondsSinceSensed > 0.9);
var young = new Brain { Goals = new[] { Goal("go", 1.0, Kinds(Thing), new[] { new Consideration(ConsiderationInput.SecondsSinceSensed, 0.0, 5.0, 1.0, 0.0) }) } };
Assert.Equal(2UL, Pick(young, p, default).Target);
var stale = new Brain { Goals = new[] { Goal("go", 1.0, Kinds(Thing), new[] { new Consideration(ConsiderationInput.SecondsSinceSensed, 0.0, 5.0, 0.0, 1.0) }) } };
Assert.Equal(1UL, Pick(stale, p, default).Target);
// Two considerations multiply: the nearer thing is quiet, the farther loud; the second curve decides.
var mixed = Hearing(At(1, 2f, intensity: 0.05), At(2, 6f, intensity: 1.0));
Assert.Equal(1UL, Pick(new Brain { Goals = new[] { Goal("go", 1.0, Kinds(Thing), new[] { Nearer(10.0) }) } }, mixed, default).Target);
var both = new Brain { Goals = new[] { Goal("go", 1.0, Kinds(Thing), new[] { Nearer(10.0), new Consideration(ConsiderationInput.Salience, 0.0, 1.0, 0.0, 1.0) }) } };
Assert.Equal(2UL, Pick(both, mixed, default).Target);
}
[Fact]
public void A_filter_holds_several_kinds_and_a_free_slot_is_never_a_target_even_of_kind_zero()
{
var brain = new Brain { Goals = new[] { Goal("idle", 1.0), Goal("chase", 5.0, Kinds(Other, Thing)) } };
Assert.Equal(new Choice(1, 1), Pick(brain, Hearing(At(1, 2f, Thing)), default));
var rev = new Brain { Goals = new[] { Goal("idle", 1.0), Goal("chase", 5.0, Kinds(Thing, Other)) } };
Assert.Equal(new Choice(1, 1), Pick(rev, Hearing(At(1, 2f, Other)), default));
// Free slots read Kind 0 and Id 0; a filter naming kind 0 still finds nothing in them.
var zero = new Brain { Goals = new[] { Goal("idle", 1.0), Goal("chase", 5.0, Kinds(0u)) } };
Assert.Equal(new Choice(0, 0), Pick(zero, Ears(), new Choice(0, 0)));
Assert.Equal(new Choice(0, 0), Pick(zero, Hearing(At(1, 2f, Thing)), new Choice(0, 0)));
}
private static Actor HunterAt(Brain brain, int regions, int senseRegion) =>
new(Dt, regions, new NerveParameters(), new WithdrawalParameters(), new DriveParameters(), brain,
new NerveParameters { Threshold = 0.05, SensitisationGrowth = 0.0, ConductionDelaySeconds = 0.0 }, senseRegion,
new PerceptParameters { Capacity = 4, MemorySeconds = 5.0 });
[Fact]
public void The_actor_measures_distance_from_the_sense_region_point()
{
var brain = new Brain { Goals = new[] { Goal("idle", 0.0), Goal("chase", 1.0, Kinds(Thing), new[] { Nearer(60.0) }) } };
var a = HunterAt(brain, 2, 1);
var x = new[] { 0f, 10f };
var y = new[] { 0f, 3f };
var z = new[] { 0f, 2f };
// Thing 1 is one unit from the sense region's point. Each of the others sits on the point a wrong reading would use:
// region 0, the point with y and z zeroed, and the point with x and y swapped.
var emitters = new[] { AtXyz(1, 11f, 3f, 2f), AtXyz(2, 0f, 0f, 0f), AtXyz(3, 10f, 0f, 0f), AtXyz(4, 3f, 10f, 2f) };
for (var i = 0; i < 40; i++) a.Tick(x, y, z, NoBoxes, new float[2], new Quat[2], emitters);
Assert.Equal(1UL, a.TargetId);
}
[Fact]
public void A_goal_without_a_target_clears_the_target_and_a_retarget_ignores_the_goals_dwell()
{
var brain = new Brain { Goals = new[] { Goal("idle", 0.0), Goal("chase", 1.0, Kinds(Thing), new[] { Nearer(30.0) }) } };
var a = Hunter(brain, memory: 0.2);
for (var i = 0; i < 40; i++) Tick(a, At(1, 5f));
Assert.Equal(1, a.GoalIndex);
Assert.Equal(1UL, a.TargetId);
// The thing is forgotten; only the untargeted goal has a pair, and it takes no target with it.
for (var i = 0; i < 80; i++) Tick(a);
Assert.Equal(0, a.GoalIndex);
Assert.Equal(0UL, a.TargetId);
// Within a long dwell, another thing in the same goal is taken a latency later all the same.
var held = new Brain
{
Goals = new[]
{
Goal("idle", 0.0),
new GoalSpec
{
Id = "chase", Priority = 1.0, MinDwellSeconds = 5.0, Target = Kinds(Thing), Considerations = new[] { Nearer(30.0) },
Behaviour = new PoseBehaviour { Keys = new[] { PainBoxBrain.Hold }, FlinchPose = PainBoxBrain.Withdraw },
},
},
};
var b = Hunter(held);
for (var i = 0; i < 40; i++) Tick(b, At(1, 5f), At(2, 9f));
Assert.Equal(1UL, b.TargetId);
for (var i = 0; i < 30; i++) Tick(b, At(1, 5f), At(2, 1f));
Assert.Equal(2UL, b.TargetId);
Assert.True(b.SecondsInGoal < 5.0);
}
[Fact]
public void A_forgotten_target_reads_id_zero_and_the_brain_reselects()
{
var brain = new Brain { Goals = new[] { Goal("chase", 1.0, Kinds(Thing), new[] { Nearer(30.0) }) } };
var a = Hunter(brain, capacity: 2, memory: 0.2);
for (var i = 0; i < 30; i++) Tick(a, At(1, 2f), At(2, 9f));
Assert.Equal(1UL, a.TargetId);
// Thing 1 stops sounding and is forgotten after its memory; its slot is taken by thing 3, which must not be read as the target.
var window = false;
for (var i = 0; i < 120 && a.TargetId == 1; i++)
{
Tick(a, At(2, 9f), At(3, 15f));
if (a.TargetId == 1 && a.Target.Id == 0) window = true;
Assert.NotEqual(3UL, a.Target.Id);
}
Assert.True(window, "the committed id outlived its percept, which should read as the default percept");
Assert.Equal(2UL, a.TargetId);
Assert.Equal(2UL, a.Target.Id);
}
[Fact]
public void Target_filters_and_considerations_are_validated()
{
static Actor Make(GoalSpec g, double commitment = 1.0) => new(Dt, 1, new NerveParameters(), new WithdrawalParameters(), new DriveParameters(),
new Brain { Goals = new[] { g }, TargetCommitment = commitment });
var ok = Goal("ok", 1.0, Kinds(Thing), new[] { Nearer(5.0) });
Make(ok);
var bad = new Action[]
{
() => Make(Goal("g", 1.0, Kinds())),
() => Make(Goal("g", 1.0, Kinds(Thing), new[] { new Consideration(ConsiderationInput.Distance, 0.0, double.NaN, 0.0, 1.0) })),
() => Make(Goal("g", 1.0, Kinds(Thing), new[] { new Consideration(ConsiderationInput.Distance, double.PositiveInfinity, 1.0, 0.0, 1.0) })),
() => Make(Goal("g", 1.0, Kinds(Thing), new[] { new Consideration(ConsiderationInput.Distance, 2.0, 2.0, 0.0, 1.0) })),
() => Make(Goal("g", 1.0, Kinds(Thing), new[] { new Consideration(ConsiderationInput.Distance, 0.0, 1.0, -0.1, 1.0) })),
() => Make(Goal("g", 1.0, Kinds(Thing), new[] { new Consideration(ConsiderationInput.Distance, 0.0, 1.0, 0.0, 1.1) })),
() => Make(Goal("g", 1.0, Kinds(Thing), new[] { new Consideration(ConsiderationInput.Distance, 0.0, 1.0, 0.0, 1.0, 0.0) })),
() => Make(Goal("g", 1.0, Kinds(Thing), new[] { new Consideration(ConsiderationInput.Distance, 0.0, 1.0, 0.0, 1.0, double.NaN) })),
() => Make(Goal("g", 1.0, null, new[] { Nearer(5.0) })),
() => Make(Goal("g", 1.0, null, new[] { new Consideration(ConsiderationInput.Salience, 0.0, 1.0, 0.0, 1.0) })),
() => Make(Goal("g", 1.0, null, new[] { new Consideration(ConsiderationInput.SecondsSinceSensed, 0.0, 1.0, 0.0, 1.0) })),
() => Make(Goal("g", -1.0, Kinds(Thing))),
() => Make(Goal("g", -1.0, null, new[] { new Consideration(ConsiderationInput.Drive, 0.0, 1.0, 0.0, 1.0) })),
() => Make(ok, 0.99),
() => Make(ok, double.NaN),
() => Make(ok, double.PositiveInfinity),
};
for (var i = 0; i < bad.Length; i++)
{
Assert.True(Throws(bad[i]), $"case {i} was accepted");
}
// A negative priority stays legal on a goal with neither.
Make(Goal("g", -1.0));
Make(Goal("g", 1.0, null, new[] { new Consideration(ConsiderationInput.Drive, 0.0, 1.0, 0.0, 1.0) }));
static bool Throws(Action a)
{
try { a(); return false; }
catch (ArgumentException e) { return e.Message.Contains("g") || e.Message.Contains("TargetCommitment"); }
}
}
[Fact]
public void Ticking_with_targets_allocates_nothing()
{
var brain = new Brain
{
TargetCommitment = 1.2,
Goals = new[]
{
Goal("idle", 0.0),
Goal("chase", 1.0, Kinds(Thing), new[] { Nearer(30.0), new Consideration(ConsiderationInput.Salience, 0.0, 1.0, 0.2, 1.0), new Consideration(ConsiderationInput.Drive, 0.0, 1.0, 0.5, 1.0, 1.0, DriveQuantity.Arousal) }),
},
};
var a = Hunter(brain);
var emitters = new[] { At(1, 5f), At(2, 9f), At(3, 2f, Other) };
for (var i = 0; i < 50; i++) a.Tick(Zero, Zero, Zero, NoBoxes, new float[2], new Quat[2], emitters);
var strengths = new float[2];
var targets = new Quat[2];
var before = GC.GetAllocatedBytesForCurrentThread();
for (var i = 0; i < 10000; i++)
{
emitters[1] = At(2, 9f - (i % 8));
a.Tick(Zero, Zero, Zero, NoBoxes, strengths, targets, emitters);
}
Assert.Equal(0L, GC.GetAllocatedBytesForCurrentThread() - before);
Assert.NotEqual(0UL, a.TargetId);
}
[Fact]
public void Ticking_with_a_want_goal_allocates_nothing()
{
const int Open = 0, Locked = 1;
var fact = new Fact(FactSubject.This, Open, true);
var brain = new Brain
{
PlanDepth = 4, TargetCommitment = 1.2,
Goals = new[]
{
Goal("idle", 0.5),
Goal("chase", 1.0, Kinds(Thing), new[] { Nearer(30.0) }) with { Want = fact },
Goal("other", 1.0, Kinds(Other), new[] { new Consideration(ConsiderationInput.PlanSteps, 1.0, 9.0, 1.0, 0.0) }) with { Want = fact },
},
};
var verbs = new[]
{
new Verb { Id = "Approach", Gives = new[] { new Fact(FactSubject.This, 63, true) } },
new Verb { Id = "Unlock", This = Kinds(Thing, Other), Needs = new[] { new Fact(FactSubject.This, 63, true), new Fact(FactSubject.This, Locked, true) }, Gives = new[] { new Fact(FactSubject.This, Locked, false) } },
new Verb { Id = "Open", This = Kinds(Thing, Other), Needs = new[] { new Fact(FactSubject.This, 63, true), new Fact(FactSubject.This, Locked, false) }, Gives = new[] { fact } },
};
var a = new Actor(Dt, 1, new NerveParameters(), new WithdrawalParameters(), new DriveParameters(), brain,
new NerveParameters { Threshold = 0.05, SensitisationGrowth = 0.0, ConductionDelaySeconds = 0.0 }, 0,
new PerceptParameters { Capacity = 4, MemorySeconds = 5.0 }, verbs: verbs);
var emitters = new[] { At(1, 5f), At(2, 9f), At(3, 2f, Other) };
emitters[0].Facts = 1UL << Locked;
for (var i = 0; i < 50; i++) a.Tick(Zero, Zero, Zero, NoBoxes, new float[2], new Quat[2], emitters);
var strengths = new float[2];
var targets = new Quat[2];
var before = GC.GetAllocatedBytesForCurrentThread();
for (var i = 0; i < 10000; i++)
{
emitters[1] = At(2, 9f - (i % 8));
a.Tick(Zero, Zero, Zero, NoBoxes, strengths, targets, emitters, selfFacts: (ulong)(i & 3));
}
Assert.Equal(0L, GC.GetAllocatedBytesForCurrentThread() - before);
Assert.NotEqual(0UL, a.TargetId);
Assert.NotEqual(0, a.PlanLength);
}
}

View file

@ -0,0 +1,65 @@
using System.Globalization;
using Lodur;
namespace Lodur.Core.Tests;
/// <summary>
/// The Actor against Bad Day Simulator's pain box at 9f59764, which that repo deletes in its next cut:
/// pain-box-golden.tsv holds, for 7 intensity/pull settings x seeds 1-60, the outcome and a hash of the
/// per-tick stimulus, pain, strain, resolve and goal stream. Regenerate with tools/pain-box-golden/generate.sh.
/// </summary>
public sealed class GoldenParityTests
{
private sealed record Row(ulong Seed, double Intensity, double Pull, string Outcome, long BreakMs, long EndMs, int Flinches, long Ticks, ulong Hash);
private static IEnumerable<Row> Rows()
{
foreach (var line in File.ReadLines(Path.Combine(AppContext.BaseDirectory, "pain-box-golden.tsv")))
{
if (line.StartsWith('#') || string.IsNullOrWhiteSpace(line)) continue;
var f = line.Trim().Split(' ');
yield return new Row(ulong.Parse(f[0]), double.Parse(f[1], CultureInfo.InvariantCulture), double.Parse(f[2], CultureInfo.InvariantCulture),
f[3], long.Parse(f[4]), long.Parse(f[5]), int.Parse(f[6]), long.Parse(f[7]), Convert.ToUInt64(f[8], 16));
}
}
[Fact]
public void The_actor_reproduces_the_pain_box_golden_table_exactly()
{
var rows = Rows().ToList();
Assert.Equal(420, rows.Count);
Assert.Contains(rows, r => r.Outcome == "Endured");
Assert.Contains(rows, r => r.Outcome == "WillBroke");
var bad = new List<string>();
foreach (var row in rows)
{
var replay = new PainBoxReplay(row.Seed, row.Intensity, row.Pull);
var h = 14695981039346656037ul;
void Byte(byte b) { h ^= b; h *= 1099511628211ul; }
void Double(double d) { foreach (var b in BitConverter.GetBytes(BitConverter.DoubleToInt64Bits(d))) Byte(b); }
long ticks = 0, broke = -1, withdrew = -1;
var flinches = 0;
var max = (long)Math.Round(120.0 / PainBoxReplay.Dt);
for (long i = 0; i <= max && withdrew < 0; i++)
{
var e = replay.Tick();
ticks++;
if ((e & TickEvents.Flinch) != 0) flinches++;
if ((e & TickEvents.WillBroke) != 0) broke = i;
if ((e & TickEvents.GoalChanged) != 0) withdrew = i;
var d = replay.Actor.Drive;
Double(replay.Actor.Stimulus(0)); Double(d.Pain); Double(d.Strain); Double(d.Resolve);
Byte((byte)(replay.Actor.Drive.WillBroken ? 1 : 0));
}
var ms = (long)Math.Round(withdrew >= 0 ? withdrew * 10.0 : max * 10.0);
var got = $"{(broke >= 0 ? "WillBroke" : "Endured")} {(broke >= 0 ? broke * 10 : -1)} {ms} {flinches} {ticks} {h:x16}";
var want = $"{row.Outcome} {row.BreakMs} {row.EndMs} {row.Flinches} {row.Ticks} {row.Hash:x16}";
if (got != want) bad.Add($"seed {row.Seed} i={row.Intensity} p={row.Pull}: got [{got}] want [{want}]");
}
Assert.True(bad.Count == 0, $"{bad.Count} of {rows.Count} runs differ; first: {bad.FirstOrDefault()}");
}
}

View file

@ -0,0 +1,670 @@
using Lodur;
using Xunit.Abstractions;
namespace Lodur.Core.Tests;
public sealed class IkTests
{
private static readonly BodyPlan Plan = BodyPlans.Humanoid();
// The tick the chains are built for; it sets the swivel step, SwivelRate * Dt.
private const double Dt = 0.01;
private readonly ITestOutputHelper _output;
public IkTests(ITestOutputHelper output) => _output = output;
private static (float X, float Y, float Z) Add((float X, float Y, float Z) a, (float X, float Y, float Z) b) => (a.X + b.X, a.Y + b.Y, a.Z + b.Z);
private static (float X, float Y, float Z) Sub((float X, float Y, float Z) a, (float X, float Y, float Z) b) => (a.X - b.X, a.Y - b.Y, a.Z - b.Z);
private static float Len((float X, float Y, float Z) a) => MathF.Sqrt(a.X * a.X + a.Y * a.Y + a.Z * a.Z);
private static (float X, float Y, float Z) Rot(Quat q, (float X, float Y, float Z) v)
{
q.Rotate(v.X, v.Y, v.Z, out var x, out var y, out var z);
return (x, y, z);
}
/// <summary>The convention applied by hand: where the wrist anchor lands for these two targets, in world coordinates.</summary>
private static (float X, float Y, float Z) Wrist(ArmChain arm, Quat parentRotation, (float X, float Y, float Z) parentPosition, Quat shoulder, Quat elbow)
{
var fs = Ik.JointFrame(Plan.Joints[arm.ShoulderJoint]);
var fe = Ik.JointFrame(Plan.Joints[arm.ElbowJoint]);
var rs = fs * shoulder * fs.Conjugate();
var re = fe * elbow * fe.Conjugate();
var a = Sub(arm.ElbowAnchor, arm.ShoulderAnchor);
var b = Sub(arm.WristAnchor, arm.ElbowAnchor);
var local = Add(arm.ShoulderAnchor, Rot(rs, Add(a, Rot(re, b))));
var centre = Plan.Parts[arm.ParentPart].Position;
return Add(parentPosition, Rot(parentRotation, Sub(local, centre)));
}
private static Quat RandomRotation(Random rng, float maxAngle)
{
var x = (float)rng.NextDouble() * 2f - 1f;
var y = (float)rng.NextDouble() * 2f - 1f;
var z = (float)rng.NextDouble() * 2f - 1f;
var l = MathF.Sqrt(x * x + y * y + z * z);
return l < 1e-3f ? Quat.Identity : Quat.FromAxisAngle(x / l, y / l, z / l, (float)rng.NextDouble() * maxAngle);
}
/// <summary>Seeded targets around one arm: a random direction and a distance the flex range can reach, under a random parent pose.</summary>
private static IEnumerable<(Quat Rotation, (float X, float Y, float Z) Position, (float X, float Y, float Z) Target)> Grid(ArmChain arm, int seed, int count)
{
var rng = new Random(seed);
var centre = Plan.Parts[arm.ParentPart].Position;
for (var i = 0; i < count; i++)
{
var rot = i % 2 == 0 ? Quat.Identity : RandomRotation(rng, 0.8f);
var pos = i % 2 == 0 ? centre : (centre.X + (float)rng.NextDouble() - 0.5f, centre.Y + (float)rng.NextDouble() - 0.5f, centre.Z + (float)rng.NextDouble() - 0.5f);
double dx, dy, dz, l;
do
{
dx = rng.NextDouble() * 2 - 1; dy = rng.NextDouble() * 2 - 1; dz = rng.NextDouble() * 2 - 1;
l = Math.Sqrt(dx * dx + dy * dy + dz * dz);
}
while (l is < 0.1 or > 1.0);
var r = (float)(0.23 + rng.NextDouble() * 0.32);
var dir = ((float)(dx / l), (float)(dy / l), (float)(dz / l));
// The shoulder in the world under this parent pose, then the target out along dir.
var shoulder = Add(pos, Rot(rot, Sub(arm.ShoulderAnchor, centre)));
yield return (rot, pos, (shoulder.X + dir.Item1 * r, shoulder.Y + dir.Item2 * r, shoulder.Z + dir.Item3 * r));
}
}
private static float ZTwist(Quat q) => 2f * MathF.Atan2(MathF.Abs(q.Z), MathF.Abs(q.W));
[Theory]
[InlineData(Side.Left)]
[InlineData(Side.Right)]
public void Arm_solve_lands_the_wrist_by_forward_kinematics(Side side)
{
var arm = ArmChain.Of(Plan, side, Dt);
var reachedCount = 0;
foreach (var (rot, pos, target) in Grid(arm, 7 + (int)side, 600))
{
// Independent goals, not a path: each is the stateless rule.
arm.Reset();
if (!arm.Solve(rot, pos.X, pos.Y, pos.Z, target.X, target.Y, target.Z, out var sq, out var eq)) continue;
reachedCount++;
var wrist = Wrist(arm, rot, pos, sq, eq);
Assert.True(Len(Sub(wrist, target)) < 1e-4f, $"wrist {wrist} missed target {target} by {Len(Sub(wrist, target))} m");
}
Assert.True(reachedCount > 100, $"only {reachedCount} grid targets were reachable; the grid no longer exercises the solve");
}
[Theory]
[InlineData(Side.Left)]
[InlineData(Side.Right)]
public void Arm_solve_twists_the_shoulder_only_where_zero_twist_would_leave_the_cone(Side side)
{
var arm = ArmChain.Of(Plan, side, Dt);
var joint = Plan.Joints[arm.ShoulderJoint];
var (n, reached, twisted) = (0, 0, 0);
foreach (var (rot, pos, target) in Grid(arm, 21 + (int)side, 600))
{
arm.Reset();
var ok = arm.Solve(rot, pos.X, pos.Y, pos.Z, target.X, target.Y, target.Z, out var sq, out _);
var swing = 2f * MathF.Asin(MathF.Min(1f, MathF.Sqrt(sq.X * sq.X + sq.Y * sq.Y)));
var twist = 2f * MathF.Atan2(sq.Z, sq.W);
Assert.True(swing <= joint.Cone + 1e-4f, $"swing {swing} past the cone {joint.Cone} for {target}");
Assert.True(twist >= joint.Lower - 1e-4f && twist <= joint.Upper + 1e-4f, $"twist {twist} outside [{joint.Lower}, {joint.Upper}] for {target}");
if (MathF.Abs(twist) > 1e-5f)
{
// A twist is taken only to keep the swing inside the cone, so the swivel sits on the boundary of the feasible range; an
// unreached goal's least-violating swivel, clamped, sits on the cone.
if (ok) twisted++;
var onLimit = MathF.Abs(swing - joint.Cone) < 1e-3f || MathF.Abs(twist - joint.Lower) < 1e-3f || MathF.Abs(twist - joint.Upper) < 1e-3f;
Assert.True(onLimit, $"shoulder target twists by {twist} rad at swing {swing} for {target}, off every limit");
}
n++;
if (ok) reached++;
}
Assert.Equal(600, n);
Assert.InRange(twisted, 1, reached / 2);
}
[Fact]
public void A_wrist_goal_the_zero_twist_swivel_cannot_reach_is_reached_by_twisting_inside_the_limits()
{
// The left ward-off wrist goal for a sound at head height, ahead and to the left: zero twist saturates the cone 20 cm short.
var arm = ArmChain.Of(Plan, Side.Left, Dt);
var joint = Plan.Joints[arm.ShoulderJoint];
var centre = Plan.Parts[arm.ParentPart].Position;
var goal = (0.2988f, 1.74f, 0.2605f);
Assert.True(arm.Solve(Quat.Identity, centre.X, centre.Y, centre.Z, goal.Item1, goal.Item2, goal.Item3, out var sq, out var eq));
var wrist = Wrist(arm, Quat.Identity, centre, sq, eq);
Assert.True(Len(Sub(wrist, goal)) < 1e-3f, $"wrist {wrist} missed {goal} by {Len(Sub(wrist, goal))} m");
var twist = 2f * MathF.Atan2(sq.Z, sq.W);
Assert.True(MathF.Abs(twist) > 0.05f && twist >= joint.Lower && twist <= joint.Upper, $"twist {twist}");
}
[Theory]
[InlineData(Side.Left)]
[InlineData(Side.Right)]
public void A_goal_crossing_out_of_the_feasible_set_moves_the_targets_continuously(Side side)
{
// Two stretches of a circle about the shoulder where a goal leaves the feasible set: past the edge no swivel keeps both swing and
// twist inside the limits. Each stretch is 2000 steps of about 0.02 mm.
var arm = ArmChain.Of(Plan, side, Dt);
var centre = Plan.Parts[arm.ParentPart].Position;
var s = arm.ShoulderAnchor;
var (worstTurn, worstFlex, worstMove) = (0f, 0f, 0f);
foreach (var (from, to) in new[] { (0.25f, 0.33f), (2.65f, 2.74f) })
{
const int steps = 2000;
var crossings = 0;
var (lastReached, lastShoulder, lastElbow, lastWrist) = (false, Quat.Identity, Quat.Identity, (0f, 0f, 0f));
// Each stretch is its own path.
arm.Reset();
for (var i = 0; i <= steps; i++)
{
var th = from + (to - from) * i / steps;
var goal = (s.X + 0.45f * MathF.Cos(th), s.Y + 0.45f * MathF.Sin(th), s.Z + 0.25f + 0.1f * MathF.Sin(2f * th));
var reached = arm.Solve(Quat.Identity, centre.X, centre.Y, centre.Z, goal.Item1, goal.Item2, goal.Item3, out var sq, out var eq);
var wrist = Wrist(arm, Quat.Identity, centre, sq, eq);
if (i > 0)
{
if (reached != lastReached) crossings++;
worstTurn = MathF.Max(worstTurn, Turn(sq, lastShoulder));
worstFlex = MathF.Max(worstFlex, Turn(eq, lastElbow));
worstMove = MathF.Max(worstMove, Len(Sub(wrist, lastWrist)));
}
(lastReached, lastShoulder, lastElbow, lastWrist) = (reached, sq, eq, wrist);
}
// Tripwire: the stretch still crosses the edge, so the bounds below still test a crossing.
Assert.Equal(1, crossings);
}
_output.WriteLine($"{side}: largest step of the shoulder target {worstTurn:F4} rad, of the elbow {worstFlex:F4} rad, of the wrist {worstMove * 1000f:F4} mm");
// The turns are bounded by the rate (StepBound). deterministic-bound-margin for the wrist: the geometric mean of the shipped worst
// and the least mutant. Shipped worst, both arms: 0.0216 mm. Mutant, the zero-twist swing clamped to the cone past the edge (the
// fallback before this test): 269.72 mm. Bound sqrt(0.0216 * 269.72) = 2.41 mm.
Assert.True(worstTurn <= StepBound, $"the shoulder target jumped {worstTurn} rad in one step");
Assert.True(worstFlex <= StepBound, $"the elbow target jumped {worstFlex} rad in one step");
Assert.True(worstMove < 0.00241f, $"the wrist jumped {worstMove} m in one step");
}
[Fact]
public void Out_of_reach_points_the_straight_arm_at_the_target_and_reports_not_reached()
{
var arm = ArmChain.Of(Plan, Side.Right, Dt);
var s = arm.ShoulderAnchor;
var centre = Plan.Parts[arm.ParentPart].Position;
var dirs = new[] { (0f, -0.5f, 0.87f), (-0.4f, -0.6f, 0.7f) };
foreach (var raw in dirs)
{
var l = Len(raw);
var dir = (raw.Item1 / l, raw.Item2 / l, raw.Item3 / l);
var target = (s.X + dir.Item1 * 2f, s.Y + dir.Item2 * 2f, s.Z + dir.Item3 * 2f);
arm.Reset();
var reached = arm.Solve(Quat.Identity, centre.X, centre.Y, centre.Z, target.Item1, target.Item2, target.Item3, out var sq, out var eq);
Assert.False(reached);
var wrist = Wrist(arm, Quat.Identity, centre, sq, eq);
var reach = arm.L1 + arm.L2 - 1e-3f;
var want = (s.X + dir.Item1 * reach, s.Y + dir.Item2 * reach, s.Z + dir.Item3 * reach);
Assert.True(Len(Sub(wrist, want)) < 1e-4f, $"wrist {wrist} is not on the line to the target at full stretch {want}");
Assert.True(MathF.Abs(2f * MathF.Atan2(eq.Z, eq.W)) < 0.15f, "the elbow is not nearly straight");
}
// The same direction well inside reach is reached.
arm.Reset();
Assert.True(arm.Solve(Quat.Identity, centre.X, centre.Y, centre.Z, s.X, s.Y, s.Z + 0.4f, out _, out _));
}
[Fact]
public void Limits_clamp_swing_flex_and_look()
{
var arm = ArmChain.Of(Plan, Side.Right, Dt);
var s = arm.ShoulderAnchor;
var c = Plan.Parts[arm.ParentPart].Position;
var cone = Plan.Joints[arm.ShoulderJoint].Cone;
var (lo, hi) = (Plan.Joints[arm.ElbowJoint].Lower, Plan.Joints[arm.ElbowJoint].Upper);
// Straight up is half a turn from the hanging arm: past the cone.
Assert.False(arm.Solve(Quat.Identity, c.X, c.Y, c.Z, s.X, s.Y + 0.45f, s.Z, out var up, out _));
Assert.Equal(cone, 2f * MathF.Atan2(MathF.Sqrt(up.X * up.X + up.Y * up.Y + up.Z * up.Z), up.W), 1e-4f);
Assert.True(ZTwist(up) < 1e-5f);
// Near the shoulder the hinge would have to fold past its range.
arm.Reset();
Assert.False(arm.Solve(Quat.Identity, c.X, c.Y, c.Z, s.X, s.Y - 0.1f, s.Z + 0.1f, out _, out var folded));
Assert.Equal(lo, 2f * MathF.Atan2(folded.Z, folded.W), 1e-4f);
// A bend inside the range is not a clamp.
arm.Reset();
Assert.True(arm.Solve(Quat.Identity, c.X, c.Y, c.Z, s.X, s.Y - 0.25f, s.Z + 0.25f, out _, out var bent));
var flex = 2f * MathF.Atan2(bent.Z, bent.W);
Assert.InRange(flex, lo + 0.05f, hi - 0.05f);
var look = LookChain.Of(Plan);
var neck = Plan.Joints[look.Joint];
var head = Plan.Parts[look.ChildPart].Position;
var parent = Plan.Parts[look.ParentPart].Position;
(float Yaw, float Pitch) Aim(float dx, float dy, float dz, out bool reached)
{
reached = look.Solve(Quat.Identity, parent.X, parent.Y, parent.Z, head.X + dx, head.Y + dy, head.Z + dz, out var q);
var f = Ik.JointFrame(neck);
var d = Rot(f * q * f.Conjugate(), (0f, 0f, 1f));
return (MathF.Atan2(d.X, d.Z), -MathF.Asin(d.Y));
}
var (yaw, _) = Aim(2f, 0f, 0.5f, out var r1);
Assert.False(r1);
Assert.Equal(neck.Upper, yaw, 1e-4f);
(yaw, _) = Aim(-2f, 0f, 0.5f, out r1);
Assert.False(r1);
Assert.Equal(neck.Lower, yaw, 1e-4f);
var (_, pitch) = Aim(0f, 2f, 0.5f, out r1);
Assert.False(r1);
Assert.Equal(-neck.Cone, pitch, 1e-4f);
(_, pitch) = Aim(0f, -2f, 0.5f, out r1);
Assert.False(r1);
Assert.Equal(neck.Cone, pitch, 1e-4f);
Aim(0.3f, 0.2f, 1f, out r1);
Assert.True(r1);
}
[Fact]
public void Left_and_right_mirror()
{
var left = ArmChain.Of(Plan, Side.Left, Dt);
var right = ArmChain.Of(Plan, Side.Right, Dt);
var c = Plan.Parts[right.ParentPart].Position;
var n = 0;
foreach (var (_, _, target) in Grid(right, 5, 300))
{
right.Reset();
left.Reset();
var rReached = right.Solve(Quat.Identity, c.X, c.Y, c.Z, target.X, target.Y, target.Z, out var rs, out var re);
var lReached = left.Solve(Quat.Identity, c.X, c.Y, c.Z, -target.X, target.Y, target.Z, out var ls, out var le);
Assert.Equal(rReached, lReached);
// A reflection across x leaves a rotation about x alone and turns the other two components over.
Assert.Equal(rs.X, ls.X, 1e-5f);
Assert.Equal(-rs.Y, ls.Y, 1e-5f);
Assert.Equal(-rs.Z, ls.Z, 1e-5f);
Assert.Equal(rs.W, ls.W, 1e-5f);
Assert.Equal(re.Z, le.Z, 1e-5f);
Assert.Equal(re.W, le.W, 1e-5f);
n++;
}
Assert.Equal(300, n);
}
[Fact]
public void Look_aims_the_head_forward_at_the_target()
{
var look = LookChain.Of(Plan);
var neck = Plan.Joints[look.Joint];
var f = Ik.JointFrame(neck);
var head = Plan.Parts[look.ChildPart].Position;
var parentCentre = Plan.Parts[look.ParentPart].Position;
var rng = new Random(11);
var aimed = 0;
for (var i = 0; i < 400; i++)
{
var rot = i % 2 == 0 ? Quat.Identity : RandomRotation(rng, 0.8f);
(float X, float Y, float Z) pos = i % 2 == 0 ? parentCentre : (parentCentre.X + 0.3f, parentCentre.Y - 0.2f, parentCentre.Z + 0.1f);
// A direction inside the yaw and pitch limits, at 0.5 to 3 m, from the head's creation-pose centre.
var yaw = (float)(rng.NextDouble() * 2 - 1) * 0.55f;
var pitch = (float)(rng.NextDouble() * 2 - 1) * 0.55f;
var d = (MathF.Sin(yaw) * MathF.Cos(pitch), -MathF.Sin(pitch), MathF.Cos(yaw) * MathF.Cos(pitch));
var r = 0.5f + (float)rng.NextDouble() * 2.5f;
var local = Add(head, (d.Item1 * r, d.Item2 * r, d.Item3 * r));
var world = Add(pos, Rot(rot, Sub(local, parentCentre)));
Assert.True(look.Solve(rot, pos.X, pos.Y, pos.Z, world.X, world.Y, world.Z, out var q));
var got = Rot(f * q * f.Conjugate(), (0f, 0f, 1f));
var cross = (got.Y * d.Item3 - got.Z * d.Item2, got.Z * d.Item1 - got.X * d.Item3, got.X * d.Item2 - got.Y * d.Item1);
Assert.True(Len(cross) < 1e-4f && got.X * d.Item1 + got.Y * d.Item2 + got.Z * d.Item3 > 0f, $"head forward {got} is off the direction {d}");
aimed++;
}
Assert.Equal(400, aimed);
}
private static float Turn(Quat a, Quat b) => 2f * MathF.Acos(MathF.Min(1f, MathF.Abs(a.X * b.X + a.Y * b.Y + a.Z * b.Z + a.W * b.W)));
private static float Swing(Quat q) => 2f * MathF.Atan2(MathF.Sqrt(q.X * q.X + q.Y * q.Y), MathF.Sqrt(q.Z * q.Z + q.W * q.W));
// Tie lines at the shoulder's sagittal plane (goal relative to the shoulder (dx, y, z)), where two mirrored swivels tie under the
// stateless rule (Soul s3 on cut-lodur-orient-goals). The first four are unreached throughout; (-0.224, -0.2) is reached beyond 4 mm
// either side; (-0.25, -0.25) is reached throughout, two feasible intervals tying.
private static readonly (float Y, float Z)[] TieLines = { (0.12f, -0.4f), (0.2f, -0.2f), (0.25f, 0f), (0.3f, -0.1f), (-0.224f, -0.2f), (-0.25f, -0.25f) };
/// <summary>
/// Walks one chain along goals, one solve per tick, from a fresh state: the largest per-tick turn of the shoulder target, the largest
/// swing of the held (unclamped) target, and the largest per-tick turn of the elbow target. With <paramref name="stateless"/> the chain
/// is reset before every solve, so it returns the stateless solution unslewed: the claimed mutant.
/// </summary>
private static (float Turn, float HeldSwing, float Flex) Walk(ArmChain arm, IEnumerable<(float X, float Y, float Z)> goals, bool stateless, Quat[]? record = null)
{
var c = Plan.Parts[arm.ParentPart].Position;
var (worst, flex, swing, last, lastE, i) = (0f, 0f, 0f, Quat.Identity, Quat.Identity, 0);
arm.Reset();
foreach (var g in goals)
{
if (stateless) arm.Reset();
arm.Solve(Quat.Identity, c.X, c.Y, c.Z, g.X, g.Y, g.Z, out var sq, out var eq);
if (i > 0) (worst, flex) = (MathF.Max(worst, Turn(sq, last)), MathF.Max(flex, Turn(eq, lastE)));
swing = MathF.Max(swing, Swing(arm.Held));
if (record != null) record[i] = sq;
(last, lastE) = (sq, eq);
i++;
}
return (worst, swing, flex);
}
private static IEnumerable<(float X, float Y, float Z)> Line((float X, float Y, float Z) s, float y, float z, float sign, int from, int to, float step)
{
for (var i = from; i <= to; i++) yield return (s.X + sign * i * step, s.Y + y, s.Z + z);
}
// The per-tick turn of either returned target is at most MaxAngularRate * Dt (0.1 rad) by construction (ruling
// lodur:ruling:ik-output-slew-limit); 1e-5 rad covers the float reading of the turn. Claimed mutants: no slew (the raw solution, as the
// stateless walk returns it), and the slew on the shoulder only (the leap test's elbow).
private static readonly float StepBound = ArmChain.MaxAngularRate * (float)Dt + 1e-5f;
[Fact]
public void Across_a_tie_line_the_arm_keeps_its_swivel_and_the_arms_mirror()
{
var left = ArmChain.Of(Plan, Side.Left, Dt);
var right = ArmChain.Of(Plan, Side.Right, Dt);
var (worst, mutant) = (0f, float.MaxValue);
var (lq, rq) = (new Quat[101], new Quat[101]);
foreach (var (y, z) in TieLines)
{
// dx from -10 to +10 mm in 0.2 mm ticks; the left arm walks the mirrored path.
var held = Walk(right, Line(right.ShoulderAnchor, y, z, 1f, -50, 50, 0.0002f), false, rq).Turn;
Walk(left, Line(left.ShoulderAnchor, y, z, -1f, -50, 50, 0.0002f), false, lq);
var jump = Walk(right, Line(right.ShoulderAnchor, y, z, 1f, -50, 50, 0.0002f), true).Turn;
_output.WriteLine($"tie line ({y}, {z}): held worst {held:F4} rad per tick, stateless {jump:F4}");
(worst, mutant) = (MathF.Max(worst, held), MathF.Min(mutant, jump));
for (var i = 0; i < 101; i++)
{
Assert.Equal(rq[i].X, lq[i].X, 1e-5f);
Assert.Equal(-rq[i].Y, lq[i].Y, 1e-5f);
Assert.Equal(-rq[i].Z, lq[i].Z, 1e-5f);
Assert.Equal(rq[i].W, lq[i].W, 1e-5f);
}
}
_output.WriteLine($"worst held {worst:F4}, least stateless worst {mutant:F4}");
// Tripwire: every line still ties under the stateless rule, so the bound still tests a tie.
Assert.True(mutant > 0.9f, $"a tie line no longer ties: the stateless rule turns only {mutant} rad");
Assert.True(worst <= StepBound, $"the shoulder target turned {worst} rad in one tick across a tie");
}
[Theory]
[InlineData(Side.Left)]
[InlineData(Side.Right)]
public void The_stateless_jumps_of_random_segments_are_held(Side side)
{
// Soul's probe: random segments about the shoulder walked in 0.4 mm steps; each step the stateless rule turns over 0.5 rad is
// bisected to a gap under 2 microns, where it persists. The held chain walks 2 mm up to the near side, across the gap in one
// tick, and 2 mm on.
// Counted: jumps where the held target swings past HalfTurnSwing, where the clamp's swing-twist split is singular and the clamped
// solution itself jumps; the tripwire keeps the bound testing that band. Each of those is also walked 20 cm along its segment
// (1001 ticks of 0.2 mm), entering and leaving the band.
const float HalfTurnSwing = 3.0f;
var arm = ArmChain.Of(Plan, side, Dt);
var s = arm.ShoulderAnchor;
var c = Plan.Parts[arm.ParentPart].Position;
var rng = new Random(side == Side.Left ? 5 : 6);
(float X, float Y, float Z) Pt()
{
double dx, dy, dz, l;
do { dx = rng.NextDouble() * 2 - 1; dy = rng.NextDouble() * 2 - 1; dz = rng.NextDouble() * 2 - 1; l = Math.Sqrt(dx * dx + dy * dy + dz * dz); }
while (l is < 0.05 or > 1.0);
var r = (float)(0.05 + rng.NextDouble() * 0.7);
return (s.X + (float)(dx / l) * r, s.Y + (float)(dy / l) * r, s.Z + (float)(dz / l) * r);
}
Quat Fresh((float X, float Y, float Z) g)
{
arm.Reset();
arm.Solve(Quat.Identity, c.X, c.Y, c.Z, g.X, g.Y, g.Z, out var q, out _);
return q;
}
static (float X, float Y, float Z) Lerp((float X, float Y, float Z) a, (float X, float Y, float Z) b, float u) => (a.X + (b.X - a.X) * u, a.Y + (b.Y - a.Y) * u, a.Z + (b.Z - a.Z) * u);
var (found, singular, worst, mutant) = (0, 0, 0f, float.MaxValue);
var path = new (float X, float Y, float Z)[12];
var band = new (float X, float Y, float Z)[1001];
var (bandWorst, bandRaw) = (0f, float.MaxValue);
for (var k = 0; k < 400 && found < 40; k++)
{
var a = Pt();
var b = Pt();
var steps = (int)(Len(Sub(b, a)) / 0.0004f) + 1;
var prev = Fresh(a);
for (var i = 1; i <= steps; i++)
{
var q1 = Fresh(Lerp(a, b, (float)i / steps));
if (Turn(q1, prev) > 0.5f)
{
found++;
var (lo, hi, qlo, qhi) = (Lerp(a, b, (float)(i - 1) / steps), Lerp(a, b, (float)i / steps), prev, q1);
for (var it = 0; it < 40 && Len(Sub(hi, lo)) > 2e-6f; it++)
{
var mid = Lerp(lo, hi, 0.5f);
var qm = Fresh(mid);
if (Turn(qm, qlo) >= Turn(qm, qhi)) (hi, qhi) = (mid, qm);
else (lo, qlo) = (mid, qm);
}
Assert.True(Turn(qlo, qhi) > 0.5f, $"a stateless jump vanished on bisection: {Turn(qlo, qhi)} rad");
var u = Sub(b, a);
var step = 0.0004f / Len(u);
for (var j = 0; j < 6; j++) path[j] = Lerp(lo, Add(lo, u), (j - 5) * step);
for (var j = 0; j < 6; j++) path[6 + j] = Lerp(hi, Add(hi, u), j * step);
var walk = Walk(arm, path, false);
if (walk.HeldSwing > HalfTurnSwing)
{
singular++;
var uh = 1f / Len(u);
for (var j = 0; j < band.Length; j++)
{
var t = (j - 500) * 0.0002f * uh;
band[j] = (lo.X + u.X * t, lo.Y + u.Y * t, lo.Z + u.Z * t);
}
var through = Walk(arm, band, false);
bandWorst = MathF.Max(bandWorst, MathF.Max(through.Turn, through.Flex));
var raw = Walk(arm, band, true);
bandRaw = MathF.Min(bandRaw, MathF.Max(raw.Turn, raw.Flex));
}
worst = MathF.Max(worst, MathF.Max(walk.Turn, walk.Flex));
mutant = MathF.Min(mutant, Walk(arm, path, true).Turn);
}
prev = q1;
}
}
_output.WriteLine($"{side}: {found} stateless jumps (worst held {worst:F4} rad per tick, least stateless worst {mutant:F4}), {singular} at the half-turn swing");
_output.WriteLine($"{side}: 20 cm walks through the half-turn band: worst {bandWorst:F4} rad per tick, least raw worst {bandRaw:F4}");
Assert.True(found >= 40, $"only {found} stateless jumps found; the probe no longer finds the ties");
Assert.True(singular >= 5, $"only {singular} jumps at the half-turn swing; the bound no longer tests the singular clamp");
Assert.True(bandWorst <= StepBound, $"a target turned {bandWorst} rad in one tick on a walk through the half-turn band");
Assert.True(worst <= StepBound, $"a target turned {worst} rad in one tick at a stateless jump");
}
[Theory]
[InlineData(Side.Left)]
[InlineData(Side.Right)]
public void A_goal_circling_the_shoulder_moves_the_targets_at_most_the_rate(Side side)
{
// Full circles about the shoulder in its horizontal plane and above and below it, 1 mm per tick, two laps each from a fresh chain.
var arm = ArmChain.Of(Plan, side, Dt);
var s = arm.ShoulderAnchor;
var (worst, raw) = (0f, 0f);
foreach (var (y, r) in new[] { (-0.3f, 0.35f), (0f, 0.45f), (0.2f, 0.4f) })
{
var steps = (int)(2f * MathF.PI * r / 0.001f);
var path = new (float X, float Y, float Z)[2 * steps + 1];
for (var i = 0; i < path.Length; i++)
{
var th = 2f * MathF.PI * i / steps;
path[i] = (s.X + r * MathF.Sin(th), s.Y + y, s.Z + r * MathF.Cos(th));
}
var walk = Walk(arm, path, false);
worst = MathF.Max(worst, MathF.Max(walk.Turn, walk.Flex));
var mutant = Walk(arm, path, true);
raw = MathF.Max(raw, MathF.Max(mutant.Turn, mutant.Flex));
}
_output.WriteLine($"{side}: worst {worst:F4} rad per tick; the raw solution's worst {raw:F4}");
// Tripwire: the raw solution jumps somewhere on the circles, so the bound tests a jump.
Assert.True(raw > 0.5f, $"the raw solution turns only {raw} rad per tick on the circles");
Assert.True(worst <= StepBound, $"a target turned {worst} rad in one tick on a circle");
}
[Theory]
[InlineData(Side.Left)]
[InlineData(Side.Right)]
public void A_leaping_goal_is_followed_at_the_rate_and_settles_on_the_solution(Side side)
{
// The goal leaps between offsets from the shoulder (mirrored for the left) and holds each for Hold ticks. Every tick both targets
// move at most the step; within Hold ticks they settle on the solution a fresh chain gives there. A second chain walking the same
// goals returns the same bits.
const int Hold = 200;
var sign = side == Side.Left ? -1f : 1f;
var arm = ArmChain.Of(Plan, side, Dt);
var twin = ArmChain.Of(Plan, side, Dt);
var fresh = ArmChain.Of(Plan, side, Dt);
var s = arm.ShoulderAnchor;
var c = Plan.Parts[arm.ParentPart].Position;
var offsets = new[] { (0f, -0.25f, 0.35f), (0f, -0.12f, 0.1f), (0f, 0.05f, 0.45f), (-0.15f, -0.3f, 0.25f), (0.1f, -0.1f, 0.15f), (0f, -0.25f, 0.35f) };
var (worstTurn, worstFlex, rawTurn, rawFlex, slowest) = (0f, 0f, 0f, 0f, 0);
var (last, lastE) = (Quat.Identity, Quat.Identity);
for (var k = 0; k < offsets.Length; k++)
{
var g = (X: s.X + sign * offsets[k].Item1, Y: s.Y + offsets[k].Item2, Z: s.Z + offsets[k].Item3);
fresh.Reset();
fresh.Solve(Quat.Identity, c.X, c.Y, c.Z, g.X, g.Y, g.Z, out var want, out var wantE);
if (k > 0) (rawTurn, rawFlex) = (MathF.Max(rawTurn, Turn(want, last)), MathF.Max(rawFlex, Turn(wantE, lastE)));
var settled = -1;
for (var i = 0; i < Hold; i++)
{
arm.Solve(Quat.Identity, c.X, c.Y, c.Z, g.X, g.Y, g.Z, out var q, out var e);
twin.Solve(Quat.Identity, c.X, c.Y, c.Z, g.X, g.Y, g.Z, out var tq, out var te);
Assert.Equal(q, tq);
Assert.Equal(e, te);
if (k > 0 || i > 0) (worstTurn, worstFlex) = (MathF.Max(worstTurn, Turn(q, last)), MathF.Max(worstFlex, Turn(e, lastE)));
if (settled < 0 && Near(q, want) && Near(e, wantE)) settled = i;
if (settled >= 0) Assert.True(Near(q, want) && Near(e, wantE), $"leap {k}: the targets left the solution after settling at tick {settled}");
(last, lastE) = (q, e);
}
Assert.True(settled >= 0, $"leap {k}: the targets did not settle on the solution within {Hold} ticks");
slowest = Math.Max(slowest, settled);
}
_output.WriteLine($"{side}: worst {worstTurn:F4} rad shoulder, {worstFlex:F4} elbow per tick; raw leaps up to {rawTurn:F3} and {rawFlex:F3}; settled by tick {slowest}");
// Tripwire: the raw solution leaps at both joints, so the slew on the shoulder only would trip the elbow's bound.
Assert.True(rawTurn > 0.5f && rawFlex > 0.5f, $"the leaps are too small to test the slew: {rawTurn}, {rawFlex} rad");
Assert.True(worstTurn <= StepBound, $"the shoulder target turned {worstTurn} rad in one tick");
Assert.True(worstFlex <= StepBound, $"the elbow target turned {worstFlex} rad in one tick");
static bool Near(Quat a, Quat b)
{
var sg = a.X * b.X + a.Y * b.Y + a.Z * b.Z + a.W * b.W < 0f ? -1f : 1f;
return MathF.Abs(a.X - sg * b.X) < 1e-4f && MathF.Abs(a.Y - sg * b.Y) < 1e-4f && MathF.Abs(a.Z - sg * b.Z) < 1e-4f && MathF.Abs(a.W - sg * b.W) < 1e-4f;
}
}
[Fact]
public void A_clearly_better_basin_is_taken_at_the_swivel_rate_and_reset_restores_the_stateless_rule()
{
// The feasible tie: goal (dx, -0.25, -0.25) from the shoulder is reached throughout, by two mirrored feasible swivels that tie at
// dx 0. From dx -10 mm in 0.2 mm ticks the arm holds its basin past the tie; once the stateless swivel's twist is smaller by the
// margin it turns there, no faster than the swivel step.
var arm = ArmChain.Of(Plan, Side.Right, Dt);
var fresh = ArmChain.Of(Plan, Side.Right, Dt);
var s = arm.ShoulderAnchor;
var c = Plan.Parts[arm.ParentPart].Position;
Quat Solve(ArmChain chain, float dx, out bool reached)
{
reached = chain.Solve(Quat.Identity, c.X, c.Y, c.Z, s.X + dx, s.Y - 0.25f, s.Z - 0.25f, out var q, out _);
return q;
}
var (worst, last, heldAt, switchedAt) = (0f, Quat.Identity, float.NaN, float.NaN);
for (var i = -50; i <= 1000; i++)
{
var dx = i * 0.0002f;
var q = Solve(arm, dx, out _);
fresh.Reset();
var stateless = Solve(fresh, dx, out _);
if (i > -50) worst = MathF.Max(worst, Turn(q, last));
if (i == 10)
{
// 2 mm past the tie the arm is still in its basin, the other side of the stateless choice.
heldAt = Turn(q, stateless);
}
if (float.IsNaN(switchedAt) && i > 10 && Turn(q, stateless) < 0.01f) switchedAt = dx;
last = q;
}
_output.WriteLine($"2 mm past the tie: {heldAt:F3} rad from the stateless target; switched by dx {switchedAt * 1000f:F1} mm; worst {worst:F4} rad per tick");
Assert.True(heldAt > 1f, $"2 mm past the tie the arm left its basin ({heldAt} rad from the stateless target)");
Assert.False(float.IsNaN(switchedAt), "the arm never took the clearly better basin");
Assert.True(worst <= StepBound, $"the shoulder target turned {worst} rad in one tick");
// Reset forgets the swivel: the next solve is the stateless rule, bit for bit, where the held arm differs.
arm.Reset();
Solve(arm, -0.01f, out _);
var held = Solve(arm, 0.002f, out _);
arm.Reset();
var reset = Solve(arm, 0.002f, out var r1);
fresh.Reset();
var expected = Solve(fresh, 0.002f, out var r2);
Assert.Equal(expected, reset);
Assert.Equal(r2, r1);
Assert.True(Turn(held, reset) > 1f, "the held arm already matched the stateless target, so the reset proves nothing");
}
[Fact]
public void Solving_allocates_nothing()
{
var arm = ArmChain.Of(Plan, Side.Right, Dt);
var look = LookChain.Of(Plan);
var s = arm.ShoulderAnchor;
var rot = Quat.FromAxisAngle(0f, 1f, 0f, 0.2f);
var up = Add((0f, 1.4f, 0f), Rot(rot, Sub(s, Plan.Parts[arm.ParentPart].Position)));
Assert.False(arm.Solve(rot, 0f, 1.4f, 0f, up.X, up.Y + 0.4f, up.Z, out _, out _));
void Work(int n)
{
for (var i = 0; i < n; i++)
{
var t = 0.3f + i % 7 * 0.03f;
arm.Solve(rot, 0f, 1.4f, 0f, s.X, s.Y - t, s.Z + t, out _, out _);
// Straight up from the shoulder, in reach: no swivel is feasible, so the least-violating search runs.
arm.Solve(rot, 0f, 1.4f, 0f, up.X, up.Y + t, up.Z, out _, out _);
look.Solve(rot, 0f, 1.4f, 0f, t, 1.7f, 2f, out _);
}
}
Work(2000);
var before = GC.GetAllocatedBytesForCurrentThread();
Work(2000);
Assert.Equal(0L, GC.GetAllocatedBytesForCurrentThread() - before);
}
[Fact]
public void A_plan_without_the_arm_is_refused()
{
var parts = new[] { new PartDef("A", Side.Center, PartShape.Sphere, (0.1f, 0f, 0f), (0f, 0f, 0f), Quat.Identity, 1f, 1f, 0f) };
var bare = new BodyPlan(parts, Array.Empty<JointDef>(), Array.Empty<SensePointDef>());
Assert.Throws<ArgumentException>(() => ArmChain.Of(bare, Side.Left, Dt));
Assert.Throws<ArgumentException>(() => LookChain.Of(bare));
}
}

View file

@ -0,0 +1,25 @@
<Project Sdk="Microsoft.NET.Sdk">
<!-- References only Lodur.Core: the core tests build and run with no physics engine present (invariant core-engine-free). -->
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<IsPackable>false</IsPackable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.14.1" />
<PackageReference Include="xunit" Version="2.9.3" />
<PackageReference Include="xunit.runner.visualstudio" Version="3.1.4" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\src\Lodur.Core\Lodur.Core.csproj" />
</ItemGroup>
<ItemGroup>
<Using Include="Xunit" />
<Content Include="pain-box-golden.tsv" CopyToOutputDirectory="PreserveNewest" />
</ItemGroup>
</Project>

View file

@ -0,0 +1,660 @@
using System;
using Lodur;
namespace Lodur.Core.Tests;
/// <summary>The orient layers: Look, Arms (Reach, WardOff, Present) and Recoil composed onto a pose, joint targets only.</summary>
public sealed class OrientTests
{
private const double Dt = 0.01;
private const uint Thing = 7;
private static readonly BodyPlan Plan = BodyPlans.Humanoid();
private static readonly int Joints = Plan.Joints.Count;
private static readonly int Torso = Plan.PartIndex("Torso");
private static readonly int Head = Plan.PartIndex("Head");
private static readonly int Neck = Plan.JointIndex("Neck");
private static readonly BoxStimulus[] NoBoxes = Array.Empty<BoxStimulus>();
private static (float X, float Y, float Z) Add((float X, float Y, float Z) a, (float X, float Y, float Z) b) => (a.X + b.X, a.Y + b.Y, a.Z + b.Z);
private static (float X, float Y, float Z) Sub((float X, float Y, float Z) a, (float X, float Y, float Z) b) => (a.X - b.X, a.Y - b.Y, a.Z - b.Z);
private static float Len((float X, float Y, float Z) a) => MathF.Sqrt(a.X * a.X + a.Y * a.Y + a.Z * a.Z);
private static (float X, float Y, float Z) Rot(Quat q, (float X, float Y, float Z) v)
{
q.Rotate(v.X, v.Y, v.Z, out var x, out var y, out var z);
return (x, y, z);
}
/// <summary>The creation pose of every part: where an unmoved body is.</summary>
private static PartPose[] Rest()
{
var poses = new PartPose[Plan.Parts.Count];
for (var p = 0; p < poses.Length; p++)
{
var d = Plan.Parts[p];
poses[p] = new PartPose(d.Rotation, d.Position.X, d.Position.Y, d.Position.Z);
}
return poses;
}
/// <summary>The unmoved body with the torso turned about y and moved and the head carried with it, so a dropped conjugate or a swapped frame shows.</summary>
private static PartPose[] Turned()
{
var poses = Rest();
var rot = Quat.FromAxisAngle(0f, 1f, 0f, 0.3f);
var c = Plan.Parts[Torso].Position;
var shift = (X: 0.05f, Y: -0.02f, Z: 0.1f);
poses[Torso] = new PartPose(rot, c.X + shift.X, c.Y + shift.Y, c.Z + shift.Z);
var h = Plan.Parts[Head].Position;
var carried = Rot(rot, Sub(h, c));
poses[Head] = new PartPose(rot, c.X + shift.X + carried.X, c.Y + shift.Y + carried.Y, c.Z + shift.Z + carried.Z);
return poses;
}
/// <summary>A key pose with a distinct rotation per joint, so a layer that touches a joint it should not shows.</summary>
private static Quat[] Key()
{
var key = new Quat[Joints];
for (var m = 0; m < Joints; m++) key[m] = Quat.FromAxisAngle(0f, 0f, 1f, 0.02f * (m + 1));
return key;
}
private static Quat[] Identity() { var k = new Quat[Joints]; Array.Fill(k, Quat.Identity); return k; }
private static PoseBehaviour Behaviour(LookLayer? look = null, ArmLayer? arms = null, RecoilLayer? recoil = null, HoldParameters? hold = null) => new()
{
Keys = new[] { Key() }, FlinchPose = Identity(), Look = look, Arms = arms, Recoil = recoil, Hold = hold ?? new HoldParameters(),
};
private static Brain BrainOf(PoseBehaviour b) => new() { Goals = new[] { new GoalSpec { Id = "g", Behaviour = b } } };
private static OrientRig RigOf(PoseBehaviour b) => new(Plan, BrainOf(b), Dt);
private static Percept At((float X, float Y, float Z) p, ulong id = 1) => new(id, Thing, p.X, p.Y, p.Z, 1.0, 0.0);
/// <summary>Ticks enough for the arms to engage from the base pose, follow any hand path and settle on their solution (1 s at the test tick).</summary>
private const int Settle = 100;
private static Quat[] Run(PoseBehaviour b, PartPose[] parts, Percept target, Side arm = Side.Right, double weight = 1.0, double leak = 0.0, float[]? strengths = null, int ticks = 1)
{
var targets = new Quat[Joints];
var rig = RigOf(b);
for (var i = 0; i < ticks; i++)
{
b.Write(weight, leak, 0.0, 0.0, 0.0, strengths ?? new float[Joints], targets, new OrientInput(rig, parts, target, arm));
}
return targets;
}
/// <summary>What the layerless behaviour writes with the same keys and flinch.</summary>
private static Quat[] Base(PoseBehaviour b) => Run(b with { Look = null, Arms = null, Recoil = null }, Rest(), default);
private static void Same(Quat a, Quat b, float tol = 1e-6f)
{
var dot = MathF.Abs(a.X * b.X + a.Y * b.Y + a.Z * b.Z + a.W * b.W);
Assert.True(dot > 1f - tol, $"{a} is not {b} (dot {dot})");
}
private static void SameBits(Quat a, Quat b) => Assert.Equal(a, b);
/// <summary>The angle of the shortest rotation from a to b.</summary>
private static float Turn(Quat a, Quat b) => 2f * MathF.Acos(MathF.Min(1f, MathF.Abs(a.X * b.X + a.Y * b.Y + a.Z * b.Z + a.W * b.W)));
private static Quat Flinched(Quat q, Quat flinch, float w) => Quat.Nlerp(q, flinch, w);
private static (float X, float Y, float Z) Wrist(ArmChain arm, PartPose parent, Quat shoulder, Quat elbow)
{
var fs = Ik.JointFrame(Plan.Joints[arm.ShoulderJoint]);
var fe = Ik.JointFrame(Plan.Joints[arm.ElbowJoint]);
var rs = fs * shoulder * fs.Conjugate();
var re = fe * elbow * fe.Conjugate();
var a = Sub(arm.ElbowAnchor, arm.ShoulderAnchor);
var b = Sub(arm.WristAnchor, arm.ElbowAnchor);
var local = Add(arm.ShoulderAnchor, Rot(rs, Add(a, Rot(re, b))));
var def = Plan.Parts[arm.ParentPart];
var rel = parent.Rotation * def.Rotation.Conjugate();
return Add((parent.X, parent.Y, parent.Z), Rot(rel, Sub(local, def.Position)));
}
private static readonly (float X, float Y, float Z) Ahead = (0.2f, 1.45f, 0.6f);
[Fact]
public void A_layered_behaviour_with_no_target_writes_the_base_and_only_Present_still_writes()
{
var look = new LookLayer();
var reach = new ArmLayer { Mode = ArmMode.Reach, Side = ArmSide.Both };
var recoil = Recoiling();
var layered = Behaviour(look, reach, recoil);
var baseline = Base(layered);
var got = Run(layered, Rest(), default);
for (var m = 0; m < Joints; m++) SameBits(baseline[m], got[m]);
var present = Behaviour(arms: new ArmLayer { Mode = ArmMode.Present, Side = ArmSide.Both, Point = (-0.2f, 1.3f, 0.3f) });
var written = Run(present, Rest(), default);
var arm = new[] { Plan.JointIndex("Shoulder", Side.Left), Plan.JointIndex("Elbow", Side.Left), Plan.JointIndex("Shoulder", Side.Right), Plan.JointIndex("Elbow", Side.Right) };
for (var m = 0; m < Joints; m++)
{
if (Array.IndexOf(arm, m) >= 0) Assert.NotEqual(Base(present)[m], written[m]);
else SameBits(Base(present)[m], written[m]);
}
}
[Fact]
public void Look_solves_the_neck_and_blends_by_weight()
{
var look = LookChain.Of(Plan);
foreach (var parts in new[] { Rest(), Turned() })
{
var t = parts[Torso];
Assert.True(look.Solve(t.Rotation, t.X, t.Y, t.Z, Ahead.X, Ahead.Y, Ahead.Z, out var solved));
var b1 = Behaviour(new LookLayer { Weight = 1.0 });
var baseline = Base(b1);
var full = Run(b1, parts, At(Ahead));
SameBits(Flinched(solved, Quat.Identity, 0f), full[Neck]);
var half = Run(Behaviour(new LookLayer { Weight = 0.5 }), parts, At(Ahead));
SameBits(Flinched(Quat.Nlerp(Key()[Neck], solved, 0.5f), Quat.Identity, 0f), half[Neck]);
var none = Run(Behaviour(new LookLayer { Weight = 0.0 }), parts, At(Ahead));
Same(baseline[Neck], none[Neck]);
for (var m = 0; m < Joints; m++)
{
if (m != Neck) SameBits(baseline[m], full[m]);
}
}
}
[Theory]
[InlineData(ArmSide.Left)]
[InlineData(ArmSide.Right)]
[InlineData(ArmSide.Both)]
public void Reach_solves_the_chosen_arm_and_leaves_the_other(ArmSide side)
{
var parts = Turned();
var b = Behaviour(arms: new ArmLayer { Mode = ArmMode.Reach, Side = side });
var baseline = Base(b);
var got = Run(b, parts, At(Ahead), ticks: Settle);
var t = parts[Torso];
foreach (var s in new[] { Side.Left, Side.Right })
{
var arm = ArmChain.Of(Plan, s, Dt);
var used = side == ArmSide.Both || (side == ArmSide.Left) == (s == Side.Left);
if (used)
{
arm.Solve(t.Rotation, t.X, t.Y, t.Z, Ahead.X, Ahead.Y, Ahead.Z, out var sh, out var el);
Same(Flinched(sh, Quat.Identity, 0f), got[arm.ShoulderJoint]);
Same(Flinched(el, Quat.Identity, 0f), got[arm.ElbowJoint]);
}
else
{
SameBits(baseline[arm.ShoulderJoint], got[arm.ShoulderJoint]);
SameBits(baseline[arm.ElbowJoint], got[arm.ElbowJoint]);
}
}
for (var m = 0; m < Joints; m++)
{
if (Plan.Joints[m].Label is not ("Shoulder" or "Elbow")) SameBits(baseline[m], got[m]);
}
}
[Fact]
public void Nearer_uses_the_arm_the_actor_holds()
{
var parts = Rest();
var b = Behaviour(arms: new ArmLayer { Mode = ArmMode.Reach, Side = ArmSide.Nearer });
var baseline = Base(b);
var left = Plan.JointIndex("Shoulder", Side.Left);
var right = Plan.JointIndex("Shoulder", Side.Right);
var asLeft = Run(b, parts, At(Ahead), Side.Left);
Assert.NotEqual(baseline[left], asLeft[left]);
SameBits(baseline[right], asLeft[right]);
var asRight = Run(b, parts, At(Ahead), Side.Right);
Assert.NotEqual(baseline[right], asRight[right]);
SameBits(baseline[left], asRight[left]);
}
[Fact]
public void WardOff_puts_the_wrists_between_head_and_target()
{
var parts = Turned();
var distance = 0.3f;
var spread = 0.15f;
var b = Behaviour(arms: new ArmLayer { Mode = ArmMode.WardOff, Side = ArmSide.Both, Distance = distance, Spread = spread });
var target = (0.0f, 1.1f, 1.2f);
var got = Run(b, parts, At(target), ticks: Settle);
var h = parts[Head];
var head = (h.X, h.Y, h.Z);
var u = Sub(target, head);
u = (u.X / Len(u), u.Y / Len(u), u.Z / Len(u));
var meet = Add(head, (u.X * distance, u.Y * distance, u.Z * distance));
var t = parts[Torso];
var leftAxis = Rot(t.Rotation * Plan.Parts[Torso].Rotation.Conjugate(), (1f, 0f, 0f));
var wristL = Wrist(ArmChain.Of(Plan, Side.Left, Dt), t, Unflinch(got, Side.Left, out var elL), elL);
var wristR = Wrist(ArmChain.Of(Plan, Side.Right, Dt), t, Unflinch(got, Side.Right, out var elR), elR);
Assert.True(Len(Sub(wristL, meet)) < spread + 1e-3f, $"left wrist {Len(Sub(wristL, meet))} m from the meeting point");
Assert.True(Len(Sub(wristR, meet)) < spread + 1e-3f, $"right wrist {Len(Sub(wristR, meet))} m from the meeting point");
// Either side of the line, the left toward the torso's left: the across sign is what separates these from each other.
var leftSide = Sub(wristL, meet);
var rightSide = Sub(wristR, meet);
Assert.True(leftSide.X * leftAxis.X + leftSide.Y * leftAxis.Y + leftSide.Z * leftAxis.Z > 0.05f);
Assert.True(rightSide.X * leftAxis.X + rightSide.Y * leftAxis.Y + rightSide.Z * leftAxis.Z < -0.05f);
}
// The targets the layer wrote for one arm (the flinch blend is zero here, so they are the solution).
private static Quat Unflinch(Quat[] targets, Side side, out Quat elbow)
{
var arm = ArmChain.Of(Plan, side, Dt);
elbow = targets[arm.ElbowJoint];
return targets[arm.ShoulderJoint];
}
[Fact]
public void Present_ignores_the_target_and_the_left_arm_mirrors_the_right_in_x()
{
var parts = Rest();
var b = Behaviour(arms: new ArmLayer { Mode = ArmMode.Present, Side = ArmSide.Both, Point = (-0.2f, 1.3f, 0.3f) });
var without = Run(b, parts, default, ticks: Settle);
var with = Run(b, parts, At((3f, 1f, -2f)), ticks: Settle);
for (var m = 0; m < Joints; m++) SameBits(without[m], with[m]);
var t = parts[Torso];
var wl = Wrist(ArmChain.Of(Plan, Side.Left, Dt), t, Unflinch(with, Side.Left, out var el), el);
var wr = Wrist(ArmChain.Of(Plan, Side.Right, Dt), t, Unflinch(with, Side.Right, out var er), er);
Assert.True(MathF.Abs(wr.X - -0.2f) < 2e-3f && MathF.Abs(wr.Y - 1.3f) < 2e-3f && MathF.Abs(wr.Z - 0.3f) < 2e-3f, $"right wrist {wr}");
Assert.True(MathF.Abs(wl.X + wr.X) < 1e-4f && MathF.Abs(wl.Y - wr.Y) < 1e-4f && MathF.Abs(wl.Z - wr.Z) < 1e-4f, $"left {wl} does not mirror right {wr}");
}
private static Quat[] Away(float angle, float x, float y, float z)
{
var q = new Quat[Joints];
for (var m = 0; m < Joints; m++) q[m] = Quat.FromAxisAngle(x, y, z, angle * (1f + 0.1f * m));
return q;
}
private static RecoilLayer Recoiling() => new()
{
AwayLeft = Away(0.5f, 1f, 0f, 0f), AwayRight = Away(0.5f, 0f, 1f, 0f),
Proximity = new Consideration(ConsiderationInput.Distance, 0.2, 2.0, 1.0, 0.0),
};
// A target `r` metres from the head centre at lateral coordinate s in the torso frame (+ is the actor's left), level with the head.
private static (float X, float Y, float Z) Bearing(float s, float r)
{
var h = Plan.Parts[Head].Position;
return (h.X + s * r, h.Y, h.Z + MathF.Sqrt(1f - s * s) * r);
}
[Fact]
public void Recoil_blends_by_bearing_and_is_continuous_across_the_midline()
{
var recoil = Recoiling();
var b = Behaviour(recoil: recoil);
var baseline = Base(b);
var depth = (float)recoil.Proximity.Response(0.5);
Assert.InRange(depth, 0.5f, 0.99f);
var far = Run(b, Rest(), At(Bearing(0.6f, 3f))); // past the curve's far end: depth 0
for (var m = 0; m < Joints; m++) Same(baseline[m], far[m]);
var leftward = Run(b, Rest(), At(Bearing(1f, 0.5f)));
var rightward = Run(b, Rest(), At(Bearing(-1f, 0.5f)));
var ahead = Run(b, Rest(), At(Bearing(0f, 0.5f)));
var key = Key();
for (var m = 0; m < Joints; m++)
{
Same(Flinched(Quat.Nlerp(key[m], recoil.Left[m], depth), Quat.Identity, 0f), leftward[m]);
Same(Flinched(Quat.Nlerp(key[m], recoil.Right[m], depth), Quat.Identity, 0f), rightward[m]);
var half = Quat.Nlerp(Quat.Nlerp(key[m], recoil.Left[m], depth * 0.5f), recoil.Right[m], depth * 0.5f);
Same(Flinched(half, Quat.Identity, 0f), ahead[m]);
}
var a = Run(b, Rest(), At(Bearing(1e-4f, 0.5f)));
var c = Run(b, Rest(), At(Bearing(-1e-4f, 0.5f)));
for (var m = 0; m < Joints; m++)
{
Same(a[m], ahead[m], 1e-5f);
Same(c[m], ahead[m], 1e-5f);
}
}
[Fact]
public void Recoil_applies_before_look_and_arms_so_a_partial_look_or_reach_blends_from_the_recoiled_pose()
{
var recoil = Recoiling();
var b = Behaviour(new LookLayer { Weight = 0.5 }, new ArmLayer { Mode = ArmMode.Reach, Side = ArmSide.Right, Weight = 0.5 }, recoil);
var parts = Rest();
var target = Bearing(0.5f, 0.5f);
var got = Run(b, parts, At(target), ticks: Settle);
var depth = (float)recoil.Proximity.Response(0.5);
var key = Key();
var recoiled = new Quat[Joints];
for (var m = 0; m < Joints; m++) recoiled[m] = Quat.Nlerp(Quat.Nlerp(key[m], recoil.Left[m], depth * 0.75f), recoil.Right[m], depth * 0.25f);
var t = parts[Torso];
LookChain.Of(Plan).Solve(t.Rotation, t.X, t.Y, t.Z, target.X, target.Y, target.Z, out var neck);
var arm = ArmChain.Of(Plan, Side.Right, Dt);
var p = parts[arm.ParentPart];
arm.Solve(p.Rotation, p.X, p.Y, p.Z, target.X, target.Y, target.Z, out var shoulder, out var elbow);
for (var m = 0; m < Joints; m++)
{
var want = m == Neck ? Quat.Nlerp(recoiled[m], neck, 0.5f)
: m == arm.ShoulderJoint ? Quat.Nlerp(recoiled[m], shoulder, 0.5f)
: m == arm.ElbowJoint ? Quat.Nlerp(recoiled[m], elbow, 0.5f)
: recoiled[m];
Same(want, got[m], 1e-5f);
}
}
[Fact]
public void The_layers_treat_a_phantom_target_as_they_treat_a_real_one_at_the_same_place()
{
// Stare-at-hands is Look and Reach on a phantom at the actor's own hand: the layers read the percept's place, never its id.
var b = Behaviour(new LookLayer(), new ArmLayer { Mode = ArmMode.Reach, Side = ArmSide.Both }, Recoiling());
foreach (var parts in new[] { Rest(), Turned() })
{
var real = Run(b, parts, At(Ahead, 1UL));
var phantom = Run(b, parts, At(Ahead, Perception.PhantomIdBit | 1UL));
for (var m = 0; m < Joints; m++) SameBits(real[m], phantom[m]);
Assert.NotEqual(Base(b)[Neck], phantom[Neck]);
}
}
[Fact]
public void The_flinch_applies_after_the_layers_and_strength_stays_the_pose_rule()
{
var parts = Rest();
var hold = new HoldParameters { HoldStrength = 0.8f, FlinchGain = 0.3 };
var flinchPose = Away(0.7f, 0f, 0f, 1f);
var b = Behaviour(new LookLayer(), new ArmLayer { Mode = ArmMode.Reach, Side = ArmSide.Both }, Recoiling(), hold) with { FlinchPose = flinchPose };
var tgt = At(Ahead);
var quiet = Run(b, parts, tgt);
foreach (var weight in new[] { 0.0, 0.25, 0.5, 1.0 })
{
foreach (var leak in new[] { 0.0, 0.4, 1.0 })
{
var strengths = new float[Joints];
var moved = Run(b, parts, tgt, weight: weight, leak: leak, strengths: strengths);
var w = (float)b.Blend(leak, 0.0, 0.0);
var want = hold.HoldStrength * (float)Math.Min(1.0, weight + leak * hold.FlinchGain);
for (var m = 0; m < Joints; m++)
{
Assert.Equal(want, strengths[m]);
// The flinch is the last blend, over the layered pose and for every joint, the solved shoulder included.
var layered = Run(b with { FlinchPose = Identity(), Hold = hold with { FlinchGain = 0.0 } }, parts, tgt)[m];
Same(Quat.Nlerp(layered, flinchPose[m], w), moved[m], 1e-5f);
}
}
}
var shoulder = Plan.JointIndex("Shoulder", Side.Left);
var leaking = Run(b, parts, tgt, leak: 1.0);
Assert.NotEqual(quiet[shoulder], leaking[shoulder]);
}
[Fact]
public void Validation_names_the_goal()
{
static void Refuses(PoseBehaviour b) => Assert.Contains("Goal g:", Assert.Throws<ArgumentException>(() => b.Validate("g")).Message);
var good = Behaviour();
good.Validate("g");
foreach (var weight in new[] { -0.1, 1.1, double.NaN, double.PositiveInfinity })
{
Refuses(Behaviour(look: new LookLayer { Weight = weight }));
Refuses(Behaviour(arms: new ArmLayer { Mode = ArmMode.Reach, Weight = weight }));
}
Refuses(Behaviour(arms: new ArmLayer { Mode = ArmMode.WardOff, Distance = 0f, Spread = 0.1f }));
Refuses(Behaviour(arms: new ArmLayer { Mode = ArmMode.WardOff, Distance = -0.3f, Spread = 0.1f }));
Refuses(Behaviour(arms: new ArmLayer { Mode = ArmMode.WardOff, Distance = 0.3f, Spread = -0.01f }));
Refuses(Behaviour(arms: new ArmLayer { Mode = ArmMode.WardOff, Distance = float.NaN, Spread = 0.1f }));
Refuses(Behaviour(arms: new ArmLayer { Mode = ArmMode.Present, Side = ArmSide.Nearer }));
Behaviour(arms: new ArmLayer { Mode = ArmMode.Present, Side = ArmSide.Both }).Validate("g");
Behaviour(arms: new ArmLayer { Mode = ArmMode.WardOff, Distance = 0.3f, Spread = 0f }).Validate("g");
var recoil = Recoiling();
Behaviour(recoil: recoil).Validate("g");
Refuses(Behaviour(recoil: recoil with { AwayLeft = new Quat[Joints - 1] }));
Refuses(Behaviour(recoil: recoil with { AwayRight = new Quat[Joints + 1] }));
Refuses(Behaviour(recoil: recoil with { Proximity = recoil.Proximity with { Input = ConsiderationInput.Salience } }));
Refuses(Behaviour(recoil: new RecoilLayer { AwayLeft = Identity(), AwayRight = Identity() }));
}
[Fact]
public void A_layered_behaviour_refuses_to_write_without_the_orient_input()
{
var b = Behaviour(new LookLayer());
Assert.Throws<ArgumentException>(() => b.Write(1.0, 0.0, 0.0, 0.0, 0.0, new float[Joints], new Quat[Joints]));
Assert.True(b.HasLayers);
Assert.False(Behaviour().HasLayers);
Behaviour().Write(1.0, 0.0, 0.0, 0.0, 0.0, new float[Joints], new Quat[Joints]);
}
[Fact]
public void Layers_copy_their_poses_and_read_back_read_only()
{
var left = Away(0.5f, 1f, 0f, 0f);
var recoil = new RecoilLayer { AwayLeft = left, AwayRight = Identity(), Proximity = new Consideration(ConsiderationInput.Distance, 0, 1, 1, 0) };
var was = recoil.AwayLeft[0];
left[0] = Quat.Identity;
Assert.Equal(was, recoil.AwayLeft[0]);
Assert.False(recoil.AwayLeft is Quat[]);
}
// The Actor: targets come from the percepts, the layers from the goal's behaviour, the poses from the caller.
private static Emitter Emit(ulong id, (float X, float Y, float Z) p) =>
new() { Channel = Channel.Audio, X = p.X, Y = p.Y, Z = p.Z, Radius = 40f, Intensity = 1.0, Id = id, Kind = Thing };
private static Brain Watching(PoseBehaviour layered) => new()
{
Goals = new[]
{
new GoalSpec { Id = "idle", Priority = 0.0, Behaviour = Behaviour() },
new GoalSpec
{
Id = "watch", Priority = 1.0, Target = new TargetFilter { Kinds = new[] { Thing } },
Considerations = new[] { new Consideration(ConsiderationInput.Distance, 0.0, 60.0, 1.0, 0.0) },
Behaviour = layered,
},
},
};
private static Actor Watcher(Brain brain, BodyPlan? body) =>
new(Dt, 1, new NerveParameters(), new WithdrawalParameters(), new DriveParameters(), brain,
new NerveParameters { Threshold = 0.05, SensitisationGrowth = 0.0, ConductionDelaySeconds = 0.0 }, 0,
new PerceptParameters { Capacity = 4, MemorySeconds = 5.0 }, body: body);
private static readonly float[] Origin = { 0f };
private static TickEvents Step(Actor a, PartPose[] parts, Quat[] targets, params Emitter[] emitters) =>
a.Tick(Origin, Origin, Origin, NoBoxes, new float[Joints], targets, emitters, parts: parts);
[Fact]
public void Nearer_holds_one_arm_per_pair_and_a_recommit_picks_again()
{
var b = Behaviour(arms: new ArmLayer { Mode = ArmMode.Reach, Side = ArmSide.Nearer });
var a = Watcher(Watching(b), Plan);
var parts = Rest();
var targets = new Quat[Joints];
var baseline = Base(b);
var left = Plan.JointIndex("Shoulder", Side.Left);
var right = Plan.JointIndex("Shoulder", Side.Right);
var onLeft = (0.9f, 1.5f, 0.5f);
var onRight = (-0.9f, 1.5f, 0.5f);
for (var i = 0; i < 40; i++) Step(a, parts, targets, Emit(1, onLeft));
Assert.Equal(1UL, a.TargetId);
Assert.NotEqual(baseline[left], targets[left]);
Same(baseline[right], targets[right]);
// The same thing moves to the right: the pair is the same pair, so the arm stays.
for (var i = 0; i < 40; i++) Step(a, parts, targets, Emit(1, onRight));
Assert.Equal(1UL, a.TargetId);
Assert.NotEqual(baseline[left], targets[left]);
Same(baseline[right], targets[right]);
// Another thing, nearer and on the right, is another pair: it commits a latency later and picks the nearer arm again.
for (var i = 0; i < 60; i++) Step(a, parts, targets, Emit(1, onRight), Emit(2, (-0.5f, 1.5f, 0.3f)));
Assert.Equal(2UL, a.TargetId);
Assert.NotEqual(baseline[right], targets[right]);
Same(baseline[left], targets[left]);
}
[Theory]
[InlineData(Side.Right)]
[InlineData(Side.Left)]
public void ResetArms_makes_both_arms_engage_from_the_base_and_settle_on_the_stateless_rule(Side side)
{
// Reach with both arms along the feasible tie of one arm's shoulder (goal (dx, -0.25, -0.25) from it, mirrored for the left), from
// dx -10 mm to 2 mm past the tie: that arm holds its basin, away from the stateless target. After ResetArms both arms are idle: the
// next tick writes within one slew step of the base pose, and with the goal held they settle on the stateless solve.
var b = Behaviour(arms: new ArmLayer { Mode = ArmMode.Reach, Side = ArmSide.Both });
var a = Watcher(Watching(b), Plan);
var parts = Rest();
var targets = new Quat[Joints];
var arms = new[] { ArmChain.Of(Plan, Side.Left, Dt), ArmChain.Of(Plan, Side.Right, Dt) };
var tie = side == Side.Left ? arms[0] : arms[1];
var sign = side == Side.Left ? -1f : 1f;
var s = tie.ShoulderAnchor;
(float X, float Y, float Z) Goal(float dx) => (s.X + sign * dx, s.Y - 0.25f, s.Z - 0.25f);
for (var i = 0; i < 40; i++) Step(a, parts, targets, Emit(1, Goal(-0.01f)));
Assert.Equal(1UL, a.TargetId);
for (var i = -50; i <= 10; i++) Step(a, parts, targets, Emit(1, Goal(i * 0.0002f)));
var held = (Quat[])targets.Clone();
a.ResetArms();
Step(a, parts, targets, Emit(1, Goal(0.002f)));
var baseline = Base(b);
foreach (var arm in arms)
{
Assert.True(Turn(baseline[arm.ShoulderJoint], targets[arm.ShoulderJoint]) <= ArmChain.MaxAngularRate * Dt + 1e-5f, "the shoulder jumped from the base on engaging");
Assert.True(Turn(baseline[arm.ElbowJoint], targets[arm.ElbowJoint]) <= ArmChain.MaxAngularRate * Dt + 1e-5f, "the elbow jumped from the base on engaging");
}
for (var i = 0; i < Settle; i++) Step(a, parts, targets, Emit(1, Goal(0.002f)));
var t = a.Target;
Assert.Equal(Goal(0.002f), (t.X, t.Y, t.Z));
foreach (var arm in arms)
{
var p = parts[arm.ParentPart];
arm.Solve(p.Rotation, p.X, p.Y, p.Z, t.X, t.Y, t.Z, out var shoulder, out var elbow);
Same(Flinched(shoulder, Quat.Identity, 0f), targets[arm.ShoulderJoint]);
Same(Flinched(elbow, Quat.Identity, 0f), targets[arm.ElbowJoint]);
}
var held2 = held[tie.ShoulderJoint];
var reset = targets[tie.ShoulderJoint];
var turn = 2f * MathF.Acos(MathF.Min(1f, MathF.Abs(held2.X * reset.X + held2.Y * reset.Y + held2.Z * reset.Z + held2.W * reset.W)));
Assert.True(turn > 1f, $"the held {side} arm was only {turn} rad from the stateless target, so the reset proves nothing");
}
[Fact]
public void A_tie_goes_to_the_right_arm()
{
var b = Behaviour(arms: new ArmLayer { Mode = ArmMode.Reach, Side = ArmSide.Nearer });
var a = Watcher(Watching(b), Plan);
var targets = new Quat[Joints];
var baseline = Base(b);
for (var i = 0; i < 40; i++) Step(a, Rest(), targets, Emit(1, (0f, 1.5f, 0.8f)));
Assert.Equal(1UL, a.TargetId);
Assert.NotEqual(baseline[Plan.JointIndex("Shoulder", Side.Right)], targets[Plan.JointIndex("Shoulder", Side.Right)]);
Same(baseline[Plan.JointIndex("Shoulder", Side.Left)], targets[Plan.JointIndex("Shoulder", Side.Left)]);
}
[Fact]
public void The_actor_gives_the_layers_the_committed_target_and_the_callers_poses()
{
var b = Behaviour(look: new LookLayer());
var a = Watcher(Watching(b), Plan);
var parts = Turned();
var targets = new Quat[Joints];
for (var i = 0; i < 40; i++) Step(a, parts, targets, Emit(1, Ahead));
var t = parts[Torso];
LookChain.Of(Plan).Solve(t.Rotation, t.X, t.Y, t.Z, Ahead.X, Ahead.Y, Ahead.Z, out var solved);
SameBits(Flinched(solved, Quat.Identity, 0f), targets[Neck]);
Assert.Same(Plan, a.Body);
}
[Fact]
public void Construction_refuses_what_the_layers_cannot_stand_on()
{
var layered = Behaviour(new LookLayer());
var noBody = Assert.Throws<ArgumentException>(() => Watcher(Watching(layered), null));
Assert.Contains("Goal watch", noBody.Message);
// One muscle too few for the body.
var short3 = new PoseBehaviour { Keys = new[] { new Quat[3] { Quat.Identity, Quat.Identity, Quat.Identity } }, FlinchPose = new Quat[3] { Quat.Identity, Quat.Identity, Quat.Identity }, Look = new LookLayer() };
var brain = new Brain { Goals = new[] { new GoalSpec { Id = "short", Behaviour = short3 } } };
Assert.Contains("Goal short", Assert.Throws<ArgumentException>(() => Watcher(brain, Plan)).Message);
// Layers on goals that none use build without a body when no goal is layered.
Watcher(Watching(Behaviour()), null);
}
private static BodyPlan WithJoint(string label, Side side, Func<JointDef, JointDef> change)
{
var joints = new JointDef[Joints];
for (var j = 0; j < Joints; j++) joints[j] = Plan.Joints[j];
var i = Plan.JointIndex(label, side);
joints[i] = change(joints[i]);
return new BodyPlan(Plan.Parts, joints, Plan.SensePoints, Plan.AirwayOpenings, Plan.AirwaySumps);
}
[Fact]
public void An_arm_the_closed_form_cannot_solve_is_refused_at_construction_naming_goal_and_side()
{
var b = Behaviour(arms: new ArmLayer { Mode = ArmMode.Reach, Side = ArmSide.Both });
// Bent at creation: the elbow anchor off the shoulder-to-wrist line.
var bent = WithJoint("Elbow", Side.Right, j => j with { Anchor = (j.Anchor.X - 0.08f, j.Anchor.Y, j.Anchor.Z + 0.05f) });
var bentError = Assert.Throws<ArgumentException>(() => Watcher(Watching(b), bent)).Message;
Assert.Contains("Goal watch", bentError);
Assert.Contains("Right", bentError);
Assert.DoesNotContain("Left", bentError);
// An elbow range straddling zero.
var straddle = WithJoint("Elbow", Side.Left, j => j with { Lower = -1f, Upper = 1f });
var straddleError = Assert.Throws<ArgumentException>(() => Watcher(Watching(b), straddle)).Message;
Assert.Contains("Goal watch", straddleError);
Assert.Contains("Left", straddleError);
// The same arm on the unused side is no matter: a Right-only layer builds on a plan whose left arm is bent.
var leftBent = WithJoint("Elbow", Side.Left, j => j with { Anchor = (j.Anchor.X + 0.08f, j.Anchor.Y, j.Anchor.Z + 0.05f) });
Watcher(Watching(Behaviour(arms: new ArmLayer { Mode = ArmMode.Reach, Side = ArmSide.Right })), leftBent);
Assert.Throws<ArgumentException>(() => Watcher(Watching(Behaviour(arms: new ArmLayer { Mode = ArmMode.Reach, Side = ArmSide.Nearer })), leftBent));
Assert.Throws<ArgumentException>(() => Watcher(Watching(Behaviour(arms: new ArmLayer { Mode = ArmMode.Present, Side = ArmSide.Both })), leftBent));
}
[Fact]
public void Parts_of_the_wrong_length_throw_at_tick_for_a_layered_goal_only()
{
var a = Watcher(Watching(Behaviour(look: new LookLayer())), Plan);
var targets = new Quat[Joints];
// The Start goal (idle) has no layers: parts are ignored, whatever they are.
Step(a, Array.Empty<PartPose>(), targets);
Step(a, new PartPose[3], targets);
for (var i = 0; i < 40; i++) Step(a, Rest(), targets, Emit(1, Ahead));
Assert.Equal(1, a.GoalIndex);
Assert.Throws<ArgumentException>(() => Step(a, new PartPose[Plan.Parts.Count - 1], targets, Emit(1, Ahead)));
Assert.Throws<ArgumentException>(() => Step(a, Array.Empty<PartPose>(), targets, Emit(1, Ahead)));
}
[Fact]
public void Ticking_with_layers_allocates_nothing()
{
var layered = Behaviour(
new LookLayer(),
new ArmLayer { Mode = ArmMode.WardOff, Side = ArmSide.Both, Distance = 0.4f, Spread = 0.1f },
Recoiling());
var a = Watcher(Watching(layered), Plan);
var parts = Turned();
var targets = new Quat[Joints];
var strengths = new float[Joints];
var emitters = new[] { Emit(1, Ahead) };
for (var i = 0; i < 60; i++) a.Tick(Origin, Origin, Origin, NoBoxes, strengths, targets, emitters, parts: parts);
Assert.Equal(1, a.GoalIndex);
var before = GC.GetAllocatedBytesForCurrentThread();
for (var i = 0; i < 10000; i++) a.Tick(Origin, Origin, Origin, NoBoxes, strengths, targets, emitters, parts: parts);
Assert.Equal(0L, GC.GetAllocatedBytesForCurrentThread() - before);
}
}

View file

@ -0,0 +1,178 @@
using Lodur;
using static Lodur.Core.Tests.PhysioFixtures;
namespace Lodur.Core.Tests;
/// <summary>
/// Blood and brain oxygen: the stores, the Breathing capacity and the content that turns brain oxygen into consciousness. The windows are the
/// literature the content constants are fitted to (placeholders, rulings bds-asphyxia-real-time and bds-heart-stop-stagger).
/// </summary>
public sealed class OxygenTests
{
private const double Dt = 1.0 / 120.0;
private static readonly BodyPlan Body = BodyPlans.Humanoid();
private static Physiology Spawn() => new(Body, PhysiologyPlans.Humanoid(), 20);
/// <summary>The humanoid's content with a smothering that never lifts added to its afflictions.</summary>
private static Physiology Smothered()
{
var h = PhysiologyPlans.Humanoid();
var choke = new AfflictionDef("Choke", PhysiologyClock.Acute, -1.0 / 40.0, false,
new[] { new Effect(EffectTarget.Breathing, EffectOp.Factor, EffectDriver.Severity, new[] { (0.0, 0.0), (1.0, 0.0) }) });
var defs = new List<AfflictionDef>(h.Afflictions) { choke };
var plan = new PhysiologyPlan(h.Parts, defs, h.OrganismEffects, h.Blood, h.Respiration, h.Airway, h.AfflictionSlots);
var p = new Physiology(Body, plan, 20);
Assert.True(p.Afflict(plan.AfflictionIndex("Choke"), Body.PartIndex("Torso"), 0, 1e9));
return p;
}
/// <summary>Steps with the given arousal; effort is the consciousness the last step left (a struggle that fades with the motor ceiling) unless fixed. Returns the second consciousness first fell to 0.1 or below and the second of death (-1 for neither).</summary>
private static (double Out, double Dead) Run(Physiology p, double arousal, double? effort, double seconds)
{
double outAt = -1.0, deadAt = -1.0, c = 1.0;
var steps = (long)(seconds / Dt);
for (long i = 0; i < steps && !p.Dead; i++)
{
p.Step(Dt, new PhysiologyInput(arousal, effort ?? c));
c = p.Consciousness;
var t = (i + 1) * Dt;
if (outAt < 0.0 && c <= 0.1) outAt = t;
if (p.Dead) deadAt = t;
}
return (outAt, deadAt);
}
[Fact]
public void A_whole_humanoid_at_rest_keeps_its_oxygen_and_full_consciousness()
{
var p = Spawn();
for (var i = 0; i < (int)(600.0 / Dt); i++)
{
p.Step(Dt);
Assert.Equal(1.0, p.Consciousness);
}
Assert.True(p.BloodOxygen >= 0.99, $"blood oxygen {p.BloodOxygen}");
Assert.True(p.BrainOxygen >= 0.99, $"brain oxygen {p.BrainOxygen}");
Assert.Equal(1.0, p.Breathing);
}
[Fact]
public void A_struggling_smothered_humanoid_is_out_in_60_to_90_s_and_dead_in_134_to_360_s()
{
var p = Smothered();
var (outAt, deadAt) = Run(p, 1.0, null, 400.0);
Assert.InRange(outAt, 60.0, 90.0);
Assert.InRange(deadAt, 134.0, 360.0);
Assert.Equal(DeathCause.Consciousness, p.Cause);
}
[Fact]
public void Calm_is_slower_than_struggling()
{
var struggling = Run(Smothered(), 1.0, null, 400.0);
var calm = Run(Smothered(), 0.0, 0.0, 1200.0);
Assert.True(calm.Out > struggling.Out, $"calm {calm.Out} s, struggling {struggling.Out} s");
}
[Fact]
public void A_destroyed_heart_staggers_for_seconds_and_kills_through_consciousness()
{
var p = Spawn();
var torso = Body.PartIndex("Torso");
Assert.True(p.Afflict(PhysiologyPlans.Humanoid().AfflictionIndex("Cut"), torso, p.TissueIndex(torso, "Heart"), 16));
p.Step(Dt);
Assert.False(p.Dead);
Assert.Equal(DeathCause.None, p.Cause);
Assert.Equal(0.0, p.BloodPumping);
var (outAt, deadAt) = Run(p, 0.0, 0.0, 60.0);
Assert.InRange(outAt + Dt, 6.0, 12.0);
Assert.True(deadAt > outAt, $"out {outAt} s, dead {deadAt} s");
Assert.Equal(DeathCause.Consciousness, p.Cause);
}
[Theory]
[InlineData(1.0)]
[InlineData(20.0)]
public void One_lung_lost_still_breathes(double slowScale)
{
var p = new Physiology(Body, PhysiologyPlans.Humanoid(), slowScale);
var torso = Body.PartIndex("Torso");
Assert.True(p.Afflict(PhysiologyPlans.Humanoid().AfflictionIndex("Bruise"), torso, p.TissueIndex(torso, "LungLeft"), 16));
double c = 1.0;
for (var i = 0; i < (int)(300.0 / Dt); i++)
{
p.Step(Dt, new PhysiologyInput(1.0, c));
c = p.Consciousness;
Assert.True(c >= 0.9, $"consciousness {c} at step {i}");
}
Assert.Equal(0.5, p.Breathing); // the bruise is a wound: real seconds, so the slow scale cannot heal it
// Half the ventilation settles the blood store at 1 - use / (uptake x breathing) = 0.978 here: uptake 1.0 gives that, 0.5 gives 0.956, 2.0 gives 0.989;
// the bounds are the geometric midpoints of the deficit (ruling deterministic-bound-margin).
Assert.InRange(p.BloodOxygen, 0.969, 0.9844);
Assert.False(p.Dead);
}
[Fact]
public void A_bruise_heals_identically_at_every_slow_scale()
{
double Left(double scale)
{
var p = new Physiology(Body, PhysiologyPlans.Humanoid(), scale);
var torso = Body.PartIndex("Torso");
Assert.True(p.Afflict(PhysiologyPlans.Humanoid().AfflictionIndex("Bruise"), torso, p.TissueIndex(torso, "LungLeft"), 16));
for (var i = 0; i < (int)(300.0 / Dt); i++) p.Step(Dt);
Assert.Equal(1, Live(p));
return p.SlotSeverity(0);
}
var real = Left(1.0);
Assert.Equal(real, Left(20.0));
Assert.Equal(16.0 - 20.0 * 300.0 / 86400.0, real, 6); // 20 HP per day of real seconds
}
[Fact]
public void A_lifted_smothering_refills()
{
var p = Make(organism: new[] { Hypoxia });
Assert.True(p.Afflict(Af("Choke"), 0, 0, 1.0)); // lifts at 40 s
double c = 1.0, lowest = 1.0;
for (var i = 0; i < (int)(39.0 / Dt); i++)
{
p.Step(Dt, new PhysiologyInput(1.0, c));
c = p.Consciousness;
lowest = Math.Min(lowest, c);
}
Assert.True(lowest < 1.0, "the smothering never dimmed the brain");
Assert.Equal(0.0, p.Breathing);
for (var i = 0; i < (int)(31.0 / Dt); i++)
{
p.Step(Dt, new PhysiologyInput(1.0, c));
c = p.Consciousness;
}
Assert.Equal(1.0, c);
Assert.False(p.Dead);
}
[Fact]
public void An_input_outside_zero_to_one_or_not_finite_is_refused_before_anything_changes()
{
var p = Spawn();
foreach (var bad in new[] { -0.1, 1.1, double.NaN, double.PositiveInfinity })
{
Assert.Throws<ArgumentException>(() => p.Step(Dt, new PhysiologyInput(bad, 0.0)));
Assert.Throws<ArgumentException>(() => p.Step(Dt, new PhysiologyInput(0.0, bad)));
}
Assert.Equal(1.0, p.BloodOxygen);
p.Step(Dt, new PhysiologyInput(1.0, 1.0));
Assert.True(p.BloodOxygen < 1.0);
}
}

View file

@ -0,0 +1,108 @@
using Lodur;
namespace Lodur.Core.Tests;
/// <summary>SplitMix64, as the pain box in Bad Day Simulator draws its seeded stream.</summary>
internal struct SplitMix64
{
private ulong _s;
public SplitMix64(ulong seed) => _s = seed;
public double NextSigned()
{
var z = _s += 0x9E3779B97F4A7C15ul;
z = (z ^ (z >> 30)) * 0xBF58476D1CE4E5B9ul;
z = (z ^ (z >> 27)) * 0x94D049BB133111EBul;
z ^= z >> 31;
return (z >> 11) * (1.0 / 9007199254740992.0) * 2.0 - 1.0;
}
}
/// <summary>
/// The pain box as a Brain: the objective holds the hold pose against the reflex; the release, entered once the
/// will breaks, is a pose behaviour with the withdraw pose as its key and no gains.
/// </summary>
internal static class PainBoxBrain
{
public static readonly Quat[] Hold = { Quat.Identity, Quat.Identity };
public static readonly Quat[] Withdraw = { Quat.FromAxisAngle(1f, 0f, 0f, 1f), Quat.FromAxisAngle(0f, 0f, 1f, -1f) };
public static Brain Make(double pull, HoldParameters? hold = null) => new Brain
{
Goals = new[]
{
new GoalSpec
{
Id = "objective", Priority = 0.0, Pull = pull,
Behaviour = new PoseBehaviour { Keys = new[] { Hold }, FlinchPose = Withdraw, Hold = hold ?? new HoldParameters() },
},
new GoalSpec
{
Id = "release", Priority = 1.0, Pull = pull, InvoluntarySeconds = double.PositiveInfinity,
When = new[] { new Condition(DriveQuantity.Breaks, ConditionOp.AtLeast, 1.0) },
Behaviour = new PoseBehaviour
{
Keys = new[] { Withdraw }, FlinchPose = Withdraw,
Hold = (hold ?? new HoldParameters()) with { FlinchGain = 0.0, StrainShake = 0.0 },
},
},
},
};
}
/// <summary>
/// Replays the pain box's stimulus for a seed (traits gain then drain, then per tick jitter, ramp, noise) into an
/// Actor whose one region sits inside the box. A small fixture, not a model: all the arithmetic is the core's.
/// </summary>
internal sealed class PainBoxReplay
{
public const double Dt = 0.01;
public readonly Actor Actor;
public readonly BoxStimulus[] Sources = { new BoxStimulus(0f, 0f, 0f, 1f, 1f, 1f) };
public readonly float[] Strengths = new float[2];
public readonly Quat[] Targets = new Quat[2];
public static Quat[] Hold => PainBoxBrain.Hold;
public static Quat[] Withdraw => PainBoxBrain.Withdraw;
private readonly float[] _p = { 0f };
private SplitMix64 _rng;
private readonly double _intensity;
public PainBoxReplay(ulong seed, double intensity = 0.8, double pull = 0.5, WithdrawalParameters? withdrawal = null,
DriveParameters? drive = null, double jitter = 0.2, Brain? brain = null, Physiology? physiology = null)
{
_rng = new SplitMix64(seed);
_intensity = intensity;
var gainTrait = 1.0 + jitter * _rng.NextSigned();
var drainTrait = 1.0 + jitter * _rng.NextSigned();
Actor = new Actor(Dt, 1, new NerveParameters { Gain = gainTrait }, withdrawal ?? new WithdrawalParameters(),
(drive ?? new DriveParameters()) with { DrainTrait = drainTrait }, brain ?? PainBoxBrain.Make(pull), physiology: physiology);
}
/// <summary>One tick of the replayed stimulus; the tick index is Actor.TickCount before the call.</summary>
public TickEvents Tick(bool boxOn = true)
{
var tick = Actor.TickCount;
var noise = _rng.NextSigned();
var ramp = Math.Min(1.0, tick * Dt / 2.0);
Sources[0].Intensity = boxOn ? Math.Max(0.0, _intensity * ramp * (1.0 + 0.1 * noise)) : 0.0;
return Actor.Tick(_p, _p, _p, Sources, Strengths, Targets);
}
/// <summary>Runs to GoalChanged or the cap; returns the tick of WillBroke and GoalChanged (-1 if never) and the flinch count.</summary>
public (long Broke, long Withdrew, int Flinches) Run(double maxSeconds)
{
long broke = -1, withdrew = -1;
var flinches = 0;
var max = (long)Math.Round(maxSeconds / Dt);
for (long i = 0; i <= max && withdrew < 0; i++)
{
var e = Tick();
if ((e & TickEvents.Flinch) != 0) flinches++;
if ((e & TickEvents.WillBroke) != 0) broke = i;
if ((e & TickEvents.GoalChanged) != 0) withdrew = i;
}
return (broke, withdrew, flinches);
}
}

View file

@ -0,0 +1,344 @@
using System;
using Lodur;
namespace Lodur.Core.Tests;
public sealed class PerceptTests
{
private const double Dt = 0.01;
private static readonly float[] Zero = { 0f };
private static readonly BoxStimulus[] NoBoxes = Array.Empty<BoxStimulus>();
private static Perception Make(int capacity = 4, double memory = 0.05, NerveParameters? senses = null) =>
new Perception(new NerveParameters(), Dt, 1, senses ?? new NerveParameters { Threshold = 0.05, SensitisationGrowth = 0.0, ConductionDelaySeconds = 0.0 },
0, new PerceptParameters { Capacity = capacity, MemorySeconds = memory });
private static void Sense(Perception p, Emitter[] emitters, double gain = 1.0) => p.Sense(Zero, Zero, Zero, NoBoxes, emitters, gain);
private static Emitter At(ulong id, float x = 0f, float radius = 2f, double intensity = 0.5, uint kind = 7, Channel channel = Channel.Audio) =>
new Emitter(channel, x, 0f, 0f, radius, intensity, id, kind);
private static int SlotOf(Perception p, ulong id)
{
for (var s = 0; s < p.PerceptCount; s++)
{
if (p.Percept(s).Id == id) return s;
}
return -1;
}
private static int Occupied(Perception p)
{
var n = 0;
for (var s = 0; s < p.PerceptCount; s++)
{
if (p.Percept(s).Id != 0) n++;
}
return n;
}
[Fact]
public void A_remembered_id_sensed_with_a_new_kind_takes_the_new_kind()
{
var p = Make();
Sense(p, new[] { At(1, kind: 7) });
Sense(p, new[] { At(1, kind: 9) });
Assert.Equal(9u, p.Percept(SlotOf(p, 1)).Kind);
}
[Fact]
public void A_free_slot_is_all_zero_after_forgetting_and_an_anonymous_emitter_cannot_write_into_it()
{
var p = Make(capacity: 2, memory: 0.05);
Sense(p, new[] { At(1, x: 0.5f) });
for (var i = 0; i < 20; i++) Sense(p, Array.Empty<Emitter>());
Assert.Equal(0, Occupied(p));
for (var i = 0; i < 3; i++) Sense(p, new[] { At(0, x: 0.5f) });
for (var s = 0; s < p.PerceptCount; s++)
{
var c = p.Percept(s);
Assert.Equal(0UL, c.Id);
Assert.Equal(0u, c.Kind);
Assert.Equal(0f, c.X);
Assert.Equal(0f, c.Y);
Assert.Equal(0f, c.Z);
Assert.Equal(0.0, c.Salience);
Assert.Equal(0.0, c.SecondsSinceSensed);
}
}
[Fact]
public void An_anonymous_emitter_loads_the_nerve_and_makes_no_percept()
{
var anonymous = Make();
var named = Make();
var emitters = new[] { At(0, 0.5f, 2f, 0.6), At(0, 1f, 3f, 0.4, channel: Channel.Visual) };
var withIds = new[] { At(11, 0.5f, 2f, 0.6), At(12, 1f, 3f, 0.4, channel: Channel.Visual) };
for (var i = 0; i < 30; i++)
{
Sense(anonymous, emitters);
Sense(named, withIds);
Assert.Equal(named.Load, anonymous.Load);
Assert.Equal(named.ChannelAfferent(Channel.Audio), anonymous.ChannelAfferent(Channel.Audio));
}
Assert.True(anonymous.Load > 0.0);
Assert.Equal(0, Occupied(anonymous));
Assert.Equal(2, Occupied(named));
}
[Fact]
public void A_thing_is_sensed_strictly_inside_its_radius_and_only_with_gain()
{
var p = Make();
Sense(p, new[] { At(1, x: 2f, radius: 2f) }); // exactly at the radius
Assert.Equal(0, Occupied(p));
Sense(p, new[] { At(1, x: 1.999f, radius: 2f) });
Assert.Equal(1, Occupied(p));
Assert.Equal(0.0, p.Percept(SlotOf(p, 1)).SecondsSinceSensed);
var deaf = Make();
Sense(deaf, new[] { At(1) }, gain: 0.0);
Assert.Equal(0, Occupied(deaf));
Sense(deaf, new[] { At(1) }, gain: 0.25);
Assert.Equal(1, Occupied(deaf));
var noRadius = Make();
Sense(noRadius, new[] { At(1, radius: 0f) });
Assert.Equal(0, Occupied(noRadius));
}
[Fact]
public void Salience_is_the_largest_received_times_the_gain_and_position_follows_it()
{
var p = Make();
// Received: 0.5 * (1 - 1/2) = 0.25 at x=1; 0.5 * (1 - 0.5/2) = 0.375 at x=0.5; a tied second emitter at x=-0.5 must not take the position.
Sense(p, new[] { At(5, 1f, 2f, 0.5, kind: 9), At(5, 0.5f, 2f, 0.5, kind: 9), At(5, -0.5f, 2f, 0.5, kind: 9), At(0, 0f, 9f, 9.0) }, gain: 0.5);
var percept = p.Percept(SlotOf(p, 5));
Assert.Equal(1, Occupied(p));
Assert.Equal(0.375 * 0.5, percept.Salience, 12);
Assert.Equal(0.5f, percept.X);
Assert.Equal(9u, percept.Kind);
// A thing that is not sensed this tick keeps its place and has no salience.
Sense(p, Array.Empty<Emitter>());
Assert.Equal(0.0, p.Percept(SlotOf(p, 5)).Salience);
Assert.Equal(0.5f, p.Percept(SlotOf(p, 5)).X);
}
[Fact]
public void An_unsensed_percept_ages_and_is_forgotten_after_the_memory_time()
{
var p = Make(memory: Dt);
Sense(p, new[] { At(3) });
Sense(p, Array.Empty<Emitter>());
var s = SlotOf(p, 3);
Assert.True(s >= 0); // since == memory is still remembered
Assert.Equal(Dt, p.Percept(s).SecondsSinceSensed);
Sense(p, Array.Empty<Emitter>());
Assert.Equal(-1, SlotOf(p, 3)); // since > memory frees it
var instant = Make(memory: 0.0);
Sense(instant, new[] { At(3) });
Assert.Equal(1, Occupied(instant));
Sense(instant, Array.Empty<Emitter>());
Assert.Equal(0, Occupied(instant));
// Out of range or deaf, a thing ages the same; sensed again it returns to zero.
var q = Make(memory: 0.05);
Sense(q, new[] { At(3) });
Sense(q, new[] { At(3, x: 5f) });
Sense(q, new[] { At(3) }, gain: 0.0);
Assert.Equal(2 * Dt, q.Percept(SlotOf(q, 3)).SecondsSinceSensed, 12);
Sense(q, new[] { At(3) });
Assert.Equal(0.0, q.Percept(SlotOf(q, 3)).SecondsSinceSensed);
}
[Fact]
public void A_full_table_evicts_the_longest_unsensed_and_drops_a_newcomer_when_all_are_sensed()
{
var p = Make(capacity: 3, memory: 1.0);
Sense(p, new[] { At(1), At(2), At(3) });
Assert.Equal(0, SlotOf(p, 1));
Assert.Equal(1, SlotOf(p, 2));
Assert.Equal(2, SlotOf(p, 3));
// 2 and 3 are sensed on, 1 goes unsensed: the newcomer takes slot 0.
Sense(p, new[] { At(2), At(3), At(4) });
Assert.Equal(0, SlotOf(p, 4));
Assert.Equal(1, SlotOf(p, 2));
Assert.Equal(2, SlotOf(p, 3));
Assert.Equal(-1, SlotOf(p, 1));
// 3 has gone unsensed longest (two ticks to 2's one): it is the one evicted, and the others keep their slots.
Sense(p, new[] { At(2), At(4) });
Sense(p, new[] { At(4), At(6) });
Assert.Equal(2, SlotOf(p, 6));
Assert.Equal(-1, SlotOf(p, 3));
Assert.Equal(1, SlotOf(p, 2));
Assert.Equal(0, SlotOf(p, 4));
// Every slot sensed this tick: the newcomer is dropped, and it stays dropped for every emitter of its id.
var full = Make(capacity: 2, memory: 1.0);
Sense(full, new[] { At(1), At(2), At(8), At(8, 0.5f) });
Assert.Equal(-1, SlotOf(full, 8));
Assert.Equal(0, SlotOf(full, 1));
Assert.Equal(1, SlotOf(full, 2));
// Equal time unsensed: the lowest slot goes.
var tie = Make(capacity: 2, memory: 1.0);
Sense(tie, new[] { At(1), At(2) });
Sense(tie, new[] { At(9) });
Assert.Equal(0, SlotOf(tie, 9));
Assert.Equal(1, SlotOf(tie, 2));
}
[Fact]
public void Sense_refuses_a_phantom_id_and_a_kind_disagreement_before_stepping()
{
var p = Make();
Sense(p, new[] { At(1, intensity: 0.6) });
var load = p.Load;
var since = p.Percept(0).SecondsSinceSensed;
var afferent = p.ChannelStimulus(Channel.Audio);
Assert.Throws<ArgumentException>(() => Sense(p, new[] { At(1), At(Perception.PhantomIdBit | 2UL) }));
Assert.Throws<ArgumentException>(() => Sense(p, new[] { At(ulong.MaxValue) }));
Assert.Throws<ArgumentException>(() => Sense(p, new[] { At(1, kind: 7), At(2), At(1, kind: 8) }));
Assert.Equal(load, p.Load);
Assert.Equal(since, p.Percept(0).SecondsSinceSensed);
Assert.Equal(afferent, p.ChannelStimulus(Channel.Audio));
// The state did not step: the next good tick is the second, not the fourth.
Sense(p, Array.Empty<Emitter>());
Assert.Equal(Dt, p.Percept(0).SecondsSinceSensed);
// Anonymous emitters may share kinds freely, and one id may speak on several channels.
Sense(p, new[] { At(0, kind: 1), At(0, kind: 2), At(4, kind: 3), At(4, kind: 3, channel: Channel.Visual) });
}
private static Emitter Fact(ulong id, ulong facts, float x = 0f, double intensity = 0.5, Channel channel = Channel.Audio) =>
new Emitter(channel, x, 0f, 0f, 2f, intensity, id, 7, facts);
[Fact]
public void Facts_are_remembered_as_last_sensed_and_cleared_on_forgetting_and_admission()
{
var p = Make(capacity: 1, memory: 0.05);
Sense(p, new[] { Fact(1, 0b101UL) });
Assert.Equal(0b101UL, p.Percept(0).Facts);
// Out of sight the facts stay as last sensed.
Sense(p, Array.Empty<Emitter>());
Assert.Equal(1UL, p.Percept(0).Id);
Assert.Equal(0b101UL, p.Percept(0).Facts);
// A fresh sensing replaces them.
Sense(p, new[] { Fact(1, 0b010UL) });
Assert.Equal(0b010UL, p.Percept(0).Facts);
// Forgetting clears them.
for (var i = 0; i < 20; i++) Sense(p, Array.Empty<Emitter>());
Assert.Equal(0UL, p.Percept(0).Id);
Assert.Equal(0UL, p.Percept(0).Facts);
// Another id taking the slot starts from 0 and then its own facts; an emitter with no facts reads 0.
Sense(p, new[] { Fact(2, 0b1UL) });
Sense(p, new[] { Fact(3, 0UL) });
Assert.Equal(3UL, p.Percept(0).Id);
Assert.Equal(0UL, p.Percept(0).Facts);
// Two emitters of one id with the same facts, on two channels, are fine.
Sense(p, new[] { Fact(3, 0b11UL), Fact(3, 0b11UL, channel: Channel.Visual) });
Assert.Equal(0b11UL, p.Percept(0).Facts);
// Eviction by a newcomer replaces the evicted thing's facts.
Sense(p, Array.Empty<Emitter>());
Sense(p, new[] { Fact(4, 0b100UL) });
Assert.Equal(4UL, p.Percept(0).Id);
Assert.Equal(0b100UL, p.Percept(0).Facts);
}
[Fact]
public void Sense_refuses_the_reach_bit_and_a_fact_disagreement_before_stepping()
{
var p = Make();
Sense(p, new[] { Fact(1, 0b1UL, intensity: 0.6) });
var load = p.Load;
var since = p.Percept(0).SecondsSinceSensed;
Assert.Throws<ArgumentException>(() => Sense(p, new[] { Fact(1, 0b1UL), Fact(2, Perception.InReachFact) }));
Assert.Throws<ArgumentException>(() => Sense(p, new[] { Fact(2, Perception.InReachFact | 1UL) }));
Assert.Throws<ArgumentException>(() => Sense(p, new[] { Fact(0, Perception.InReachFact) }));
Assert.Throws<ArgumentException>(() => Sense(p, new[] { Fact(1, 0b1UL), Fact(3, 0UL), Fact(1, 0b11UL) }));
Assert.Equal(load, p.Load);
Assert.Equal(since, p.Percept(0).SecondsSinceSensed);
Assert.Equal(0b1UL, p.Percept(0).Facts);
Assert.Equal(1, Occupied(p));
// The state did not step: the next good tick is the second, not the fifth.
Sense(p, Array.Empty<Emitter>());
Assert.Equal(Dt, p.Percept(0).SecondsSinceSensed);
// Anonymous emitters may disagree freely on facts; the top fact bit below 63 is the game's.
Sense(p, new[] { Fact(0, 1UL), Fact(0, 2UL), Fact(5, 1UL << 62) });
}
[Fact]
public void Percept_parameters_are_validated()
{
static void Build(PerceptParameters pp) =>
_ = new Perception(new NerveParameters(), Dt, 1, new NerveParameters(), 0, pp);
Build(new PerceptParameters { Capacity = 1, MemorySeconds = 0.0 });
Build(new PerceptParameters { Capacity = 256 });
Assert.Throws<ArgumentException>(() => Build(new PerceptParameters { Capacity = 0 }));
Assert.Throws<ArgumentException>(() => Build(new PerceptParameters { Capacity = 257 }));
Assert.Throws<ArgumentException>(() => Build(new PerceptParameters { MemorySeconds = -0.001 }));
Assert.Throws<ArgumentException>(() => Build(new PerceptParameters { MemorySeconds = double.NaN }));
Assert.Throws<ArgumentException>(() => Build(new PerceptParameters { MemorySeconds = double.PositiveInfinity }));
Assert.Equal(16, new PerceptParameters().Capacity);
Assert.Equal(5.0, new PerceptParameters().MemorySeconds);
// No senses, no percepts, whatever the parameters.
var deaf = new Perception(new NerveParameters(), Dt, 1);
Assert.Equal(0, deaf.PerceptCount);
Assert.Equal(4, Make().PerceptCount);
}
[Fact]
public void Sensing_with_percepts_allocates_nothing()
{
var p = Make(capacity: 4, memory: 0.05);
var near = new[] { At(1), At(2), At(3), At(4), At(5), At(5, 0.5f), At(0, 0.2f) };
var far = new[] { At(1, x: 9f), At(6) };
for (var i = 0; i < 50; i++) Sense(p, i % 2 == 0 ? near : far); // warm, and churn the table
var before = GC.GetAllocatedBytesForCurrentThread();
for (var i = 0; i < 10000; i++) Sense(p, i % 3 == 0 ? near : far);
Assert.Equal(0L, GC.GetAllocatedBytesForCurrentThread() - before);
}
[Fact]
public void The_actor_passes_percepts_through()
{
var nerve = new NerveParameters();
var senses = new NerveParameters { SensitisationGrowth = 0.0, ConductionDelaySeconds = 0.0 };
var actor = new Actor(Dt, 1, nerve, new WithdrawalParameters(), new DriveParameters(), PainBoxBrain.Make(0.5),
senses, 0, new PerceptParameters { Capacity = 3, MemorySeconds = 1.0 });
Assert.Equal(3, actor.PerceptCount);
var strengths = new float[2];
var targets = new Quat[2];
actor.Tick(Zero, Zero, Zero, NoBoxes, strengths, targets, new[] { At(42, 0.5f, 2f, 0.8, kind: 5) });
var seen = actor.Percept(0);
Assert.Equal(42UL, seen.Id);
Assert.Equal(5u, seen.Kind);
Assert.Equal(0.5f, seen.X);
Assert.True(seen.Salience > 0.0);
Assert.Equal(0UL, actor.Percept(1).Id);
var deaf = new Actor(Dt, 1, nerve, new WithdrawalParameters(), new DriveParameters(), PainBoxBrain.Make(0.5));
Assert.Equal(0, deaf.PerceptCount);
}
}

View file

@ -0,0 +1,82 @@
using Lodur;
namespace Lodur.Core.Tests;
public sealed class PerceptionTests
{
private static readonly float[] Zero = { 0f };
private static double AfferentAt(Perception p, BoxStimulus[] src)
{
p.Sense(Zero, Zero, Zero, src);
return p.Afferent(0);
}
[Theory]
[InlineData(0.01, 0.06, 6)]
[InlineData(0.005, 0.06, 12)]
[InlineData(0.01, 0.0, 1)]
public void Afferent_arrives_exactly_the_conduction_delay_after_a_step_stimulus(double dt, double delay, int ticks)
{
var p = new Perception(new NerveParameters { ConductionDelaySeconds = delay }, dt, 1);
var src = new[] { new BoxStimulus(0f, 0f, 0f, 1f, 1f, 1f, 0.05) }; // below the 0.1 threshold: nothing
for (var i = 0; i < 20; i++) Assert.Equal(0.0, AfferentAt(p, src));
src[0].Intensity = 0.8;
for (var i = 0; i < ticks; i++) Assert.Equal(0.0, AfferentAt(p, src)); // still in flight
Assert.True(AfferentAt(p, src) > 0.0); // arrives on tick `ticks`
}
[Fact]
public void A_sustained_stimulus_drives_sensitisation_to_its_cap_and_it_recovers_after()
{
var p = new Perception(new NerveParameters(), 0.01, 1);
var src = new[] { new BoxStimulus(0f, 0f, 0f, 1f, 1f, 1f, 0.8) };
double a = 0;
for (var i = 0; i < 20000; i++) a = AfferentAt(p, src);
Assert.Equal(0.7 * 2.0, a, 9); // (stimulus - threshold) * SensitisationCap
// Gone for 300 s: sensitisation is back near 1, so the same weak stimulus reads as weak.
src[0].Intensity = 0.0;
for (var i = 0; i < 30000; i++) AfferentAt(p, src);
src[0].Intensity = 0.15;
double first = 0;
for (var i = 0; i < 7; i++) first = AfferentAt(p, src);
Assert.InRange(first, 0.05, 0.0502);
// Gone for one second only: still sensitised.
var q = new Perception(new NerveParameters(), 0.01, 1);
src[0].Intensity = 0.8;
for (var i = 0; i < 20000; i++) AfferentAt(q, src);
src[0].Intensity = 0.0;
for (var i = 0; i < 100; i++) AfferentAt(q, src);
src[0].Intensity = 0.15;
for (var i = 0; i < 7; i++) first = AfferentAt(q, src);
Assert.True(first > 0.09);
}
[Fact]
public void A_point_outside_every_box_senses_zero_on_a_face_the_intensity_inside_two_the_larger()
{
var p = new Perception(new NerveParameters { ConductionDelaySeconds = 0.0 }, 0.01, 3);
var src = new[]
{
new BoxStimulus(0f, 0f, 0f, 1f, 1f, 1f, 0.4),
new BoxStimulus(0.5f, 0f, 0f, 1f, 1f, 1f, 0.9),
};
// outside both; on the face x = 1 of the first (inside the second); inside both
float[] x = { 5f, 1f, 0.2f }, y = { 0f, 0f, 0f }, z = { 0f, 0f, 0f };
p.Sense(x, y, z, src);
Assert.Equal(0.0, p.Stimulus(0));
Assert.Equal(0.9, p.Stimulus(1));
Assert.Equal(0.9, p.Stimulus(2));
src[1].Intensity = 0.0; // isolate the first box
p.Sense(x, y, z, src);
Assert.Equal(0.4, p.Stimulus(1)); // exactly on a face: inclusive
Assert.Equal(0.4, p.Stimulus(2));
x[1] = 1.0001f;
p.Sense(x, y, z, src);
Assert.Equal(0.0, p.Stimulus(1));
}
}

View file

@ -0,0 +1,143 @@
using Lodur;
namespace Lodur.Core.Tests;
/// <summary>A three-part, two-joint body and a plain physiology over it, for the tests that are about a rule rather than about the humanoid's content.</summary>
internal static class PhysioFixtures
{
public static BodyPlan Body3()
{
PartDef P(string label) => new(label, Side.Center, PartShape.Box, (0.1f, 0.1f, 0.1f), (0f, 0f, 0f), Quat.Identity, 1000f, 0.8f, 0f);
JointDef J(string label, int child) => new(label, Side.Center, JointKind.Spherical, 0, child, (0f, 0f, 0f), (0f, 1f, 0f), 0f, 0f, 0f, new MuscleGains(1f, 1f, 1f, 1f));
return new BodyPlan(new[] { P("Root"), P("A"), P("B") }, new[] { J("J0", 1), J("J1", 2) }, Array.Empty<SensePointDef>());
}
public const int BrainLayer = 0, Heart = 1, RootMuscle = 2;
private static Effect Const(EffectTarget t, EffectOp op, double v) => new(t, op, EffectDriver.Severity, new[] { (0.0, v), (1.0, v) });
private static AfflictionDef Def(string label, double rate, bool injures, PhysiologyClock clock, params Effect[] effects) => new(label, clock, rate, injures, effects);
public static readonly AfflictionDef[] Defs =
{
Def("Lesion", 0, true, PhysiologyClock.Acute),
Def("Mark", 0, false, PhysiologyClock.Acute),
Def("Heal", -1, true, PhysiologyClock.Acute),
Def("SlowHeal", -1, true, PhysiologyClock.Slow),
Def("Bleeder", 0, false, PhysiologyClock.Acute, new Effect(EffectTarget.Bleed, EffectOp.Offset, EffectDriver.Severity, new[] { (0.0, 0.0), (1.0, 1e-3) })),
Def("Dim", 0, false, PhysiologyClock.Acute, Const(EffectTarget.Consciousness, EffectOp.Offset, -0.1)),
Def("Halve", 0, false, PhysiologyClock.Acute, Const(EffectTarget.Consciousness, EffectOp.Factor, 0.5)),
Def("MotorHalf", 0, false, PhysiologyClock.Acute, Const(EffectTarget.Motor, EffectOp.Factor, 0.5)),
Def("Clot", 0, false, PhysiologyClock.Acute,
Const(EffectTarget.Bleed, EffectOp.Offset, 1e-3),
new Effect(EffectTarget.Bleed, EffectOp.Factor, EffectDriver.Age, new[] { (0.0, 1.0), (60.0, 0.5), (300.0, 0.1) })),
Def("MotorDim", 0, false, PhysiologyClock.Acute, Const(EffectTarget.Motor, EffectOp.Offset, -0.2)),
Def("Staunch", 0, false, PhysiologyClock.Acute, Const(EffectTarget.Bleed, EffectOp.Offset, -1e-3)),
Def("Fading", -0.1, false, PhysiologyClock.Acute, new Effect(EffectTarget.Bleed, EffectOp.Offset, EffectDriver.Severity, new[] { (0.0, 0.0), (1.0, 1e-5) })),
Def("SlowBleeder", 0, false, PhysiologyClock.Slow, new Effect(EffectTarget.Bleed, EffectOp.Offset, EffectDriver.Severity, new[] { (0.0, 0.0), (1.0, 1e-3) })),
// A test smothering: ventilation is zero until it lifts, 40 s at severity 1.
Def("Choke", -1.0 / 40.0, false, PhysiologyClock.Acute, Const(EffectTarget.Breathing, EffectOp.Factor, 0.0)),
};
public static int Af(string label)
{
for (var i = 0; i < Defs.Length; i++) if (Defs[i].Label == label) return i;
throw new ArgumentException(label);
}
public static BloodDef DefaultBlood => new(0.005, 0.5, 0.0);
/// <summary>The same literature-shaped placeholders as the humanoid's content.</summary>
public static RespirationDef DefaultRespiration => PhysiologyPlans.Humanoid().Respiration;
/// <summary>No liquid ever counts as at the airway: the airway stays empty and the hold is never wanted.</summary>
public static AirwayDef InertAirway => new(150e-6, 1.0, 1.0, 1.0, 1e9, 2.0, new[] { (0.3, 0.0), (0.6, 1.0) }, 0.1, 0.05);
/// <summary>A cough-free, drain-free airway with a breath that draws the liquid at the openings and holds at 1e-3 of it.</summary>
public static AirwayDef Quiet => new(150e-6, 1.0, 1.0, 1.0, 1e-3, 0.0, new[] { (0.0, 0.0), (1.0, 0.0) }, 0.0, 0.05);
public static Physiology Bleeding(double share, double gain, AirwayDef? airway = null, BloodDef? blood = null)
{
var root = new[]
{
new TissueDef("brain", 10, 1, Consciousness: 1),
new TissueDef("heart", 10, 4, true, BloodPumping: 1),
new TissueDef("muscle", 10, 1, Motor: 1) { AirwayShare = share },
};
var p = new Physiology(Body3(), Plan3(root: root, airway: airway ?? Quiet, blood: blood), 20.0, gain);
Assert.True(p.Afflict(Af("Bleeder"), 0, RootMuscle, 1));
return p;
}
/// <summary>The humanoid's hypoxia curve: brain oxygen to consciousness, flat 1 above 0.70.</summary>
public static Effect Hypoxia => new(EffectTarget.Consciousness, EffectOp.Factor, EffectDriver.BrainOxygen, new[] { (0.10, 0.0), (0.35, 0.1), (0.70, 1.0) });
/// <summary>Root: brain (weight 1), heart (pumping 1, vital unless asked otherwise), a muscle; A and B: a muscle each. Every tissue has Hp 10.</summary>
public static PhysiologyPlan Plan3(bool heartVital = true, BloodDef? blood = null, int slots = 8, IReadOnlyList<Effect>? organism = null, TissueDef[]? root = null, TissueDef[]? limbA = null, AirwayDef? airway = null)
{
var stack = root ?? new[]
{
new TissueDef("brain", 10, 1, Consciousness: 1),
new TissueDef("heart", 10, 4, heartVital, BloodPumping: 1),
new TissueDef("muscle", 10, 1, Motor: 1),
};
var limb = new[] { new TissueDef("muscle", 10, 1, Motor: 1) };
return new PhysiologyPlan(
new[] { new PartTissuesDef("Root", Side.Center, stack), new PartTissuesDef("A", Side.Center, limbA ?? limb), new PartTissuesDef("B", Side.Center, limb) },
Defs, organism ?? Array.Empty<Effect>(), blood ?? DefaultBlood, DefaultRespiration, airway ?? InertAirway, slots);
}
public static Physiology Make(double slowScale = 20.0, bool heartVital = true, BloodDef? blood = null, int slots = 8, IReadOnlyList<Effect>? organism = null, TissueDef[]? root = null, TissueDef[]? limbA = null) =>
new(Body3(), Plan3(heartVital, blood, slots, organism, root, limbA), slowScale);
/// <summary>
/// Body3 with a lung on the root (Breathing 1), the hypoxia curve, the humanoid's respiration and airway, and the test afflictions (Choke lifts at 40 s at severity 1;
/// the airway tests bind it at 1e9 to keep it). A real Actor over it needs a brain with a goal that reads air hunger: <see cref="StruggleBrain"/>.
/// </summary>
public static Physiology Breather(double slowScale = 20.0)
{
var h = PhysiologyPlans.Humanoid();
var root = new[]
{
new TissueDef("brain", 10, 1, Consciousness: 1),
new TissueDef("heart", 10, 4, true, BloodPumping: 1),
new TissueDef("lung", 10, 2, Breathing: 1),
new TissueDef("muscle", 10, 1, Motor: 1),
};
var limb = new[] { new TissueDef("muscle", 10, 1, Motor: 1) };
var plan = new PhysiologyPlan(
new[] { new PartTissuesDef("Root", Side.Center, root), new PartTissuesDef("A", Side.Center, limb), new PartTissuesDef("B", Side.Center, limb) },
Defs, new[] { Hypoxia }, DefaultBlood, h.Respiration, h.Airway, 8);
return new Physiology(Body3(), plan, slowScale);
}
/// <summary>The goal that hunger drives: rest holds the pose at 0.7; the struggle, eligible at air hunger 0.3 and above, outranks it, runs involuntary throughout (nothing to break) and loops the two poses at full strength.</summary>
public static Brain StruggleBrain() => new()
{
Goals = new[]
{
new GoalSpec
{
Id = "rest", Priority = 0.0,
Behaviour = new PoseBehaviour { Keys = new[] { PainBoxBrain.Hold }, FlinchPose = PainBoxBrain.Withdraw, Hold = new HoldParameters { HoldStrength = 0.7f } },
},
new GoalSpec
{
Id = "struggle", Priority = 1.0, InvoluntarySeconds = double.PositiveInfinity,
When = new[] { new Condition(DriveQuantity.AirHunger, ConditionOp.AtLeast, 0.3) },
Behaviour = new PoseBehaviour
{
Keys = new[] { PainBoxBrain.Hold, PainBoxBrain.Withdraw }, FlinchPose = PainBoxBrain.Withdraw, SecondsPerKey = 0.5,
Hold = new HoldParameters { HoldStrength = 1f, FlinchGain = 0.0, StrainShake = 0.0 },
},
},
},
};
public static int Live(Physiology p)
{
var n = 0;
for (var s = 0; s < p.SlotCount; s++) if (p.SlotDef(s) >= 0) n++;
return n;
}
}

View file

@ -0,0 +1,184 @@
using Lodur;
namespace Lodur.Core.Tests;
/// <summary>The physiology content is validated at construction, and resolved against a body plan by the Physiology: each rule refuses.</summary>
public sealed class PhysiologyPlanTests
{
private static readonly (double X, double Y)[] Ramp = { (0, 0), (1, 1) };
private static Effect Fx(EffectTarget t = EffectTarget.Consciousness, EffectDriver d = EffectDriver.BloodLoss, params (double X, double Y)[] curve) =>
new(t, EffectOp.Offset, d, curve.Length == 0 ? Ramp : curve);
private static BloodDef GoodBlood => new(0.005, 0.5, 0.001);
private static RespirationDef GoodRespiration => PhysioFixtures.DefaultRespiration;
private static PhysiologyPlan Plan(
IReadOnlyList<TissueDef>? tissues = null, IReadOnlyList<AfflictionDef>? afflictions = null,
IReadOnlyList<Effect>? organism = null, BloodDef? blood = null, int slots = 4, RespirationDef? respiration = null) =>
new(new[] { new PartTissuesDef("A", Side.Center, tissues ?? new[] { new TissueDef("brain", 10, 1, Consciousness: 1, Motor: 1) }) },
afflictions ?? new[] { new AfflictionDef("a", PhysiologyClock.Acute, 0, true, Array.Empty<Effect>()) },
organism ?? Array.Empty<Effect>(), blood ?? GoodBlood, respiration ?? GoodRespiration, PhysioFixtures.InertAirway, slots);
private static void Refuses(Action build) => Assert.Throws<ArgumentException>(build);
private static TissueDef Core(string label, TissueSite? site) => new TissueDef(label, 10, 1, Consciousness: 1, Motor: 1) { Site = site };
private static PartDef OnePart(PartShape shape, (float X, float Y, float Z) size) =>
new("A", Side.Center, shape, size, (0f, 0f, 0f), Quat.Identity, 1000f, 0.8f, 0f);
private static void ResolvesOnePart(PartShape shape, (float X, float Y, float Z) size, (float X, float Y, float Z) centre, bool inside)
{
var plan = Plan(new[] { new TissueDef("skin", 10, 1) { Thickness = 0.01 }, Core("core", new TissueSite(centre, 0.01f)) });
var body = new BodyPlan(new[] { OnePart(shape, size) }, Array.Empty<JointDef>(), Array.Empty<SensePointDef>());
if (inside) plan.Resolve(body);
else Assert.Throws<ArgumentException>(() => plan.Resolve(body));
}
[Fact]
public void Sites_are_validated()
{
Refuses(() => Plan(new[] { new TissueDef("skin", 10, 1) { Thickness = 0.01, Site = new TissueSite((0f, 0f, 0f), 0.01f) }, Core("core", null) }));
Refuses(() => Plan(new[] { Core("core", new TissueSite((0f, 0f, 0f), 0f)) }));
Refuses(() => Plan(new[] { Core("core", new TissueSite((0f, 0f, 0f), float.NaN)) }));
Refuses(() => Plan(new[] { Core("core", new TissueSite((float.NaN, 0f, 0f), 0.01f)) }));
Plan(new[] { Core("core", new TissueSite((0f, 0f, 0f), 0.01f)) });
}
[Fact]
public void Resolve_refuses_a_site_centre_outside_a_sphere_a_box_and_a_capsule_and_accepts_one_just_inside()
{
ResolvesOnePart(PartShape.Sphere, (0.1f, 0f, 0f), (0.099f, 0f, 0f), true);
ResolvesOnePart(PartShape.Sphere, (0.1f, 0f, 0f), (0.1f, 0f, 0f), false);
ResolvesOnePart(PartShape.Box, (0.1f, 0.2f, 0.3f), (0.099f, 0.199f, 0.299f), true);
ResolvesOnePart(PartShape.Box, (0.1f, 0.2f, 0.3f), (0.1f, 0f, 0f), false);
ResolvesOnePart(PartShape.Box, (0.1f, 0.2f, 0.3f), (0f, 0f, -0.3f), false);
ResolvesOnePart(PartShape.Capsule, (0.05f, 0.1f, 0f), (0f, 0.149f, 0f), true);
ResolvesOnePart(PartShape.Capsule, (0.05f, 0.1f, 0f), (0f, 0.15f, 0f), false);
ResolvesOnePart(PartShape.Capsule, (0.05f, 0.1f, 0f), (0.049f, 0f, 0f), true);
ResolvesOnePart(PartShape.Capsule, (0.05f, 0.1f, 0f), (0.05f, 0f, 0f), false);
}
[Fact]
public void A_well_formed_plan_constructs_and_finds_afflictions_by_label()
{
var plan = Plan(organism: new[] { Fx() });
Assert.Equal(0, plan.AfflictionIndex("a"));
Assert.Throws<ArgumentException>(() => plan.AfflictionIndex("b"));
}
[Fact]
public void A_curve_is_piecewise_linear_clamped_at_the_ends_and_an_equal_x_pair_is_a_step_that_holds_its_later_value_from_x()
{
var ramp = Fx(curve: new[] { (0.0, 0.0), (2.0, 1.0) });
Assert.Equal(0.0, ramp.Eval(-5));
Assert.Equal(0.25, ramp.Eval(0.5));
Assert.Equal(1.0, ramp.Eval(2));
Assert.Equal(1.0, ramp.Eval(9));
var step = Fx(curve: new[] { (0.0, 0.0), (0.15, 0.0), (0.15, -0.1), (0.30, -0.1) });
Assert.Equal(0.0, step.Eval(0.1499));
Assert.Equal(-0.1, step.Eval(0.15));
Assert.Equal(-0.1, step.Eval(1.0));
}
[Fact]
public void Each_validation_rule_refuses()
{
var t = new TissueDef("t", 10, 1, Consciousness: 1, Motor: 1);
Refuses(() => Plan(new[] { t, t })); // duplicate tissue label
Refuses(() => Plan(new[] { t with { Label = "" } })); // empty tissue label
Refuses(() => Plan(new[] { t with { Hp = 0 } }));
Refuses(() => Plan(new[] { t with { Hp = double.NaN } }));
Refuses(() => Plan(new[] { t with { Hp = double.PositiveInfinity } }));
Refuses(() => Plan(new[] { t with { Vascularity = -1 } }));
Refuses(() => Plan(new[] { t with { Vascularity = double.NaN } }));
Refuses(() => Plan(new[] { t with { Consciousness = -1 } }));
Refuses(() => Plan(new[] { t with { BloodPumping = double.NaN } }));
Refuses(() => Plan(new[] { t with { Motor = double.PositiveInfinity } }));
var sheet = new SheetDef(0.1, 1e-4, 1e-3, 1e6);
var shell = t with { Label = "shell", Thickness = 0.01, Sheet = sheet };
Refuses(() => Plan(new[] { t with { Thickness = -1 } }));
Refuses(() => Plan(new[] { t with { Thickness = double.NaN } }));
Refuses(() => Plan(new[] { t with { Thickness = double.PositiveInfinity } }));
Refuses(() => Plan(new[] { t with { Sheet = sheet } })); // a sheet on Thickness 0
Refuses(() => Plan(new[] { shell with { Sheet = sheet with { Spacing = 0 } } }));
Refuses(() => Plan(new[] { shell with { Sheet = sheet with { Spacing = double.NaN } } }));
Refuses(() => Plan(new[] { shell with { Sheet = sheet with { Spacing = double.PositiveInfinity } } }));
Refuses(() => Plan(new[] { shell with { Sheet = sheet with { EdgeCompliance = -1 } } }));
Refuses(() => Plan(new[] { shell with { Sheet = sheet with { EdgeCompliance = double.PositiveInfinity } } }));
Refuses(() => Plan(new[] { shell with { Sheet = sheet with { EdgeCompliance = double.NaN } } }));
Refuses(() => Plan(new[] { shell with { Sheet = sheet with { AttachCompliance = -1 } } }));
Refuses(() => Plan(new[] { shell with { Sheet = sheet with { AttachCompliance = double.PositiveInfinity } } }));
Refuses(() => Plan(new[] { shell with { Sheet = sheet with { TensileStrength = 0 } } }));
Refuses(() => Plan(new[] { shell with { Sheet = sheet with { TensileStrength = double.NaN } } }));
Refuses(() => Plan(new[] { shell with { Sheet = sheet with { TensileStrength = double.PositiveInfinity } } }));
Refuses(() => Plan(new[] { t, shell })); // a shell after a core
var vessel = t with { Label = "vessel", Site = new TissueSite((0f, 0f, 0f), 0.01f) };
Plan(new[] { vessel, shell }); // a sited tissue may precede a shell: stack order is depth order
Refuses(() => Plan(new[] { t, vessel, shell })); // a shell after an unsited core, a sited tissue between or not
var a = new AfflictionDef("a", PhysiologyClock.Acute, 0, true, Array.Empty<Effect>());
Refuses(() => Plan(afflictions: new[] { a, a })); // duplicate affliction label
Refuses(() => Plan(afflictions: new[] { a with { Label = "" } }));
Refuses(() => Plan(afflictions: new[] { a with { SeverityRate = double.NaN } }));
Refuses(() => Plan(afflictions: new[] { a with { Effects = new[] { new Effect(EffectTarget.Consciousness, EffectOp.Offset, EffectDriver.Severity, Array.Empty<(double X, double Y)>()) } } }));
Refuses(() => Plan(afflictions: new[] { a with { Effects = new[] { Fx(curve: new[] { (1.0, 0.0), (0.5, 0.0) }) } } })); // x decreases
Refuses(() => Plan(afflictions: new[] { a with { Effects = new[] { Fx(curve: new[] { (0.0, double.NaN) }) } } }));
Refuses(() => Plan(afflictions: new[] { a with { Effects = new[] { Fx(curve: new[] { (double.PositiveInfinity, 0.0) }) } } }));
Refuses(() => Plan(organism: new[] { Fx(d: EffectDriver.Severity) })); // a driver only an affliction has
Refuses(() => Plan(organism: new[] { Fx(d: EffectDriver.Age) }));
Refuses(() => Plan(organism: new[] { Fx(t: EffectTarget.Bleed) })); // a target only an affliction has
Refuses(() => Plan(organism: new[] { Fx(t: EffectTarget.Motor) }));
Refuses(() => Plan(new[] { new TissueDef("brain", 10, 1, Consciousness: 1, Motor: 1, Breathing: -1) }));
Refuses(() => Plan(new[] { new TissueDef("brain", 10, 1, Consciousness: 1, Motor: 1, Breathing: double.NaN) }));
Refuses(() => Plan(respiration: GoodRespiration with { UptakePerSecond = -1 }));
Refuses(() => Plan(respiration: GoodRespiration with { BasalUsePerSecond = -1 }));
Refuses(() => Plan(respiration: GoodRespiration with { ArousalUse = double.NaN }));
Refuses(() => Plan(respiration: GoodRespiration with { EffortUse = double.PositiveInfinity }));
Refuses(() => Plan(respiration: GoodRespiration with { BrainSeconds = 0 }));
Refuses(() => Plan(respiration: GoodRespiration with { BrainSeconds = double.NaN }));
Refuses(() => Plan(blood: GoodBlood with { NominalVolume = 0 }));
Refuses(() => Plan(blood: GoodBlood with { NominalVolume = double.NaN }));
Refuses(() => Plan(blood: GoodBlood with { LethalLossFraction = 0 }));
Refuses(() => Plan(blood: GoodBlood with { LethalLossFraction = 1.5 }));
Refuses(() => Plan(blood: GoodBlood with { RegenPerSecond = -1 }));
Refuses(() => Plan(slots: 0));
}
[Fact]
public void A_positional_tissue_has_no_thickness_and_no_sheet_and_zero_compliance_is_accepted()
{
var t = new TissueDef("t", 10, 1, Consciousness: 1, Motor: 1);
Assert.Equal(0.0, t.Thickness);
Assert.Null(t.Sheet);
Plan(new[] { t });
Plan(new[] { t with { Label = "s", Thickness = 0.01, Sheet = new SheetDef(0.1, 0, 0, 1) }, t });
}
[Fact]
public void An_affliction_may_use_every_driver_and_the_boundary_values_of_the_rules_are_accepted()
{
var effects = new[] { Fx(EffectTarget.Bleed, EffectDriver.Severity), Fx(EffectTarget.Motor, EffectDriver.Age), Fx(EffectTarget.Consciousness, EffectDriver.BloodLoss), Fx(EffectTarget.Consciousness, EffectDriver.BrainOxygen), Fx(curve: new[] { (1.0, 0.0), (1.0, 1.0) }) };
Plan(afflictions: new[] { new AfflictionDef("a", PhysiologyClock.Slow, -1, false, effects) }, blood: GoodBlood with { LethalLossFraction = 1, RegenPerSecond = 0 }, slots: 1);
Plan(organism: new[] { Fx(EffectTarget.Breathing, EffectDriver.BrainOxygen) }); // organism: a capacity driven by a store
Plan(organism: new[] { Fx(EffectTarget.BloodPumping, EffectDriver.BloodLoss) });
}
[Fact]
public void The_plan_owns_a_copy_of_what_it_was_given()
{
var curve = new List<(double X, double Y)> { (0, 0), (1, 1) };
var tissues = new List<TissueDef> { new("t", 10, 1, Consciousness: 1, Motor: 1) };
var plan = Plan(tissues, organism: new[] { new Effect(EffectTarget.Consciousness, EffectOp.Offset, EffectDriver.BloodLoss, curve) });
curve[1] = (1, double.NaN);
tissues.Clear();
Assert.Equal(1.0, plan.OrganismEffects[0].Eval(1));
Assert.Single(plan.Parts[0].Tissues);
}
}

View file

@ -0,0 +1,182 @@
using Lodur;
namespace Lodur.Core.Tests;
/// <summary>The humanoid's physiology content resolves against the humanoid body and behaves as the content says.</summary>
public sealed class PhysiologyPlansTests
{
private static readonly BodyPlan Body = BodyPlans.Humanoid();
private static Physiology Spawn() => new(Body, PhysiologyPlans.Humanoid(), 20);
private static int Cut => PhysiologyPlans.Humanoid().AfflictionIndex("Cut");
private static int Bruise => PhysiologyPlans.Humanoid().AfflictionIndex("Bruise");
[Fact]
public void The_humanoid_resolves_and_spawns_whole()
{
var p = Spawn();
Assert.Equal(Body.Joints.Count, p.JointCount);
Assert.Equal(1.0, p.Consciousness);
Assert.Equal(1.0, p.BloodPumping);
Assert.Equal(0.005, p.BloodVolume);
for (var j = 0; j < p.JointCount; j++) Assert.Equal(1.0, p.MotorCeiling(j));
Assert.False(p.Dead);
}
[Fact]
public void The_brain_is_vital_the_heart_is_not_and_a_skull_is_not()
{
var head = Body.PartIndex("Head");
var torso = Body.PartIndex("Torso");
var brain = Spawn();
Assert.True(brain.Afflict(Cut, head, brain.TissueIndex(head, "Brain"), 11));
brain.Step(0.01);
Assert.Equal(DeathCause.VitalTissue, brain.Cause);
var heart = Spawn();
Assert.True(heart.Afflict(Cut, torso, heart.TissueIndex(torso, "Heart"), 16));
heart.Step(0.01);
Assert.False(heart.Dead); // a stopped heart kills through brain oxygen and consciousness (ruling bds-heart-stop-stagger)
Assert.Equal(DeathCause.None, heart.Cause);
var skull = Spawn();
Assert.True(skull.Afflict(Bruise, head, skull.TissueIndex(head, "Skull"), 26));
skull.Step(0.01);
Assert.False(skull.Dead);
Assert.Equal(0.0, skull.Integrity(head, skull.TissueIndex(head, "Skull")));
var lung = Spawn();
Assert.True(lung.Afflict(Bruise, torso, lung.TissueIndex(torso, "LungLeft"), 16));
lung.Step(0.01);
Assert.False(lung.Dead); // a lung carries Breathing, not a vital flag; one lost still breathes
}
[Fact]
public void Every_side_of_every_limb_has_its_own_stack()
{
var p = Spawn();
foreach (var side in new[] { Side.Left, Side.Right })
{
var shin = Body.PartIndex("Shin", side);
Assert.True(p.Afflict(Bruise, shin, p.TissueIndex(shin, "Tibia"), 26));
}
p.Step(0.01);
Assert.Equal(0.0, p.Integrity(Body.PartIndex("Shin", Side.Left), p.TissueIndex(Body.PartIndex("Shin", Side.Left), "Tibia")));
Assert.Equal(0.0, p.Integrity(Body.PartIndex("Shin", Side.Right), p.TissueIndex(Body.PartIndex("Shin", Side.Right), "Tibia")));
Assert.Equal(1.0, p.Integrity(Body.PartIndex("Thigh", Side.Left), 0));
}
[Fact]
public void The_humanoid_stacks_carry_skin_everywhere_muscle_sheets_on_six_kinds_and_fat_as_thickness()
{
var plan = PhysiologyPlans.Humanoid();
var stacks = plan.Resolve(Body);
var sheetKinds = new[] { "Pelvis", "Torso", "UpperArm", "LowerArm", "Thigh", "Shin" };
var fatKinds = new HashSet<string>(sheetKinds) { "Head" };
var muscleSheets = 0;
var fats = 0;
for (var p = 0; p < Body.Parts.Count; p++)
{
var label = Body.Parts[p].Label;
var tissues = plan.Parts[stacks[p]].Tissues;
var skin = tissues[0];
Assert.Equal("Skin", skin.Label);
Assert.NotNull(skin.Sheet);
Assert.Equal(0.00256, skin.Thickness);
Assert.Equal(21.6e6, skin.Sheet!.Value.TensileStrength);
var fat = tissues.Count > 1 && tissues[1].Label == "Fat";
Assert.Equal(fatKinds.Contains(label), fat);
if (fat)
{
fats++;
Assert.True(tissues[1].Thickness > 0.0);
Assert.Null(tissues[1].Sheet);
Assert.Equal(skin.Hp, tissues[1].Hp);
}
var muscleSheet = tissues.Any(t => t.Label == "Muscle" && t.Sheet != null);
var shells = 1 + (fat ? 1 : 0) + (muscleSheet ? 1 : 0);
Assert.Equal(shells, tissues.Count(t => t.Thickness > 0.0));
var lastShell = tissues.ToList().FindLastIndex(t => t.Thickness > 0.0);
for (var l = 0; l < lastShell; l++) Assert.True(tissues[l].Thickness > 0.0 || tissues[l].Site != null, $"{label}: an unsited core precedes a shell"); // only a sited tissue (a vessel) sits among the shells
Assert.Equal(Array.IndexOf(sheetKinds, label) >= 0, muscleSheet);
if (muscleSheet) muscleSheets++;
}
Assert.Equal(10, muscleSheets);
Assert.Equal(11, fats);
}
[Fact]
public void Blood_loss_stages_drop_consciousness_by_the_ruled_steps()
{
var p = Spawn();
var torso = Body.PartIndex("Torso");
var muscle = p.TissueIndex(torso, "Muscle");
for (var i = 0; i < 3; i++) Assert.True(p.Afflict(Cut, torso, muscle, 100)); // 3 x 100 HP of cut: a wound far past the muscle's 40
void ReachAndRead(double loss, double expected)
{
for (var i = 0; i < 100000 && p.BloodLoss < loss; i++) p.Step(0.01);
Assert.False(p.Dead);
Assert.True(p.BloodLoss >= loss && p.BloodLoss < loss + 0.05, $"loss {p.BloodLoss}");
p.Step(0.01); // the next step reads the blood the last one left
Assert.Equal(expected, p.Consciousness, 12);
}
// 0.5 x 0.16 of the nominal volume lost reads the 0.15 stage; 0.31 reads the 0.30 stage.
ReachAndRead(0.16, 0.9);
ReachAndRead(0.31, 0.8);
}
[Fact]
public void A_cut_bleeds_and_clots_and_a_bruise_does_not_bleed()
{
var p = Spawn();
var torso = Body.PartIndex("Torso");
var muscle = p.TissueIndex(torso, "Muscle");
Assert.True(p.Afflict(Bruise, torso, muscle, 40));
p.Step(0.01);
Assert.Equal(0.0, p.Bleed(torso));
Assert.True(p.Afflict(Cut, torso, muscle, 20));
p.Step(0.01);
var fresh = p.Bleed(torso);
Assert.InRange(fresh, 1.9e-5, 2e-5); // 1 mL/s per HP of severity (2e-5 m^3/s at 20), x vascularity 1 x pumping 1, a hair clotted
for (var i = 0; i < 600; i++) p.Step(0.1); // 60 real seconds: the clot factor has fallen to a half
Assert.False(p.Dead);
Assert.True(p.Bleed(torso) > 0.0 && p.Bleed(torso) < fresh * 0.55);
}
[Fact]
public void A_cut_bleeds_and_clots_in_real_seconds_whatever_the_slow_scale()
{
(double Bleed3, double Lost60) Run(double scale)
{
var p = new Physiology(Body, PhysiologyPlans.Humanoid(), scale);
var torso = Body.PartIndex("Torso");
Assert.True(p.Afflict(Cut, torso, p.TissueIndex(torso, "Muscle"), 10));
var at3 = 0.0;
for (var i = 1; i <= 1200; i++)
{
p.Step(0.05);
if (i == 60) at3 = p.Bleed(torso);
}
Assert.False(p.Dead);
return (at3, 0.005 - p.BloodVolume);
}
var one = Run(1);
var twenty = Run(20);
Assert.InRange(one.Bleed3, 9.5e-6, 9.9e-6); // about 9.7 mL/s at 3 s: 10 HP x 1 mL/s, a hair clotted
Assert.InRange(one.Lost60, 4.4e-4, 4.6e-4); // about 450 mL in 60 s
Assert.Equal(one.Bleed3, twenty.Bleed3);
Assert.Equal(one.Lost60, twenty.Lost60);
}
}

View file

@ -0,0 +1,716 @@
using Lodur;
using static Lodur.Core.Tests.PhysioFixtures;
namespace Lodur.Core.Tests;
/// <summary>The Physiology's rules: resolution against a body, integrity from injuries, capacities, the clocks, bleeding, death, the bounded table.</summary>
public sealed class PhysiologyTests
{
private static void Afflict(Physiology p, string label, int part, int layer, double severity) =>
Assert.True(p.Afflict(Af(label), part, layer, severity));
// Resolution against a body.
private static BodyPlan Tiny()
{
PartDef P(string label) => new(label, Side.Center, PartShape.Box, (0.1f, 0.1f, 0.1f), (0f, 0f, 0f), Quat.Identity, 1000f, 0.8f, 0f);
var joint = new JointDef("J", Side.Center, JointKind.Spherical, 0, 1, (0f, 0f, 0f), (0f, 1f, 0f), 0f, 0f, 0f, new MuscleGains(1f, 1f, 1f, 1f));
return new BodyPlan(new[] { P("Root"), P("Kid") }, new[] { joint }, Array.Empty<SensePointDef>());
}
private static PartTissuesDef Stack(string part, params TissueDef[] tissues) => new(part, Side.Center, tissues);
private static PhysiologyPlan Over(params PartTissuesDef[] parts) =>
new(parts, Array.Empty<AfflictionDef>(), Array.Empty<Effect>(), DefaultBlood, DefaultRespiration, InertAirway, 4);
private static readonly TissueDef BrainT = new("brain", 10, 1, Consciousness: 1);
private static readonly TissueDef MuscleT = new("muscle", 10, 1, Motor: 1);
[Fact]
public void A_physiology_resolves_a_plan_whose_stacks_cover_the_body_parts_exactly()
{
var ok = new Physiology(Tiny(), Over(Stack("Root", BrainT), Stack("Kid", MuscleT)), 20);
Assert.Equal(1, ok.JointCount);
Assert.Equal(1.0, ok.Consciousness);
Assert.Equal(1.0, ok.MotorCeiling(0));
}
[Fact]
public void A_physiology_refuses_a_body_part_with_no_stack_a_stack_naming_no_part_and_a_part_with_two_stacks()
{
Assert.Throws<ArgumentException>(() => new Physiology(Tiny(), Over(Stack("Root", BrainT)), 20));
Assert.Throws<ArgumentException>(() => new Physiology(Tiny(), Over(Stack("Root", BrainT), Stack("Kid", MuscleT), Stack("Ghost", MuscleT)), 20));
Assert.Throws<ArgumentException>(() => new Physiology(Tiny(), Over(Stack("Root", BrainT), Stack("Kid", MuscleT), Stack("Kid", MuscleT)), 20));
Assert.Throws<ArgumentException>(() => new Physiology(Tiny(),
Over(Stack("Root", BrainT), Stack("Kid", MuscleT) with { Side = Side.Left }), 20)); // the side is part of the name
}
[Fact]
public void Resolve_maps_each_body_part_to_its_stack()
{
Assert.Equal(new[] { 1, 0 }, Over(Stack("Kid", MuscleT), Stack("Root", BrainT)).Resolve(Tiny()));
}
[Fact]
public void Resolve_refuses_the_join_rules_itself()
{
var body = Tiny();
Assert.Throws<ArgumentException>(() => Over(Stack("Root", BrainT)).Resolve(body));
Assert.Throws<ArgumentException>(() => Over(Stack("Root", BrainT), Stack("Kid", MuscleT), Stack("Ghost", MuscleT)).Resolve(body));
Assert.Throws<ArgumentException>(() => Over(Stack("Root", BrainT), Stack("Kid", MuscleT), Stack("Kid", MuscleT)).Resolve(body));
}
[Fact]
public void Shells_must_fit_inside_the_part_by_its_smallest_half_extent()
{
PhysiologyPlan Shelled(double t) => Over(Stack("Root", BrainT with { Thickness = t }), Stack("Kid", MuscleT));
Assert.Throws<ArgumentException>(() => Shelled(0.1).Resolve(Tiny()));
Assert.Throws<ArgumentException>(() => Shelled(0.2).Resolve(Tiny()));
Shelled(0.0999).Resolve(Tiny());
PartDef Slab(string label) => new(label, Side.Center, PartShape.Box, (0.1f, 0.02f, 0.1f), (0f, 0f, 0f), Quat.Identity, 1000f, 0.8f, 0f);
var joint = new JointDef("J", Side.Center, JointKind.Spherical, 0, 1, (0f, 0f, 0f), (0f, 1f, 0f), 0f, 0f, 0f, new MuscleGains(1f, 1f, 1f, 1f));
var slab = new BodyPlan(new[] { Slab("Root"), Slab("Kid") }, new[] { joint }, Array.Empty<SensePointDef>());
Assert.Throws<ArgumentException>(() => Shelled(0.03).Resolve(slab));
Shelled(0.019).Resolve(slab);
}
private static BodyPlan RootOf(PartShape shape, (float X, float Y, float Z) size)
{
PartDef P(string label, PartShape sh, (float X, float Y, float Z) sz) => new(label, Side.Center, sh, sz, (0f, 0f, 0f), Quat.Identity, 1000f, 0.8f, 0f);
var joint = new JointDef("J", Side.Center, JointKind.Spherical, 0, 1, (0f, 0f, 0f), (0f, 1f, 0f), 0f, 0f, 0f, new MuscleGains(1f, 1f, 1f, 1f));
return new BodyPlan(new[] { P("Root", shape, size), P("Kid", PartShape.Box, (0.1f, 0.1f, 0.1f)) }, new[] { joint }, Array.Empty<SensePointDef>());
}
private static PhysiologyPlan Layered(params double[] shells)
{
var tissues = new TissueDef[shells.Length + 1];
for (var i = 0; i < shells.Length; i++) tissues[i] = new TissueDef("s" + i, 10, 1) with { Thickness = shells[i] };
tissues[shells.Length] = BrainT;
return Over(Stack("Root", tissues), Stack("Kid", MuscleT));
}
[Fact]
public void Every_shell_counts_and_every_box_axis_bounds_the_fit()
{
var cube = RootOf(PartShape.Box, (0.1f, 0.1f, 0.1f));
Layered(0.04, 0.04).Resolve(cube);
Assert.Throws<ArgumentException>(() => Layered(0.06, 0.06).Resolve(cube)); // the sum, not the first or the largest
Assert.Throws<ArgumentException>(() => Layered(0.01, 0.05, 0.05).Resolve(cube)); // the last shell counts
foreach (var thin in new[] { (0.02f, 0.1f, 0.1f), (0.1f, 0.02f, 0.1f), (0.1f, 0.1f, 0.02f) })
{
var body = RootOf(PartShape.Box, thin);
Layered(0.019).Resolve(body);
Assert.Throws<ArgumentException>(() => Layered(0.03).Resolve(body));
}
}
[Fact]
public void A_capsule_and_a_sphere_fit_shells_inside_the_radius()
{
foreach (var body in new[] { RootOf(PartShape.Capsule, (0.1f, 0.5f, 0f)), RootOf(PartShape.Sphere, (0.1f, 0f, 0f)) })
{
Layered(0.0999).Resolve(body);
Assert.Throws<ArgumentException>(() => Layered(0.1).Resolve(body));
Assert.Throws<ArgumentException>(() => Layered(0.06, 0.06).Resolve(body));
}
}
[Fact]
public void A_physiology_refuses_a_body_with_no_consciousness_tissue_or_a_joint_child_with_no_motor_tissue()
{
Assert.Throws<ArgumentException>(() => new Physiology(Tiny(), Over(Stack("Root", MuscleT), Stack("Kid", MuscleT)), 20));
Assert.Throws<ArgumentException>(() => new Physiology(Tiny(), Over(Stack("Root", BrainT), Stack("Kid", BrainT)), 20));
}
[Fact]
public void A_physiology_refuses_a_slow_scale_that_is_not_finite_and_above_zero()
{
foreach (var bad in new[] { 0.0, -1.0, double.NaN, double.PositiveInfinity })
{
Assert.Throws<ArgumentException>(() => new Physiology(Tiny(), Over(Stack("Root", BrainT), Stack("Kid", MuscleT)), bad));
}
}
// Integrity.
[Fact]
public void Integrity_is_derived_from_the_injuries_bound_to_a_tissue()
{
var p = Make();
Afflict(p, "Lesion", 1, 0, 3);
Afflict(p, "Lesion", 1, 0, 2); // a second instance, never merged
Assert.Equal(2, Live(p));
Assert.Equal(1.0, p.Integrity(1, 0)); // nothing has stepped: integrity is a step's output
p.Step(0.01);
Assert.Equal(0.5, p.Integrity(1, 0));
Assert.Equal(1.0, p.Integrity(2, 0));
Assert.Equal(1.0, p.Integrity(0, p.TissueIndex(0, "brain")));
}
[Fact]
public void An_affliction_that_does_not_injure_leaves_integrity_whole()
{
var p = Make();
Afflict(p, "Mark", 1, 0, 9);
p.Step(0.01);
Assert.Equal(1.0, p.Integrity(1, 0));
}
[Fact]
public void Healing_to_zero_severity_frees_the_slot_and_restores_integrity()
{
var p = Make();
Afflict(p, "Heal", 1, 0, 1.0); // rate -1 per second
p.Step(0.5);
Assert.Equal(0.95, p.Integrity(1, 0), 12);
Assert.Equal(1, Live(p));
p.Step(0.5); // severity reaches 0: freed
Assert.Equal(0, Live(p));
Assert.Equal(1.0, p.Integrity(1, 0));
}
[Fact]
public void A_wound_past_the_tissues_hp_leaves_integrity_at_zero_not_below()
{
var p = Make();
Afflict(p, "Lesion", 1, 0, 25);
p.Step(0.01);
Assert.Equal(0.0, p.Integrity(1, 0));
Assert.Equal(0.0, p.MotorCeiling(0));
}
[Fact]
public void Afflict_refuses_a_severity_that_is_not_finite_and_above_zero_and_names_that_are_not_there()
{
var p = Make();
foreach (var bad in new[] { 0.0, -1.0, double.NaN, double.PositiveInfinity })
{
Assert.Throws<ArgumentException>(() => p.Afflict(Af("Lesion"), 1, 0, bad));
}
Assert.Throws<ArgumentException>(() => p.Afflict(-1, 1, 0, 1));
Assert.Throws<ArgumentException>(() => p.Afflict(Defs.Length, 1, 0, 1));
Assert.Throws<ArgumentException>(() => p.Afflict(0, 3, 0, 1));
Assert.Throws<ArgumentException>(() => p.Afflict(0, 1, 1, 1));
Assert.Throws<ArgumentException>(() => p.Afflict(0, 1, -1, 1));
Assert.Throws<ArgumentException>(() => p.TissueIndex(1, "brain"));
Assert.Equal(0, Live(p));
Assert.Equal(0, p.Refused);
}
// Capacities.
[Fact]
public void Capacities_fold_offsets_then_factors()
{
var p = Make();
var brain = p.TissueIndex(0, "brain");
Afflict(p, "Lesion", 0, brain, 6);
p.Step(0.01);
Assert.Equal(0.4, p.Consciousness, 12);
Afflict(p, "Dim", 0, brain, 1); // Offset -0.1
Afflict(p, "Halve", 0, brain, 1); // Factor 0.5
p.Step(0.01);
Assert.Equal((0.4 - 0.1) * 0.5, p.Consciousness, 12); // not 0.4 x 0.5 - 0.1
}
[Fact]
public void A_capacity_is_the_weighted_mean_integrity_of_the_tissues_that_carry_it()
{
var root = new[]
{
new TissueDef("left", 10, 1, Consciousness: 1),
new TissueDef("right", 10, 1, Consciousness: 3),
new TissueDef("skin", 10, 1, Motor: 1),
new TissueDef("heart", 10, 4, BloodPumping: 1),
};
var p = Make(root: root);
Afflict(p, "Lesion", 0, 0, 5); // left at 0.5, right whole
p.Step(0.01);
Assert.Equal((0.5 * 1 + 1.0 * 3) / 4, p.Consciousness, 12);
Assert.Equal(1.0, p.BloodPumping);
Afflict(p, "Lesion", 0, 2, 10); // a tissue with no consciousness weight does not touch it
p.Step(0.01);
Assert.Equal((0.5 * 1 + 1.0 * 3) / 4, p.Consciousness, 12);
}
[Fact]
public void Blood_pumping_is_one_when_no_tissue_pumps()
{
var p = Make(root: new[] { new TissueDef("brain", 10, 1, Consciousness: 1), new TissueDef("muscle", 10, 1, Motor: 1) });
Afflict(p, "Bleeder", 0, 1, 1);
p.Step(0.01);
Assert.Equal(1.0, p.BloodPumping);
Assert.Equal(1e-3, p.Bleed(0), 15);
}
[Fact]
public void An_organism_effect_reads_the_blood_loss_as_the_step_began()
{
var organism = new[] { new Effect(EffectTarget.Consciousness, EffectOp.Offset, EffectDriver.BloodLoss, new[] { (0.0, 0.0), (0.2, 0.0), (0.2, -0.3), (1.0, -0.3) }) };
var p = Make(organism: organism);
Afflict(p, "Bleeder", 2, 0, 1);
while (p.BloodLoss < 0.2) p.Step(0.01);
Assert.True(p.Consciousness == 1.0, "the step that crosses the stage has not read it yet");
p.Step(0.01);
Assert.Equal(0.7, p.Consciousness, 12);
}
// Motor ceiling.
[Fact]
public void The_motor_ceiling_is_the_child_parts_integrity_and_its_effects_times_consciousness()
{
var p = Make();
Afflict(p, "Lesion", 1, 0, 4); // A's muscle at 0.6
Afflict(p, "MotorHalf", 2, 0, 1); // Factor 0.5 on B
p.Step(0.01);
Assert.Equal(0.6, p.MotorCeiling(0), 12);
Assert.Equal(0.5, p.MotorCeiling(1), 12);
Afflict(p, "Lesion", 0, BrainLayer, 4); // consciousness 0.6 scales every ceiling
p.Step(0.01);
Assert.Equal(0.6, p.Consciousness, 12);
Assert.Equal(0.6 * 0.6, p.MotorCeiling(0), 12);
Assert.Equal(0.5 * 0.6, p.MotorCeiling(1), 12);
}
[Fact]
public void A_motor_effect_binds_to_the_part_it_was_afflicted_on_not_to_the_body()
{
var p = Make();
Afflict(p, "MotorHalf", 1, 0, 1);
p.Step(0.01);
Assert.Equal(0.5, p.MotorCeiling(0));
Assert.Equal(1.0, p.MotorCeiling(1));
Assert.Equal(1.0, p.Consciousness);
}
[Fact]
public void A_motor_ceiling_is_the_motor_weighted_mean_then_offsets_then_factors()
{
var a = new[] { new TissueDef("light", 10, 1, Motor: 1), new TissueDef("heavy", 10, 1, Motor: 3) };
var p = Make(limbA: a);
Afflict(p, "Lesion", 1, 0, 10); // the light layer is gone: (1 x 0 + 3 x 1) / 4
p.Step(0.01);
Assert.Equal(0.75, p.MotorCeiling(0), 12);
Afflict(p, "MotorDim", 1, 0, 1); // offset -0.2
Afflict(p, "MotorHalf", 1, 0, 1); // factor 0.5
p.Step(0.01);
Assert.Equal((0.75 - 0.2) * 0.5, p.MotorCeiling(0), 12); // offsets before factors
Assert.Equal(1.0, p.MotorCeiling(1));
}
// Clocks.
[Fact]
public void A_slow_affliction_moves_on_the_scaled_clock_and_an_acute_one_on_the_callers()
{
var p = Make(slowScale: 20);
Afflict(p, "SlowHeal", 1, 0, 5);
Afflict(p, "Heal", 2, 0, 5);
for (var i = 0; i < 10; i++) p.Step(0.01);
var slow = 0;
var acute = 0;
for (var s = 0; s < p.SlotCount; s++)
{
if (p.SlotDef(s) == Af("SlowHeal")) slow = s;
if (p.SlotDef(s) == Af("Heal")) acute = s;
}
Assert.Equal(5 - 10 * 20 * 1 * 0.01, p.SlotSeverity(slow), 12);
Assert.Equal(5 - 10 * 1 * 0.01, p.SlotSeverity(acute), 12);
Assert.Equal(10 * 20 * 0.01, p.SlotAge(slow), 12); // age counts the clock's seconds
Assert.Equal(10 * 0.01, p.SlotAge(acute), 12);
}
[Fact]
public void Bleeding_is_real_time_whatever_the_slow_scale()
{
double Remaining(double scale)
{
var p = Make(slowScale: scale);
Afflict(p, "Bleeder", 1, 0, 1);
for (var i = 0; i < 200; i++) p.Step(0.01);
return p.BloodVolume;
}
Assert.Equal(Remaining(1), Remaining(20));
Assert.Equal(0.005 - 1e-3 * 2.0, Remaining(1), 12);
}
[Fact]
public void Blood_regrows_only_while_nothing_bleeds_and_on_the_slow_clock()
{
double Regrown(double scale)
{
var p = Make(slowScale: scale, blood: DefaultBlood with { RegenPerSecond = 1e-5 });
Afflict(p, "Fading", 1, 0, 1); // bleeds, shrinking by 0.1 severity per second, until it is gone
var last = p.BloodVolume;
while (Live(p) > 0)
{
p.Step(0.01);
if (Live(p) > 0) Assert.True(p.BloodVolume <= last, "blood grew while something bled");
last = p.BloodVolume;
}
var settled = p.BloodVolume;
for (var i = 0; i < 100; i++) p.Step(0.01);
Assert.True(p.BloodVolume < 0.005);
return (p.BloodVolume - settled) / scale;
}
Assert.Equal(1e-5 * 0.005 * 100 * 0.01, Regrown(1), 12);
Assert.Equal(Regrown(1), Regrown(20), 12);
}
[Fact]
public void Regrowth_is_capped_at_the_nominal_volume()
{
var p = Make(blood: DefaultBlood with { RegenPerSecond = 10 });
Afflict(p, "Fading", 1, 0, 1);
for (var i = 0; i < 2000; i++) p.Step(0.01);
Assert.Equal(0.005, p.BloodVolume);
}
// Bleeding.
[Fact]
public void Volume_falls_by_the_sum_of_the_parts_bleed_times_dt()
{
var p = Make();
Afflict(p, "Bleeder", 1, 0, 1);
Afflict(p, "Bleeder", 2, 0, 0.5);
Afflict(p, "Bleeder", 0, RootMuscle, 0.25);
for (var i = 0; i < 20; i++)
{
var before = p.BloodVolume;
p.Step(0.05);
var sum = p.Bleed(0) + p.Bleed(1) + p.Bleed(2);
Assert.Equal(before - sum * 0.05, p.BloodVolume, 15);
}
Assert.Equal(1e-3, p.Bleed(1), 15); // severity 1 x vascularity 1 x pumping 1
Assert.Equal(1e-3 * 0.5, p.Bleed(2), 15);
Assert.Equal(1e-3 * 0.25, p.Bleed(0), 15);
}
[Fact]
public void Bleeding_goes_through_the_tissues_vascularity()
{
var p = Make();
Afflict(p, "Bleeder", 0, Heart, 1); // the heart's vascularity is 4
Afflict(p, "Bleeder", 0, RootMuscle, 1); // the muscle's is 1
p.Step(0.01);
Assert.Equal(1e-3 * 4 + 1e-3, p.Bleed(0), 15);
}
[Fact]
public void An_affliction_never_bleeds_negatively_nor_cancels_another_afflictions_bleed()
{
var p = Make();
Afflict(p, "Staunch", 1, 0, 1);
p.Step(0.01);
Assert.Equal(0.0, p.Bleed(1));
Assert.Equal(0.005, p.BloodVolume);
Afflict(p, "Bleeder", 1, 0, 1);
p.Step(0.01);
Assert.Equal(1e-3, p.Bleed(1), 15); // the staunch slot clamps at 0 on its own; it does not subtract from the bleeder
}
[Fact]
public void A_dead_body_reads_the_dying_steps_bleed_and_then_none()
{
var p = Make();
Afflict(p, "Bleeder", 1, 0, 1);
Afflict(p, "Lesion", 0, BrainLayer, 10); // consciousness 0: dead on this step, the heart still pumping
p.Step(0.01);
Assert.True(p.Dead);
Assert.Equal(DeathCause.Consciousness, p.Cause);
Assert.Equal(1e-3, p.Bleed(1), 15); // the dying step's own bleed: the last Step that ran
p.Step(0.01);
Assert.Equal(0.0, p.Bleed(1)); // a Step on the dead zeroes the flows
}
[Fact]
public void A_reused_slot_starts_at_age_zero()
{
var p = Make();
Afflict(p, "Heal", 1, 0, 0.5); // slot 0, healed away in one second
p.Step(1.0);
Assert.Equal(0, Live(p));
Afflict(p, "Clot", 1, 0, 1); // reuses slot 0
Assert.Equal(Af("Clot"), p.SlotDef(0));
Assert.Equal(0.0, p.SlotAge(0));
p.Step(0.01);
Assert.Equal(0.01, p.SlotAge(0), 15);
}
[Fact]
public void Bleeding_reads_the_pumping_so_a_stopped_non_vital_heart_bleeds_nothing()
{
var p = Make(heartVital: false);
Afflict(p, "Bleeder", 1, 0, 1);
p.Step(0.01);
Assert.Equal(1e-3, p.Bleed(1), 15);
Afflict(p, "Lesion", 0, Heart, 10);
p.Step(0.01);
Assert.False(p.Dead);
Assert.Equal(0.0, p.BloodPumping);
Assert.Equal(0.0, p.Bleed(1));
var v = p.BloodVolume;
p.Step(0.01);
Assert.Equal(v, p.BloodVolume);
}
[Fact]
public void An_age_factor_halves_a_bleed_at_its_age()
{
var p = Make(blood: new BloodDef(10.0, 0.5, 0.0));
Afflict(p, "Clot", 1, 0, 1);
for (var i = 0; i < 60; i++) p.Step(1.0);
Assert.Equal(0.5e-3, p.Bleed(1), 15);
for (var i = 0; i < 240; i++) p.Step(1.0);
Assert.Equal(0.1e-3, p.Bleed(1), 15);
}
// Death.
[Fact]
public void A_vital_tissue_at_zero_integrity_kills_on_that_step_and_one_short_is_alive()
{
var p = Make();
Afflict(p, "Lesion", 0, Heart, 9.5);
p.Step(0.01);
Assert.False(p.Dead);
Assert.Equal(DeathCause.None, p.Cause);
Assert.Equal(-1, p.DiedAtStep);
Afflict(p, "Lesion", 0, Heart, 0.5);
p.Step(0.01);
Assert.True(p.Dead);
Assert.Equal(DeathCause.VitalTissue, p.Cause);
Assert.Equal(1, p.DiedAtStep);
}
[Fact]
public void Blood_loss_to_the_lethal_fraction_kills_with_that_cause()
{
var p = Make();
Afflict(p, "Bleeder", 1, 0, 1);
for (var i = 0; i < 100 && !p.Dead; i++)
{
Assert.True(p.BloodLoss < 1.0);
p.Step(0.1);
}
Assert.True(p.Dead);
Assert.Equal(DeathCause.BloodLoss, p.Cause);
Assert.True(p.BloodLoss >= 1.0 && p.BloodLoss < 1.1);
}
[Fact]
public void A_non_vital_brain_at_zero_integrity_kills_by_consciousness_and_one_short_is_alive()
{
var p = Make();
Afflict(p, "Lesion", 0, BrainLayer, 9.5);
p.Step(0.01);
Assert.False(p.Dead);
Assert.Equal(0.05, p.Consciousness, 12);
Afflict(p, "Lesion", 0, BrainLayer, 0.5);
p.Step(0.01);
Assert.True(p.Dead);
Assert.Equal(DeathCause.Consciousness, p.Cause);
}
[Fact]
public void Consciousness_driven_to_zero_by_effects_kills_too_and_the_first_rule_names_the_cause()
{
var p = Make(slots: 16);
for (var i = 0; i < 10; i++) Afflict(p, "Dim", 0, BrainLayer, 1);
p.Step(0.01);
Assert.False(p.Dead); // ten offsets of -0.1 leave a hair above zero in doubles
Afflict(p, "Dim", 0, BrainLayer, 1);
p.Step(0.01);
Assert.True(p.Dead);
Assert.Equal(DeathCause.Consciousness, p.Cause);
var both = Make();
Afflict(both, "Lesion", 0, BrainLayer, 10);
Afflict(both, "Lesion", 0, Heart, 10);
both.Step(0.01);
Assert.Equal(DeathCause.VitalTissue, both.Cause); // the vital rule comes first
}
[Fact]
public void When_several_rules_hold_in_one_step_the_first_in_the_ruled_order_names_the_cause()
{
// One 3 s step: a 1 mL/s bleed loses 3 mL of a 5 mL body (past the lethal half) while the brain is wiped out.
var vitalBrain = new[] { new TissueDef("brain", 10, 1, Vital: true, Consciousness: 1), new TissueDef("heart", 10, 4, BloodPumping: 1), new TissueDef("muscle", 10, 1, Motor: 1) };
var vital = Make(root: vitalBrain);
Afflict(vital, "Bleeder", 1, 0, 1);
Afflict(vital, "Lesion", 0, 0, 10);
vital.Step(3.0);
Assert.True(vital.BloodLoss >= 1.0);
Assert.Equal(DeathCause.VitalTissue, vital.Cause); // vital before blood
var plain = Make();
Afflict(plain, "Bleeder", 1, 0, 1);
Afflict(plain, "Lesion", 0, BrainLayer, 10);
plain.Step(3.0);
Assert.True(plain.BloodLoss >= 1.0 && plain.Consciousness == 0.0);
Assert.Equal(DeathCause.BloodLoss, plain.Cause); // blood before consciousness
}
[Fact]
public void Death_is_permanent_and_limp_and_nothing_changes_after_it_but_the_table_still_takes_wounds()
{
var p = Make();
Afflict(p, "Bleeder", 1, 0, 1);
Afflict(p, "Clot", 2, 0, 1);
Afflict(p, "Lesion", 0, Heart, 10);
p.Step(0.01);
Assert.True(p.Dead);
Assert.Equal(0, p.DiedAtStep);
Assert.Equal(0.0, p.Consciousness);
Assert.Equal(0.0, p.BloodPumping);
Assert.Equal(0.0, p.Bleed(1)); // the heart is the cause here: pumping 0 on the dying step, so nothing bleeds
Assert.Equal(0.0, p.MotorCeiling(0));
Assert.Equal(0.0, p.MotorCeiling(1));
var volume = p.BloodVolume;
var severity = new double[p.SlotCount];
var age = new double[p.SlotCount];
for (var s = 0; s < p.SlotCount; s++) { severity[s] = p.SlotSeverity(s); age[s] = p.SlotAge(s); }
var integrity = p.Integrity(0, Heart);
for (var i = 0; i < 100; i++) p.Step(1.0);
Assert.Equal(0.0, p.Bleed(1)); // one Step on the dead zeroes the flows
Assert.Equal(volume, p.BloodVolume);
Assert.Equal(0, p.DiedAtStep);
Assert.Equal(DeathCause.VitalTissue, p.Cause);
for (var s = 0; s < p.SlotCount; s++) { Assert.Equal(severity[s], p.SlotSeverity(s)); Assert.Equal(age[s], p.SlotAge(s)); }
Assert.Equal(integrity, p.Integrity(0, Heart));
Assert.True(p.Afflict(Af("Lesion"), 1, 0, 1)); // the wound is recorded, nothing steps
Assert.Equal(4, Live(p));
p.Step(1.0);
Assert.Equal(1.0, p.Integrity(1, 0));
}
// The table.
[Fact]
public void A_full_table_refuses_the_next_wound_and_overwrites_nothing()
{
var p = Make(slots: 4);
for (var i = 0; i < 4; i++) Assert.True(p.Afflict(Af("Lesion"), 1, 0, 1 + i));
Assert.False(p.Afflict(Af("Lesion"), 1, 0, 50));
Assert.Equal(1, p.Refused);
for (var s = 0; s < 4; s++) Assert.Equal(1.0 + s, p.SlotSeverity(s));
Assert.False(p.Afflict(Af("Lesion"), 2, 0, 50));
Assert.Equal(2, p.Refused);
p.Step(0.01);
Assert.Equal(0.0, p.Integrity(1, 0)); // 1+2+3+4 = 10 of 10
Assert.Equal(1.0, p.Integrity(2, 0));
}
[Fact]
public void A_freed_slot_takes_the_next_wound()
{
var p = Make(slots: 1);
Assert.True(p.Afflict(Af("Heal"), 1, 0, 0.5));
Assert.False(p.Afflict(Af("Lesion"), 1, 0, 1));
p.Step(1.0);
Assert.Equal(0, Live(p));
Assert.True(p.Afflict(Af("Lesion"), 1, 0, 1));
}
private static readonly TissueDef[] TwoLayers = { new("skin", 10, 1), new("muscle", 10, 1, Motor: 1) };
[Fact]
public void A_span_afflict_is_all_or_none()
{
var p = Make(slots: 3, limbA: TwoLayers);
Assert.True(p.Afflict(Af("Lesion"), 0, 0, 1));
Assert.True(p.Afflict(Af("Lesion"), 0, 1, 2)); // one free slot, two layers
Assert.False(p.Afflict(Af("Lesion"), 1, new[] { 0, 1 }, 5));
Assert.Equal(1, p.Refused);
Assert.Equal(2, Live(p));
Assert.Equal(-1, p.SlotDef(2));
var q = Make(slots: 2, limbA: TwoLayers); // exactly enough
Assert.True(q.Afflict(Af("Lesion"), 1, new[] { 1, 0 }, 5));
Assert.Equal(0, q.Refused);
Assert.Equal(2, Live(q));
Assert.Equal(5.0, q.SlotSeverity(0));
Assert.Equal(5.0, q.SlotSeverity(1));
Assert.False(q.Afflict(Af("Lesion"), 1, new[] { 0 }, 5));
Assert.Equal(1, q.Refused);
}
[Fact]
public void A_healed_slot_is_free_to_the_span_call()
{
var p = Make(slots: 3, limbA: TwoLayers);
Assert.True(p.Afflict(Af("Heal"), 1, 0, 0.5));
Assert.True(p.Afflict(Af("Lesion"), 0, 0, 1));
Assert.True(p.Afflict(Af("Lesion"), 0, 1, 1));
Assert.False(p.Afflict(Af("Lesion"), 1, new[] { 0, 1 }, 1)); // full
p.Step(1.0); // Heal is gone, its slot is free
Assert.Equal(2, Live(p));
Assert.False(p.Afflict(Af("Lesion"), 1, new[] { 0, 1 }, 1)); // one free, two wanted
Assert.Equal(2, p.Refused);
Assert.True(p.Afflict(Af("Lesion"), 1, new[] { 1 }, 1));
Assert.Equal(3, Live(p));
}
[Fact]
public void A_bad_or_repeated_layer_throws_before_any_write()
{
var p = Make(slots: 8, limbA: TwoLayers);
var lesion = Af("Lesion");
Assert.Throws<ArgumentException>(() => p.Afflict(lesion, 1, new[] { 0, 2 }, 1));
Assert.Throws<ArgumentException>(() => p.Afflict(lesion, 1, new[] { 0, -1 }, 1));
Assert.Throws<ArgumentException>(() => p.Afflict(lesion, 1, new[] { 0, 1, 0 }, 1));
Assert.Throws<ArgumentException>(() => p.Afflict(lesion, 1, ReadOnlySpan<int>.Empty, 1));
Assert.Throws<ArgumentException>(() => p.Afflict(lesion, 9, new[] { 0 }, 1));
Assert.Throws<ArgumentException>(() => p.Afflict(lesion, 1, new[] { 0, 1 }, 0));
Assert.Throws<ArgumentException>(() => p.Afflict(99, 1, new[] { 0, 1 }, 1));
Assert.Equal(0, Live(p));
Assert.Equal(0, p.Refused);
}
// Determinism.
private static (long Volume, long Consciousness, long Motor) Bits(Physiology p) =>
(BitConverter.DoubleToInt64Bits(p.BloodVolume), BitConverter.DoubleToInt64Bits(p.Consciousness), BitConverter.DoubleToInt64Bits(p.MotorCeiling(0)));
[Fact]
public void Two_identical_runs_agree_bit_for_bit_every_step()
{
Physiology Run()
{
var p = Make(slowScale: 20, blood: new BloodDef(1.0, 0.5, 1e-4));
Afflict(p, "Bleeder", 1, 0, 0.7);
Afflict(p, "Clot", 2, 0, 1);
Afflict(p, "SlowHeal", 0, BrainLayer, 3);
Afflict(p, "Fading", 0, RootMuscle, 1);
return p;
}
var a = Run();
var b = Run();
for (var i = 0; i < 3000; i++)
{
a.Step(0.01);
b.Step(0.01);
Assert.Equal(Bits(a), Bits(b));
}
Assert.True(a.BloodVolume < 1.0 && !a.Dead);
Assert.True(a.Consciousness > 0.9);
}
}

View file

@ -0,0 +1,343 @@
using System;
using System.Collections.Generic;
using System.Linq;
using Lodur;
namespace Lodur.Core.Tests;
/// <summary>
/// The planner against a forward breadth-first reference that shares none of its machinery: random small worlds, the same
/// depth, the same answer. The reference also picks, among all plans of the shallowest length, the one the spec orders first.
/// </summary>
public sealed class PlannerEquivalenceTests
{
private const int Slots = 4;
private const int Depth = 4;
private const int Reach = 63;
private static readonly float[] Zero = { 0f };
private readonly record struct Step(int Verb, int This, int Tool);
private sealed class World
{
public Perception Perception = null!;
public Verb[] Verbs = null!;
public ulong SelfFacts;
public ulong[] Start = null!; // thing 0 is self, thing 1 + s is slot s, the reach bit derived
public uint[] Kind = null!;
public int WantThing;
public int WantBit;
public bool WantValue;
}
private static Fact Fact(FactSubject s, int bit, bool v) => new(s, bit, v);
private static Fact[] RandomFacts(Random rng, int count, bool hasTool, bool selfAllowed, int reachOneIn)
{
var chosen = new List<Fact>();
for (var i = 0; i < count; i++)
{
var subject = (FactSubject)rng.Next(hasTool ? 3 : 2);
if (subject == FactSubject.Self && !selfAllowed)
{
subject = FactSubject.This;
}
var bit = subject != FactSubject.Self && rng.Next(reachOneIn) == 0 ? Reach : rng.Next(4);
if (chosen.Any(f => f.Subject == subject && f.Bit == bit))
{
continue;
}
chosen.Add(Fact(subject, bit, rng.Next(2) == 0));
}
return chosen.ToArray();
}
private static TargetFilter? RandomFilter(Random rng, int chance)
{
if (rng.Next(100) >= chance)
{
return null;
}
var kinds = new List<uint> { (uint)(1 + rng.Next(3)) };
if (rng.Next(2) == 0)
{
kinds.Add((uint)(1 + rng.Next(3)));
}
return new TargetFilter { Kinds = kinds.ToArray() };
}
private static World Generate(Random rng)
{
var w = new World { Kind = new uint[Slots] };
var things = 3 + rng.Next(2);
var emitters = new List<Emitter>();
w.Start = new ulong[Slots + 1];
for (var i = 0; i < things; i++)
{
var kind = (uint)(1 + rng.Next(3));
var facts = (ulong)rng.Next(16);
var x = rng.Next(3) switch { 0 => 0.5f, 1 => 1.2f, _ => 5f };
emitters.Add(new Emitter(Channel.Visual, x, 0f, 0f, 100f, 1.0, (ulong)(10 + i), kind, facts));
}
w.Perception = new Perception(new NerveParameters(), 0.01, 1,
new NerveParameters { Threshold = 0.05, SensitisationGrowth = 0.0, ConductionDelaySeconds = 0.0 }, 0,
new PerceptParameters { Capacity = Slots, MemorySeconds = 5.0 });
w.Perception.Sense(Zero, Zero, Zero, Array.Empty<BoxStimulus>(), emitters.ToArray());
w.SelfFacts = (ulong)rng.Next(16);
w.Start[0] = w.SelfFacts;
for (var s = 0; s < Slots; s++)
{
var p = w.Perception.Percept(s);
w.Kind[s] = p.Kind;
w.Start[s + 1] = p.Id == 0 ? 0UL : (p.Facts & ~Perception.InReachFact) | (p.X * p.X <= 1.0 ? Perception.InReachFact : 0UL);
}
var verbs = new List<Verb>();
for (var v = 0; v < 2 + rng.Next(5); v++)
{
var tool = RandomFilter(rng, 30);
verbs.Add(new Verb
{
Id = "v" + v,
This = RandomFilter(rng, 60),
Tool = tool,
Needs = RandomFacts(rng, rng.Next(4), tool is not null, true, 3),
Gives = RandomFacts(rng, 1 + rng.Next(3), tool is not null, false, 4).DefaultIfEmpty(Fact(FactSubject.This, 0, true)).ToArray(),
});
}
w.Verbs = verbs.ToArray();
var occupied = Enumerable.Range(0, Slots).Where(s => w.Perception.Percept(s).Id != 0).ToArray();
if (rng.Next(2) == 0)
{
w.WantThing = 0;
w.WantBit = rng.Next(4);
}
else
{
w.WantThing = 1 + occupied[rng.Next(occupied.Length)];
w.WantBit = rng.Next(2) == 0 ? Reach : rng.Next(4);
}
w.WantValue = rng.Next(2) == 0;
return w;
}
private static bool Holds(ulong[] state, int thing, int bit, bool value) => (((state[thing] >> bit) & 1UL) != 0UL) == value;
private static IEnumerable<Step> Groundings(World w)
{
for (var v = 0; v < w.Verbs.Length; v++)
{
var verb = w.Verbs[v];
for (var a = 0; a < Slots; a++)
{
if (w.Perception.Percept(a).Id == 0 || (verb.This is not null && !verb.This.Kinds.Contains(w.Kind[a])))
{
continue;
}
if (verb.Tool is null)
{
yield return new Step(v, a, -1);
continue;
}
for (var b = 0; b < Slots; b++)
{
if (b != a && w.Perception.Percept(b).Id != 0 && verb.Tool.Kinds.Contains(w.Kind[b]))
{
yield return new Step(v, a, b);
}
}
}
}
}
private static int ThingOf(Fact f, Step s) => f.Subject == FactSubject.Self ? 0 : 1 + (f.Subject == FactSubject.This ? s.This : s.Tool);
// The reach test of the start state and of a move alike: squared distance of the remembered positions against reach squared.
private static bool Near(World w, int a, int b)
{
Percept pa = w.Perception.Percept(a), pb = w.Perception.Percept(b);
double dx = pa.X - pb.X, dy = pa.Y - pb.Y, dz = pa.Z - pb.Z;
return dx * dx + dy * dy + dz * dz <= 1.0;
}
// moves: a verb with a This give of reach true takes every other thing out of reach unless it is near the verb's This.
private static ulong[]? Apply(World w, ulong[] state, Step s, bool moves = true)
{
var verb = w.Verbs[s.Verb];
foreach (var n in verb.Needs)
{
if (!Holds(state, ThingOf(n, s), n.Bit, n.Value))
{
return null;
}
}
var next = (ulong[])state.Clone();
// The move first, then the verb's own gives: a give of reach on a thing is a literal and stands.
if (moves && verb.Gives.Any(g => g.Subject == FactSubject.This && g.Bit == Reach && g.Value))
{
for (var o = 0; o < Slots; o++)
{
if (o != s.This && w.Perception.Percept(o).Id != 0)
{
next[o + 1] = Near(w, o, s.This) ? next[o + 1] | Perception.InReachFact : next[o + 1] & ~Perception.InReachFact;
}
}
}
foreach (var g in verb.Gives)
{
var thing = ThingOf(g, s);
next[thing] = g.Value ? next[thing] | (1UL << g.Bit) : next[thing] & ~(1UL << g.Bit);
}
return next;
}
private static string Key(ulong[] state) => string.Join(",", state);
// The shallowest plan length by breadth-first search over states, or -1 past the depth.
private static int Shallowest(World w, List<Step> all, bool moves = true)
{
var frontier = new List<ulong[]> { w.Start };
var seen = new HashSet<string> { Key(w.Start) };
for (var d = 0; d <= Depth; d++)
{
if (frontier.Any(s => Holds(s, w.WantThing, w.WantBit, w.WantValue)))
{
return d;
}
var next = new List<ulong[]>();
foreach (var state in frontier)
{
foreach (var step in all)
{
var n = Apply(w, state, step, moves);
if (n is not null && seen.Add(Key(n)))
{
next.Add(n);
}
}
}
frontier = next;
}
return -1;
}
// The first plan of exactly n steps in the spec's order: the last step's (verb, This, Tool) ascending first, then the step before it.
private static Step[]? First(World w, List<Step> all, int n, bool moves = true)
{
var chosen = new Step[n];
return Choose(n) ? chosen : null;
// Fills chosen from the last step backwards; once every step is chosen, replays them forward.
bool Choose(int left)
{
if (left == 0)
{
var state = w.Start;
foreach (var step in chosen)
{
var next = Apply(w, state, step, moves);
if (next is null)
{
return false;
}
state = next;
}
return Holds(state, w.WantThing, w.WantBit, w.WantValue);
}
foreach (var step in all)
{
chosen[left - 1] = step;
if (Choose(left - 1))
{
return true;
}
}
return false;
}
}
private static string Dump(World w, PlanStep[] plan, int n) =>
Environment.NewLine + string.Join(Environment.NewLine, w.Verbs.Select(v => $"{v.Id} this={(v.This is null ? "-" : string.Join(",", v.This.Kinds))} tool={(v.Tool is null ? "-" : string.Join(",", v.Tool.Kinds))} needs={string.Join(",", v.Needs.Select(f => $"{f.Subject}{f.Bit}{f.Value}"))} gives={string.Join(",", v.Gives.Select(f => $"{f.Subject}{f.Bit}{f.Value}"))}"))
+ $"{Environment.NewLine}start={Key(w.Start)} kinds={string.Join(",", w.Kind)} want={w.WantThing}/{w.WantBit}/{w.WantValue} plan={string.Join(" ", plan.Take(Math.Max(n, 0)))} xs={string.Join(",", Enumerable.Range(0, Slots).Select(q => w.Perception.Percept(q).X))}";
[Fact]
public void The_plan_is_sound_complete_and_shallowest_against_a_forward_search_on_4000_random_worlds()
{
var rng = new Random(20261125);
int solved = 0, none = 0, ordered = 0, changed = 0;
var plan = new PlanStep[Depth];
for (var i = 0; i < 4000; i++)
{
var w = Generate(rng);
var all = Groundings(w).ToList();
var expected = Shallowest(w, all);
if (expected != Shallowest(w, all, moves: false))
{
changed++;
}
var planner = new Planner(w.Verbs, Slots, Depth, 1.0);
var targetSlot = w.WantThing == 0 ? 0 : w.WantThing - 1;
var want = new Fact(w.WantThing == 0 ? FactSubject.Self : FactSubject.This, w.WantBit, w.WantValue);
var n = planner.Plan(w.Perception, w.SelfFacts, 0f, 0f, 0f, targetSlot, want, Depth, plan);
Assert.True(n == expected, $"world {i}: planner {n}, forward search {expected}{Dump(w, plan, n)}");
Assert.True(planner.LastNodes <= Planner.NodeBudget, $"world {i} spent the budget{Dump(w, plan, n)}");
if (n < 0)
{
none++;
continue;
}
solved++;
var slotOf = Enumerable.Range(0, Slots).ToDictionary(s => w.Perception.Percept(s).Id, s => s);
var steps = new Step[n];
var state = w.Start;
for (var k = 0; k < n; k++)
{
steps[k] = new Step(plan[k].Verb, slotOf[plan[k].This], plan[k].Tool == 0UL ? -1 : slotOf[plan[k].Tool]);
var next = Apply(w, state, steps[k]);
Assert.True(next is not null, $"world {i}: step {k} is not applicable");
state = next!;
}
Assert.True(Holds(state, w.WantThing, w.WantBit, w.WantValue), $"world {i}: the plan does not reach the want");
if (n <= 3 && n > 0)
{
ordered++;
var first = First(w, all, n)!;
Assert.True(first.SequenceEqual(steps), $"world {i}: tie order, planner {string.Join(" ", steps)} against {string.Join(" ", first)}");
if (expected == Shallowest(w, all, moves: false) && First(w, all, n, moves: false) is { } without && !without.SequenceEqual(first))
{
changed++;
}
}
}
Assert.True(solved > 1000 && none > 500 && ordered > 100, $"the worlds are too one-sided: {solved} solved, {none} none, {ordered} ordered");
Assert.True(changed > 50, $"the move rule changes the plan or verdict of only {changed} worlds");
}
}

View file

@ -0,0 +1,426 @@
using System;
using System.Collections.Generic;
using Lodur;
namespace Lodur.Core.Tests;
/// <summary>
/// A futile direct try ends (ruling bds-unplannable-tries-direct): after FrustrationSeconds at PlanLength -1 the Actor bars the pair's direct try, reports Frustrated and decides again
/// past the dwell; the bar ends when the target is forgotten or after RetrySeconds, and a pair that becomes plannable is offered through it; a changed fact does not lift it (ruling frustration-lifts-without-fact-changes).
/// </summary>
public sealed class PlannerFrustrationTests
{
private const uint Door = 1, Knife = 3;
private const int Open = 0, Locked = 1, Latched = 2, Held = 3, Fed = 4, Noise = 5;
private const int Reach = 63;
private const double Dt = 0.01;
private const int Latency = 10;
private static readonly float[] Zero = { 0f };
private static readonly BoxStimulus[] NoBoxes = Array.Empty<BoxStimulus>();
private static readonly Emitter[] None = Array.Empty<Emitter>();
private static Fact Self(int bit, bool v = true) => new(FactSubject.Self, bit, v);
private static Fact This(int bit, bool v = true) => new(FactSubject.This, bit, v);
private static Fact Tool(int bit, bool v = true) => new(FactSubject.Tool, bit, v);
private static TargetFilter Kinds(params uint[] kinds) => new() { Kinds = kinds };
private static Verb[] Catalogue() => new[]
{
new Verb { Id = "Approach", Gives = new[] { This(Reach) } },
new Verb { Id = "Unlock", This = Kinds(Door), Needs = new[] { This(Reach), This(Locked) }, Gives = new[] { This(Locked, false) } },
new Verb { Id = "Unlatch", This = Kinds(Door), Needs = new[] { This(Reach), This(Latched) }, Gives = new[] { This(Latched, false) } },
new Verb { Id = "Open", This = Kinds(Door), Needs = new[] { This(Reach), This(Locked, false), This(Latched, false) }, Gives = new[] { This(Open) } },
new Verb { Id = "Calm", This = Kinds(Knife), Needs = new[] { This(Reach) }, Gives = new[] { Self(Fed) } },
};
// A knife held in the hand pries any door open in two steps (approach, pry); with no knife there is no plan at all.
private static Verb[] WithPry() => new[]
{
new Verb { Id = "Approach", Gives = new[] { This(Reach) } },
new Verb { Id = "Pry", This = Kinds(Door), Tool = Kinds(Knife), Needs = new[] { Tool(Held), This(Reach) }, Gives = new[] { This(Open) } },
};
private static GoalSpec Goal(string id, double priority, TargetFilter? target = null, Fact? want = null, double dwell = 0.0) => new()
{
Id = id, Priority = priority, Target = target, Want = want, MinDwellSeconds = dwell,
Behaviour = new PoseBehaviour { Keys = new[] { PainBoxBrain.Hold }, FlinchPose = PainBoxBrain.Withdraw },
};
private static Emitter Thing(ulong id, uint kind, float x, ulong facts = 0UL) =>
new(Channel.Visual, x, 0f, 0f, 100f, 1.0, id, kind, facts);
private static Emitter BoltedDoor(ulong facts = 0UL) => Thing(1, Door, 6f, (1UL << Locked) | (1UL << Latched) | facts);
// Idle (1) against the door goal (3, direct at the discount 0.5: 1.5); the bolted door is four steps from open, past a depth of 3.
private static Brain Make(double frustration = 1.0, double retry = 30.0, int depth = 3, double dwell = 0.0) => new()
{
PlanDepth = depth, DirectDiscount = 0.5, FrustrationSeconds = frustration, RetrySeconds = retry,
Goals = new[] { Goal("idle", 1.0), Goal("open", 3.0, Kinds(Door), This(Open), dwell) },
};
private static Actor Build(Brain brain, double memory = 5.0, IReadOnlyList<Verb>? verbs = null) =>
new(Dt, 1, new NerveParameters(), new WithdrawalParameters(), new DriveParameters(), brain,
new NerveParameters { Threshold = 0.05, SensitisationGrowth = 0.0, ConductionDelaySeconds = 0.0 }, 0,
new PerceptParameters { Capacity = 8, MemorySeconds = memory }, verbs: verbs ?? Catalogue());
private sealed class Bench
{
public readonly Actor A;
public readonly float[] Strengths = new float[2];
public readonly Quat[] Targets = new Quat[2];
public readonly List<long> Frustrated = new();
public Bench(Actor a) => A = a;
public long Now => A.TickCount;
public TickEvents Step(Emitter[] emitters, ulong selfFacts = 0UL)
{
var t = A.TickCount;
var events = A.Tick(Zero, Zero, Zero, NoBoxes, Strengths, Targets, emitters, selfFacts: selfFacts);
if ((events & TickEvents.Frustrated) != 0)
{
Frustrated.Add(t);
}
return events;
}
public void Run(int ticks, Emitter[] emitters, ulong selfFacts = 0UL)
{
for (var i = 0; i < ticks; i++)
{
Step(emitters, selfFacts);
}
}
// Runs until the first tick that leaves PlanLength -1 and returns that tick's number (the pair's first direct tick).
public long RunToDirect(Emitter[] emitters, ulong selfFacts = 0UL)
{
for (var i = 0; i < 500; i++)
{
var t = A.TickCount;
Step(emitters, selfFacts);
if (A.PlanLength == -1)
{
return t;
}
}
throw new InvalidOperationException("He never went direct.");
}
// Runs until Frustrated and returns its tick.
public long RunToFrustration(Emitter[] emitters, ulong selfFacts = 0UL)
{
for (var i = 0; i < 2000; i++)
{
if ((Step(emitters, selfFacts) & TickEvents.Frustrated) != 0)
{
return Frustrated[^1];
}
}
throw new InvalidOperationException("He never frustrated.");
}
}
[Fact]
public void A_bolted_door_tried_direct_frustrates_exactly_on_time()
{
var b = new Bench(Build(Make()));
var door = new[] { BoltedDoor() };
var direct = b.RunToDirect(door);
Assert.Equal(1, b.A.GoalIndex);
Assert.Equal(-1, b.A.PlanLength);
var frustrated = direct + 100; // FrustrationSeconds 1.0 is 100 ticks
while (b.Now < frustrated) // none a tick early
{
Assert.Equal(TickEvents.None, b.Step(door) & TickEvents.Frustrated);
Assert.Equal(1, b.A.GoalIndex);
}
Assert.Equal(TickEvents.Frustrated, b.Step(door) & TickEvents.Frustrated); // once, on the tick
Assert.Equal(new[] { frustrated }, b.Frustrated);
for (var i = 0; i < Latency - 1; i++)
{
b.Step(door);
Assert.Equal(1, b.A.GoalIndex); // the decision commits a latency later, not before
}
b.Step(door);
Assert.Equal(0, b.A.GoalIndex);
Assert.Equal(0UL, b.A.TargetId);
b.Run(300, door);
Assert.Equal(0, b.A.GoalIndex); // barred: he does not go back
Assert.Single(b.Frustrated);
}
[Fact]
public void Frustration_decides_again_past_the_dwell()
{
var b = new Bench(Build(Make(dwell: 60.0)));
var door = new[] { BoltedDoor() };
b.RunToFrustration(door);
b.Run(Latency, door);
Assert.Equal(0, b.A.GoalIndex); // MinDwellSeconds 60 would have held the goal for 6000 ticks
}
[Fact]
public void Alone_he_lets_go_of_the_target_and_does_not_frustrate_again()
{
var brain = new Brain
{
PlanDepth = 3, FrustrationSeconds = 1.0, RetrySeconds = 30.0,
Goals = new[] { Goal("open", 3.0, Kinds(Door), This(Open)) },
};
var b = new Bench(Build(brain));
var door = new[] { BoltedDoor() };
b.RunToFrustration(door);
b.Run(Latency, door);
Assert.Equal(0, b.A.GoalIndex);
Assert.Equal(0UL, b.A.TargetId);
Assert.Equal(0, b.A.PlanLength);
b.Run(1000, door);
Assert.Equal(0UL, b.A.TargetId);
Assert.Single(b.Frustrated);
}
[Fact]
public void The_door_is_tried_again_after_the_retry()
{
var b = new Bench(Build(Make(retry: 2.0)));
var door = new[] { BoltedDoor() };
var first = b.RunToFrustration(door);
b.Run(1000, door);
// The bar lifts 200 ticks on, the decision commits a latency later, and 100 ticks of direct try end in the next frustration.
Assert.Equal(first + 200 + Latency + 100, b.Frustrated[1]);
Assert.Equal(first + 2 * (200 + Latency + 100), b.Frustrated[2]);
}
[Fact]
public void Infinite_seconds_never_frustrate_and_never_retry()
{
var door = new[] { BoltedDoor() };
var never = new Bench(Build(Make(frustration: double.PositiveInfinity)));
never.Run(3000, door);
Assert.Empty(never.Frustrated);
Assert.Equal(1, never.A.GoalIndex);
Assert.Equal(-1, never.A.PlanLength);
var stuck = new Bench(Build(Make(retry: double.PositiveInfinity)));
stuck.Run(5000, door);
Assert.Single(stuck.Frustrated);
Assert.Equal(0, stuck.A.GoalIndex);
}
[Fact]
public void A_changed_fact_or_self_fact_does_not_lift_the_bar_but_a_forgotten_door_does()
{
// Barred, idle in force; a change of the door's facts or his own leaves the bar standing (ruling frustration-lifts-without-fact-changes).
void Holds(Action<Bench, Emitter[]> change)
{
var b = new Bench(Build(Make(), memory: 0.5));
var door = new[] { BoltedDoor() };
b.RunToFrustration(door);
b.Run(Latency + 20, door);
Assert.Equal(0, b.A.GoalIndex);
change(b, door);
b.Run(Latency + 200, new[] { BoltedDoor(1UL << Noise) }, 1UL << Noise);
Assert.Equal(0, b.A.GoalIndex);
Assert.Single(b.Frustrated);
}
Holds((b, _) => b.Run(Latency + 2, new[] { BoltedDoor(1UL << Noise) })); // an unrelated bit of the door's facts
Holds((b, door) => b.Run(Latency + 2, door, 1UL << Noise)); // an unrelated self fact
// The door leaving memory (0.5 s) ends the bar: sensed again, unchanged, the try resumes.
var f = new Bench(Build(Make(), memory: 0.5));
var same = new[] { BoltedDoor() };
f.RunToFrustration(same);
f.Run(Latency + 20, same);
Assert.Equal(0, f.A.GoalIndex);
f.Run(60, None);
f.Run(Latency + 2, same);
Assert.Equal(1, f.A.GoalIndex);
Assert.Equal(1UL, f.A.TargetId);
}
[Fact]
public void A_fact_that_flips_for_200_seconds_frustrates_a_bounded_number_of_times()
{
// His own futile try may rattle the door's facts; with the bar standing the count is that of the retries (30 s), not of the flips (every 0.5 s).
var b = new Bench(Build(Make(frustration: 1.0, retry: 30.0)));
for (var i = 0; i < 20000; i++)
{
b.Step(new[] { BoltedDoor((i / 50) % 2 == 0 ? 0UL : 1UL << Noise) });
}
Assert.InRange(b.Frustrated.Count, 1, 7);
}
[Fact]
public void A_barred_pair_that_now_plans_is_offered()
{
var b = new Bench(Build(Make(), verbs: WithPry()));
var door = new[] { BoltedDoor() };
b.RunToFrustration(door);
b.Run(Latency + 20, door);
Assert.Equal(0, b.A.GoalIndex);
// A held knife appears: the door's facts and his own are unchanged, so the bar stands, but the pair now plans (approach, pry) and is not a direct try.
b.Run(Latency + 2, new[] { BoltedDoor(), Thing(2, Knife, 1f, 1UL << Held) });
Assert.Equal(1, b.A.GoalIndex);
Assert.Equal(1UL, b.A.TargetId);
Assert.Equal(2, b.A.PlanLength);
Assert.Single(b.Frustrated);
}
[Fact]
public void Impatience_lasts_one_select()
{
// Calm and idle tie on priority (1), so a switch between them is never accepted on priority; calm scores 1 direct, idle 0.9.
var brain = new Brain
{
PlanDepth = 3, DirectDiscount = 1.0, FrustrationSeconds = 1.0, RetrySeconds = 30.0, Start = 0,
Goals = new[]
{
Goal("calm", 1.0, null, Self(Fed), 60.0),
Goal("idle", 1.0, dwell: 60.0) with { Considerations = new[] { new Consideration(ConsiderationInput.Drive, 0.0, 1.0, 0.9, 0.9, 1.0, DriveQuantity.Pain) } },
},
};
var b = new Bench(Build(brain));
b.RunToFrustration(None);
b.Run(Latency, None);
Assert.Equal(1, b.A.GoalIndex); // past calm's 60 s dwell, by impatience
b.Run(Latency + 2, None, 1UL << Held); // the bar lifts, calm scores 1 against idle's 0.9, but idle's own dwell holds and there is no impatience left
Assert.Equal(1, b.A.GoalIndex);
}
[Fact]
public void The_timer_starts_again_when_one_direct_try_replaces_another()
{
var brain = new Brain
{
PlanDepth = 3, DirectDiscount = 0.5, FrustrationSeconds = 1.0, RetrySeconds = 30.0,
Goals = new[] { Goal("idle", 1.0), Goal("open", 3.0, Kinds(Door), This(Open)), Goal("calm", 4.0, null, Self(Fed)) },
};
var b = new Bench(Build(brain));
var door = new[] { BoltedDoor() };
b.RunToDirect(door, 1UL << Fed); // fed, so only the door is tried
b.Run(60, door, 1UL << Fed);
long calmSince;
for (; ; )
{
var t = b.Now;
b.Step(door); // hungry: calm outranks and replaces him at the door, direct as well
if (b.A.GoalIndex == 2)
{
calmSince = t;
break;
}
}
Assert.Equal(-1, b.A.PlanLength);
Assert.Equal(calmSince + 100, b.RunToFrustration(door));
}
[Fact]
public void Depth_zero_frustrates_like_any_direct_try()
{
var b = new Bench(Build(Make(depth: 0)));
var door = new[] { Thing(1, Door, 6f) }; // even a plain door is direct at depth 0
var direct = b.RunToDirect(door);
var f = b.RunToFrustration(door);
Assert.Equal(direct + 100, f);
b.Run(Latency, door);
Assert.Equal(0, b.A.GoalIndex);
}
[Fact]
public void A_self_want_with_no_target_frustrates_and_lifts_only_after_the_retry()
{
var brain = new Brain
{
PlanDepth = 3, DirectDiscount = 0.5, FrustrationSeconds = 1.0, RetrySeconds = 30.0,
Goals = new[] { Goal("idle", 1.0), Goal("calm", 3.0, null, Self(Fed)) },
};
var b = new Bench(Build(brain));
b.RunToFrustration(None);
b.Run(Latency + 20, None);
Assert.Equal(0, b.A.GoalIndex);
b.Run(Latency + 200, None, 1UL << Held); // a self fact changes: the bar stands
Assert.Equal(0, b.A.GoalIndex);
for (var i = 0; i < 3000 && b.A.GoalIndex == 0; i++) // the retry passes: the try resumes
{
b.Step(None);
}
Assert.Equal(1, b.A.GoalIndex);
Assert.Equal(0UL, b.A.TargetId);
Assert.Equal(-1, b.A.PlanLength);
}
[Fact]
public void Zero_seconds_frustrate_once_not_every_tick()
{
var b = new Bench(Build(Make(frustration: 0.0)));
var door = new[] { BoltedDoor() };
b.Run(400, door);
Assert.Single(b.Frustrated);
Assert.Equal(0, b.A.GoalIndex);
}
[Fact]
public void Frustration_is_deterministic_and_allocates_nothing_in_a_cycle()
{
List<long> Trace(out int goal)
{
var b = new Bench(Build(Make(frustration: 0.5, retry: 1.0)));
b.Run(1500, new[] { BoltedDoor() });
goal = b.A.GoalIndex;
return b.Frustrated;
}
var one = Trace(out var goalOne);
var two = Trace(out var goalTwo);
Assert.True(one.Count >= 5);
Assert.Equal(one, two);
Assert.Equal(goalOne, goalTwo);
// Frustrate, lift by retry, try again: the cycle repeats every 160 ticks. Nothing is allocated once it has run.
var a = Build(Make(frustration: 0.5, retry: 1.0));
var door = new[] { BoltedDoor() };
var strengths = new float[2];
var targets = new Quat[2];
for (var i = 0; i < 1000; i++)
{
a.Tick(Zero, Zero, Zero, NoBoxes, strengths, targets, door);
}
var before = GC.GetAllocatedBytesForCurrentThread();
var events = TickEvents.None;
for (var i = 0; i < 1000; i++)
{
events |= a.Tick(Zero, Zero, Zero, NoBoxes, strengths, targets, door);
}
var after = GC.GetAllocatedBytesForCurrentThread();
Assert.True((events & TickEvents.Frustrated) != 0); // the window held at least one full cycle
Assert.Equal(0L, after - before);
}
[Fact]
public void Validation_refuses_NaN_and_negatives_and_accepts_infinity()
{
foreach (var bad in new[] { double.NaN, -1.0, double.NegativeInfinity })
{
Assert.Throws<ArgumentException>(() => Build(Make(frustration: bad)));
Assert.Throws<ArgumentException>(() => Build(Make(retry: bad)));
}
Assert.Throws<ArgumentException>(() => Build(Make(frustration: 0.5, retry: 0.0)));
Build(Make(frustration: double.PositiveInfinity, retry: double.PositiveInfinity));
Build(Make(frustration: 0.0, retry: 1.0));
}
}

View file

@ -0,0 +1,406 @@
using System;
using System.Collections.Generic;
using System.Linq;
using Lodur;
namespace Lodur.Core.Tests;
/// <summary>
/// The planner's move rule and budget against an independent forward oracle on wide and deep random worlds (Soul's probes of cut lodur-planner-moves, committed:
/// follow-up lodur:follow_up:planner-moves-s1-lows). The deep generator makes plans of 3 to 5 steps through several movers; the asserted counts keep the fuzz honest.
/// </summary>
public sealed class PlannerMoveOracleTests
{
private const int Reach = 63;
private static readonly float[] Zero = { 0f }; public static double R = 1.0; private static readonly int[] Depths = { 0, 2, 5 };
private readonly record struct Step(int Verb, int This, int Tool);
private sealed class World
{
public Perception P = null!; public Verb[] Verbs = null!; public ulong SelfFacts; public ulong[] Start = null!; public uint[] Kind = null!;
public int WantThing, WantBit; public bool WantValue; public int Slots; public int Depth = 4;
}
// mode: 0 old generator rates (base), 1 head generator, 2 wide (3-D, boundary distances, 5 slots, high reach rates)
private static Fact[] RandomFacts(Random rng, int count, bool hasTool, bool selfAllowed, int reachOneIn)
{
var chosen = new List<Fact>();
for (var i = 0; i < count; i++)
{
var subject = (FactSubject)rng.Next(hasTool ? 3 : 2);
if (subject == FactSubject.Self && !selfAllowed) subject = FactSubject.This;
var bit = subject != FactSubject.Self && rng.Next(reachOneIn) == 0 ? Reach : rng.Next(4);
if (chosen.Any(f => f.Subject == subject && f.Bit == bit)) continue;
chosen.Add(new Fact(subject, bit, rng.Next(2) == 0));
}
return chosen.ToArray();
}
private static TargetFilter? RandomFilter(Random rng, int chance)
{
if (rng.Next(100) >= chance) return null;
var kinds = new List<uint> { (uint)(1 + rng.Next(3)) };
if (rng.Next(2) == 0) kinds.Add((uint)(1 + rng.Next(3)));
return new TargetFilter { Kinds = kinds.ToArray() };
}
private static World Generate(Random rng, int mode)
{
var slots = mode == 2 ? 5 : 4;
var w = new World { Kind = new uint[slots], Slots = slots };
var things = 3 + rng.Next(mode == 2 ? 3 : 2);
var emitters = new List<Emitter>();
w.Start = new ulong[slots + 1];
(float, float, float)[] lattice = { (0, 0, 0), (1, 0, 0), (0, 1, 0), (0, 0, 1), (0.5f, 0, 0), (1.5f, 0, 0), (1.2f, 0, 0), (0, 0.9f, 0.9f), (5, 0, 0), (0, 5, 0), (0.7f, 0.7f, 0), (2, 0, 0) };
for (var i = 0; i < things; i++)
{
var kind = (uint)(1 + rng.Next(3));
var facts = (ulong)rng.Next(16);
float x = 0, y = 0, z = 0;
if (mode == 0) x = rng.Next(2) == 0 ? 0.5f : 5f;
else if (mode == 1) x = rng.Next(3) switch { 0 => 0.5f, 1 => 1.2f, _ => 5f };
else (x, y, z) = lattice[rng.Next(lattice.Length)];
emitters.Add(new Emitter(Channel.Visual, (float)(x * R), (float)(y * R), (float)(z * R), 100f, 1.0, (ulong)(10 + i), kind, facts));
}
w.P = new Perception(new NerveParameters(), 0.01, 1,
new NerveParameters { Threshold = 0.05, SensitisationGrowth = 0.0, ConductionDelaySeconds = 0.0 }, 0,
new PerceptParameters { Capacity = slots, MemorySeconds = 5.0 });
w.P.Sense(Zero, Zero, Zero, Array.Empty<BoxStimulus>(), emitters.ToArray());
w.SelfFacts = (ulong)rng.Next(16);
w.Start[0] = w.SelfFacts;
for (var s = 0; s < slots; s++)
{
var p = w.P.Percept(s);
w.Kind[s] = p.Kind;
w.Start[s + 1] = p.Id == 0 ? 0UL : (p.Facts & ~Perception.InReachFact) | (p.X * p.X + p.Y * p.Y + p.Z * p.Z <= R * R ? Perception.InReachFact : 0UL);
}
var needs1 = mode == 0 ? 4 : mode == 1 ? 3 : 3;
var gives1 = mode == 0 ? 4 : mode == 1 ? 4 : 3;
var verbs = new List<Verb>();
for (var v = 0; v < 2 + rng.Next(mode == 2 ? 6 : 5); v++)
{
var tool = RandomFilter(rng, 30);
verbs.Add(new Verb
{
Id = "v" + v, This = RandomFilter(rng, 60), Tool = tool,
Needs = RandomFacts(rng, rng.Next(4), tool is not null, true, needs1),
Gives = RandomFacts(rng, 1 + rng.Next(3), tool is not null, false, gives1).DefaultIfEmpty(new Fact(FactSubject.This, 0, true)).ToArray(),
});
}
w.Verbs = verbs.ToArray();
var occupied = Enumerable.Range(0, slots).Where(s => w.P.Percept(s).Id != 0).ToArray();
if (rng.Next(2) == 0) { w.WantThing = 0; w.WantBit = rng.Next(4); }
else { w.WantThing = 1 + occupied[rng.Next(occupied.Length)]; w.WantBit = rng.Next(mode == 0 ? 4 : 2) == 0 ? Reach : rng.Next(4); }
w.WantValue = rng.Next(2) == 0;
return w;
}
private static IEnumerable<Step> Groundings(World w)
{
for (var v = 0; v < w.Verbs.Length; v++)
{
var verb = w.Verbs[v];
for (var a = 0; a < w.Slots; a++)
{
if (w.P.Percept(a).Id == 0 || (verb.This is not null && !verb.This.Kinds.Contains(w.Kind[a]))) continue;
if (verb.Tool is null) { yield return new Step(v, a, -1); continue; }
for (var b = 0; b < w.Slots; b++)
if (b != a && w.P.Percept(b).Id != 0 && verb.Tool.Kinds.Contains(w.Kind[b])) yield return new Step(v, a, b);
}
}
}
private static int ThingOf(Fact f, Step s) => f.Subject == FactSubject.Self ? 0 : 1 + (f.Subject == FactSubject.This ? s.This : s.Tool);
private static bool Holds(ulong[] st, int thing, int bit, bool v) => (((st[thing] >> bit) & 1UL) != 0UL) == v;
private static bool Near(World w, int a, int b)
{
Percept pa = w.P.Percept(a), pb = w.P.Percept(b);
double dx = pa.X - pb.X, dy = pa.Y - pb.Y, dz = pa.Z - pb.Z;
return dx * dx + dy * dy + dz * dz <= R * R;
}
// order 0: no moves; 1: move then gives (Hands); 2: gives then move (spec's oracle)
private static ulong[]? Apply(World w, ulong[] state, Step s, int order)
{
var verb = w.Verbs[s.Verb];
foreach (var n in verb.Needs) if (!Holds(state, ThingOf(n, s), n.Bit, n.Value)) return null;
var next = (ulong[])state.Clone();
var mover = order != 0 && verb.Gives.Any(g => g.Subject == FactSubject.This && g.Bit == Reach && g.Value);
void Move()
{
for (var o = 0; o < w.Slots; o++)
if (o != s.This && w.P.Percept(o).Id != 0)
next[o + 1] = Near(w, o, s.This) ? next[o + 1] | Perception.InReachFact : next[o + 1] & ~Perception.InReachFact;
}
if (mover && order == 1) Move();
foreach (var g in verb.Gives)
{
var t = ThingOf(g, s);
next[t] = g.Value ? next[t] | (1UL << g.Bit) : next[t] & ~(1UL << g.Bit);
}
if (mover && order == 2) Move();
return next;
}
private static string Key(ulong[] st) => string.Join(",", st);
private static int Shallowest(World w, List<Step> all, int order)
{
var frontier = new List<ulong[]> { w.Start };
var seen = new HashSet<string> { Key(w.Start) };
bool Goal(ulong[] st) => Holds(st, w.WantThing, w.WantBit, w.WantValue);
if (Goal(w.Start)) return 0;
for (var d = 1; d <= w.Depth; d++)
{
var next = new List<ulong[]>();
foreach (var st in frontier)
foreach (var step in all)
{
var n = Apply(w, st, step, order);
if (n is not null && seen.Add(Key(n))) { if (Goal(n)) return d; next.Add(n); }
}
frontier = next;
}
return -1;
}
private static Fact WantOf(World w) => new(w.WantThing == 0 ? FactSubject.Self : FactSubject.This, w.WantBit, w.WantValue);
private static int TargetSlot(World w) => w.WantThing == 0 ? 0 : w.WantThing - 1;
private static bool IsMover(Verb v) => v.Gives.Any(g => g.Subject == FactSubject.This && g.Bit == Reach && g.Value);
// A forward breadth-first oracle that shares none of the planner's machinery, on worlds with boundary distances, 3-D positions and a high rate of reach facts.
// The oracle applies a move first, then the verb's gives (order 1); gives-then-move (order 2) is the other reading a mutation could fake.
[Fact]
public void The_planner_equals_a_forward_oracle_on_12000_wide_worlds()
{
var rng = new Random(777);
int N = 12000, mism1 = 0, mism2 = 0, spec2only = 0, exhausted = 0, solved = 0, moverWorlds = 0, planMover = 0, deep3 = 0, toolGiveMover = 0;
var plan = new PlanStep[4];
for (var i = 0; i < N; i++)
{
var w = Generate(rng, 2);
var all = Groundings(w).ToList();
var e1 = Shallowest(w, all, 1); var e2 = Shallowest(w, all, 2);
var pl = new Planner(w.Verbs, w.Slots, 4, R);
var n = pl.Plan(w.P, w.SelfFacts, 0f, 0f, 0f, TargetSlot(w), WantOf(w), 4, plan);
if (pl.LastExhausted) { exhausted++; continue; }
if (w.Verbs.Any(IsMover)) moverWorlds++;
if (w.Verbs.Any(v => IsMover(v) && v.Gives.Any(g => g.Subject == FactSubject.Tool && g.Bit == Reach))) toolGiveMover++;
if (n >= 0) solved++;
if (n >= 3) deep3++;
if (n > 0 && Enumerable.Range(0, n).Any(k => IsMover(w.Verbs[plan[k].Verb]))) planMover++;
if (n != e1) { mism1++; }
if (n != e2) { mism2++; if (e1 != e2) spec2only++; }
}
Assert.True(moverWorlds > 5000 && planMover > 300 && toolGiveMover > 200 && solved > 5000, $"the worlds are too one-sided: {moverWorlds} with a mover, {planMover} plans through one, {toolGiveMover} giving a tool reach, {solved} solved");
Assert.Equal(0, mism1);
}
// chain-rich generator: bit ladders, movers, reach needs; makes plans of length 3-5
private static World GenerateDeep(Random rng)
{
var slots = 5; var w = new World { Kind = new uint[slots], Slots = slots, Depth = 5 };
var things = 3 + rng.Next(3);
(float, float, float)[] lattice = { (0, 0, 0), (1, 0, 0), (0, 1, 0), (0.5f, 0, 0), (1.5f, 0, 0), (5, 0, 0), (5.8f, 0, 0), (0, 0, 5), (2, 0, 0), (1.4f, 0.1f, 0) };
var emitters = new List<Emitter>(); w.Start = new ulong[slots + 1];
for (var i = 0; i < things; i++)
{
var (x, y, z) = lattice[rng.Next(lattice.Length)];
emitters.Add(new Emitter(Channel.Visual, (float)(x * R), (float)(y * R), (float)(z * R), 100f, 1.0, (ulong)(10 + i), (uint)(1 + rng.Next(2)), (ulong)(rng.Next(3) == 0 ? 1 : 0)));
}
w.P = new Perception(new NerveParameters(), 0.01, 1, new NerveParameters { Threshold = 0.05, SensitisationGrowth = 0.0, ConductionDelaySeconds = 0.0 }, 0, new PerceptParameters { Capacity = slots, MemorySeconds = 5.0 });
w.P.Sense(Zero, Zero, Zero, Array.Empty<BoxStimulus>(), emitters.ToArray());
w.SelfFacts = 0; w.Start[0] = 0;
for (var s = 0; s < slots; s++)
{
var p = w.P.Percept(s); w.Kind[s] = p.Kind;
w.Start[s + 1] = p.Id == 0 ? 0UL : (p.Facts & ~Perception.InReachFact) | (p.X * p.X + p.Y * p.Y + p.Z * p.Z <= R * R ? Perception.InReachFact : 0UL);
}
var verbs = new List<Verb>();
var nv = 3 + rng.Next(5);
for (var v = 0; v < nv; v++)
{
var tool = rng.Next(100) < 30 ? new TargetFilter { Kinds = new[] { (uint)(1 + rng.Next(2)) } } : null;
var thisF = rng.Next(100) < 50 ? new TargetFilter { Kinds = new[] { (uint)(1 + rng.Next(2)) } } : null;
var needs = new List<Fact>(); var gives = new List<Fact>();
var k = rng.Next(4);
if (k > 0 && rng.Next(100) < 80) needs.Add(new Fact(FactSubject.This, k - 1 + 1 - 1 >= 0 ? k - 1 : 0, true));
if (rng.Next(100) < 45) needs.Add(new Fact(FactSubject.This, Reach, rng.Next(5) != 0));
if (tool is not null && rng.Next(100) < 50) needs.Add(new Fact(FactSubject.Tool, Reach, rng.Next(4) != 0));
if (tool is not null && rng.Next(100) < 30) needs.Add(new Fact(FactSubject.Tool, rng.Next(3), true));
var mover = rng.Next(100) < 45;
if (mover) gives.Add(new Fact(FactSubject.This, Reach, true));
if (!mover || rng.Next(100) < 70) gives.Add(new Fact(FactSubject.This, k, true));
if (tool is not null && rng.Next(100) < 12) gives.Add(new Fact(FactSubject.Tool, Reach, rng.Next(2) == 0));
if (rng.Next(100) < 10) gives.Add(new Fact(FactSubject.Self, rng.Next(2), true));
verbs.Add(new Verb { Id = "v" + v, This = thisF, Tool = tool, Needs = needs.GroupBy(f => (f.Subject, f.Bit)).Select(g => g.First()).ToArray(), Gives = gives.GroupBy(f => (f.Subject, f.Bit)).Select(g => g.First()).ToArray() });
}
w.Verbs = verbs.ToArray();
var occ = Enumerable.Range(0, slots).Where(s => w.P.Percept(s).Id != 0).ToArray();
w.WantThing = 1 + occ[rng.Next(occ.Length)]; w.WantBit = rng.Next(5) == 0 ? Reach : 2 + rng.Next(2); w.WantValue = w.WantBit == Reach ? rng.Next(2) == 0 : true;
return w;
}
[Fact]
public void The_planner_equals_a_forward_oracle_on_6000_deep_worlds_of_plans_up_to_five_steps()
{
var rng = new Random(4242);
int N = 6000, mism = 0, exhausted = 0, specOnly = 0; long nodesTot = 0; var hist = new int[7]; int planMover2 = 0, twoMoves = 0;
var plan = new PlanStep[5];
for (var i = 0; i < N; i++)
{
var w = GenerateDeep(rng);
var all = Groundings(w).ToList();
var e1 = Shallowest(w, all, 1); var e2 = Shallowest(w, all, 2); var e0 = Shallowest(w, all, 0);
var pl = new Planner(w.Verbs, w.Slots, 5, R);
var n = pl.Plan(w.P, w.SelfFacts, 0f, 0f, 0f, TargetSlot(w), WantOf(w), 5, plan);
if (pl.LastExhausted) { exhausted++; continue; }
hist[n + 1]++; nodesTot += pl.LastNodes;
if (n >= 2 && Enumerable.Range(0, n).Count(k => IsMover(w.Verbs[plan[k].Verb])) >= 2) twoMoves++;
if (e0 != e1) planMover2++;
if (n != e1) { mism++; }
if (e1 != e2) specOnly++;
}
Assert.True(hist[4] + hist[5] + hist[6] >= 200 && twoMoves >= 100 && planMover2 >= 150 && specOnly >= 3,
$"the deep worlds are too shallow: {hist[4] + hist[5] + hist[6]} plans of 3+ steps, {twoMoves} through 2+ movers, {planMover2} where a move changes the length, {specOnly} where gives-then-move would differ");
Assert.Equal(0, mism);
}
[Fact]
public void The_budget_boundary_is_exact_at_every_budget_up_to_the_full_cost()
{
var rng = new Random(99);
int worlds = 0, solvedW = 0, unsolvedW = 0, bad = 0, checks = 0, skippedExh = 0;
var plan = new PlanStep[5]; var plan2 = new PlanStep[5];
for (var i = 0; i < 3000; i++)
{
var w = GenerateDeep(rng);
var pl = new Planner(w.Verbs, w.Slots, 5, R);
var ts = w.WantThing == 0 ? 0 : w.WantThing - 1;
var want = new Fact(w.WantThing == 0 ? FactSubject.Self : FactSubject.This, w.WantBit, w.WantValue);
var n = pl.Plan(w.P, w.SelfFacts, 0f, 0f, 0f, ts, want, 5, plan);
if (pl.LastExhausted) { skippedExh++; continue; }
var full = pl.LastNodes; worlds++;
if (n > 0) solvedW++; else if (n < 0) unsolvedW++; else continue;
var steps = plan.Take(Math.Max(n, 0)).ToArray();
for (var b = 1; b <= Math.Min(full + 2, 40); b++)
{
var m = pl.Plan(w.P, w.SelfFacts, 0f, 0f, 0f, ts, want, 5, plan2, b);
checks++;
bool shouldFind = n > 0 && full <= b;
bool shouldExh = full > b;
bool ok = shouldExh ? (m == -1 && pl.LastExhausted && pl.LastNodes == b + 1)
: (m == n && !pl.LastExhausted && pl.LastNodes == full && plan2.Take(Math.Max(m, 0)).SequenceEqual(steps));
if (!ok) { bad++; }
}
}
Assert.Equal(0, bad);
}
[Fact]
public void The_planner_is_deterministic_and_allocates_nothing_with_movers()
{
var rng = new Random(5); int bad = 0, n0 = 0;
var plan = new PlanStep[5]; var plan2 = new PlanStep[5]; var junk = new PlanStep[5];
for (var i = 0; i < 400; i++)
{
var w = GenerateDeep(rng);
var shared = new Planner(w.Verbs, w.Slots, 5, R); var fresh = new Planner(w.Verbs, w.Slots, 5, R);
var occ = Enumerable.Range(0, w.Slots).Where(s => w.P.Percept(s).Id != 0).ToArray();
for (var k = 0; k < 8; k++)
{
var s = occ[rng.Next(occ.Length)];
shared.Plan(w.P, (ulong)rng.Next(4), 0f, 0f, 0f, s, new Fact(FactSubject.This, rng.Next(4) == 0 ? 63 : rng.Next(4), rng.Next(2) == 0), rng.Next(6), junk, rng.Next(3) == 0 ? 3 : 4096);
}
var ts = w.WantThing == 0 ? 0 : w.WantThing - 1;
var want = new Fact(w.WantThing == 0 ? FactSubject.Self : FactSubject.This, w.WantBit, w.WantValue);
var a = shared.Plan(w.P, w.SelfFacts, 0f, 0f, 0f, ts, want, 5, plan);
var b = fresh.Plan(w.P, w.SelfFacts, 0f, 0f, 0f, ts, want, 5, plan2);
n0++;
if (a != b || shared.LastNodes != fresh.LastNodes || shared.LastExhausted != fresh.LastExhausted || !plan.Take(Math.Max(a, 0)).SequenceEqual(plan2.Take(Math.Max(b, 0)))) bad++;
}
Assert.Equal(0, bad);
// allocation: movers, budgets, exhausted calls, success, none
var ws = Enumerable.Range(0, 40).Select(_ => GenerateDeep(rng)).ToArray();
var pls = ws.Select(w => new Planner(w.Verbs, w.Slots, 5, R)).ToArray();
void Round()
{
for (var q = 0; q < ws.Length; q++)
{
var w = ws[q]; var ts = w.WantThing == 0 ? 0 : w.WantThing - 1;
var want = new Fact(w.WantThing == 0 ? FactSubject.Self : FactSubject.This, w.WantBit, w.WantValue);
foreach (var d in Depths) { pls[q].Plan(w.P, w.SelfFacts, 0f, 0f, 0f, ts, want, d, plan); pls[q].Plan(w.P, w.SelfFacts, 0f, 0f, 0f, ts, want, d, plan, 7); }
}
}
for (var k = 0; k < 5; k++) Round();
var before = GC.GetAllocatedBytesForCurrentThread();
for (var k = 0; k < 50; k++) Round();
var delta = GC.GetAllocatedBytesForCurrentThread() - before;
Assert.Equal(0, delta);
// LastExhausted after a throw and after a depth-0 return
var wx = ws[0];
var px = pls[0];
try { px.Plan(wx.P, wx.SelfFacts, 0f, 0f, 0f, 0, new Fact(FactSubject.Self, 0, true), 4, plan, 0); } catch (ArgumentOutOfRangeException) { }
Assert.False(px.LastExhausted);
}
[Fact]
public void The_move_rule_holds_at_other_reach_radii()
{
foreach (var r in new[] { 0.5, 2.5 })
{
R = r;
try
{
var rng = new Random(31); int mism = 0, exh = 0, tested = 0; var plan = new PlanStep[5];
for (var i = 0; i < 4000; i++)
{
var w = i % 2 == 0 ? GenerateDeep(rng) : Generate(rng, 2);
var all = Groundings(w).ToList(); var e1 = Shallowest(w, all, 1);
var pl = new Planner(w.Verbs, w.Slots, w.Depth, r);
var n = pl.Plan(w.P, w.SelfFacts, 0f, 0f, 0f, TargetSlot(w), WantOf(w), w.Depth, plan);
if (pl.LastExhausted) { exh++; continue; }
tested++; if (n != e1) mism++;
}
Assert.Equal(0, mism);
}
finally { R = 1.0; }
}
}
// M11/M12: a verb that gives This reach false, or Tool reach true, is not a move
[Fact]
public void A_verb_that_drops_its_This_reach_or_gives_a_Tool_reach_is_not_a_move()
{
const uint A = 1, B = 2;
Emitter E(ulong id, uint k, float x) => new Emitter(Channel.Visual, x, 0f, 0f, 100f, 1.0, id, k, 0UL);
Perception Mk(params Emitter[] es)
{
var p = new Perception(new NerveParameters(), 0.01, 1, new NerveParameters { Threshold = 0.05, SensitisationGrowth = 0.0, ConductionDelaySeconds = 0.0 }, 0, new PerceptParameters { Capacity = 4, MemorySeconds = 5.0 });
p.Sense(Zero, Zero, Zero, Array.Empty<BoxStimulus>(), es); return p;
}
var plan = new PlanStep[4];
// (a) Drop gives This reach false (not a move): the knife B stays in reach, Use(B, tool A) goes
var verbsA = new[]
{
new Verb { Id = "Drop", This = new TargetFilter { Kinds = new[] { A } }, Gives = new[] { new Fact(FactSubject.This, 1, true), new Fact(FactSubject.This, Reach, false) } },
new Verb { Id = "Use", This = new TargetFilter { Kinds = new[] { B } }, Tool = new TargetFilter { Kinds = new[] { A } }, Needs = new[] { new Fact(FactSubject.Tool, 1, true), new Fact(FactSubject.This, Reach, true) }, Gives = new[] { new Fact(FactSubject.This, 2, true) } },
};
var pa = Mk(E(10, A, 5f), E(11, B, 0.5f));
var plA = new Planner(verbsA, 4, 4, 1.0);
var nA = plA.Plan(pa, 0UL, 0f, 0f, 0f, 1, new Fact(FactSubject.This, 2, true), 4, plan);
// (b) Fetch gives Tool reach true only (not a move): same shape
var verbsB = new[]
{
new Verb { Id = "Fetch", This = new TargetFilter { Kinds = new[] { B } }, Tool = new TargetFilter { Kinds = new[] { A } }, Gives = new[] { new Fact(FactSubject.Tool, 1, true), new Fact(FactSubject.Tool, Reach, true) } },
new Verb { Id = "Use", This = new TargetFilter { Kinds = new[] { B } }, Tool = new TargetFilter { Kinds = new[] { A } }, Needs = new[] { new Fact(FactSubject.Tool, 1, true), new Fact(FactSubject.This, Reach, true) }, Gives = new[] { new Fact(FactSubject.This, 2, true) } },
};
var plB = new Planner(verbsB, 4, 4, 1.0);
var nB = plB.Plan(pa, 0UL, 0f, 0f, 0f, 1, new Fact(FactSubject.This, 2, true), 4, plan);
Assert.Equal(2, nA); Assert.Equal(2, nB);
}
}

View file

@ -0,0 +1,883 @@
using System;
using System.Collections.Generic;
using System.Linq;
using Lodur;
namespace Lodur.Core.Tests;
/// <summary>
/// The want gate of Brain.Select and the plan on the Actor: a satisfied want is not offered, a planned pair is scored by its length, an unplanned one is tried direct
/// at a discount, one think budget serves a whole Select, and a Select with no pair lets go of the target.
/// </summary>
public sealed class PlannerSelectTests
{
private const uint Door = 1, Key = 2, Knife = 3, Junk = 4;
private const int Open = 0, Locked = 1, Latched = 2, Held = 3, Fed = 4;
private const int Reach = 63;
private const double Dt = 0.01;
private static readonly float[] Zero = { 0f };
private static readonly BoxStimulus[] NoBoxes = Array.Empty<BoxStimulus>();
private static Fact Self(int bit, bool v = true) => new(FactSubject.Self, bit, v);
private static Fact This(int bit, bool v = true) => new(FactSubject.This, bit, v);
private static Fact Tool(int bit, bool v = true) => new(FactSubject.Tool, bit, v);
private static TargetFilter Kinds(params uint[] kinds) => new() { Kinds = kinds };
// Approach (anything, no needs: a move), Unlock and Unlatch (a door, in reach), Open (a door in reach, neither locked nor latched), Grab (a knife or key in reach), Calm (a knife in reach: fed).
private static Verb[] Catalogue() => new[]
{
new Verb { Id = "Approach", Gives = new[] { This(Reach) } },
new Verb { Id = "Unlock", This = Kinds(Door), Needs = new[] { This(Reach), This(Locked) }, Gives = new[] { This(Locked, false) } },
new Verb { Id = "Unlatch", This = Kinds(Door), Needs = new[] { This(Reach), This(Latched) }, Gives = new[] { This(Latched, false) } },
new Verb { Id = "Open", This = Kinds(Door), Needs = new[] { This(Reach), This(Locked, false), This(Latched, false) }, Gives = new[] { This(Open) } },
new Verb { Id = "Grab", This = Kinds(Knife, Key), Needs = new[] { This(Reach) }, Gives = new[] { This(Held) } },
new Verb { Id = "Calm", This = Kinds(Knife), Needs = new[] { This(Reach) }, Gives = new[] { Self(Fed) } },
};
private static GoalSpec Goal(string id, double priority, TargetFilter? target = null, Fact? want = null, params Consideration[] considerations) => new()
{
Id = id, Priority = priority, Target = target, Want = want, Considerations = considerations,
Behaviour = new PoseBehaviour { Keys = new[] { PainBoxBrain.Hold }, FlinchPose = PainBoxBrain.Withdraw },
};
// 1 at plan length 1 falling to 0 at length 9: a longer plan is worth less, in exact eighths.
private static Consideration Shorter() => new(ConsiderationInput.PlanSteps, 1.0, 9.0, 1.0, 0.0);
private static Emitter Thing(ulong id, uint kind, float x, ulong facts = 0UL, float y = 0f, float z = 0f) =>
new(Channel.Visual, x, y, z, 100f, 1.0, id, kind, facts);
private static Perception Ears(int capacity)
{
return new Perception(new NerveParameters(), Dt, 1,
new NerveParameters { Threshold = 0.05, SensitisationGrowth = 0.0, ConductionDelaySeconds = 0.0 }, 0,
new PerceptParameters { Capacity = capacity, MemorySeconds = 5.0 });
}
private static Perception See(int capacity, params Emitter[] emitters)
{
var p = Ears(capacity);
p.Sense(Zero, Zero, Zero, NoBoxes, emitters);
return p;
}
private static Actor Build(Brain brain, int capacity = 8, double memory = 5.0, IReadOnlyList<Verb>? verbs = null) =>
new(Dt, 1, new NerveParameters(), new WithdrawalParameters(), new DriveParameters(), brain,
new NerveParameters { Threshold = 0.05, SensitisationGrowth = 0.0, ConductionDelaySeconds = 0.0 }, 0,
new PerceptParameters { Capacity = capacity, MemorySeconds = memory }, verbs: verbs ?? Catalogue());
private static void Run(Actor a, int ticks, Emitter[] emitters, ulong selfFacts = 0UL)
{
var strengths = new float[2];
var targets = new Quat[2];
for (var i = 0; i < ticks; i++)
{
a.Tick(Zero, Zero, Zero, NoBoxes, strengths, targets, emitters, selfFacts: selfFacts);
}
}
private const int Settle = 40; // well past the deliberate latency (10 ticks)
// The doors: a plain one two steps away (approach, open), a locked and latched one four (approach, unlock, unlatch, open).
private static Emitter PlainDoor(ulong id, float x = 6f) => Thing(id, Door, x);
private static Emitter BoltedDoor(ulong id, float x = 6f) => Thing(id, Door, x, (1UL << Locked) | (1UL << Latched));
[Fact]
public void A_satisfied_want_is_not_offered()
{
var brain = new Brain { PlanDepth = 6, Goals = new[] { Goal("idle", 1.0), Goal("open", 5.0, Kinds(Door), This(Open)) } };
var done = Build(brain);
Run(done, Settle, new[] { Thing(1, Door, 6f, 1UL << Open) });
Assert.Equal(0, done.GoalIndex);
Assert.Equal(0UL, done.TargetId);
Assert.Equal(0, done.PlanLength);
// Flip the door's facts: the pair is offered, planned in two steps, and wins.
var todo = Build(brain);
Run(todo, Settle, new[] { PlainDoor(1) });
Assert.Equal(1, todo.GoalIndex);
Assert.Equal(1UL, todo.TargetId);
Assert.Equal(2, todo.PlanLength);
// The same Actor, the door opened on the way: the pair is withdrawn and the goal lets go.
Run(todo, Settle, new[] { Thing(1, Door, 6f, 1UL << Open) });
Assert.Equal(0, todo.GoalIndex);
Assert.Equal(0, todo.PlanLength);
}
[Fact]
public void A_satisfied_self_want_drops_every_pair_of_its_goal()
{
var brain = new Brain { PlanDepth = 4, Goals = new[] { Goal("idle", 1.0), Goal("calm", 5.0, Kinds(Knife), Self(Fed)) } };
var hungry = Build(brain);
Run(hungry, Settle, new[] { Thing(1, Knife, 5f), Thing(2, Knife, 3f) });
Assert.Equal(1, hungry.GoalIndex);
Assert.Equal(2, hungry.PlanLength);
var fed = Build(brain);
Run(fed, Settle, new[] { Thing(1, Knife, 5f), Thing(2, Knife, 3f) }, 1UL << Fed);
Assert.Equal(0, fed.GoalIndex);
Assert.Equal(0UL, fed.TargetId);
}
[Fact]
public void A_planned_pair_scores_by_its_length()
{
// The bolted door is first in the slots, so only its longer plan can lose it the tie.
var brain = new Brain { PlanDepth = 4, Goals = new[] { Goal("idle", 1.0), Goal("open", 4.0, Kinds(Door), This(Open), Shorter()) } };
var a = Build(brain);
Run(a, Settle, new[] { BoltedDoor(1), PlainDoor(2, 9f) });
Assert.Equal(1, a.GoalIndex);
Assert.Equal(2UL, a.TargetId);
Assert.Equal(2, a.PlanLength);
Assert.Equal(new PlanStep(0, 2, 0), a.PlanStep(0));
Assert.Equal(new PlanStep(3, 2, 0), a.PlanStep(1));
Assert.Throws<ArgumentOutOfRangeException>(() => a.PlanStep(2));
// Without the length consideration the tie goes to the lowest slot: the longer plan is not worse.
var flat = Build(new Brain { PlanDepth = 4, Goals = new[] { Goal("idle", 1.0), Goal("open", 4.0, Kinds(Door), This(Open)) } });
Run(flat, Settle, new[] { BoltedDoor(1), PlainDoor(2, 9f) });
Assert.Equal(1UL, flat.TargetId);
Assert.Equal(4, flat.PlanLength);
Assert.Equal(new PlanStep(2, 1, 0), flat.PlanStep(1));
Assert.Equal(new PlanStep(1, 1, 0), flat.PlanStep(2));
}
[Fact]
public void Too_dim_to_plan_tries_direct_at_the_discount()
{
// The bolted door needs four steps. Direct is raw x DirectDiscount (the length factor at depth + 1 is 1 with no consideration).
Brain Make(int depth, double priority) => new()
{
PlanDepth = depth, DirectDiscount = 0.5,
Goals = new[] { Goal("idle", 1.0), Goal("open", priority, Kinds(Door), This(Open)) },
};
var tries = Build(Make(3, 3.0)); // 3 x 0.5 = 1.5 beats idle's 1
Run(tries, Settle, new[] { BoltedDoor(1) });
Assert.Equal(1, tries.GoalIndex);
Assert.Equal(1UL, tries.TargetId);
Assert.Equal(-1, tries.PlanLength);
Assert.Throws<ArgumentOutOfRangeException>(() => tries.PlanStep(0));
var gives = Build(Make(3, 1.5)); // 1.5 x 0.5 = 0.75 loses to idle
Run(gives, Settle, new[] { BoltedDoor(1) });
Assert.Equal(0, gives.GoalIndex);
Assert.Equal(0, gives.PlanLength);
var plans = Build(Make(4, 1.5)); // depth 4 finds the plan: 1.5 beats idle
Run(plans, Settle, new[] { BoltedDoor(1) });
Assert.Equal(1, plans.GoalIndex);
Assert.Equal(4, plans.PlanLength);
// The factor at depth + 1 reads the length consideration: direct at depth 3 is x(4) = 0.625 of raw, then the discount.
var curve = Build(new Brain { PlanDepth = 3, DirectDiscount = 0.5, Goals = new[] { Goal("idle", 1.0), Goal("open", 3.0, Kinds(Door), This(Open), Shorter()) } });
Run(curve, Settle, new[] { BoltedDoor(1) }); // 3 x 0.625 x 0.5 = 0.9375 < 1
Assert.Equal(0, curve.GoalIndex);
var curveWins = Build(new Brain { PlanDepth = 3, DirectDiscount = 0.5, Goals = new[] { Goal("idle", 0.9), Goal("open", 3.0, Kinds(Door), This(Open), Shorter()) } });
Run(curveWins, Settle, new[] { BoltedDoor(1) });
Assert.Equal(1, curveWins.GoalIndex);
Assert.Equal(-1, curveWins.PlanLength);
}
[Fact]
public void Depth_zero_tries_every_unsatisfied_want_direct()
{
var brain = new Brain { PlanDepth = 0, Goals = new[] { Goal("idle", 1.0), Goal("open", 3.0, Kinds(Door), This(Open)) } };
var a = Build(brain);
Run(a, Settle, new[] { PlainDoor(1) });
Assert.Equal(1, a.GoalIndex);
Assert.Equal(-1, a.PlanLength);
// A satisfied want is still not offered at depth 0.
var done = Build(brain);
Run(done, Settle, new[] { Thing(1, Door, 6f, 1UL << Open) });
Assert.Equal(0, done.GoalIndex);
// A Brain with no want selects as the public Select does at any depth, and never plans.
var free = new Brain { PlanDepth = 5, Goals = new[] { Goal("idle", 1.0), Goal("chase", 3.0, Kinds(Door)) } };
var p = See(4, PlainDoor(1));
var viaActor = Build(free);
Run(viaActor, Settle, new[] { PlainDoor(1) });
Assert.Equal(free.Select(default, p, 0f, 0f, 0f, new Choice(0, 0)), new Choice(viaActor.GoalIndex, viaActor.TargetId));
Assert.Equal(0, viaActor.PlanLength);
}
[Fact]
public void The_public_select_refuses_a_brain_with_wants()
{
var brain = new Brain { Goals = new[] { Goal("idle", 1.0), Goal("open", 3.0, Kinds(Door), This(Open)) } };
Assert.Throws<InvalidOperationException>(() => brain.Select(default, See(4, PlainDoor(1)), 0f, 0f, 0f, new Choice(0, 0)));
}
[Fact]
public void Deepening_finds_short_plans_first()
{
// One want goal on two doors at equal raw 4: the bolted door (slot 0, four steps) and the plain one (slot 1, two steps).
var percepts = See(4, BoltedDoor(1), PlainDoor(2, 9f));
var probe = new Planner(Catalogue(), 4, 4, 0.6);
var steps = new PlanStep[4];
var rounds = 0;
for (var k = 1; k <= 2; k++)
{
for (var slot = 0; slot < 2; slot++)
{
probe.Plan(percepts, 0UL, 0f, 0f, 0f, slot, This(Open), k, steps, Planner.NodeBudget, k);
rounds += probe.LastNodes;
}
}
(Choice Pick, int Spent) Select(int budget, double idle = 1.5)
{
var brain = new Brain
{
PlanDepth = 4, ThinkBudget = budget, DirectDiscount = 0.5,
Goals = new[] { Goal("idle", idle), Goal("open", 4.0, Kinds(Door), This(Open), Shorter()) },
};
var d = new Deliberation(brain, Catalogue(), 4);
return (brain.Select(default, percepts, 0f, 0f, 0f, new Choice(0, 0), d), d.Spent);
}
// The plain door (4 x 0.875 = 3.5) wins in round 2 and the bolted door, bounded by 4 x 0.75 after it, is pruned before round 3:
// the budget paid for round 1 and round 2 of both pairs and nothing more, not the four-step search.
Assert.Equal((new Choice(1, 2), rounds), Select(rounds));
Assert.Equal((new Choice(1, 2), rounds), Select(int.MaxValue));
// One grounding short, the plain door's round 2 runs the budget out: it goes direct (4 x 0.25 = 1 < idle), and so does the bolted one.
Assert.Equal((new Choice(0, 0), rounds - 1), Select(rounds - 1));
Assert.Equal(new Choice(1, 1), Select(rounds - 1, idle: 0.5).Pick);
}
[Fact]
public void A_dead_end_does_not_starve_a_short_plan()
{
// Two doors with four bolts (approach, four unbolts, open: six steps, past PlanDepth 4) at raw 6, a knife with a two-step want (approach, calm) at raw 3.
const int Barred = 5, Chained = 6;
var verbs = new[]
{
Catalogue()[0], Catalogue()[1], Catalogue()[2],
new Verb { Id = "Unbar", This = Kinds(Door), Needs = new[] { This(Reach), This(Barred) }, Gives = new[] { This(Barred, false) } },
new Verb { Id = "Unchain", This = Kinds(Door), Needs = new[] { This(Reach), This(Chained) }, Gives = new[] { This(Chained, false) } },
new Verb { Id = "Open", This = Kinds(Door), Needs = new[] { This(Reach), This(Locked, false), This(Latched, false), This(Barred, false), This(Chained, false) }, Gives = new[] { This(Open) } },
Catalogue()[5],
};
const ulong Bolts = (1UL << Locked) | (1UL << Latched) | (1UL << Barred) | (1UL << Chained);
var percepts = See(4, Thing(1, Door, 6f, Bolts), Thing(2, Door, 8f, Bolts), Thing(3, Knife, 3f));
var probe = new Planner(verbs, 4, 4, 0.6);
var steps = new PlanStep[4];
var rounds = 0;
for (var k = 1; k <= 2; k++)
{
for (var slot = 0; slot < 3; slot++)
{
probe.Plan(percepts, 0UL, 0f, 0f, 0f, slot == 2 ? 0 : slot, slot == 2 ? Self(Fed) : This(Open), k, steps, Planner.NodeBudget, k);
rounds += probe.LastNodes;
}
}
Assert.Equal(-1, probe.Plan(percepts, 0UL, 0f, 0f, 0f, 0, This(Open), 4, steps));
Assert.True(probe.LastNodes > rounds, $"one full dead-end search ({probe.LastNodes}) must cost more than rounds 1 and 2 of all three pairs ({rounds})");
var brain = new Brain
{
PlanDepth = 4, ThinkBudget = rounds, DirectDiscount = 0.5,
Goals = new[] { Goal("idle", 0.5), Goal("dead", 6.0, Kinds(Door), This(Open), Shorter()), Goal("calm", 3.0, Kinds(Knife), Self(Fed), Shorter()) },
};
var d = new Deliberation(brain, verbs, 4);
// The doors go direct at 6 x 0.25 = 1.5; the knife's plan, 3 x 0.875 = 2.625, wins. Best raw first would have spent the whole budget on the first door.
Assert.Equal(new Choice(2, 3), brain.Select(default, percepts, 0f, 0f, 0f, new Choice(0, 0), d));
Assert.Equal(rounds, d.Spent);
}
[Fact]
public void A_self_want_is_planned_once_for_all_its_pairs()
{
// Three knives, one budget just over one plan: every pair of the goal shares the plan found for the first.
var percepts = See(4, Thing(1, Knife, 5f), Thing(2, Knife, 3f), Thing(3, Knife, 4f));
var probe = new Planner(Catalogue(), 4, 4, 0.6);
var steps = new PlanStep[4];
Assert.Equal(2, probe.Plan(percepts, 0UL, 0f, 0f, 0f, 0, Self(Fed), 4, steps));
var brain = new Brain { PlanDepth = 4, ThinkBudget = probe.LastNodes, Goals = new[] { Goal("idle", 1.0), Goal("calm", 3.0, Kinds(Knife), Self(Fed), Shorter()) } };
var d = new Deliberation(brain, Catalogue(), 4);
// 3 x 0.875 = 2.625 for every pair, the lowest slot wins, and the budget paid for one plan, not three.
Assert.Equal(new Choice(1, 1), brain.Select(default, percepts, 0f, 0f, 0f, new Choice(0, 0), d));
Assert.Equal(probe.LastNodes, d.Spent);
// The commitment breaks the tie toward the current pair.
var committed = brain with { TargetCommitment = 1.1 };
var d2 = new Deliberation(committed, Catalogue(), 4);
Assert.Equal(new Choice(1, 3), committed.Select(default, percepts, 0f, 0f, 0f, new Choice(1, 3), d2));
}
[Fact]
public void Ties_resolve_by_key_not_by_the_order_pairs_are_offered()
{
// An untargeted goal at index 2 and a want pair at index 1 tie at 2: the want pair is offered later (pass 2) and wins on the lowest goal index.
var percepts = See(4, PlainDoor(1));
var brain = new Brain { PlanDepth = 4, Goals = new[] { Goal("idle", 0.5), Goal("open", 2.0, Kinds(Door), This(Open)), Goal("also", 2.0) } };
var d = new Deliberation(brain, Catalogue(), 4);
Assert.Equal(new Choice(1, 1), brain.Select(default, percepts, 0f, 0f, 0f, new Choice(0, 0), d));
// The same tie with the untargeted pair current: current wins.
Assert.Equal(new Choice(2, 0), brain.Select(default, percepts, 0f, 0f, 0f, new Choice(2, 0), d));
}
[Fact]
public void No_pair_lets_go_of_the_target()
{
// A want goal whose door stands open, and then a plain one whose door is forgotten.
var brain = new Brain { PlanDepth = 4, Goals = new[] { Goal("open", 3.0, Kinds(Door), This(Open)) } };
var a = Build(brain, memory: 0.5);
Run(a, Settle, new[] { PlainDoor(1) });
Assert.Equal(1UL, a.TargetId);
Run(a, Settle, new[] { Thing(1, Door, 6f, 1UL << Open) });
Assert.Equal(0, a.GoalIndex);
Assert.Equal(0UL, a.TargetId);
var forgetful = Build(brain, memory: 0.5);
Run(forgetful, Settle, new[] { PlainDoor(1) });
Assert.Equal(1UL, forgetful.TargetId);
Run(forgetful, 120, Array.Empty<Emitter>()); // the memory runs out, the door is gone
Assert.Equal(0, forgetful.GoalIndex);
Assert.Equal(0UL, forgetful.TargetId);
Assert.Equal(0, forgetful.PlanLength);
// The Brain-level rule: nothing offered keeps the goal in force and drops the target.
var none = See(4);
var d = new Deliberation(brain, Catalogue(), 4);
Assert.Equal(new Choice(0, 0), brain.Select(default, none, 0f, 0f, 0f, new Choice(0, 55), d));
}
[Fact]
public void The_plan_is_made_with_the_decision_and_carried()
{
var brain = new Brain { PlanDepth = 4, Goals = new[] { Goal("idle", 1.0), Goal("open", 3.0, Kinds(Door), This(Open)) } };
var a = Build(brain);
Run(a, Settle, new[] { BoltedDoor(1) });
Assert.Equal(4, a.PlanLength);
// The plan in force is the one the Select made, step for step.
var probe = new Planner(Catalogue(), 8, 4, 0.6);
var expected = new PlanStep[4];
var seen = See(8, BoltedDoor(1));
Assert.Equal(4, probe.Plan(seen, 0UL, 0f, 0f, 0f, 0, This(Open), 4, expected));
for (var i = 0; i < 4; i++)
{
Assert.Equal(expected[i], a.PlanStep(i));
}
// The pending plan becomes the plan in force on the tick the decision commits, before any later Select could make it again.
var c = Build(brain);
for (var i = 0; i < 60 && c.GoalIndex != 1; i++)
{
Run(c, 1, new[] { BoltedDoor(1) });
}
Assert.Equal(1, c.GoalIndex);
Assert.Equal(4, c.PlanLength);
for (var i = 0; i < 4; i++)
{
Assert.Equal(expected[i], c.PlanStep(i));
}
// The door is sensed unlocked while the Select re-chooses the pair: the plan shortens the same tick.
Run(a, 1, new[] { PlainDoor(1) });
Assert.Equal(2, a.PlanLength);
var shorter = new PlanStep[4];
Assert.Equal(2, probe.Plan(See(8, PlainDoor(1)), 0UL, 0f, 0f, 0f, 0, This(Open), 4, shorter));
for (var i = 0; i < 2; i++)
{
Assert.Equal(shorter[i], a.PlanStep(i)); // the re-chosen pair's new steps, not the old ones under a new length
}
// The door is seen open: the pair is no longer offered and the switch is pending, so this tick only checks the plan, and the want holds.
Run(a, 1, new[] { Thing(1, Door, 6f, 1UL << Open) });
Assert.Equal(1, a.GoalIndex);
Assert.Equal(1UL, a.TargetId);
Assert.Equal(0, a.PlanLength);
Run(a, Settle, new[] { Thing(1, Door, 6f, 1UL << Open) });
Assert.Equal(0, a.GoalIndex);
Assert.Equal(0, a.PlanLength);
}
[Fact]
public void A_carried_plan_goes_direct_when_a_step_s_thing_is_forgotten()
{
var brain = new Brain { PlanDepth = 4, Goals = new[] { Goal("idle", 1.0), Goal("calm", 3.0, Kinds(Knife), Self(Fed)) } };
var a = Build(brain, memory: 0.5);
Run(a, Settle, new[] { Thing(1, Knife, 5f) });
Assert.Equal(1, a.GoalIndex);
Assert.Equal(2, a.PlanLength);
// The knife leaves memory: the Select lets the goal go, a latency later; in between the plan in force is checked, and its steps have nothing to act on.
var lengths = new HashSet<int>();
for (var i = 0; i < 120; i++)
{
Run(a, 1, Array.Empty<Emitter>());
lengths.Add(a.PlanLength);
}
Assert.Contains(-1, lengths);
Assert.Equal(0, a.GoalIndex);
Assert.Equal(0, a.PlanLength);
}
[Fact]
public void A_refused_select_replans_the_pair_in_force()
{
// The open goal is in force and inside its minimum dwell; a knife appears that a second goal of equal priority would take at once, so the Select is refused.
Brain Make(int budget) => new()
{
PlanDepth = 4, ThinkBudget = budget,
Goals = new[]
{
Goal("idle", 0.5),
Goal("open", 3.0, Kinds(Door), This(Open), Shorter()) with { MinDwellSeconds = 50.0 },
Goal("grab", 3.0, Kinds(Knife), This(Held), Shorter()),
},
};
var a = Build(Make(Planner.NodeBudget));
Run(a, Settle, new[] { BoltedDoor(1) });
Assert.Equal(1, a.GoalIndex);
Assert.Equal(4, a.PlanLength);
Run(a, 1, new[] { PlainDoor(1), Thing(2, Knife, 0.3f) });
Assert.Equal(1, a.GoalIndex);
Assert.Equal(2, a.PlanLength); // the refused Select planned the pair in force again, from this tick's percepts
// With the budget spent by the Select itself nothing is left to plan the pair in force: its plan is carried, only checked.
var b = Build(Make(1));
Run(b, Settle, new[] { BoltedDoor(1) });
Assert.Equal(1, b.GoalIndex);
Assert.Equal(-1, b.PlanLength); // no budget to plan: he goes direct
Run(b, 1, new[] { PlainDoor(1), Thing(2, Knife, 0.3f) });
Assert.Equal(1, b.GoalIndex);
Assert.Equal(-1, b.PlanLength);
Run(b, 1, new[] { Thing(1, Door, 6f, 1UL << Open), Thing(2, Knife, 0.3f) });
Assert.Equal(0, b.PlanLength);
}
[Fact]
public void The_pending_plan_is_checked_on_the_tick_it_takes_force()
{
// The door is seen on the first tick only and forgotten (0.06 s) before the decision commits (10 ticks): the plan the Select made takes force, and is checked that tick.
var brain = new Brain { PlanDepth = 4, Goals = new[] { Goal("idle", 1.0), Goal("open", 3.0, Kinds(Door), This(Open)) } };
var a = Build(brain, memory: 0.06);
Run(a, 1, new[] { BoltedDoor(1) });
var committed = false;
for (var i = 0; i < 20 && !committed; i++)
{
Run(a, 1, Array.Empty<Emitter>());
if (a.GoalIndex == 1)
{
committed = true;
Assert.Equal(0, a.PlanLength); // its target has left memory
}
}
Assert.True(committed);
}
[Fact]
public void A_refused_select_that_exhausts_its_leftover_budget_keeps_the_plan_in_force()
{
Brain Make(int budget) => new()
{
PlanDepth = 4, ThinkBudget = budget,
Goals = new[]
{
Goal("idle", 0.5),
Goal("open", 3.0, Kinds(Door), This(Open), Shorter()) with { MinDwellSeconds = 50.0 },
Goal("grab", 3.0, Kinds(Knife), This(Held), Shorter()),
},
};
var planned = 0;
for (var budget = 1; budget <= 60; budget++)
{
var a = Build(Make(budget));
Run(a, Settle, new[] { BoltedDoor(1) });
var before = a.PlanLength;
Run(a, 1, new[] { BoltedDoor(1), Thing(2, Knife, 0.3f) });
var refused = a.PlanLength;
Run(a, 1, new[] { BoltedDoor(1), Thing(2, Knife, 0.3f) });
if (before == 4)
{
// Unchanged percepts: a valid plan is never replaced by a search that ran out.
Assert.Equal(1, a.GoalIndex);
Assert.Equal(4, refused);
Assert.Equal(4, a.PlanLength);
planned++;
}
}
Assert.True(planned > 20);
foreach (var budget in new[] { 28, 29 })
{
var a = Build(Make(budget));
Run(a, Settle, new[] { BoltedDoor(1) });
Assert.Equal(4, a.PlanLength);
}
}
[Fact]
public void A_refused_select_checks_the_plan_in_force_against_a_forgotten_target()
{
var brain = new Brain
{
PlanDepth = 4,
Goals = new[]
{
Goal("idle", 0.5),
Goal("open", 3.0, Kinds(Door), This(Open), Shorter()) with { MinDwellSeconds = 50.0 },
Goal("grab", 3.0, Kinds(Knife), This(Held), Shorter()),
},
};
var a = Build(brain, memory: 0.06);
Run(a, Settle, new[] { BoltedDoor(1) });
Assert.Equal(4, a.PlanLength);
// The door goes and a knife comes: the Select would switch, the dwell refuses it, and the plan in force has no target to act on.
Run(a, 20, new[] { Thing(2, Knife, 0.3f) });
Assert.Equal(1, a.GoalIndex);
Assert.Equal(0, a.PlanLength);
}
[Fact]
public void A_carried_plan_goes_direct_when_a_step_s_tool_is_forgotten()
{
const uint Strap = 5, Other = 7;
var verbs = new[]
{
new Verb { Id = "Approach", Gives = new[] { This(Reach) } },
new Verb { Id = "Grab", This = Kinds(Knife), Needs = new[] { This(Reach) }, Gives = new[] { This(Held) } },
new Verb { Id = "Cut", This = Kinds(Strap), Tool = Kinds(Knife), Needs = new[] { Tool(Held), This(Reach) }, Gives = new[] { This(Open) } },
};
var brain = new Brain
{
PlanDepth = 6, ReachMeters = 1.0,
Goals = new[] { Goal("idle", 0.5), Goal("free", 2.0, Kinds(Strap), This(Open), Shorter()), Goal("other", 3.0, Kinds(Other)) },
};
var a = Build(brain, memory: 0.06, verbs: verbs);
var room = new[] { Thing(1, Strap, 0.3f), Thing(2, Knife, 5f, 1UL << Held) }; // the knife is already held: the tool appears in one step only, as its Tool
Run(a, Settle, room);
Assert.Equal(1, a.GoalIndex);
Assert.True(a.PlanLength > 0);
var tooled = false;
for (var i = 0; i < a.PlanLength; i++)
{
tooled |= a.PlanStep(i).Tool != 0UL;
}
Assert.True(tooled);
// Something outranks the goal; while that decision is in flight the knife is forgotten and the strap is not.
Run(a, 1, new[] { room[0], room[1], Thing(3, Other, 4f) });
var lengths = new HashSet<int>();
for (var i = 0; i < 9; i++)
{
Run(a, 1, new[] { room[0], Thing(3, Other, 4f) });
if (a.GoalIndex == 1)
{
lengths.Add(a.PlanLength);
}
}
Assert.Contains(-1, lengths);
}
[Fact]
public void A_self_goal_s_plan_is_shared_with_its_later_pairs_after_the_budget_is_gone()
{
var percepts = See(4, Thing(1, Knife, 5f), Thing(2, Knife, 3f), Thing(3, Door, 6f, (1UL << Locked) | (1UL << Latched)));
var goals = new[] { Goal("idle", 0.5), Goal("calm", 3.0, Kinds(Knife), Self(Fed), Shorter()), Goal("open", 2.0, Kinds(Door), This(Open), Shorter()) };
var rich = new Brain { PlanDepth = 4, Goals = goals };
var d = new Deliberation(rich, Catalogue(), 4);
d.Begin(percepts, 0f, 0f, 0f);
Assert.Equal(0, d.PlanAt(1, Self(Fed), 0, 1));
Assert.Equal(2, d.PlanAt(1, Self(Fed), 0, 2));
var found = d.Spent;
// The budget is exactly what the Self want's search cost: another goal's pair finds none left, and the Self goal's second pair still takes the plan found.
var poor = rich with { ThinkBudget = found };
var d2 = new Deliberation(poor, Catalogue(), 4);
d2.Begin(percepts, 0f, 0f, 0f);
Assert.Equal(0, d2.PlanAt(1, Self(Fed), 0, 1));
Assert.Equal(2, d2.PlanAt(1, Self(Fed), 0, 2));
Assert.Equal(-1, d2.PlanAt(2, This(Open), 2, 1)); // gone
Assert.Equal(-1, d2.PlanAt(2, This(Open), 2, 2)); // and it stays gone
Assert.Equal(2, d2.PlanAt(1, Self(Fed), 1, 2)); // shared at no cost
Assert.Equal(found, d2.Spent);
}
[Fact]
public void A_kept_self_plan_is_not_overwritten_by_another_goal_s_search()
{
var percepts = See(4, Thing(1, Knife, 5f), Thing(3, Door, 6f));
var brain = new Brain { PlanDepth = 4, Goals = new[] { Goal("idle", 0.5), Goal("calm", 3.0, Kinds(Knife), Self(Fed), Shorter()), Goal("open", 2.0, Kinds(Door), This(Open), Shorter()) } };
var d = new Deliberation(brain, Catalogue(), 4);
d.Begin(percepts, 0f, 0f, 0f);
Assert.Equal(0, d.PlanAt(1, Self(Fed), 0, 1));
Assert.Equal(2, d.PlanAt(1, Self(Fed), 0, 2));
Assert.Equal(0, d.PlanAt(2, This(Open), 1, 1));
Assert.Equal(2, d.PlanAt(2, This(Open), 1, 2)); // the planner's last plan is now the door's: approach, open
d.KeepBest(1, 2, true);
d.Refresh();
var probe = new Planner(Catalogue(), 4, 4, 0.6);
var expected = new PlanStep[4];
Assert.Equal(2, probe.Plan(percepts, 0UL, 0f, 0f, 0f, 0, Self(Fed), 4, expected));
Assert.Equal(2, d.InForceLength);
Assert.Equal(expected[0], d.Step(0));
Assert.Equal(expected[1], d.Step(1));
}
[Fact]
public void Self_facts_reach_the_planner_and_bit_63_is_refused()
{
var brain = new Brain { PlanDepth = 4, Goals = new[] { Goal("idle", 1.0), Goal("calm", 3.0, Kinds(Knife), Self(Fed)) } };
var a = Build(brain);
var strengths = new float[2];
var targets = new Quat[2];
Assert.Throws<ArgumentException>(() => a.Tick(Zero, Zero, Zero, NoBoxes, strengths, targets, selfFacts: 1UL << 63));
Assert.Equal(0L, a.TickCount);
Run(a, Settle, new[] { Thing(1, Knife, 5f) }, 1UL << Fed);
Assert.Equal(0, a.GoalIndex);
}
[Fact]
public void Validation_refuses_bad_wants_and_fields()
{
static Actor Make(Brain b) => Build(b);
void Refuses(Brain b) => Assert.Throws<ArgumentException>(() => Make(b));
Brain With(params GoalSpec[] goals) => new() { PlanDepth = 2, Goals = goals };
Make(With(Goal("idle", 1.0), Goal("open", 3.0, Kinds(Door), This(Open)))); // the baseline is fine
Refuses(With(Goal("a", 1.0, Kinds(Door), Tool(Open)))); // Tool refused
Refuses(With(Goal("a", 1.0, null, This(Open)))); // This needs a Target
Refuses(With(Goal("a", 1.0, null, Self(Reach)))); // a Self want is not on bit 63
Refuses(With(Goal("a", 1.0, Kinds(Door), new Fact(FactSubject.This, 64, true)))); // bit out of range
Refuses(With(Goal("a", -1.0, Kinds(Door), This(Open)))); // a want goal's Priority >= 0
Refuses(With(Goal("a", 1.0, Kinds(Door), null, Shorter()))); // PlanSteps only on want goals
Make(With(Goal("a", 1.0, null, Self(Fed), Shorter()))); // ... and a Self want needs no target
Refuses(With(Goal("a", 1.0, Kinds(Door), This(Open))) with { PlanDepth = 9 });
Refuses(With(Goal("a", 1.0, Kinds(Door), This(Open))) with { PlanDepth = -1 });
Refuses(With(Goal("a", 1.0, Kinds(Door), This(Open))) with { DirectDiscount = 1.5 });
Refuses(With(Goal("a", 1.0, Kinds(Door), This(Open))) with { DirectDiscount = double.NaN });
Refuses(With(Goal("a", 1.0, Kinds(Door), This(Open))) with { ThinkBudget = 0 });
Refuses(With(Goal("a", 1.0, Kinds(Door), This(Open))) with { ReachMeters = 0.0 });
Refuses(With(Goal("a", 1.0, Kinds(Door), This(Open))) with { ReachMeters = double.PositiveInfinity });
// A want needs percepts to plan over.
Assert.Throws<ArgumentException>(() => new Actor(Dt, 1, new NerveParameters(), new WithdrawalParameters(), new DriveParameters(), With(Goal("a", 1.0, null, Self(Fed)))));
}
// ----- reference: every pair planned on its own, the original index-order tournament
private static Choice Reference(Brain brain, Perception p, Planner planner, ulong selfFacts, Choice current)
{
var buf = new PlanStep[Math.Max(1, brain.PlanDepth)];
var best = default(Choice);
var bestScore = 0.0;
var bestIsCurrent = false;
var found = false;
for (var g = 0; g < brain.Goals.Count; g++)
{
var goal = brain.Goals[g];
if (goal.Target is null)
{
Consider(g, goal, -1, 0UL, goal.Score(default, default, 0f, 0f, 0f));
continue;
}
for (var s = 0; s < p.PerceptCount; s++)
{
var pc = p.Percept(s);
if (pc.Id != 0UL && goal.Target.Accepts(pc.Kind))
{
Consider(g, goal, s, pc.Id, goal.Score(default, pc, 0f, 0f, 0f));
}
}
}
return found ? best : new Choice(current.Goal, 0UL);
void Consider(int g, GoalSpec goal, int slot, ulong target, double raw)
{
var isCurrent = g == current.Goal && target == current.Target;
if (isCurrent)
{
raw *= brain.TargetCommitment;
}
if (goal.Want is { } want)
{
var n = planner.Plan(p, selfFacts, 0f, 0f, 0f, want.Subject == FactSubject.Self ? 0 : slot, want, brain.PlanDepth, buf);
if (n == 0)
{
return;
}
raw *= n > 0 ? goal.PlanFactor(n) : goal.PlanFactor(brain.PlanDepth + 1) * brain.DirectDiscount;
}
if (!found || raw > bestScore || (raw == bestScore && isCurrent && !bestIsCurrent))
{
best = new Choice(g, target);
bestScore = raw;
bestIsCurrent = isCurrent;
found = true;
}
}
}
[Fact]
public void Ordered_selection_equals_the_exhaustive_reference()
{
var rng = new Random(20261126);
var wantChosen = 0;
var depthsSeen = new HashSet<int>();
for (var w = 0; w < 300; w++)
{
const int Slots = 16;
var emitters = new List<Emitter>();
var things = 5 + rng.Next(12);
for (var i = 0; i < things; i++)
{
var kind = (uint)(1 + rng.Next(4));
var facts = (ulong)rng.Next(8) << 1; // bits 1..3: locked, latched, held, never Open
var x = new[] { 0.3f, 0.5f, 1.0f, 2.0f, 5.0f }[rng.Next(5)];
emitters.Add(Thing((ulong)(10 + i), kind, x, facts, y: new[] { 0f, 0.4f, 3f }[rng.Next(3)]));
}
var percepts = See(Slots, emitters.ToArray());
var priorities = new[] { 1.0, 2.0, 3.0, 4.0 };
var goals = new List<GoalSpec>
{
Goal("idle", priorities[rng.Next(4)]),
Goal("open", priorities[rng.Next(4)], Kinds(Door), This(Open), rng.Next(2) == 0 ? new[] { Shorter() } : Array.Empty<Consideration>()),
Goal("grab", priorities[rng.Next(4)], Kinds(Knife, Key), This(Held), rng.Next(2) == 0 ? new[] { Shorter() } : Array.Empty<Consideration>()),
Goal("calm", priorities[rng.Next(4)], Kinds(Knife), Self(Fed), Shorter()),
Goal("rest", priorities[rng.Next(4)], null, Self(Fed), rng.Next(2) == 0 ? new[] { Shorter() } : Array.Empty<Consideration>()),
Goal("junk", priorities[rng.Next(4)], Kinds(Junk)),
};
var depth = rng.Next(6);
depthsSeen.Add(depth);
var brain = new Brain
{
Goals = goals, PlanDepth = depth, ThinkBudget = int.MaxValue, DirectDiscount = new[] { 0.25, 0.5, 0.75 }[rng.Next(3)],
TargetCommitment = new[] { 1.0, 1.25 }[rng.Next(2)], ReachMeters = 1.0,
};
var selfFacts = rng.Next(4) == 0 ? 1UL << Fed : 0UL;
var cur = new Choice(rng.Next(goals.Count), rng.Next(3) == 0 ? (ulong)(10 + rng.Next(things)) : 0UL);
var d = new Deliberation(brain, Catalogue(), Slots) { SelfFacts = selfFacts };
var planner = new Planner(Catalogue(), Slots, depth, 1.0);
var expected = Reference(brain, percepts, planner, selfFacts, cur);
var actual = brain.Select(default, percepts, 0f, 0f, 0f, cur, d);
Assert.True(expected == actual, $"world {w} depth {depth}: reference {expected}, select {actual}");
if (brain.Goals[actual.Goal].Want is not null)
{
wantChosen++;
}
}
Assert.True(wantChosen > 100 && depthsSeen.Count == 6, $"the worlds are too one-sided: {wantChosen} want pairs chosen, depths {depthsSeen.Count}");
}
// ----- the crowded room: how often a bounded budget changes the decision
private static (Perception Percepts, Verb[] Verbs, Emitter[] Emitters) Crowd(Random rng, int things)
{
const uint Strap = 5, Switch = 6;
var emitters = new List<Emitter> { Thing(1, Strap, 0.3f), Thing(2, Knife, 0.5f) };
for (var i = 2; i < things; i++)
{
// Knives, keys, doors (70% locked), switches and four junk kinds, all within 12 m.
var pick = rng.Next(100);
var kind = pick switch { < 6 => Knife, < 12 => Key, < 20 => Door, < 26 => Switch, _ => (uint)(10 + rng.Next(4)) };
var facts = kind == Door && rng.Next(10) < 7 ? 1UL << Locked : 0UL;
emitters.Add(Thing((ulong)(1 + i), kind, (float)(rng.NextDouble() * 12.0), facts, (float)(rng.NextDouble() * 6.0 - 3.0)));
}
var verbs = new[]
{
new Verb { Id = "Approach", Needs = new[] { Self(Fed) }, Gives = new[] { This(Reach) } },
new Verb { Id = "Grab", This = Kinds(Knife, Key), Needs = new[] { This(Reach) }, Gives = new[] { This(Held) } },
new Verb { Id = "Cut", This = Kinds(Strap), Tool = Kinds(Knife), Needs = new[] { Tool(Held), This(Reach) }, Gives = new[] { Self(Fed), This(Open) } },
new Verb { Id = "Pry", This = Kinds(Strap), Tool = Kinds(Door), Needs = new[] { Tool(Reach), This(Reach) }, Gives = new[] { Self(Fed), This(Open) } },
new Verb { Id = "Switch", This = Kinds(Switch), Needs = new[] { This(Reach) }, Gives = new[] { This(Open) } },
new Verb { Id = "Unlock", This = Kinds(Door), Tool = Kinds(Key), Needs = new[] { Tool(Held), This(Reach), This(Locked) }, Gives = new[] { This(Locked, false) } },
new Verb { Id = "Open", This = Kinds(Door), Needs = new[] { This(Reach), This(Locked, false) }, Gives = new[] { This(Open) } },
new Verb { Id = "Fiddle", This = Kinds(10, 11), Needs = new[] { This(Reach) }, Gives = new[] { This(Latched) } },
new Verb { Id = "Stack", This = Kinds(12, 13), Tool = Kinds(10, 11), Needs = new[] { Tool(Latched), This(Reach) }, Gives = new[] { This(Latched) } },
};
var all = emitters.ToArray();
return (See(things, all), verbs, all);
}
private static Brain Crowded(int depth, int budget) => new()
{
PlanDepth = depth, ThinkBudget = budget, DirectDiscount = 0.5, ReachMeters = 1.0, TargetCommitment = 1.1,
Goals = new[]
{
Goal("idle", 0.5),
Goal("free", 2.0, Kinds(5), This(Open), Shorter()),
Goal("door", 3.0, Kinds(Door), This(Open), Shorter()),
Goal("switch", 2.5, Kinds(6), This(Open), Shorter()),
Goal("knife", 1.5, Kinds(Knife), This(Held), Shorter()),
},
};
private static int Differing(int things, int depth, int firstSeed, int seeds)
{
var differ = 0;
for (var seed = firstSeed; seed < firstSeed + seeds; seed++)
{
var rng = new Random(seed);
var (p, verbs, _) = Crowd(rng, things);
var bounded = Crowded(depth, Planner.NodeBudget);
var unbounded = Crowded(depth, int.MaxValue);
var cur = new Choice(0, 0);
var db = new Deliberation(bounded, verbs, things);
var du = new Deliberation(unbounded, verbs, things);
var a = bounded.Select(default, p, 0f, 0f, 0f, cur, db);
var b = unbounded.Select(default, p, 0f, 0f, 0f, cur, du);
if (a != b)
{
differ++;
}
}
return differ;
}
[Fact]
public void Ticking_a_crowded_room_allocates_nothing()
{
// Rounds of deepening, deferral, the decision plan swaps, and the carried check all run in these ticks; each Select spends the whole budget at depth 6.
var (_, verbs, emitters) = Crowd(new Random(3), 48);
var a = Build(Crowded(6, Planner.NodeBudget), 48, 5.0, verbs);
var strengths = new float[2];
var targets = new Quat[2];
for (var i = 0; i < 80; i++)
{
a.Tick(Zero, Zero, Zero, NoBoxes, strengths, targets, emitters);
}
var before = GC.GetAllocatedBytesForCurrentThread();
for (var i = 0; i < 200; i++)
{
a.Tick(Zero, Zero, Zero, NoBoxes, strengths, targets, emitters);
}
Assert.Equal(0L, GC.GetAllocatedBytesForCurrentThread() - before);
}
[Fact]
public void A_crowded_room_changes_few_decisions()
{
// A rate, not a bound, and it is depth-independent: a bounded budget changes 1 of 400 decisions at 48 things and 11 of 400 at 64 (seeds 5000-5399; seeds 0-399 give 1 and 13,
// seeds 9000-9399 give 3 and 23). The seeds are fixed so the counts are exact; the ceilings sit well above every range measured, so the pin is a margin, not one seed set.
foreach (var depth in new[] { 4, 5, 6, 8 })
{
Assert.InRange(Differing(48, depth, 5000, 400), 0, Differ48Of400Max);
}
Assert.InRange(Differing(64, 6, 5000, 400), 0, Differ64Of400Max);
}
private const int Differ48Of400Max = 8; // 2%: above 3 of 400, the worst of three ranges
private const int Differ64Of400Max = 40; // 10%: above 23 of 400, the worst of three ranges
}

View file

@ -0,0 +1,630 @@
using System;
using System.Collections.Generic;
using System.Linq;
using Lodur;
namespace Lodur.Core.Tests;
public sealed class PlannerTests
{
// The test world: kinds, then the fact bits the verbs speak of. Lodur reads none of them.
private const uint Knife = 1, Strap = 2, Switch = 3, Door = 4, Key = 5;
private const int Held = 0, Cut = 1, Off = 2, Open = 3, Locked = 4, Free = 5;
private const int Reach = 63;
private const int ApproachV = 0, GrabV = 1, CutStrapV = 2, SwitchOffV = 3, UnlockV = 4, OpenV = 5;
private const double Dt = 0.01;
private static readonly float[] Zero = { 0f };
private static readonly BoxStimulus[] NoBoxes = Array.Empty<BoxStimulus>();
private static Fact Self(int bit, bool v = true) => new(FactSubject.Self, bit, v);
private static Fact This(int bit, bool v = true) => new(FactSubject.This, bit, v);
private static Fact Tool(int bit, bool v = true) => new(FactSubject.Tool, bit, v);
private static Fact[] Many(int n) => Enumerable.Range(0, n).Select(i => This(i)).ToArray();
private static TargetFilter Kinds(params uint[] kinds) => new TargetFilter { Kinds = kinds };
private static Verb[] Catalogue() => new[]
{
new Verb { Id = "Approach", Needs = new[] { Self(Free) }, Gives = new[] { This(Reach) } },
new Verb { Id = "Grab", This = Kinds(Knife, Key), Needs = new[] { This(Reach) }, Gives = new[] { This(Held) } },
new Verb { Id = "CutStrap", This = Kinds(Strap), Tool = Kinds(Knife), Needs = new[] { Tool(Held), This(Reach) }, Gives = new[] { Self(Free), This(Cut) } },
new Verb { Id = "SwitchOff", This = Kinds(Switch), Needs = new[] { This(Reach) }, Gives = new[] { This(Off) } },
new Verb { Id = "Unlock", This = Kinds(Door), Tool = Kinds(Key), Needs = new[] { Tool(Held), This(Reach), This(Locked) }, Gives = new[] { This(Locked, false) } },
new Verb { Id = "Open", This = Kinds(Door), Needs = new[] { This(Reach), This(Locked, false) }, Gives = new[] { This(Open) } },
};
private static Perception Make(int capacity = 8, double memory = 5.0) =>
new Perception(new NerveParameters(), Dt, 1,
new NerveParameters { Threshold = 0.05, SensitisationGrowth = 0.0, ConductionDelaySeconds = 0.0 }, 0,
new PerceptParameters { Capacity = capacity, MemorySeconds = memory });
private static Emitter Thing(ulong id, uint kind, float x, ulong facts = 0) =>
new Emitter(Channel.Visual, x, 0f, 0f, 100f, 1.0, id, kind, facts);
private static void Sense(Perception p, params Emitter[] emitters) => p.Sense(Zero, Zero, Zero, NoBoxes, emitters);
// Ids in the order sensed: knife 1 and strap 2 within a metre, switch 3, key 4 and door 5 further out, the door locked.
private static Perception World(float switchX = 5f, ulong doorFacts = 1UL << Locked, ulong keyFacts = 0)
{
var p = Make();
Sense(p, Thing(1, Knife, 0.5f), Thing(2, Strap, 0.5f), Thing(3, Switch, switchX), Thing(4, Key, 8f, keyFacts), Thing(5, Door, 12f, doorFacts));
return p;
}
private static int SlotOf(Perception p, ulong id)
{
for (var s = 0; s < p.PerceptCount; s++)
{
if (p.Percept(s).Id == id) return s;
}
return -1;
}
private static Planner Build(Verb[]? verbs = null, int depth = 8, double reach = 1.0) => new Planner(verbs ?? Catalogue(), 8, depth, reach);
private static (int Length, PlanStep[] Steps) Run(Planner planner, Perception p, ulong id, Fact want, int depth, ulong self = 0UL, float ox = 0f)
{
var steps = new PlanStep[8];
var n = planner.Plan(p, self, ox, 0f, 0f, SlotOf(p, id), want, depth, steps);
return (n, steps);
}
private static void Expect(PlanStep[] steps, params (int Verb, ulong This, ulong Tool)[] expected)
{
for (var i = 0; i < expected.Length; i++)
{
Assert.Equal(new PlanStep(expected[i].Verb, expected[i].This, expected[i].Tool), steps[i]);
}
}
[Fact]
public void A_want_that_already_holds_is_a_plan_of_length_zero()
{
var planner = Build();
var p = World();
var steps = new PlanStep[8];
Array.Fill(steps, new PlanStep(-9, 9, 9));
// The target's own fact, the self's, and the derived reach all count.
Assert.Equal(0, planner.Plan(p, 0UL, 0f, 0f, 0f, SlotOf(p, 4), This(Locked, false), 7, steps));
Assert.Equal(0, planner.Plan(p, 1UL << Free, 0f, 0f, 0f, SlotOf(p, 3), Self(Free), 7, steps));
Assert.Equal(0, planner.Plan(p, 0UL, 0f, 0f, 0f, SlotOf(p, 1), This(Reach), 7, steps));
Assert.Equal(0, planner.Plan(p, 0UL, 0f, 0f, 0f, SlotOf(p, 5), This(Locked), 0, steps));
foreach (var s in steps) Assert.Equal(new PlanStep(-9, 9, 9), s);
// At depth 0 a want that does not hold is no plan, not a crash.
Assert.Equal(-1, planner.Plan(p, 0UL, 0f, 0f, 0f, SlotOf(p, 3), This(Off), 0, steps));
}
[Fact]
public void Switching_off_needs_four_steps_and_depth_three_finds_none()
{
var planner = Build();
var p = World();
var (n, steps) = Run(planner, p, 3, This(Off), 4);
Assert.Equal(4, n);
Expect(steps, (GrabV, 1, 0), (CutStrapV, 2, 1), (ApproachV, 3, 0), (SwitchOffV, 3, 0));
Assert.Equal(-1, Run(planner, p, 3, This(Off), 3).Length);
// A deeper allowance still returns the shallowest.
var (m, deeper) = Run(planner, p, 3, This(Off), 8);
Assert.Equal(4, m);
Expect(deeper, (GrabV, 1, 0), (CutStrapV, 2, 1), (ApproachV, 3, 0), (SwitchOffV, 3, 0));
}
[Fact]
public void FromDepth_searches_exactly_that_depth()
{
var planner = Build();
var p = World();
var steps = new PlanStep[8];
var off = SlotOf(p, 3);
var cut = SlotOf(p, 2);
// Switching off is four steps: found at exactly four, none at exactly three.
Assert.Equal(4, planner.Plan(p, 0UL, 0f, 0f, 0f, off, This(Off), 4, steps, Planner.NodeBudget, 4));
Expect(steps, (GrabV, 1, 0), (CutStrapV, 2, 1), (ApproachV, 3, 0), (SwitchOffV, 3, 0));
Assert.Equal(-1, planner.Plan(p, 0UL, 0f, 0f, 0f, off, This(Off), 3, steps, Planner.NodeBudget, 3));
Assert.False(planner.LastExhausted);
// Cutting the strap is two: a search that starts at three returns no shallower plan.
Assert.Equal(2, planner.Plan(p, 0UL, 0f, 0f, 0f, cut, This(Cut), 2, steps, Planner.NodeBudget, 2));
Assert.Equal(-1, planner.Plan(p, 0UL, 0f, 0f, 0f, cut, This(Cut), 3, steps, Planner.NodeBudget, 3));
Assert.Equal(2, planner.Plan(p, 0UL, 0f, 0f, 0f, cut, This(Cut), 3, steps));
// A want that holds is still 0, whatever the first depth.
Assert.Equal(0, planner.Plan(p, 0UL, 0f, 0f, 0f, SlotOf(p, 4), This(Locked, false), 3, steps, Planner.NodeBudget, 3));
Assert.ThrowsAny<ArgumentException>(() => planner.Plan(p, 0UL, 0f, 0f, 0f, off, This(Off), 4, steps, Planner.NodeBudget, 0));
Assert.ThrowsAny<ArgumentException>(() => planner.Plan(p, 0UL, 0f, 0f, 0f, off, This(Off), 4, steps, Planner.NodeBudget, 5));
Assert.ThrowsAny<ArgumentException>(() => planner.Plan(p, 0UL, 0f, 0f, 0f, off, This(Off), 0, steps, Planner.NodeBudget, 2));
}
[Fact]
public void Opening_the_locked_door_needs_seven_and_six_finds_none()
{
var planner = Build();
var p = World();
var (n, steps) = Run(planner, p, 5, This(Open), 7);
Assert.Equal(7, n);
Expect(steps, (GrabV, 1, 0), (CutStrapV, 2, 1), (ApproachV, 4, 0), (GrabV, 4, 0), (ApproachV, 5, 0), (UnlockV, 5, 4), (OpenV, 5, 0));
Assert.Equal(-1, Run(planner, p, 5, This(Open), 6).Length);
}
[Fact]
public void The_shallowest_plan_wins_and_ties_go_to_the_lower_verb_then_slot()
{
const int a = 20, b = 21, c = 22;
// A 3-step route through the lowest verb, a 2-step route through the highest: the 2-step one wins.
var routes = new[]
{
new Verb { Id = "Long", Needs = new[] { This(b) }, Gives = new[] { This(a) } },
new Verb { Id = "Prep1", Needs = new[] { This(c) }, Gives = new[] { This(b) } },
new Verb { Id = "Prep2", Gives = new[] { This(c) } },
new Verb { Id = "Direct", Needs = new[] { This(c) }, Gives = new[] { This(a) } },
};
var p = Make();
Sense(p, Thing(7, 1, 0f));
var (n, steps) = Run(new Planner(routes, 8, 3, 1.0), p, 7, This(a), 3);
Assert.Equal(2, n);
Expect(steps, (2, 7, 0), (3, 7, 0));
// Equal routes: the lower verb, then the lower This slot (the ids run against the slots), then the lower Tool slot.
var ties = new[]
{
new Verb { Id = "A", This = Kinds(2), Tool = Kinds(3), Gives = new[] { Self(1) } },
new Verb { Id = "B", This = Kinds(2), Tool = Kinds(3), Gives = new[] { Self(1) } },
};
var q = Make();
Sense(q, Thing(30, 2, 0f), Thing(10, 2, 0f), Thing(40, 3, 0f), Thing(20, 3, 0f));
var tied = new PlanStep[1];
Assert.Equal(1, new Planner(ties, 8, 1, 1.0).Plan(q, 0UL, 0f, 0f, 0f, 0, Self(1), 1, tied));
Assert.Equal(new PlanStep(0, 30, 40), tied[0]);
// The same two verbs the other way round: the plan names the other verb index, and a verb that cannot ground loses to one that can.
var reordered = new[] { ties[1] with { Id = "B" }, ties[0] with { Id = "A", This = Kinds(9) } };
Assert.Equal(1, new Planner(reordered, 8, 1, 1.0).Plan(q, 0UL, 0f, 0f, 0f, 0, Self(1), 1, tied));
Assert.Equal(new PlanStep(0, 30, 40), tied[0]);
var onlySecond = new[] { ties[0] with { This = Kinds(9) }, ties[1] };
Assert.Equal(1, new Planner(onlySecond, 8, 1, 1.0).Plan(q, 0UL, 0f, 0f, 0f, 0, Self(1), 1, tied));
Assert.Equal(new PlanStep(1, 30, 40), tied[0]);
}
[Fact]
public void A_gives_that_contradicts_a_need_is_not_relevant()
{
// Drop undoes Held; Grab gives it. The want is Held, so Drop is never a step toward it.
var verbs = new[]
{
new Verb { Id = "Drop", Gives = new[] { This(Held, false) } },
new Verb { Id = "Grab", Gives = new[] { This(Held) } },
};
var p = Make();
Sense(p, Thing(1, 1, 0f));
var planner = new Planner(verbs, 8, 3, 1.0);
var (n, steps) = Run(planner, p, 1, This(Held), 3);
Assert.Equal(1, n);
Assert.Equal(new PlanStep(1, 1, 0), steps[0]);
// The want Held false is the other verb's: Drop.
var q = Make();
Sense(q, Thing(1, 1, 0f, 1UL << Held));
(n, steps) = Run(planner, q, 1, This(Held, false), 3);
Assert.Equal(1, n);
Assert.Equal(new PlanStep(0, 1, 0), steps[0]);
// Smash gives Cut but undoes Off. Where Off is still needed alongside Cut it is skipped for Tidy, which gives Cut alone.
var both = new[]
{
new Verb { Id = "Smash", Gives = new[] { This(Cut), This(Off, false) } },
new Verb { Id = "Tidy", Gives = new[] { This(Cut) } },
new Verb { Id = "Finish", Needs = new[] { This(Cut), This(Off) }, Gives = new[] { This(Open) } },
};
var r = Make();
Sense(r, Thing(1, 1, 0f, 1UL << Off));
(n, steps) = Run(new Planner(both, 8, 3, 1.0), r, 1, This(Open), 3);
Assert.Equal(2, n);
Assert.Equal(new PlanStep(1, 1, 0), steps[0]);
Assert.Equal(new PlanStep(2, 1, 0), steps[1]);
// Where Off is not needed before the step, Smash is fine: Switch gives Off after it.
var later = new[]
{
new Verb { Id = "Smash", Gives = new[] { This(Cut), This(Off, false) } },
new Verb { Id = "Switch", Needs = new[] { This(Cut) }, Gives = new[] { This(Off) } },
};
var t = Make();
Sense(t, Thing(1, 1, 0f));
(n, steps) = Run(new Planner(later, 8, 3, 1.0), t, 1, This(Off), 3);
Assert.Equal(2, n);
Assert.Equal(new PlanStep(0, 1, 0), steps[0]);
Assert.Equal(new PlanStep(1, 1, 0), steps[1]);
// A verb whose need contradicts a literal still needed is pruned (Sever needs Cut false while Cut is wanted): Mend is the route.
var absurd = new[]
{
new Verb { Id = "Sever", Needs = new[] { This(Cut, false) }, Gives = new[] { This(Off) } },
new Verb { Id = "Mend", Gives = new[] { This(Off) } },
new Verb { Id = "Finish", Needs = new[] { This(Cut), This(Off) }, Gives = new[] { This(Open) } },
};
var u = Make();
Sense(u, Thing(1, 1, 0f, 1UL << Cut));
(n, steps) = Run(new Planner(absurd, 8, 3, 1.0), u, 1, This(Open), 3);
Assert.Equal(2, n);
Assert.Equal(new PlanStep(1, 1, 0), steps[0]);
Assert.Equal(new PlanStep(2, 1, 0), steps[1]);
}
[Fact]
public void Reach_is_derived_from_distance()
{
var planner = Build();
// The switch inside the reach needs no Approach, nor anything else: switching it off is one step.
var near = World(switchX: 0.8f);
var (n, steps) = Run(planner, near, 3, This(Off), 4);
Assert.Equal(1, n);
Expect(steps, (SwitchOffV, 3, 0));
Assert.Equal(1, Run(planner, World(switchX: 1f), 3, This(Off), 4).Length);
Assert.Equal(4, Run(planner, World(switchX: 1.001f), 3, This(Off), 4).Length);
Assert.Equal(1, Run(planner, World(switchX: 5.5f), 3, This(Off), 4, ox: 4.5f).Length);
// An emitter's own bit 63 is never read: Sense refuses it.
var p = Make();
Assert.ThrowsAny<ArgumentException>(() => Sense(p, Thing(3, Switch, 5f, 1UL << Reach)));
Assert.Equal(0, Occupied(p));
}
private static int Occupied(Perception p)
{
var n = 0;
for (var s = 0; s < p.PerceptCount; s++) if (p.Percept(s).Id != 0) n++;
return n;
}
[Fact]
public void Self_facts_come_from_the_caller()
{
var planner = Build();
var p = World();
var (n, steps) = Run(planner, p, 3, This(Off), 4, self: 1UL << Free);
Assert.Equal(2, n);
Expect(steps, (ApproachV, 3, 0), (SwitchOffV, 3, 0));
// The reach bit of self is cleared, not read: a caller passing it gets the same plan.
(n, steps) = Run(planner, p, 3, This(Off), 4, self: (1UL << Free) | Perception.InReachFact);
Assert.Equal(2, n);
}
[Fact]
public void Remembered_facts_are_as_last_sensed()
{
var planner = Build();
var p = Make();
var self = 1UL << Free;
// Door and held key within a metre; the door sensed locked.
Sense(p, Thing(4, Key, 0.4f, 1UL << Held), Thing(5, Door, 0.5f, 1UL << Locked));
var (n, steps) = Run(planner, p, 5, This(Open), 3, self: self);
Assert.Equal(2, n);
Expect(steps, (UnlockV, 5, 4), (OpenV, 5, 0));
// Unsensed but still remembered while the game would now say unlocked: the plan still includes Unlock.
for (var i = 0; i < 20; i++) Sense(p, Thing(4, Key, 0.4f, 1UL << Held));
Assert.Equal(5UL, p.Percept(SlotOf(p, 5)).Id);
(n, steps) = Run(planner, p, 5, This(Open), 3, self: self);
Assert.Equal(2, n);
Expect(steps, (UnlockV, 5, 4), (OpenV, 5, 0));
// Re-sensed unlocked: Open alone.
Sense(p, Thing(4, Key, 0.4f, 1UL << Held), Thing(5, Door, 0.5f, 0UL));
(n, steps) = Run(planner, p, 5, This(Open), 3, self: self);
Assert.Equal(1, n);
Expect(steps, (OpenV, 5, 0));
}
[Fact]
public void Tool_is_another_slot_of_an_accepted_kind()
{
var verbs = new[]
{
new Verb { Id = "Combine", This = Kinds(1), Tool = Kinds(1), Needs = new[] { Tool(Held) }, Gives = new[] { This(Cut) } },
};
var planner = new Planner(verbs, 8, 2, 1.0);
// A thing is never its own tool.
var p = Make();
Sense(p, Thing(1, 1, 0f, 1UL << Held));
Assert.Equal(-1, Run(planner, p, 1, This(Cut), 1).Length);
// A second thing of the kind, holding: it grounds the Tool literal.
var q = Make();
Sense(q, Thing(1, 1, 0f), Thing(2, 1, 0f, 1UL << Held));
var (n, steps) = Run(planner, q, 1, This(Cut), 1);
Assert.Equal(1, n);
Assert.Equal(new PlanStep(0, 1, 2), steps[0]);
// A second thing of another kind is rejected by the Tool filter.
var r = Make();
Sense(r, Thing(1, 1, 0f), Thing(2, 9, 0f, 1UL << Held));
Assert.Equal(-1, Run(planner, r, 1, This(Cut), 1).Length);
// A free slot reads kind 0 and facts 0, and grounds nothing even where a filter accepts kind 0 and a need is a fact being false.
var anyThing = new[] { new Verb { Id = "Idle", This = Kinds(0), Gives = new[] { Self(1) } } };
Assert.Equal(-1, Run(new Planner(anyThing, 8, 1, 1.0), Make(), 0, Self(1), 1).Length);
var lonelyTool = new[] { new Verb { Id = "Lone", This = Kinds(1), Tool = Kinds(0), Needs = new[] { Tool(Held, false) }, Gives = new[] { Self(1) } } };
var lone = Make();
Sense(lone, Thing(1, 1, 0f));
Assert.Equal(-1, new Planner(lonelyTool, 8, 1, 1.0).Plan(lone, 0UL, 0f, 0f, 0f, 0, Self(1), 1, new PlanStep[1]));
// A free slot grounds nothing, however its facts read: forgotten, the second thing is no tool.
var s = Make(memory: 0.05);
Sense(s, Thing(1, 1, 0f), Thing(2, 1, 0f, 1UL << Held));
for (var i = 0; i < 20; i++) Sense(s, Thing(1, 1, 0f));
Assert.Equal(0UL, s.Percept(1).Id);
Assert.Equal(-1, Run(planner, s, 1, This(Cut), 1).Length);
}
[Fact]
public void Construction_and_Plan_refuse_bad_input()
{
var good = Catalogue();
_ = new Planner(good, 1, 0, 0.001);
_ = new Planner(good, 256, 8, 1e9);
_ = new Planner(Array.Empty<Verb>(), 4, 3, 1.0);
Assert.ThrowsAny<ArgumentException>(() => new Planner(good, 8, -1, 1.0));
Assert.ThrowsAny<ArgumentException>(() => new Planner(good, 8, 9, 1.0));
Assert.ThrowsAny<ArgumentException>(() => new Planner(good, 8, 3, 0.0));
Assert.ThrowsAny<ArgumentException>(() => new Planner(good, 8, 3, -1.0));
Assert.ThrowsAny<ArgumentException>(() => new Planner(good, 8, 3, double.NaN));
Assert.ThrowsAny<ArgumentException>(() => new Planner(good, 8, 3, double.PositiveInfinity));
Assert.ThrowsAny<ArgumentException>(() => new Planner(good, 0, 3, 1.0));
Assert.ThrowsAny<ArgumentException>(() => new Planner(good, 257, 3, 1.0));
Assert.ThrowsAny<ArgumentException>(() => new Planner(new Verb[] { null! }, 8, 3, 1.0));
static void Refused(Verb v) => Assert.ThrowsAny<ArgumentException>(() => new Planner(new[] { v }, 8, 3, 1.0));
var ok = new Verb { Gives = new[] { This(0) } };
_ = new Planner(new[] { ok }, 8, 3, 1.0);
Refused(new Verb()); // no Gives
Refused(ok with { Needs = Many(9) }); // more than 8 Needs
Refused(ok with { Gives = Many(9) }); // more than 8 Gives
_ = new Planner(new[] { ok with { Needs = Many(8), Gives = Many(8) } }, 8, 3, 1.0);
Refused(ok with { Gives = new[] { This(64) } }); // Bit above 63
Refused(ok with { Gives = new[] { This(-1) } }); // Bit below 0
Refused(ok with { Needs = new[] { This(64) } });
Refused(ok with { Needs = new[] { Tool(0) } }); // Tool fact, no Tool filter
Refused(ok with { Gives = new[] { Tool(0) } });
_ = new Planner(new[] { ok with { Tool = Kinds(1), Gives = new[] { Tool(0) } } }, 8, 3, 1.0);
Refused(ok with { Gives = new[] { Self(63) } }); // Self on bit 63
Refused(ok with { Needs = new[] { Self(63, false) } });
_ = new Planner(new[] { ok with { Gives = new[] { This(63) } } }, 8, 3, 1.0); // This on 63 is the reach
Refused(ok with { Gives = new[] { This(1), This(1, false) } }); // both values
Refused(ok with { Needs = new[] { Self(2), Self(2, false) } });
_ = new Planner(new[] { ok with { Needs = new[] { This(2), Self(2, false) } } }, 8, 3, 1.0); // different subjects are different literals
Refused(ok with { This = Kinds() }); // filter with no kinds
Refused(ok with { Tool = Kinds() });
// Plan.
var planner = new Planner(good, 8, 4, 1.0);
var p = World();
var steps = new PlanStep[8];
var slot = SlotOf(p, 3);
Assert.ThrowsAny<ArgumentException>(() => planner.Plan(Make(4), 0UL, 0f, 0f, 0f, 0, Self(Free), 1, steps)); // wrong capacity
Assert.ThrowsAny<ArgumentException>(() => planner.Plan(p, 0UL, 0f, 0f, 0f, slot, This(Off), -1, steps));
Assert.ThrowsAny<ArgumentException>(() => planner.Plan(p, 0UL, 0f, 0f, 0f, slot, This(Off), 5, steps));
Assert.ThrowsAny<ArgumentException>(() => planner.Plan(p, 0UL, 0f, 0f, 0f, slot, This(Off), 4, steps.AsSpan(0, 3)));
Assert.Equal(4, planner.Plan(p, 0UL, 0f, 0f, 0f, slot, This(Off), 4, steps.AsSpan(0, 4)));
Assert.ThrowsAny<ArgumentException>(() => planner.Plan(p, 0UL, 0f, 0f, 0f, slot, Tool(Off), 4, steps)); // want on Tool
Assert.ThrowsAny<ArgumentException>(() => planner.Plan(p, 0UL, 0f, 0f, 0f, slot, Self(63), 4, steps)); // Self reach
Assert.ThrowsAny<ArgumentException>(() => planner.Plan(p, 0UL, 0f, 0f, 0f, slot, This(64), 4, steps));
Assert.ThrowsAny<ArgumentException>(() => planner.Plan(p, 0UL, 0f, 0f, 0f, 7, This(Off), 4, steps)); // free slot
Assert.ThrowsAny<ArgumentException>(() => planner.Plan(p, 0UL, 0f, 0f, 0f, -1, This(Off), 4, steps));
Assert.ThrowsAny<ArgumentException>(() => planner.Plan(p, 0UL, 0f, 0f, 0f, 8, This(Off), 4, steps));
Assert.Equal(0, planner.Plan(p, 0UL, 0f, 0f, 0f, 7, Self(Held, false), 4, steps)); // a Self want needs no target
Assert.Equal(0, planner.Plan(p, 0UL, 0f, 0f, 0f, slot, This(Reach, false), 4, steps)); // This reach is a want
}
[Fact]
public void Verb_lists_are_copied_and_read_only()
{
var needs = new[] { This(1) };
var verb = new Verb { Needs = needs, Gives = new[] { This(2) } };
needs[0] = This(9);
Assert.Equal(This(1), verb.Needs[0]);
Assert.Throws<NotSupportedException>(() => ((IList<Fact>)verb.Needs)[0] = This(3));
}
[Fact]
public void Planning_allocates_nothing()
{
var planner = Build();
var p = World();
var steps = new PlanStep[8];
var slot = SlotOf(p, 5);
Assert.Equal(7, planner.Plan(p, 0UL, 0f, 0f, 0f, slot, This(Open), 7, steps));
var wrong = 0;
var before = GC.GetAllocatedBytesForCurrentThread();
for (var i = 0; i < 2000; i++)
{
if (planner.Plan(p, 0UL, 0f, 0f, 0f, slot, This(Open), 7, steps) != 7) wrong++;
}
var allocated = GC.GetAllocatedBytesForCurrentThread() - before;
Assert.Equal(0, wrong);
Assert.Equal(0L, allocated);
}
[Fact]
public void A_chain_of_n_steps_is_found_at_depth_n_and_not_at_n_minus_one()
{
// Step k gives bit k on the target and needs bit k - 1: the want on bit n - 1 is exactly n steps away.
var chain = Enumerable.Range(0, 4).Select(k => new Verb { Id = "Link" + k, Needs = k == 0 ? Array.Empty<Fact>() : new[] { This(k - 1) }, Gives = new[] { This(k) } }).ToArray();
var p = Make();
Sense(p, Thing(1, 1, 0f));
var planner = new Planner(chain, 8, 8, 1.0);
for (var n = 1; n <= 4; n++)
{
var (found, steps) = Run(planner, p, 1, This(n - 1), n);
Assert.Equal(n, found);
for (var k = 0; k < n; k++) Assert.Equal(new PlanStep(k, 1, 0), steps[k]);
Assert.Equal(-1, Run(planner, p, 1, This(n - 1), n - 1).Length);
Assert.Equal(n, Run(planner, p, 1, This(n - 1), 8).Length);
}
}
[Fact]
public void Ties_in_a_longer_plan_go_to_the_last_step_first()
{
// Slots 0 and 1 are things 30 and 10, one kind. Grab gives a thing Held; Use takes Held in its tool and gives Self 1, on a different thing.
// The last step takes the lowest slot it can, which leaves slot 1 for Grab; taking the first step lowest would put Grab on slot 0.
var verbs = new[]
{
new Verb { Id = "Grab", This = Kinds(2), Gives = new[] { This(Held) } },
new Verb { Id = "Use", This = Kinds(2), Tool = Kinds(2), Needs = new[] { Tool(Held) }, Gives = new[] { Self(1) } },
};
var q = Make();
Sense(q, Thing(30, 2, 0f), Thing(10, 2, 0f));
var planner = new Planner(verbs, 8, 3, 1.0);
var steps = new PlanStep[3];
Assert.Equal(2, planner.Plan(q, 0UL, 0f, 0f, 0f, 0, Self(1), 3, steps));
Expect(steps, (0, 10, 0), (1, 30, 10));
Assert.Equal(-1, planner.Plan(q, 0UL, 0f, 0f, 0f, 0, Self(1), 1, steps));
}
[Fact]
public void A_want_that_cannot_be_reached_is_given_up_within_the_budget_at_any_depth()
{
var planner = Build();
var p = World();
var steps = new PlanStep[8];
foreach (var depth in new[] { 4, 5, 6 })
{
// The door cannot be opened in fewer than seven steps; relevance is what keeps the search from trying every verb on every thing.
Assert.Equal(-1, planner.Plan(p, 0UL, 0f, 0f, 0f, SlotOf(p, 5), This(Open), depth, steps));
Assert.True(planner.LastNodes < Planner.NodeBudget / 8, $"depth {depth} regressed {planner.LastNodes} groundings");
}
// The longest honest search in this world, the seven-step door, uses a fraction of the budget.
Assert.Equal(7, planner.Plan(p, 0UL, 0f, 0f, 0f, SlotOf(p, 5), This(Open), 8, steps));
Assert.True(planner.LastNodes < Planner.NodeBudget / 4, $"the door took {planner.LastNodes} groundings");
}
[Fact]
public void A_search_that_outgrows_the_budget_returns_no_plan_at_the_same_count_every_time()
{
// Two verbs ask each other's fact of any of eight things: every level is relevant and nothing ever grounds, so the tree is 16 wide.
var verbs = new[]
{
new Verb { Id = "A", This = Kinds(1), Needs = new[] { Self(2) }, Gives = new[] { Self(1) } },
new Verb { Id = "B", This = Kinds(1), Needs = new[] { Self(1) }, Gives = new[] { Self(2) } },
};
var p = Make();
Sense(p, Enumerable.Range(1, 8).Select(i => Thing((ulong)i, 1, 0f)).ToArray());
var planner = new Planner(verbs, 8, 8, 1.0);
var steps = new PlanStep[8];
for (var i = 0; i < 3; i++)
{
Assert.Equal(-1, planner.Plan(p, 0UL, 0f, 0f, 0f, 0, Self(1), 8, steps));
Assert.Equal(Planner.NodeBudget + 1, planner.LastNodes);
Assert.True(planner.LastExhausted);
}
// The call's budget is the cut-off, not the constant.
Assert.Equal(-1, planner.Plan(p, 0UL, 0f, 0f, 0f, 0, Self(1), 8, steps, budget: 100));
Assert.Equal(101, planner.LastNodes);
Assert.True(planner.LastExhausted);
// A short plan in the same world is not touched by the budget the long one spent.
Assert.Equal(1, planner.Plan(p, 1UL << 2, 0f, 0f, 0f, 0, Self(1), 8, steps));
Assert.Equal(new PlanStep(0, 1, 0), steps[0]);
Assert.False(planner.LastExhausted);
// No plan within the depth is not a spent budget.
Assert.Equal(-1, planner.Plan(p, 0UL, 0f, 0f, 0f, 0, Self(3), 8, steps));
Assert.False(planner.LastExhausted);
Assert.ThrowsAny<ArgumentOutOfRangeException>(() => planner.Plan(p, 0UL, 0f, 0f, 0f, 0, Self(1), 8, steps, budget: 0));
// The switch plan needs four steps: a small budget gives up on it, the default finds it.
var catalogue = Build();
var world = World();
var run = new PlanStep[8];
Assert.Equal(-1, catalogue.Plan(world, 0UL, 0f, 0f, 0f, SlotOf(world, 3), This(Off), 8, run, budget: 5));
Assert.True(catalogue.LastExhausted);
Assert.Equal(4, catalogue.Plan(world, 0UL, 0f, 0f, 0f, SlotOf(world, 3), This(Off), 8, run));
Assert.False(catalogue.LastExhausted);
}
// The test world's verbs but for what a test needs: Approach with no needs and Use of a Switch with a Knife that needs both in reach.
private static Verb[] Movers() => new[]
{
new Verb { Id = "Approach", This = Kinds(Switch, Knife), Gives = new[] { This(Reach) } },
new Verb { Id = "Use", This = Kinds(Switch), Tool = Kinds(Knife), Needs = new[] { This(Reach), Tool(Reach) }, Gives = new[] { This(Cut) } },
};
[Fact]
public void A_move_takes_reach_of_far_things_away()
{
var planner = Build(Movers());
var far = Make();
Sense(far, Thing(1, Switch, 5f), Thing(2, Knife, -5f));
Assert.Equal(-1, Run(planner, far, 1, This(Cut), 8).Length);
Assert.False(planner.LastExhausted);
var close = Make();
Sense(close, Thing(1, Switch, 5f), Thing(2, Knife, 5.5f));
var (n, steps) = Run(planner, close, 1, This(Cut), 8);
Assert.Equal(2, n);
Expect(steps, (0, 1, 0), (1, 1, 2));
}
[Fact]
public void A_move_brings_near_things_into_reach()
{
// The key is not a thing Approach accepts, but a switch beside it is.
var planner = Build(new[] { new Verb { Id = "Approach", This = Kinds(Switch), Gives = new[] { This(Reach) } } });
var p = Make();
Sense(p, Thing(1, Key, 5f), Thing(2, Switch, 5.3f));
var (n, steps) = Run(planner, p, 1, This(Reach), 4);
Assert.Equal(1, n);
Expect(steps, (0, 2, 0));
// Far from the key it brings nothing.
var apart = Make();
Sense(apart, Thing(1, Key, 5f), Thing(2, Switch, -5f));
Assert.Equal(-1, Run(planner, apart, 1, This(Reach), 4).Length);
// And out of reach is wanted just the same: going to the switch takes the key out of reach.
var kept = Make();
Sense(kept, Thing(1, Key, 0.5f), Thing(2, Switch, 5f));
(n, steps) = Run(planner, kept, 1, This(Reach, false), 4);
Assert.Equal(1, n);
Expect(steps, (0, 2, 0));
}
[Fact]
public void A_move_away_leaves_the_start_reach_behind()
{
var verbs = new[]
{
new Verb { Id = "Approach", This = Kinds(Switch, Knife), Gives = new[] { This(Reach) } },
new Verb { Id = "SwitchOff", This = Kinds(Switch), Needs = new[] { This(Reach) }, Gives = new[] { This(Off) } },
new Verb { Id = "Pry", This = Kinds(Knife), Tool = Kinds(Switch), Needs = new[] { Tool(Off), This(Reach) }, Gives = new[] { This(Cut) } },
};
var planner = Build(verbs);
var p = Make();
Sense(p, Thing(1, Knife, 0.5f), Thing(2, Switch, 5f));
// The knife is in reach at the start, but not after going to the switch: a second Approach.
var (n, steps) = Run(planner, p, 1, This(Cut), 8);
Assert.Equal(4, n);
Expect(steps, (0, 2, 0), (1, 2, 0), (0, 1, 0), (2, 1, 2));
}
}

View file

@ -0,0 +1,181 @@
using Lodur;
namespace Lodur.Core.Tests;
public sealed class PoseBehaviourTests
{
private static readonly Quat[] Hold = { Quat.Identity, Quat.FromAxisAngle(1f, 0f, 0f, -1f) };
private static readonly Quat[] Withdraw = { Quat.Identity, Quat.FromAxisAngle(1f, 0f, 0f, 0.3f) };
private static PoseBehaviour Held(HoldParameters? p = null) =>
new() { Keys = new[] { Hold }, FlinchPose = Withdraw, Hold = p ?? new HoldParameters() };
private static (float[] S, Quat[] T) Write(PoseBehaviour b, double leak, double strain, double t, double inGoal = 0.0, double weight = 1.0)
{
var s = new float[2];
var q = new Quat[2];
b.Write(weight, leak, strain, t, inGoal, s, q);
return (s, q);
}
private static float AngleAboutX(Quat q) => 2f * MathF.Atan2(q.X, q.W);
private static void SameBits(Quat want, Quat got)
{
Assert.Equal(BitConverter.SingleToInt32Bits(want.X), BitConverter.SingleToInt32Bits(got.X));
Assert.Equal(BitConverter.SingleToInt32Bits(want.Y), BitConverter.SingleToInt32Bits(got.Y));
Assert.Equal(BitConverter.SingleToInt32Bits(want.Z), BitConverter.SingleToInt32Bits(got.Z));
Assert.Equal(BitConverter.SingleToInt32Bits(want.W), BitConverter.SingleToInt32Bits(got.W));
}
[Fact]
public void One_key_is_held_and_the_leak_and_shake_blend_it_toward_the_flinch_pose_exactly_as_the_old_reflex_did()
{
var b = Held();
var (s, q) = Write(b, 0.0, 0.0, 0.123);
Assert.Equal(-1f, AngleAboutX(q[1]), 4);
Assert.All(s, x => Assert.Equal(1f, x));
foreach (var (leak, strain, t) in new[] { (0.4, 0.0, 0.0), (0.1, 2.5, 0.07), (0.0, 3.0, 1.234), (50.0, 50.0, 0.1) })
{
var w = Math.Min(Math.Max(leak * 0.3 + 0.08 * strain * Math.Sin(2.0 * Math.PI * 3.5 * t), 0.0), 1.0);
(s, q) = Write(b, leak, strain, t, inGoal: 9.9);
for (var m = 0; m < 2; m++) SameBits(Quat.Nlerp(Hold[m], Withdraw[m], (float)w), q[m]);
Assert.All(s, x => Assert.InRange(x, 0f, 1f));
}
}
[Fact]
public void The_release_form_a_key_equal_to_the_flinch_pose_with_gains_zero_writes_the_old_withdraw_pose_bit_for_bit()
{
var release = new PoseBehaviour
{
Keys = new[] { PainBoxBrain.Withdraw }, FlinchPose = PainBoxBrain.Withdraw,
Hold = new HoldParameters { FlinchGain = 0.0, StrainShake = 0.0 },
};
foreach (var (leak, strain, t) in new[] { (0.0, 0.0, 0.0), (0.9, 4.0, 3.3), (50.0, 50.0, 7.7) })
{
var (s, q) = Write(release, leak, strain, t, inGoal: 1.0);
for (var m = 0; m < 2; m++) SameBits(Quat.Nlerp(PainBoxBrain.Hold[m], PainBoxBrain.Withdraw[m], 1f), q[m]);
Assert.All(s, x => Assert.Equal(1f, x));
}
}
[Fact]
public void A_shipped_hold_strength_is_what_every_muscle_is_written_at()
{
var (s, _) = Write(Held(new HoldParameters { HoldStrength = 0.6f }), 0.0, 0.0, 0.0);
Assert.All(s, x => Assert.Equal(0.6f, x));
}
[Theory]
[InlineData(1.0, 0.0, 1.0)]
[InlineData(0.5, 0.0, 0.5)]
[InlineData(0.0, 0.0, 0.0)]
[InlineData(0.2, 0.1, 0.5)]
[InlineData(0.9, 0.2, 1.0)] // capped at 1, never past it
public void A_voluntary_strength_is_the_hold_strength_scaled_by_the_weight_plus_the_leak_capped_at_one(double weight, double leak, double expectedScale)
{
var hold = new HoldParameters { HoldStrength = 0.8f, FlinchGain = 3.0, StrainShake = 0.0 };
var (s, _) = Write(Held(hold), leak, 0.0, 0.0, weight: weight);
// weight + leak x FlinchGain: 0.2 + 0.1 x 3 = 0.5; 0.9 + 0.2 x 3 caps at 1.
Assert.All(s, x => Assert.Equal(0.8f * (float)expectedScale, x));
}
[Fact]
public void The_weight_scales_strength_only_the_targets_are_the_same_at_every_weight()
{
var b = Held(new HoldParameters { StrainShake = 0.4 });
var (_, full) = Write(b, 0.07, 0.6, 0.31, weight: 1.0);
var (_, faint) = Write(b, 0.07, 0.6, 0.31, weight: 0.1);
for (var m = 0; m < full.Length; m++) SameBits(full[m], faint[m]);
}
[Theory]
[InlineData(-0.01)]
[InlineData(1.01)]
[InlineData(double.NaN)]
public void A_weight_outside_zero_to_one_is_refused(double weight) =>
Assert.Throws<ArgumentOutOfRangeException>(() => Held().Write(weight, 0.0, 0.0, 0.0, 0.0, new float[2], new Quat[2]));
[Fact]
public void The_shake_is_zero_at_zero_strain_and_its_amplitude_grows_with_strain()
{
var b = Held();
double Peak(double strain)
{
var peak = 0.0;
for (var i = 0; i < 400; i++) peak = Math.Max(peak, b.Blend(0.0, strain, i * 0.005));
return peak;
}
Assert.Equal(0.0, Peak(0.0));
Assert.True(Peak(1.0) > 0.0);
Assert.True(Peak(2.0) > Peak(1.0) * 1.9);
Assert.True(Peak(4.0) > Peak(2.0) * 1.9);
}
[Fact]
public void Keys_are_walked_in_a_loop_key_zero_exactly_at_phase_zero_the_nlerp_midpoint_half_way_and_back_to_key_zero_after_k()
{
var keys = new[]
{
new[] { Quat.FromAxisAngle(0f, 0f, 1f, 0.0f), Quat.FromAxisAngle(0f, 1f, 0f, 0.1f) },
new[] { Quat.FromAxisAngle(0f, 0f, 1f, 0.5f), Quat.FromAxisAngle(0f, 1f, 0f, 0.7f) },
new[] { Quat.FromAxisAngle(0f, 0f, 1f, 1.0f), Quat.FromAxisAngle(0f, 1f, 0f, 0.2f) },
new[] { Quat.FromAxisAngle(0f, 0f, 1f, 1.5f), Quat.FromAxisAngle(0f, 1f, 0f, -0.4f) },
};
var b = new PoseBehaviour
{
Keys = keys, SecondsPerKey = 0.5, FlinchPose = keys[0], // flinch = key 0 and w = 0: only the base shows
Hold = new HoldParameters { FlinchGain = 0.0, StrainShake = 0.0 },
};
var (_, q) = Write(b, 0.0, 0.0, 0.0, inGoal: 0.0);
for (var m = 0; m < 2; m++) SameBits(Quat.Nlerp(keys[0][m], keys[0][m], 0f), q[m]);
(_, q) = Write(b, 0.0, 0.0, 0.0, inGoal: 0.25); // half way from key 0 to key 1
for (var m = 0; m < 2; m++) SameBits(Quat.Nlerp(Quat.Nlerp(keys[0][m], keys[1][m], 0.5f), keys[0][m], 0f), q[m]);
(_, q) = Write(b, 0.0, 0.0, 0.0, inGoal: 1.0); // key 2 exactly
for (var m = 0; m < 2; m++) SameBits(Quat.Nlerp(keys[2][m], keys[0][m], 0f), q[m]);
(_, q) = Write(b, 0.0, 0.0, 0.0, inGoal: 1.75); // half way from the last key back to key 0
for (var m = 0; m < 2; m++) SameBits(Quat.Nlerp(Quat.Nlerp(keys[3][m], keys[0][m], 0.5f), keys[0][m], 0f), q[m]);
(_, q) = Write(b, 0.0, 0.0, 0.0, inGoal: 2.0); // after k keys, key 0 again
var (_, start) = Write(b, 0.0, 0.0, 0.0, inGoal: 0.0);
for (var m = 0; m < 2; m++) SameBits(start[m], q[m]);
(_, q) = Write(b, 0.0, 0.0, 0.0, inGoal: 4.25); // and the second lap is the first
var (_, first) = Write(b, 0.0, 0.0, 0.0, inGoal: 0.25);
for (var m = 0; m < 2; m++) SameBits(first[m], q[m]);
}
[Fact]
public void A_behaviour_is_checked_against_its_own_shape_and_writes_into_spans_of_its_muscle_count_only()
{
var b = Held();
Assert.Equal(2, b.MuscleCount);
Assert.Throws<ArgumentException>(() => b.Write(1.0, 0.0, 0.0, 0.0, 0.0, new float[1], new Quat[2]));
Assert.Throws<ArgumentException>(() => b.Write(1.0, 0.0, 0.0, 0.0, 0.0, new float[2], new Quat[3]));
Brain Of(PoseBehaviour p) => new() { Goals = new[] { new GoalSpec { Id = "g", Behaviour = p } } };
Assert.Throws<ArgumentException>(() => new Actor(0.01, 1, new NerveParameters(), new WithdrawalParameters(), new DriveParameters(), Of(new PoseBehaviour())));
Assert.Throws<ArgumentException>(() => new Actor(0.01, 1, new NerveParameters(), new WithdrawalParameters(), new DriveParameters(),
Of(b with { FlinchPose = new Quat[1] })));
Assert.Throws<ArgumentException>(() => new Actor(0.01, 1, new NerveParameters(), new WithdrawalParameters(), new DriveParameters(),
Of(b with { Keys = new[] { Hold, new Quat[1] } })));
}
[Fact]
public void Nlerp_takes_the_shorter_arc_and_returns_a_unit_quaternion()
{
var a = Quat.FromAxisAngle(0f, 0f, 1f, 0.2f);
var b = Quat.FromAxisAngle(0f, 0f, 1f, 0.6f);
var negB = new Quat(-b.X, -b.Y, -b.Z, -b.W); // same rotation, opposite sign
var m = Quat.Nlerp(a, negB, 0.5f);
Assert.Equal(0.4f, 2f * MathF.Atan2(m.Z, m.W), 3);
Assert.Equal(1f, m.X * m.X + m.Y * m.Y + m.Z * m.Z + m.W * m.W, 5);
Assert.Equal(a.Z, Quat.Nlerp(a, b, 0f).Z, 6);
Assert.Equal(b.Z, Quat.Nlerp(a, b, 1f).Z, 6);
}
}

View file

@ -0,0 +1,179 @@
using Lodur;
namespace Lodur.Core.Tests;
public sealed class SensoryPerceptionTests
{
private const double Dt = 0.01;
private static readonly float[] Zero = { 0f };
private static readonly BoxStimulus[] NoBoxes = System.Array.Empty<BoxStimulus>();
/// <summary>A sensory nerve with sensitisation off, so afferent = (stimulus - threshold) * gain.</summary>
private static NerveParameters Plain(double threshold = 0.05, double delay = 0.0, double gain = 1.0) =>
new NerveParameters { Threshold = threshold, SensitisationGrowth = 0.0, ConductionDelaySeconds = delay, Gain = gain };
private static Perception Senses(NerveParameters senses, int regions = 1, int senseRegion = 0) =>
new Perception(new NerveParameters(), Dt, regions, senses, senseRegion);
private static void Sense(Perception p, Emitter[] emitters) => p.Sense(Zero, Zero, Zero, NoBoxes, emitters);
[Fact]
public void An_emitter_is_full_at_its_position_half_at_half_its_radius_and_zero_at_and_beyond_the_radius()
{
var e = new Emitter(Channel.Audio, 1f, 2f, 3f, 4f, 0.8);
Assert.Equal(0.8, e.Received(1f, 2f, 3f), 12);
Assert.Equal(0.4, e.Received(3f, 2f, 3f), 12); // 2 m along x: half the radius
Assert.Equal(0.4, e.Received(1f, 2f, 5f), 12); // distance is Euclidean, not per axis
Assert.Equal(0.0, e.Received(5f, 2f, 3f)); // exactly at the radius
Assert.Equal(0.0, e.Received(9f, 2f, 3f));
Assert.Equal(0.0, new Emitter(Channel.Audio, 0f, 0f, 0f, 0f, 0.8).Received(0f, 0f, 0f)); // no radius, no reach
}
[Fact]
public void Within_a_channel_the_larger_emitter_wins_and_across_channels_the_signals_saturate()
{
var p = Senses(Plain());
Sense(p, new[] { new Emitter(Channel.Audio, 0f, 0f, 0f, 1f, 0.3), new Emitter(Channel.Audio, 0f, 0f, 0f, 1f, 0.5) });
Sense(p, new[] { new Emitter(Channel.Audio, 0f, 0f, 0f, 1f, 0.3), new Emitter(Channel.Audio, 0f, 0f, 0f, 1f, 0.5) });
Assert.Equal(0.5, p.ChannelStimulus(Channel.Audio), 12);
Assert.Equal(0.45, p.ChannelAfferent(Channel.Audio), 12); // not 0.3 + 0.5, not the sum of two afferents
var q = Senses(Plain());
var both = new[] { new Emitter(Channel.Audio, 0f, 0f, 0f, 1f, 0.5), new Emitter(Channel.Visual, 0f, 0f, 0f, 1f, 0.35) };
Sense(q, both);
Sense(q, both);
double a = 0.45, b = 0.30;
Assert.Equal(a, q.ChannelAfferent(Channel.Audio), 12);
Assert.Equal(b, q.ChannelAfferent(Channel.Visual), 12);
Assert.Equal(0.0, q.ChannelAfferent(Channel.Interrupt));
Assert.Equal(1.0 - (1.0 - a) * (1.0 - b), q.Load, 12);
Assert.True(q.Load < a + b);
// One afferent past 1 is capped before combining, so the load never leaves 0..1.
var r = Senses(Plain(gain: 5.0));
var loud = new[] { new Emitter(Channel.Audio, 0f, 0f, 0f, 1f, 0.5), new Emitter(Channel.Interrupt, 0f, 0f, 0f, 1f, 0.2) };
Sense(r, loud);
Sense(r, loud);
Assert.Equal(1.0, r.Load);
}
[Theory]
[InlineData(0.01, 0.06, 6)]
[InlineData(0.005, 0.06, 12)]
[InlineData(0.01, 0.0, 1)]
public void A_step_emitters_afferent_arrives_exactly_the_conduction_delay_later(double dt, double delay, int ticks)
{
var p = new Perception(new NerveParameters(), dt, 1, Plain(delay: delay), 0);
var quiet = new[] { new Emitter(Channel.Visual, 0f, 0f, 0f, 1f, 0.01) }; // under the threshold
for (var i = 0; i < 20; i++) { Sense(p, quiet); Assert.Equal(0.0, p.Load); }
var loud = new[] { new Emitter(Channel.Visual, 0f, 0f, 0f, 1f, 0.8) };
for (var i = 0; i < ticks; i++) { Sense(p, loud); Assert.Equal(0.0, p.Load); } // still in flight
Sense(p, loud);
Assert.True(p.Load > 0.0);
Assert.Equal(0.0, p.ChannelAfferent(Channel.Audio));
}
[Fact]
public void A_sustained_emitter_sensitises_its_channel_as_a_noxious_stimulus_does()
{
var p = Senses(new NerveParameters { Threshold = 0.1 });
var e = new[] { new Emitter(Channel.Audio, 0f, 0f, 0f, 1f, 0.8) };
for (var i = 0; i < 20000; i++) Sense(p, e);
Assert.Equal(0.7 * 2.0, p.ChannelAfferent(Channel.Audio), 9); // (stimulus - threshold) * SensitisationCap
}
[Fact]
public void Only_the_sense_regions_point_decides_what_the_emitters_reach()
{
float[] x = { 0f, 0f }, y = { 0f, 0f }, z = { 0f, 0f };
var emitters = new[] { new Emitter(Channel.Audio, 0f, 0f, 0f, 1f, 0.8) };
Perception Make() => Senses(Plain(), regions: 2, senseRegion: 1);
// The sense region (1) is far from the emitter; region 0 sitting on it changes nothing.
var far = Make();
x[0] = 0f; x[1] = 5f;
for (var i = 0; i < 5; i++) far.Sense(x, y, z, NoBoxes, emitters);
Assert.Equal(0.0, far.ChannelStimulus(Channel.Audio));
Assert.Equal(0.0, far.Load);
// Moving the sense region next to it does.
x[1] = 0f;
for (var i = 0; i < 5; i++) far.Sense(x, y, z, NoBoxes, emitters);
Assert.Equal(0.8, far.ChannelStimulus(Channel.Audio), 12);
Assert.True(far.Load > 0.0);
// And with region 0 far away and region 1 on it, it still reaches.
var near = Make();
x[0] = 5f; x[1] = 0f;
for (var i = 0; i < 5; i++) near.Sense(x, y, z, NoBoxes, emitters);
Assert.Equal(0.8, near.ChannelStimulus(Channel.Audio), 12);
}
[Fact]
public void Without_senses_or_without_emitters_the_load_and_every_channel_stay_zero()
{
var deaf = new Perception(new NerveParameters(), Dt, 1);
var loud = new[] { new Emitter(Channel.Audio, 0f, 0f, 0f, 1f, 1.0) };
var hearing = Senses(Plain());
for (var i = 0; i < 10000; i++)
{
deaf.Sense(Zero, Zero, Zero, NoBoxes, loud);
hearing.Sense(Zero, Zero, Zero, NoBoxes);
Assert.Equal(0.0, deaf.Load);
Assert.Equal(0.0, hearing.Load);
}
foreach (var c in new[] { Channel.Audio, Channel.Visual, Channel.Interrupt })
{
Assert.Equal(0.0, deaf.ChannelStimulus(c));
Assert.Equal(0.0, deaf.ChannelAfferent(c));
Assert.Equal(0.0, hearing.ChannelAfferent(c));
}
}
[Fact]
public void A_sense_region_outside_the_body_is_refused()
{
Assert.Throws<ArgumentOutOfRangeException>(() => Senses(Plain(), regions: 2, senseRegion: 2));
}
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(2)]
public void The_sense_point_is_the_sense_regions_and_the_distance_counts_every_axis(int axis)
{
// Three regions; the sense region is the middle one. The first and last sit exactly on the emitter, the middle one half a radius away along one axis.
float[] x = { 0f, 0f, 0f }, y = { 0f, 0f, 0f }, z = { 0f, 0f, 0f };
var offset = new[] { x, y, z }[axis];
offset[1] = 0.5f;
var p = Senses(Plain(), regions: 3, senseRegion: 1);
var emitters = new[] { new Emitter(Channel.Audio, 0f, 0f, 0f, 1f, 0.8) };
p.Sense(x, y, z, NoBoxes, emitters);
Assert.Equal(0.4, p.ChannelStimulus(Channel.Audio), 12);
}
[Fact]
public void An_emitter_with_a_channel_outside_the_three_is_refused_up_front_and_leaves_the_tick_unrun()
{
var p = Senses(Plain());
var good = new[] { new Emitter(Channel.Audio, 0f, 0f, 0f, 1f, 0.8) };
for (var i = 0; i < 3; i++) Sense(p, good);
var stimulus = p.ChannelStimulus(Channel.Audio);
var afferent = p.ChannelAfferent(Channel.Audio);
var load = p.Load;
var bad = new[] { new Emitter(Channel.Audio, 0f, 0f, 0f, 1f, 0.8), new Emitter((Channel)7, 0f, 0f, 0f, 1f, 0.8) };
var e = Assert.Throws<ArgumentException>(() => Sense(p, bad));
Assert.Contains("Emitter 1", e.Message);
Assert.Equal(stimulus, p.ChannelStimulus(Channel.Audio));
Assert.Equal(afferent, p.ChannelAfferent(Channel.Audio));
Assert.Equal(load, p.Load);
// The tick did not advance: a twin that never saw the bad call stays identical from here on.
var twin = Senses(Plain());
for (var i = 0; i < 3; i++) Sense(twin, good);
for (var i = 0; i < 20; i++) { Sense(p, good); Sense(twin, good); Assert.Equal(twin.Load, p.Load); }
}
}

View file

@ -0,0 +1,110 @@
using Lodur;
namespace Lodur.Core.Tests;
/// <summary>
/// The humanoid's vessel bands on a real Actor: a knife cut at the BDS knife's severity and the BDS blood gain (ruling bds-blood-gain-simulated; both fixtures here, named, as
/// the BDS client maps them) kills in about 30 s of blood loss when it opens a carotid or the femoral, and drowns him first when it opens the front of the throat
/// (rulings bds-bleed-by-vessels, bds-drown-in-own-blood-first). The Actor's brain clutches on air hunger, as a body that struggles for breath does.
/// </summary>
public sealed class VesselTests
{
private const double Dt = 0.01;
private const double KnifeSeverity = 20.0;
private const double BloodGain = 10.0;
private static readonly BodyPlan Body = BodyPlans.Humanoid();
private static readonly PhysiologyPlan Plan = PhysiologyPlans.Humanoid();
private static readonly float[] NoPoint = { 0f };
private readonly record struct Band(DeathCause Cause, double DeadAt, double OutAt, double BrainOxygenOut, double BloodLossOut, double MaxOcclusion, double OcclusionFullAt, string[] Layers);
/// <summary>The identity pose of every joint of the humanoid, the pose the clutch goal holds.</summary>
private static Quat[] Identity() => Enumerable.Repeat(Quat.Identity, Body.Joints.Count).ToArray();
private static Brain Clutch() => new()
{
Goals = new[]
{
new GoalSpec
{
Id = "rest", Priority = 0.0,
Behaviour = new PoseBehaviour { Keys = new[] { Identity() }, FlinchPose = Identity(), Hold = new HoldParameters { HoldStrength = 0.7f } },
},
new GoalSpec
{
Id = "clutch", Priority = 3.0, InvoluntarySeconds = double.PositiveInfinity,
When = new[] { new Condition(DriveQuantity.AirHunger, ConditionOp.AtLeast, 0.3) },
Behaviour = new PoseBehaviour { Keys = new[] { Identity() }, FlinchPose = Identity(), Hold = new HoldParameters { HoldStrength = 0.8f, FlinchGain = 0.0, StrainShake = 0.0 } },
},
},
};
/// <summary>One knife wound of the fixture's severity at <paramref name="point"/> (the part's frame) and <paramref name="depth"/>, then the real Actor ticked until it dies.</summary>
private static Band Cut(string part, Side side, (float X, float Y, float Z) point, double depth)
{
var p = new Physiology(Body, Plan, 20.0, BloodGain);
var a = new Actor(Dt, 1, new NerveParameters(), new WithdrawalParameters(), new DriveParameters(), Clutch(), physiology: p);
var pi = Body.PartIndex(part, side);
var stack = Plan.Parts.First(s => s.PartLabel == part && s.Side == side);
Span<int> layers = stackalloc int[stack.Tissues.Count];
var n = stack.Reach(point, depth, layers);
Assert.True(p.Afflict(Plan.AfflictionIndex("Cut"), pi, layers[..n], KnifeSeverity));
var names = layers[..n].ToArray().Select(i => stack.Tissues[i].Label).ToArray();
var s = new float[p.JointCount];
var q = new Quat[p.JointCount];
double deadAt = -1, outAt = -1, oxygen = -1, loss = -1, maxOcc = 0, fullAt = -1;
for (long i = 0; i < (long)(600.0 / Dt) && !p.Dead; i++)
{
a.Tick(NoPoint, NoPoint, NoPoint, default, s, q);
var t = (i + 1) * Dt;
if (p.Dead) deadAt = t;
maxOcc = Math.Max(maxOcc, p.Occlusion);
if (fullAt < 0 && p.Occlusion >= 0.99) fullAt = t;
if (outAt < 0 && p.Consciousness <= 0.1)
{
outAt = t;
oxygen = p.BrainOxygen;
loss = p.BloodLoss;
}
}
return new Band(p.Cause, deadAt, outAt, oxygen, loss, maxOcc, fullAt, names);
}
// The clutch fixture is the spec's probe setup: hold 0.8, priority 3. Shipped readings (deterministic, Release): either carotid and either femoral die of BloodLoss at 29.73 s, out at 16.82 s with brain oxygen 0.995 and no occlusion;
// the front of the throat fills the airway at 1.29 s, is out at 95.56 s with brain oxygen 0.376 and blood loss 0.4937 and dies of Consciousness at 184.8 s. Mutants measured the same way: VesselV 1.0 dies at 79.35 s;
// a carotid with no site (reached at the front of the throat too) at 16.15 s; cough 2.0 fills the airway at 129.95 s, is out at 127.7 s with brain oxygen 0.994 and blood loss 0.6000 and dies of BloodLoss at 380.9 s;
// larynx V 1.0 fills at 0.85 s, is out at 86.61 s with brain oxygen 0.435 and blood loss 0.6001, dies of BloodLoss at 191.0 s. Every bound is the geometric midpoint of shipped and its least claimed mutant (ruling deterministic-bound-margin).
[Theory]
[InlineData("Head", Side.Center, 0.0778f, -0.0778f, 0f, "CarotidLeft")]
[InlineData("Head", Side.Center, -0.0778f, -0.0778f, 0f, "CarotidRight")]
[InlineData("Thigh", Side.Left, -0.0495f, 0.12f, 0.0495f, "Femoral")]
[InlineData("Thigh", Side.Right, 0.0495f, 0.12f, 0.0495f, "Femoral")]
public void A_vessel_kills_in_about_30_seconds_of_blood_loss_and_does_not_drown(string part, Side side, float x, float y, float z, string vessel)
{
// Death in (21.9, 48.6) s: shipped 29.73 (ruling bds-bleed-by-vessels, about 30 s, sets the target, not a band); the bounds are the midpoints sqrt(29.73 x 16.15) for the unsited carotid and sqrt(29.73 x 79.35) for VesselV 1.0, separation 1.84 and 2.67.
var r = Cut(part, side, (x, y, z), 0.02);
Assert.Contains(vessel, r.Layers);
Assert.Equal(DeathCause.BloodLoss, r.Cause);
Assert.InRange(r.DeadAt, 21.9, 48.6);
Assert.Equal(0.0, r.MaxOcclusion); // no airway tissue reached: exactly zero
}
[Fact]
public void The_front_of_the_throat_drowns_him_before_it_bleeds_him_out()
{
var r = Cut("Head", Side.Center, (0f, -0.0778f, 0.0778f), 0.02);
Assert.Equal(new[] { "Skin", "Fat", "Larynx" }, r.Layers); // no carotid at the front
// Occlusion full within 12.9 s = sqrt(1.29 x 129.95): shipped 1.29 s, cough 2.0 129.95 s, separation 10.
Assert.InRange(r.OcclusionFullAt, 0.0, 12.9);
Assert.True(r.OutAt > 0.0, "he never loses consciousness");
// Brain oxygen at consciousness 0.1: shipped 0.376, cough 2.0 0.994; bound sqrt(0.376 x 0.994) = 0.611 (separation 2.6).
Assert.True(r.BrainOxygenOut < 0.611, $"brain oxygen {r.BrainOxygenOut}");
// Blood loss then: shipped 0.4937, cough 2.0 0.60004 and larynx V 1.0 0.60008; bound sqrt(0.4937 x 0.60004) = 0.5443 (separation 1.2155).
Assert.True(r.BloodLossOut < 0.5443, $"blood loss {r.BloodLossOut}");
Assert.Equal(DeathCause.Consciousness, r.Cause);
}
}

View file

@ -0,0 +1,617 @@
using Lodur;
namespace Lodur.Core.Tests;
/// <summary>The will breaks when resolve reaches zero, mends when it climbs back to WillMendsAt, and can break again.</summary>
public sealed class WillTests
{
private static Brain Gate(DriveQuantity q, double threshold) => new()
{
Goals = new[]
{
new GoalSpec { Id = "objective", Behaviour = new PoseBehaviour { Keys = new[] { PainBoxBrain.Hold }, FlinchPose = PainBoxBrain.Withdraw } },
new GoalSpec
{
Id = "release", Priority = 1.0,
When = new[] { new Condition(q, ConditionOp.AtLeast, threshold) },
Behaviour = new PoseBehaviour { Keys = new[] { PainBoxBrain.Withdraw }, FlinchPose = PainBoxBrain.Withdraw },
},
},
};
/// <summary>Ticks the box on (or off) until the predicate holds or the cap runs out; counts WillBroke events on the way.</summary>
private static long Until(PainBoxReplay r, bool boxOn, Func<DriveState, bool> done, ref int breaks, long cap = 40000)
{
for (long i = 0; i < cap; i++)
{
if ((r.Tick(boxOn) & TickEvents.WillBroke) != 0) breaks++;
if (done(r.Actor.Drive)) return i;
}
Assert.Fail("the predicate never held");
return -1;
}
[Fact]
public void A_will_that_mends_can_break_again_and_each_break_is_reported_and_counted_but_resolve_parked_at_zero_breaks_once()
{
var r = new PainBoxReplay(1, brain: Gate(DriveQuantity.Breaks, 99.0));
var breaks = 0;
Until(r, true, d => d.WillBroken, ref breaks);
Assert.Equal(1, breaks);
Assert.Equal(1, r.Actor.Drive.Breaks);
for (var i = 0; i < 3000; i++) r.Tick(true); // held under the box, resolve parked at zero
Assert.Equal(0.0, r.Actor.Drive.Resolve);
Assert.True(r.Actor.Drive.WillBroken);
for (var i = 0; i < 3000; i++) if ((r.Tick(true) & TickEvents.WillBroke) != 0) breaks++;
Assert.Equal(1, breaks);
Until(r, false, d => !d.WillBroken, ref breaks);
Assert.True(r.Actor.Drive.Resolve >= new DriveParameters().WillMendsAt);
Assert.Equal(1, r.Actor.Drive.Breaks);
Until(r, true, d => d.WillBroken, ref breaks);
Assert.Equal(2, breaks);
Assert.Equal(2, r.Actor.Drive.Breaks);
}
[Fact]
public void A_mend_waits_for_resolve_to_reach_WillMendsAt_not_merely_to_leave_zero()
{
var mends = new DriveParameters { WillMendsAt = 0.6 };
var r = new PainBoxReplay(1, drive: mends, brain: Gate(DriveQuantity.Breaks, 99.0));
var breaks = 0;
Until(r, true, d => d.WillBroken, ref breaks);
Until(r, false, d => d.Resolve > 0.0, ref breaks);
var mended = Until(r, false, d => !d.WillBroken, ref breaks);
Assert.True(mended > 0, "the will mended the moment resolve left zero");
Assert.True(r.Actor.Drive.Resolve >= 0.6);
}
[Theory]
[InlineData(DriveQuantity.Breaks, true)]
[InlineData(DriveQuantity.WillBroken, false)]
public void A_release_gated_on_Breaks_holds_after_the_will_mends_and_one_gated_on_WillBroken_returns_to_the_objective(DriveQuantity q, bool holds)
{
var r = new PainBoxReplay(1, brain: Gate(q, 1.0));
var breaks = 0;
Until(r, true, d => d.WillBroken, ref breaks);
for (var i = 0; i < 50; i++) r.Tick(true);
Assert.Equal(1, r.Actor.GoalIndex);
Until(r, false, d => !d.WillBroken, ref breaks);
for (var i = 0; i < 100; i++) r.Tick(false);
Assert.Equal(holds ? 1 : 0, r.Actor.GoalIndex);
}
[Fact]
public void A_condition_on_Breaks_at_two_follows_the_second_break_by_the_latency_not_the_first()
{
var r = new PainBoxReplay(1, brain: Gate(DriveQuantity.Breaks, 2.0));
var breaks = 0;
Until(r, true, d => d.WillBroken, ref breaks);
for (var i = 0; i < 100; i++) r.Tick(true);
Assert.Equal(0, r.Actor.GoalIndex);
Until(r, false, d => !d.WillBroken, ref breaks);
Until(r, true, d => d.Breaks == 2, ref breaks);
var second = r.Actor.TickCount;
long changed = -1;
for (var i = 0; i < 30 && changed < 0; i++)
{
if ((r.Tick(true) & TickEvents.GoalChanged) != 0) changed = r.Actor.TickCount;
}
Assert.Equal(second + 10, changed);
}
[Fact]
public void Will_is_resolve_bit_for_bit_while_attention_and_consciousness_are_slots_that_read_one()
{
var r = new PainBoxReplay(3);
for (var i = 0; i < 2500; i++)
{
r.Tick(true);
var d = r.Actor.Drive;
Assert.Equal(1.0, d.Attention);
Assert.Equal(1.0, d.Consciousness);
Assert.Equal(BitConverter.DoubleToInt64Bits(d.Resolve), BitConverter.DoubleToInt64Bits(d.Will));
}
}
[Theory]
[InlineData(0.0)]
[InlineData(-0.1)]
[InlineData(1.01)]
[InlineData(double.NaN)]
public void A_WillMendsAt_outside_zero_exclusive_to_one_is_refused(double mendsAt) =>
Assert.Throws<ArgumentException>(() => new PainBoxReplay(1, drive: new DriveParameters { WillMendsAt = mendsAt }));
[Fact]
public void A_WillMendsAt_of_one_is_allowed() => _ = new PainBoxReplay(1, drive: new DriveParameters { WillMendsAt = 1.0 });
private static PoseBehaviour Pose => new() { Keys = new[] { PainBoxBrain.Hold }, FlinchPose = PainBoxBrain.Withdraw };
private static Brain Rage(double? entry) => new()
{
Goals = new[]
{
new GoalSpec { Id = "composure", Behaviour = Pose },
new GoalSpec
{
Id = "rage", Priority = 1.0, EntryResolve = entry,
When = new[] { new Condition(DriveQuantity.Breaks, ConditionOp.AtLeast, 1.0) },
Behaviour = Pose,
},
},
};
[Theory]
[InlineData(1.0, false)]
[InlineData(0.1, true)]
public void A_goals_entry_resolve_is_set_on_the_tick_it_takes_over_and_mends_the_will_only_if_it_reaches_WillMendsAt(double entry, bool stillBroken)
{
var r = new PainBoxReplay(1, brain: Rage(entry));
TickEvents e;
do { e = r.Tick(true); } while ((e & TickEvents.GoalChanged) == 0 && r.Actor.TickCount < 5000);
Assert.NotEqual(0, (int)(e & TickEvents.GoalChanged));
Assert.Equal(1, r.Actor.GoalIndex);
Assert.Equal(entry, r.Actor.Drive.Resolve);
Assert.Equal(stillBroken, r.Actor.Drive.WillBroken);
Assert.Equal(1, r.Actor.Drive.Breaks);
}
[Fact]
public void A_goal_with_no_entry_resolve_leaves_resolve_alone()
{
var r = new PainBoxReplay(1, brain: Rage(null));
TickEvents e;
do { e = r.Tick(true); } while ((e & TickEvents.GoalChanged) == 0 && r.Actor.TickCount < 5000);
Assert.Equal(0.0, r.Actor.Drive.Resolve);
Assert.True(r.Actor.Drive.WillBroken);
}
[Theory]
[InlineData(1.0, 0.0, 0.5)]
[InlineData(1.0, 0.4, 2.0)]
[InlineData(0.0, 0.0, 0.5)]
public void Effort_drains_resolve_only_after_the_involuntary_onset_by_effort_times_one_minus_pull_times_the_trait(double onset, double pull, double effort)
{
var drive = new DriveParameters { ResolveRecovery = 0.0, DrainTrait = 1.0 };
var brain = new Brain { Goals = new[] { new GoalSpec { Id = "g", Pull = pull, Effort = effort, InvoluntarySeconds = onset, Behaviour = Pose } } };
var r = new PainBoxReplay(1, drive: drive, brain: brain, jitter: 0.0);
var first = -1L;
var last = 1.0;
var steps = 0;
for (long i = 0; i < 400; i++)
{
r.Tick(false);
var now = r.Actor.Drive.Resolve;
if (now <= 0.0) break; // the floor clips the last step
if (now < 1.0 && first < 0)
{
first = i;
last = 1.0;
}
if (first >= 0)
{
Assert.Equal(0.01 * effort * (1.0 - pull), last - now, 12);
steps++;
}
last = now;
}
Assert.Equal((long)Math.Round(onset / 0.01), first);
Assert.True(steps > 20);
}
[Fact]
public void An_infinitely_involuntary_goal_never_pays_its_effort()
{
var brain = new Brain { Goals = new[] { new GoalSpec { Id = "g", Effort = 5.0, InvoluntarySeconds = double.PositiveInfinity, Behaviour = Pose } } };
var r = new PainBoxReplay(1, brain: brain);
for (var i = 0; i < 500; i++) r.Tick(false);
Assert.Equal(1.0, r.Actor.Drive.Resolve);
}
[Fact]
public void Onset_is_counted_from_the_tick_the_goal_takes_over_not_from_the_start()
{
var late = new GoalSpec { Id = "late", Priority = 1.0, Effort = 1.0, InvoluntarySeconds = 0.5, When = new[] { new Condition(DriveQuantity.Pain, ConditionOp.AtLeast, 0.3) }, Behaviour = Pose };
var brain = new Brain { Goals = new[] { new GoalSpec { Id = "calm", Behaviour = Pose }, late } };
var r = new PainBoxReplay(1, brain: brain, drive: new DriveParameters { ResolveRecovery = 0.0 });
long took = -1;
long firstEffort = -1;
for (long i = 0; i < 3000 && firstEffort < 0; i++)
{
var before = r.Actor.Drive;
var e = r.Tick(true);
if ((e & TickEvents.GoalChanged) != 0) took = i;
var drainedWithoutEffort = before.Resolve - r.Actor.Drive.Resolve;
if (took >= 0 && drainedWithoutEffort > 0.01 * 1.0 * 0.5 * 0.99) firstEffort = i;
}
Assert.True(took > 0);
Assert.True(firstEffort - took >= 50, $"effort began {firstEffort - took} ticks after the goal took over, under the 50 of the onset");
}
[Fact]
public void Goal_values_outside_their_ranges_are_refused_naming_the_goal()
{
Brain Of(GoalSpec g) => new() { Goals = new[] { g } };
GoalSpec Base() => new() { Id = "bad", Behaviour = Pose };
void Refused(GoalSpec g)
{
var ex = Assert.Throws<ArgumentException>(() => new Actor(0.01, 1, new NerveParameters(), new WithdrawalParameters(), new DriveParameters(), Of(g)));
Assert.Contains("bad", ex.Message);
}
Refused(Base() with { EntryResolve = -0.01 });
Refused(Base() with { EntryResolve = 1.01 });
Refused(Base() with { EntryResolve = double.NaN });
Refused(Base() with { Effort = -1.0 });
Refused(Base() with { Effort = double.PositiveInfinity });
Refused(Base() with { Effort = double.NaN });
Refused(Base() with { InvoluntarySeconds = -0.1 });
Refused(Base() with { InvoluntarySeconds = double.NaN });
_ = new Actor(0.01, 1, new NerveParameters(), new WithdrawalParameters(), new DriveParameters(),
Of(Base() with { EntryResolve = 0.0, Effort = 0.0, InvoluntarySeconds = double.PositiveInfinity }));
_ = new Actor(0.01, 1, new NerveParameters(), new WithdrawalParameters(), new DriveParameters(), Of(Base() with { EntryResolve = 1.0 }));
}
private static HoldParameters Hold07 => new() { HoldStrength = 0.7f };
[Fact]
public void A_voluntary_goal_writes_its_hold_strength_times_Will_to_the_WillCurve_with_no_leak()
{
// Effort drains resolve at a known rate with recovery off and the box off, so the leak is zero and Will is a clean ramp.
var drive = new DriveParameters { ResolveRecovery = 0.0, WillCurve = 0.5 };
var pose = new PoseBehaviour { Keys = new[] { PainBoxBrain.Hold }, FlinchPose = PainBoxBrain.Withdraw, Hold = Hold07 };
var brain = new Brain { Goals = new[] { new GoalSpec { Id = "g", Effort = 0.5, Behaviour = pose } } };
var r = new PainBoxReplay(1, drive: drive, brain: brain, jitter: 0.0);
var last = float.MaxValue;
for (var i = 0; i < 150; i++)
{
r.Tick(false);
Assert.Equal(0.0, r.Actor.Afferent(0));
var will = r.Actor.Drive.Will;
Assert.Equal(0.7f * (float)Math.Sqrt(will), r.Strengths[0]);
Assert.Equal(r.Strengths[0], r.Strengths[1]);
Assert.True(r.Strengths[0] <= last);
last = r.Strengths[0];
}
Assert.True(last < 0.6f, "the strength never fell with the will");
}
[Fact]
public void A_goal_that_takes_over_at_resolve_zero_writes_full_hold_strength_while_involuntary_and_what_leaks_while_voluntary()
{
float AtBreak(double involuntary)
{
var release = new GoalSpec
{
Id = "release", Priority = 1.0, InvoluntarySeconds = involuntary,
When = new[] { new Condition(DriveQuantity.Breaks, ConditionOp.AtLeast, 1.0) },
Behaviour = new PoseBehaviour { Keys = new[] { PainBoxBrain.Withdraw }, FlinchPose = PainBoxBrain.Withdraw, Hold = Hold07 },
};
var brain = new Brain { Goals = new[] { new GoalSpec { Id = "objective", Behaviour = new PoseBehaviour { Keys = new[] { PainBoxBrain.Hold }, FlinchPose = PainBoxBrain.Withdraw, Hold = Hold07 } }, release } };
var r = new PainBoxReplay(1, brain: brain);
TickEvents e;
do { e = r.Tick(true); } while ((e & TickEvents.GoalChanged) == 0 && r.Actor.TickCount < 5000);
Assert.Equal(0.0, r.Actor.Drive.Resolve);
Assert.True(r.Actor.Afferent(0) > 0.3);
return r.Strengths[0];
}
Assert.Equal(0.7f, AtBreak(double.PositiveInfinity));
Assert.True(AtBreak(0.0) < 0.7f * 0.5f, "a voluntary goal at zero will held its strength");
}
[Theory]
[InlineData(1.0, 0.7f)]
[InlineData(0.3, 0.7f * 0.7401198f)] // 0.3 ^ 0.25
public void The_tick_a_goal_takes_over_its_entry_resolve_is_the_will_its_first_write_is_weighted_by(double entry, float expected)
{
var pose = new PoseBehaviour { Keys = new[] { PainBoxBrain.Hold }, FlinchPose = PainBoxBrain.Withdraw, Hold = Hold07 };
var brain = new Brain
{
Goals = new[]
{
new GoalSpec { Id = "composure", Behaviour = pose },
new GoalSpec { Id = "rage", Priority = 1.0, EntryResolve = entry, When = new[] { new Condition(DriveQuantity.Breaks, ConditionOp.AtLeast, 1.0) }, Behaviour = pose },
},
};
var r = new PainBoxReplay(1, brain: brain);
TickEvents e;
do { e = r.Tick(r.Actor.Drive.Breaks == 0); } while ((e & TickEvents.GoalChanged) == 0 && r.Actor.TickCount < 5000);
Assert.Equal(0.0, r.Actor.Afferent(0));
Assert.Equal(expected, r.Strengths[0], 4);
}
[Theory]
[InlineData(0.0)]
[InlineData(-1.0)]
[InlineData(double.NaN)]
[InlineData(double.PositiveInfinity)]
public void A_WillCurve_that_is_not_finite_and_above_zero_is_refused(double curve) =>
Assert.Throws<ArgumentException>(() => new PainBoxReplay(1, drive: new DriveParameters { WillCurve = curve }));
public static IEnumerable<object[]> BadDrives() => new[]
{
new object[] { new DriveParameters { DrainTrait = double.NaN } },
new object[] { new DriveParameters { DrainTrait = -1.0 } },
new object[] { new DriveParameters { PainRise = double.PositiveInfinity } },
new object[] { new DriveParameters { PainDecay = double.NaN } },
new object[] { new DriveParameters { StrainRecover = -0.1 } },
new object[] { new DriveParameters { ResolveDrainPain = double.NaN } },
new object[] { new DriveParameters { ResolveDrainStrain = double.NegativeInfinity } },
new object[] { new DriveParameters { ResolveRecovery = double.NaN } },
new object[] { new DriveParameters { ResolveRecoversBelowPain = double.NaN } },
new object[] { new DriveParameters { ArousalRise = -1.0 } },
new object[] { new DriveParameters { ArousalDecay = double.NaN } },
new object[] { new DriveParameters { ResolveDrainArousal = double.PositiveInfinity } },
new object[] { new DriveParameters { ResolveRecoversBelowArousal = double.NaN } },
};
[Theory]
[MemberData(nameof(BadDrives))]
public void A_drive_value_the_drive_cannot_run_on_is_refused_at_construction_before_any_tick(DriveParameters bad) =>
Assert.Throws<ArgumentException>(() => new Actor(0.01, 1, new NerveParameters(), new WithdrawalParameters(), bad, PainBoxBrain.Make(0.5)));
[Theory]
[InlineData(1.0 / 120.0, 1.85, 222)] // 222 x (1/120) is just under 1.85 in floating point
[InlineData(1.0 / 60.0, 0.9, 54)]
[InlineData(0.01, 0.5, 50)]
[InlineData(0.01, 0.29, 29)] // 0.29 / 0.01 is 28.999999999999996: rounds to 29, floors to 28
public void The_involuntary_onset_is_the_requested_seconds_in_whole_ticks_whatever_the_tick_length(double dt, double onset, long ticks)
{
var brain = new Brain { Goals = new[] { new GoalSpec { Id = "g", Effort = 1.0, InvoluntarySeconds = onset, Behaviour = Pose } } };
var actor = new Actor(dt, 1, new NerveParameters(), new WithdrawalParameters(), new DriveParameters { ResolveRecovery = 0.0 }, brain);
float[] p = { 0f }, strengths = new float[2];
var targets = new Quat[2];
long firstDrain = -1, firstWeighted = -1;
for (long i = 0; i < ticks + 20; i++)
{
var before = actor.Drive.Resolve;
actor.Tick(p, p, p, System.Array.Empty<BoxStimulus>(), strengths, targets);
if (firstDrain < 0 && actor.Drive.Resolve < before) firstDrain = i;
if (firstWeighted < 0 && strengths[0] < 1f) firstWeighted = i;
}
Assert.Equal(ticks, firstDrain);
Assert.Equal(ticks, firstWeighted);
}
[Theory]
[InlineData(1e300)]
[InlineData(1e19)]
[InlineData(double.PositiveInfinity)]
public void An_onset_past_the_range_of_a_tick_count_is_involuntary_throughout_not_a_wrapped_negative(double onset)
{
var brain = new Brain { Goals = new[] { new GoalSpec { Id = "g", Effort = 1.0, InvoluntarySeconds = onset, Behaviour = Pose } } };
var actor = new Actor(0.01, 1, new NerveParameters(), new WithdrawalParameters(), new DriveParameters { ResolveRecovery = 0.0 }, brain);
float[] p = { 0f }, strengths = new float[2];
var targets = new Quat[2];
for (var i = 0; i < 500; i++)
{
actor.Tick(p, p, p, System.Array.Empty<BoxStimulus>(), strengths, targets);
Assert.Equal(1.0, actor.Drive.Resolve);
Assert.Equal(1f, strengths[0]);
}
}
[Fact]
public void A_puppet_that_starts_in_a_goal_with_an_entry_resolve_begins_at_it()
{
var brain = new Brain { Start = 1, Goals = new[] { new GoalSpec { Id = "calm", Behaviour = Pose }, new GoalSpec { Id = "rage", EntryResolve = 0.6, Behaviour = Pose } } };
var actor = new Actor(0.01, 1, new NerveParameters(), new WithdrawalParameters(), new DriveParameters(), brain);
Assert.Equal(0.6, actor.Drive.Resolve);
var calm = new Actor(0.01, 1, new NerveParameters(), new WithdrawalParameters(), new DriveParameters(), brain with { Start = 0 });
Assert.Equal(1.0, calm.Drive.Resolve);
}
// The slots read 1 in the core today; these tests lower attention through the internal seam and consciousness through a physiology
// (a brain of 1 Hp lesioned by 1 - c), and watch every consumer of Will move.
private static Actor Hold(double attention, double consciousness, DriveParameters? drive = null)
{
var brain = new Brain { Goals = new[] { new GoalSpec { Id = "g", Behaviour = new PoseBehaviour { Keys = new[] { PainBoxBrain.Hold }, FlinchPose = PainBoxBrain.Withdraw, Hold = Hold07 } } } };
var root = new[] { new TissueDef("brain", 1, 1, Consciousness: 1), new TissueDef("muscle", 10, 1, Motor: 1) };
var physiology = new Physiology(PhysioFixtures.Body3(), PhysioFixtures.Plan3(root: root), 20);
if (consciousness < 1.0)
{
Assert.True(physiology.Afflict(PhysioFixtures.Af("Lesion"), 0, 0, 1.0 - consciousness));
}
var actor = new Actor(0.01, 1, new NerveParameters(), new WithdrawalParameters(), drive ?? new DriveParameters(), brain, physiology: physiology);
actor.SetAttention(attention);
return actor;
}
private static readonly float[] NoPoint = { 0f };
private static TickEvents Step(Actor a, double boxIntensity, float[] strengths, Quat[] targets)
{
var box = new[] { new BoxStimulus(0f, 0f, 0f, 1f, 1f, 1f) { Intensity = boxIntensity } };
return a.Tick(NoPoint, NoPoint, NoPoint, box, strengths, targets);
}
[Theory]
[InlineData(1.0, 1.0)]
[InlineData(0.5, 1.0)]
[InlineData(1.0, 0.3)]
[InlineData(0.5, 0.3)]
[InlineData(0.5, 0.9)]
[InlineData(0.0, 1.0)]
public void Will_is_resolve_times_attention_capped_by_consciousness(double attention, double consciousness)
{
var a = Hold(attention, consciousness);
var s = new float[2];
var q = new Quat[2];
for (var i = 0; i < 300; i++)
{
Step(a, 0.6, s, q);
var d = a.Drive;
Assert.Equal(consciousness, d.Consciousness, 12); // 1 - (1 - c) is not c in doubles
Assert.Equal(Math.Min(d.Resolve * attention, d.Consciousness), d.Will);
}
}
[Fact]
public void Reflex_suppression_reads_Will_so_a_lowered_slot_releases_it_though_resolve_is_full()
{
// A held reflex accrues strain; with attention gone nothing is held, whatever resolve says.
double StrainAfter(double attention, double consciousness)
{
var a = Hold(attention, consciousness);
var s = new float[2];
var q = new Quat[2];
var died = false;
for (var i = 0; i < 100; i++) died |= (Step(a, 0.8, s, q) & TickEvents.Died) != 0;
Assert.True(a.Drive.Resolve > 0.9);
Assert.Equal(consciousness == 0.0, died); // no consciousness is a death by the ruled rule, on the first tick
return a.Drive.Strain;
}
var full = StrainAfter(1.0, 1.0);
Assert.True(full > 0.1);
Assert.Equal(0.0, StrainAfter(0.0, 1.0));
Assert.Equal(0.0, StrainAfter(1.0, 0.0));
var half = StrainAfter(0.5, 1.0);
Assert.True(half > 0.0 && half < full);
var capped = StrainAfter(1.0, 0.5);
Assert.True(capped > 0.0 && capped < full);
}
[Fact]
public void The_flinch_gate_reads_Will_so_no_flinch_is_reported_when_there_is_no_will_to_leak_from()
{
int Flinches(double attention)
{
var a = Hold(attention, 1.0);
var s = new float[2];
var q = new Quat[2];
var n = 0;
for (var i = 0; i < 400; i++) if ((Step(a, 0.9, s, q) & TickEvents.Flinch) != 0) n++;
Assert.True(a.Drive.Resolve > 0.5);
return n;
}
Assert.True(Flinches(0.3) > 0);
Assert.Equal(0, Flinches(0.0));
}
[Theory]
[InlineData(0.5, 1.0)]
[InlineData(1.0, 0.2)]
[InlineData(0.5, 0.4)]
public void The_voluntary_weight_reads_Will_so_a_lowered_slot_slackens_the_hold(double attention, double consciousness)
{
var a = Hold(attention, consciousness, new DriveParameters { WillCurve = 0.5 });
var s = new float[2];
var q = new Quat[2];
for (var i = 0; i < 20; i++)
{
Step(a, 0.0, s, q); // no stimulus, no leak
var c = a.Drive.Consciousness;
Assert.Equal(consciousness, c, 12);
Assert.Equal(0.7f * (float)Math.Sqrt(Math.Min(a.Drive.Resolve * attention, c)) * (float)c, s[0]); // the motor ceiling is the capacity times consciousness
}
}
[Fact]
public void An_entered_goals_resolve_is_set_once_on_the_takeover_so_a_rage_with_effort_drains_the_will_it_was_given()
{
var rage = new GoalSpec
{
Id = "rage", Priority = 1.0, EntryResolve = 1.0, Effort = 0.5, InvoluntarySeconds = 0.3,
When = new[] { new Condition(DriveQuantity.Breaks, ConditionOp.AtLeast, 1.0) }, Behaviour = Pose,
};
var r = new PainBoxReplay(1, brain: new Brain { Goals = new[] { new GoalSpec { Id = "composure", Behaviour = Pose }, rage } });
TickEvents e;
do { e = r.Tick(true); } while ((e & TickEvents.GoalChanged) == 0 && r.Actor.TickCount < 5000);
Assert.Equal(1.0, r.Actor.Drive.Resolve);
var onsetTicks = 30;
for (var i = 0; i < onsetTicks - 1; i++)
{
r.Tick(false);
Assert.True(r.Actor.Drive.Resolve > 0.95); // the onset runs on the refilled will without paying its effort
}
for (var i = 0; i < 170; i++) r.Tick(false);
Assert.Equal(1, r.Actor.GoalIndex);
Assert.True(r.Actor.Drive.Resolve < 0.3, $"resolve is {r.Actor.Drive.Resolve}: the entry effect ran again, or the effort never drained it");
}
[Fact]
public void Each_entry_to_a_goal_sets_resolve_once_and_a_re_entry_sets_it_again()
{
var calm = new GoalSpec { Id = "calm", Behaviour = Pose };
var rage = new GoalSpec { Id = "rage", Priority = 1.0, EntryResolve = 0.5, When = new[] { new Condition(DriveQuantity.Pain, ConditionOp.AtLeast, 0.5) }, Behaviour = Pose };
var r = new PainBoxReplay(1, brain: new Brain { Goals = new[] { calm, rage } });
var entries = 0;
long sinceEntry = -1;
var checkedInside = 0;
for (var i = 0; i < 8000; i++)
{
var on = i < 800 || (i >= 4500 && i < 5300);
var e = r.Tick(on);
if ((e & TickEvents.GoalChanged) != 0 && r.Actor.GoalIndex == 1)
{
entries++;
sinceEntry = 0;
Assert.Equal(0.5, r.Actor.Drive.Resolve);
}
else if (sinceEntry >= 0 && r.Actor.GoalIndex == 1 && ++sinceEntry == 100)
{
Assert.True(r.Actor.Drive.Resolve < 0.499, $"resolve is {r.Actor.Drive.Resolve} 100 ticks into the goal: it was set again");
checkedInside++;
}
}
Assert.Equal(2, entries);
Assert.Equal(2, checkedInside);
}
[Fact]
public void A_goal_whose_entry_resolve_is_exactly_WillMendsAt_mends_the_will()
{
var rage = new GoalSpec { Id = "rage", Priority = 1.0, EntryResolve = 0.5, When = new[] { new Condition(DriveQuantity.Breaks, ConditionOp.AtLeast, 1.0) }, Behaviour = Pose };
var r = new PainBoxReplay(1, drive: new DriveParameters { WillMendsAt = 0.5 }, brain: new Brain { Goals = new[] { new GoalSpec { Id = "composure", Behaviour = Pose }, rage } });
TickEvents e;
do { e = r.Tick(true); } while ((e & TickEvents.GoalChanged) == 0 && r.Actor.TickCount < 5000);
Assert.Equal(0.5, r.Actor.Drive.Resolve);
Assert.False(r.Actor.Drive.WillBroken);
}
[Fact]
public void Recovery_that_lands_exactly_on_WillMendsAt_mends_the_will_on_that_tick()
{
// Run once with a will that never mends to record resolve; then set WillMendsAt to a value that trace reaches exactly.
var trace = new List<double>();
var first = new PainBoxReplay(1, drive: new DriveParameters { WillMendsAt = 1.0 }, brain: Gate(DriveQuantity.Breaks, 99.0));
while (!first.Actor.Drive.WillBroken) first.Tick(true);
for (var i = 0; i < 7000; i++) { first.Tick(false); trace.Add(first.Actor.Drive.Resolve); }
var j = 6500;
var at = trace[j];
Assert.True(at > trace[j - 1] && at > 0.0 && at < 1.0, "the trace is not recovering at the probe tick");
var k = trace.FindIndex(x => x >= at);
Assert.Equal(j, k);
var second = new PainBoxReplay(1, drive: new DriveParameters { WillMendsAt = at }, brain: Gate(DriveQuantity.Breaks, 99.0));
while (!second.Actor.Drive.WillBroken) second.Tick(true);
for (var i = 0; i < 7000; i++)
{
second.Tick(false);
Assert.Equal(i < k, second.Actor.Drive.WillBroken);
}
}
}

View file

@ -0,0 +1,237 @@
using Lodur;
namespace Lodur.Core.Tests;
/// <summary>Which layers a wound at a point and depth reaches: the rule on a hand-built stack, then the humanoid's content probed against it.</summary>
public sealed class WoundReachTests
{
private static readonly PhysiologyPlan Humanoid = PhysiologyPlans.Humanoid();
private static TissueDef Shell(string label, double t) => new(label, 10, 1) { Thickness = t };
private static TissueDef Core(string label, TissueSite? site = null) => new(label, 10, 1) { Site = site };
private static PartTissuesDef Stack(params TissueDef[] tissues) => new("A", Side.Center, tissues);
private static int[] Reach(PartTissuesDef stack, (float X, float Y, float Z) point, double depth)
{
Span<int> layers = stackalloc int[stack.Tissues.Count];
var n = stack.Reach(point, depth, layers);
return layers[..n].ToArray();
}
private static string[] Labels(string part, (float X, float Y, float Z) point, double depth)
{
var stack = Humanoid.Parts.First(p => p.PartLabel == part && p.Side == Side.Center);
return Reach(stack, point, depth).Select(i => stack.Tissues[i].Label).ToArray();
}
[Fact]
public void Shells_are_reached_by_cumulative_thickness_strictly()
{
var stack = Stack(Shell("Skin", 0.002), Shell("Fat", 0.005), Core("Core"));
var p = (0f, 0f, 0f);
Assert.Equal(new[] { 0 }, Reach(stack, p, 0.001));
Assert.Equal(new[] { 0, 1 }, Reach(stack, p, 0.003));
Assert.Equal(new[] { 0, 1 }, Reach(stack, p, 0.007));
Assert.Equal(new[] { 0, 1, 2 }, Reach(stack, p, 0.0071));
Assert.Equal(new[] { 0 }, Reach(stack, p, 0.002));
}
[Fact]
public void A_sited_core_is_reached_only_past_the_shells_and_its_sites_surface()
{
var stack = Stack(Shell("Skin", 0.002), Shell("Fat", 0.005), Core("Organ", new TissueSite((0f, 0f, 0.05f), 0.01f)));
var p = (0f, 0f, 0.1f);
Assert.Equal(new[] { 0, 1 }, Reach(stack, p, 0.039));
Assert.Equal(new[] { 0, 1, 2 }, Reach(stack, p, 0.0401));
// Close to the site, the shells still gate it.
var near = (0f, 0f, 0.06f);
Assert.Equal(new[] { 0, 1 }, Reach(stack, near, 0.007));
Assert.Equal(new[] { 0, 1, 2 }, Reach(stack, near, 0.0071));
}
[Fact]
public void A_sited_tissue_between_shells_is_gated_by_the_shells_before_it_only()
{
// Skin 2 mm, Fat 5 mm, a vessel sited on the point, Muscle sheet 15 mm, an unsited core: the vessel sits at 7 mm (the shells before it), the core at 22 mm (all of them).
var stack = Stack(Shell("Skin", 0.002), Shell("Fat", 0.005), Core("Vessel", new TissueSite((0f, 0f, 0f), 0.01f)), Shell("Muscle", 0.015), Core("Fill"));
var p = (0f, 0f, 0f);
Assert.Equal(new[] { 0, 1 }, Reach(stack, p, 0.0069)); // kills: gate by nothing
Assert.Equal(new[] { 0, 1, 2, 3 }, Reach(stack, p, 0.0071));
Assert.Equal(new[] { 0, 1, 2, 3 }, Reach(stack, p, 0.021)); // kills: gate by the total (22 mm)
Assert.Equal(new[] { 0, 1, 2, 3, 4 }, Reach(stack, p, 0.0221)); // the unsited core keeps the total
// The distance still gates it: the site's surface is 0.04 m from this point.
Assert.Equal(new[] { 0, 1, 3 }, Reach(stack, (0f, 0f, 0.05f), 0.021));
}
/// <summary>The rule before vessel sites: every core, sited or not, is gated by the shells' total.</summary>
private static int[] ShippedReach(PartTissuesDef stack, (float X, float Y, float Z) point, double depth)
{
var shells = 0.0;
foreach (var t in stack.Tissues) shells += t.Thickness;
var hit = new List<int>();
var before = 0.0;
for (var i = 0; i < stack.Tissues.Count; i++)
{
var t = stack.Tissues[i];
if (t.Thickness > 0.0)
{
if (depth > before) hit.Add(i);
before += t.Thickness;
}
else if (depth > shells)
{
if (t.Site is not TissueSite site) hit.Add(i);
else
{
double dx = point.X - site.Centre.X, dy = point.Y - site.Centre.Y, dz = point.Z - site.Centre.Z;
if (depth > Math.Sqrt(dx * dx + dy * dy + dz * dz) - site.Radius) hit.Add(i);
}
}
}
return hit.ToArray();
}
[Fact]
public void Over_the_humanoid_only_the_femoral_sites_differ_from_the_rule_before_vessel_sites()
{
// Every part, a 9 x 9 x 9 grid of points 4 cm apart about the part's origin, depths 1 to 60 mm: the carotids sit after every shell of the head, so they gate as before; only a Femoral,
// listed before the thigh's muscle sheet, may be reached where the total would not.
var cases = 0;
var femoralGained = 0;
foreach (var stack in Humanoid.Parts)
{
var femoral = stack.PartLabel == "Thigh" ? stack.Tissues.ToList().FindIndex(t => t.Label == "Femoral") : -1;
for (var ix = -4; ix <= 4; ix++)
for (var iy = -4; iy <= 4; iy++)
for (var iz = -4; iz <= 4; iz++)
for (var mm = 1; mm <= 60; mm++)
{
var point = (0.04f * ix, 0.04f * iy, 0.04f * iz);
var now = Reach(stack, point, mm / 1000.0);
var before = ShippedReach(stack, point, mm / 1000.0);
cases++;
if (femoral < 0) { Assert.Equal(before, now); continue; }
var nowSansFemoral = now.Where(i => i != femoral).ToArray();
Assert.Equal(before.Where(i => i != femoral), nowSansFemoral);
if (now.Contains(femoral) && !before.Contains(femoral)) femoralGained++;
Assert.True(!before.Contains(femoral) || now.Contains(femoral), "a Femoral the old rule reached is lost");
}
}
Assert.True(cases > 800000, $"{cases} cases");
Assert.True(femoralGained > 0, "no Femoral is reached where the shells' total would have gated it");
}
[Fact]
public void A_depth_exactly_at_a_sites_surface_does_not_reach_it()
{
// Exact floats: the centre is 0.25 from the point, the radius 0.125, so the surface is 0.125 away.
var stack = Stack(Shell("Skin", 0.002), Core("Organ", new TissueSite((0f, 0f, 0.25f), 0.125f)));
var p = (0f, 0f, 0.5f);
Assert.Equal(new[] { 0 }, Reach(stack, p, 0.125));
Assert.Equal(new[] { 0, 1 }, Reach(stack, p, 0.1251));
}
[Fact]
public void Unsited_cores_fill_the_part_and_output_is_in_stack_order()
{
var stack = Stack(Shell("Skin", 0.002), Core("Far", new TissueSite((0f, 0f, 0.5f), 0.01f)), Core("Fill"));
Assert.Equal(new[] { 0, 2 }, Reach(stack, (0f, 0f, 0f), 0.01));
var two = Stack(Shell("Skin", 0.002), Core("Fill"), Core("Near", new TissueSite((0f, 0f, 0f), 0.01f)));
Assert.Equal(new[] { 0, 1, 2 }, Reach(two, (0f, 0f, 0f), 0.01));
}
[Fact]
public void Reach_refuses_bad_input()
{
var stack = Stack(Shell("Skin", 0.002), Core("Fill"));
var p = (0f, 0f, 0f);
foreach (var depth in new[] { 0.0, -0.01, double.NaN, double.PositiveInfinity })
{
Assert.Throws<ArgumentException>(() => Reach(stack, p, depth));
}
foreach (var bad in new[] { float.NaN, float.PositiveInfinity })
{
Assert.Throws<ArgumentException>(() => Reach(stack, (bad, 0f, 0f), 0.01));
Assert.Throws<ArgumentException>(() => Reach(stack, (0f, bad, 0f), 0.01));
Assert.Throws<ArgumentException>(() => Reach(stack, (0f, 0f, bad), 0.01));
}
Assert.Throws<ArgumentException>(() =>
{
Span<int> short1 = stackalloc int[1];
stack.Reach(p, 0.01, short1);
});
}
[Fact]
public void The_humanoid_throat_reaches_the_larynx_the_scalp_does_not()
{
Assert.Equal(new[] { "Skin", "Fat", "Larynx" }, Labels("Head", (0f, -0.0778f, 0.0778f), 0.02));
var scalp = Labels("Head", (0f, 0.11f, 0f), 0.02);
Assert.DoesNotContain("Larynx", scalp);
Assert.DoesNotContain("Brain", scalp);
Assert.Equal(new[] { "Skin", "Fat", "Skull" }, scalp);
Assert.Contains("Brain", Labels("Head", (0f, 0.11f, 0f), 0.04));
// The side of the neck reaches a carotid (mirrored left to right), the front of the throat none, the back of the neck neither.
Assert.Equal(new[] { "Skin", "Fat", "CarotidLeft", "Muscle" }, Labels("Head", (0.0778f, -0.0778f, 0f), 0.02));
Assert.Equal(new[] { "Skin", "Fat", "CarotidRight", "Muscle" }, Labels("Head", (-0.0778f, -0.0778f, 0f), 0.02));
Assert.Equal(new[] { "Skin", "Fat", "Muscle" }, Labels("Head", (0f, -0.0778f, -0.0778f), 0.02));
Assert.DoesNotContain("CarotidLeft", Labels("Head", (0f, -0.0778f, 0.0778f), 0.04));
var chest = Labels("Torso", (0.02f, 0.05f, 0.09f), 0.04);
Assert.Contains("Heart", chest);
Assert.DoesNotContain("Liver", chest);
Assert.DoesNotContain("KidneyLeft", chest);
Assert.DoesNotContain("KidneyRight", chest);
Assert.DoesNotContain("Trachea", chest);
Assert.Contains("LungLeft", Labels("Torso", (0.02f, 0.05f, 0.09f), 0.06));
Assert.Contains("Liver", Labels("Torso", (-0.06f, -0.1f, 0.09f), 0.06));
var thigh = Humanoid.Parts.First(p => p.PartLabel == "Thigh" && p.Side == Side.Left);
string[] Thigh(double depth) => Reach(thigh, (0.07f, 0f, 0f), depth).Select(i => thigh.Tissues[i].Label).ToArray();
Assert.Equal(new[] { "Skin", "Fat", "Muscle" }, Thigh(0.02));
Assert.Equal(new[] { "Skin", "Fat", "Muscle", "Femur" }, Thigh(0.03));
// The femoral vessel is at the inner thigh: -x on the left thigh, +x on the right.
string[] ThighOf(Side side, float x, double depth)
{
var stack = Humanoid.Parts.First(p => p.PartLabel == "Thigh" && p.Side == side);
return Reach(stack, (x, 0.12f, 0.0495f), depth).Select(i => stack.Tissues[i].Label).ToArray();
}
Assert.Equal(new[] { "Skin", "Fat", "Femoral", "Muscle" }, ThighOf(Side.Left, -0.0495f, 0.02));
Assert.Equal(new[] { "Skin", "Fat", "Femoral", "Muscle" }, ThighOf(Side.Right, 0.0495f, 0.02));
Assert.Equal(new[] { "Skin", "Fat", "Muscle" }, ThighOf(Side.Left, 0.0495f, 0.02));
Assert.Equal(new[] { "Skin", "Fat", "Muscle" }, ThighOf(Side.Right, -0.0495f, 0.02));
}
[Fact]
public void The_trachea_and_the_left_kidney_sit_where_the_content_puts_them()
{
// Trachea (0,0.2,0.06) r 0.015: reached from the front at its height, not from the back.
Assert.Contains("Trachea", Labels("Torso", (0f, 0.2f, 0.09f), 0.04));
Assert.DoesNotContain("Trachea", Labels("Torso", (0f, 0.2f, -0.09f), 0.04));
Assert.DoesNotContain("Trachea", Labels("Torso", (0f, -0.1f, 0.09f), 0.04));
// KidneyLeft (+x, 0.06,-0.15,-0.05) r 0.03: reached from the back on the left, not the right, not the front.
Assert.Contains("KidneyLeft", Labels("Torso", (0.06f, -0.15f, -0.09f), 0.04));
Assert.DoesNotContain("KidneyRight", Labels("Torso", (0.06f, -0.15f, -0.09f), 0.04));
Assert.Contains("KidneyRight", Labels("Torso", (-0.06f, -0.15f, -0.09f), 0.04));
Assert.DoesNotContain("KidneyLeft", Labels("Torso", (-0.06f, -0.15f, -0.09f), 0.04));
Assert.DoesNotContain("KidneyLeft", Labels("Torso", (0.06f, -0.15f, 0.09f), 0.04));
}
[Fact]
public void Every_head_and_torso_organ_core_is_sited()
{
foreach (var part in new[] { "Head", "Torso" })
{
var stack = Humanoid.Parts.First(p => p.PartLabel == part && p.Side == Side.Center);
var unsited = stack.Tissues.Where(t => t.Thickness == 0.0 && t.Site == null).Select(t => t.Label).ToArray();
Assert.Equal(part == "Torso" ? new[] { "Ribcage" } : Array.Empty<string>(), unsited);
}
}
}

View file

@ -0,0 +1,422 @@
# Generated by tools/pain-box-golden/generate.sh from BadDaySimulator 9f59764 PainBoxSimulation (tick 10 ms, one sample row per tick). Do not edit.
# seed intensity pull outcome break_ms end_ms flinches ticks hash
1 0.8 0.5 WillBroke 14730 14830 16 1484 1ceb743a21f5ff5a
2 0.8 0.5 WillBroke 14600 14700 16 1471 7259484084f5a927
3 0.8 0.5 WillBroke 16520 16620 16 1663 1d6bba4a157df7a6
4 0.8 0.5 WillBroke 14660 14760 15 1477 e5eebd484761de72
5 0.8 0.5 WillBroke 15270 15370 16 1538 3c4747a8445cefd7
6 0.8 0.5 WillBroke 15160 15260 17 1527 195b3053e604f362
7 0.8 0.5 WillBroke 18400 18500 20 1851 9f21e1a7ce0e8e45
8 0.8 0.5 WillBroke 14950 15050 16 1506 70030d48d40f4b19
9 0.8 0.5 WillBroke 14330 14430 16 1444 42e87dc3299a52ac
10 0.8 0.5 WillBroke 16720 16820 16 1683 ac540aa974f86a3d
11 0.8 0.5 WillBroke 17460 17560 18 1757 27c1801dd3b14200
12 0.8 0.5 WillBroke 14090 14190 15 1420 319ec304c2b2cc96
13 0.8 0.5 WillBroke 15470 15570 17 1558 c5df29d2946eb2d0
14 0.8 0.5 WillBroke 17950 18050 20 1806 9ae75b13832bd3e4
15 0.8 0.5 WillBroke 14730 14830 16 1484 9d430ea61e812af0
16 0.8 0.5 WillBroke 18100 18200 20 1821 8e5fb25cbd4fb1fe
17 0.8 0.5 WillBroke 16190 16290 18 1630 05610c511c4d19c1
18 0.8 0.5 WillBroke 16630 16730 16 1674 f5e2796f88e62ef6
19 0.8 0.5 WillBroke 16540 16640 18 1665 b25f6c3df9d287d6
20 0.8 0.5 WillBroke 19200 19300 20 1931 bfd2524973119a17
21 0.8 0.5 WillBroke 16150 16250 16 1626 125a8dcf62f71b8a
22 0.8 0.5 WillBroke 13550 13650 15 1366 7507771068c765e1
23 0.8 0.5 WillBroke 14200 14300 16 1431 3bcf5023b59ce3a8
24 0.8 0.5 WillBroke 14710 14810 16 1482 1a491d9500a4ee8a
25 0.8 0.5 WillBroke 16820 16920 19 1693 f0830cd17098c811
26 0.8 0.5 WillBroke 15070 15170 17 1518 c9e6b86dbee77d05
27 0.8 0.5 WillBroke 14840 14940 16 1495 5e57b1ae95415f2d
28 0.8 0.5 WillBroke 14770 14870 16 1488 2c0b8e2781a51ee3
29 0.8 0.5 WillBroke 14250 14350 16 1436 c32ad3049a90f668
30 0.8 0.5 WillBroke 14500 14600 16 1461 4910c161327cdb00
31 0.8 0.5 WillBroke 13930 14030 15 1404 1bdcd50e804b9bdd
32 0.8 0.5 WillBroke 14180 14280 16 1429 2ab161925bd68a7e
33 0.8 0.5 WillBroke 19070 19170 20 1918 5c18119adec71cce
34 0.8 0.5 WillBroke 14590 14690 15 1470 64587cd7060ee804
35 0.8 0.5 WillBroke 16120 16220 17 1623 78ac045afa3e8511
36 0.8 0.5 WillBroke 15050 15150 17 1516 82450899d9167065
37 0.8 0.5 WillBroke 14190 14290 16 1430 ae4a4d35b3f54257
38 0.8 0.5 WillBroke 16400 16500 19 1651 e0ea8c58df2c29c5
39 0.8 0.5 WillBroke 13580 13680 15 1369 6d1697c268835c76
40 0.8 0.5 WillBroke 15190 15290 15 1530 3c4a7a8be8eb2453
41 0.8 0.5 WillBroke 17060 17160 17 1717 38ae8fdfa2ca5b91
42 0.8 0.5 WillBroke 16310 16410 18 1642 3ff1fef4fb1442de
43 0.8 0.5 WillBroke 14650 14750 16 1476 19f85bbaf383110c
44 0.8 0.5 WillBroke 14110 14210 16 1422 027af17c0ac0fdc7
45 0.8 0.5 WillBroke 12960 13060 14 1307 d1fb96d0ee7ba804
46 0.8 0.5 WillBroke 16280 16380 18 1639 c8e839df23f5a211
47 0.8 0.5 WillBroke 16600 16700 18 1671 e7f53b160c1853ae
48 0.8 0.5 WillBroke 17070 17170 16 1718 aeec09055f384b43
49 0.8 0.5 WillBroke 17970 18070 18 1808 f212a3419dd45eb8
50 0.8 0.5 WillBroke 14720 14820 16 1483 138dc377b6038fc6
51 0.8 0.5 WillBroke 17000 17100 18 1711 91bf94bf4f9b80a9
52 0.8 0.5 WillBroke 15330 15430 18 1544 479d44543e6d898f
53 0.8 0.5 WillBroke 16910 17010 19 1702 23c9ae667a13b1b8
54 0.8 0.5 WillBroke 15710 15810 18 1582 5db0798e7430331f
55 0.8 0.5 WillBroke 18080 18180 20 1819 bb57883965df4728
56 0.8 0.5 WillBroke 14690 14790 16 1480 db298aebc9ac6475
57 0.8 0.5 WillBroke 17110 17210 18 1722 a8b179b65459b425
58 0.8 0.5 WillBroke 16040 16140 17 1615 9311f9bf9c30c9fa
59 0.8 0.5 WillBroke 15280 15380 17 1539 d357274a150ed640
60 0.8 0.5 WillBroke 16430 16530 18 1654 dce27d808a54e389
1 1.0 0.5 WillBroke 12700 12800 15 1281 3778c1c08b0e4636
2 1.0 0.5 WillBroke 12590 12690 15 1270 d2e72be9df803e3d
3 1.0 0.5 WillBroke 14160 14260 16 1427 0b18cbb4d9d49fbb
4 1.0 0.5 WillBroke 12650 12750 15 1276 da78405420316abd
5 1.0 0.5 WillBroke 13140 13240 15 1325 c95a030fe020dd7a
6 1.0 0.5 WillBroke 13040 13140 16 1315 44fd3277642c8a9a
7 1.0 0.5 WillBroke 15660 15760 19 1577 017b21240992c769
8 1.0 0.5 WillBroke 12880 12980 15 1299 599e66b4a1a5921e
9 1.0 0.5 WillBroke 12370 12470 15 1248 cb45d1000cf1ea08
10 1.0 0.5 WillBroke 14320 14420 16 1443 32fa60bc328344e0
11 1.0 0.5 WillBroke 14910 15010 17 1502 fe8e6683df6f44c1
12 1.0 0.5 WillBroke 12180 12280 14 1229 d7ceb4d09ec176aa
13 1.0 0.5 WillBroke 13290 13390 16 1340 e8036a983b52c1ab
14 1.0 0.5 WillBroke 15310 15410 18 1542 0b8a9b1c08492fbe
15 1.0 0.5 WillBroke 12700 12800 15 1281 a8ed8929fa4337f0
16 1.0 0.5 WillBroke 15430 15530 18 1554 eb95c4903824bb05
17 1.0 0.5 WillBroke 13890 13990 16 1400 6db1399b0be214fa
18 1.0 0.5 WillBroke 14250 14350 15 1436 535d36145c307a6a
19 1.0 0.5 WillBroke 14160 14260 17 1427 547e4a683939cf31
20 1.0 0.5 WillBroke 16310 16410 19 1642 0653fd31b3fc42d8
21 1.0 0.5 WillBroke 13860 13960 15 1397 abb9fb41943aed14
22 1.0 0.5 WillBroke 11720 11820 14 1183 1174869087f230c6
23 1.0 0.5 WillBroke 12260 12360 15 1237 d5074ba63114d34f
24 1.0 0.5 WillBroke 12680 12780 15 1279 d075ca28021bcb2f
25 1.0 0.5 WillBroke 14390 14490 18 1450 ca018f228e141313
26 1.0 0.5 WillBroke 12970 13070 16 1308 3c559d5142622b8a
27 1.0 0.5 WillBroke 12790 12890 15 1290 04d51fbe35ed5cd5
28 1.0 0.5 WillBroke 12730 12830 15 1284 e32fd88365db7019
29 1.0 0.5 WillBroke 12300 12400 15 1241 e865da9fc3e136dd
30 1.0 0.5 WillBroke 12500 12600 15 1261 ee7b9626cecaa543
31 1.0 0.5 WillBroke 12030 12130 15 1214 58cfcc93405f718b
32 1.0 0.5 WillBroke 12240 12340 15 1235 4a7a33fc862b87b6
33 1.0 0.5 WillBroke 16210 16310 19 1632 a4321c62d0942b51
34 1.0 0.5 WillBroke 12580 12680 15 1269 8d8084c506399075
35 1.0 0.5 WillBroke 13830 13930 16 1394 80eab6a1a91fe47e
36 1.0 0.5 WillBroke 12960 13060 16 1307 a3bf0483a30b9832
37 1.0 0.5 WillBroke 12250 12350 15 1236 591a92e077f7fb7e
38 1.0 0.5 WillBroke 14040 14140 17 1415 a37a6c6e88296d4c
39 1.0 0.5 WillBroke 11750 11850 14 1186 c8e91a1813d1cf7f
40 1.0 0.5 WillBroke 13080 13180 14 1319 59ad5f054dacf9b5
41 1.0 0.5 WillBroke 14600 14700 16 1471 d6c53c1e324f31bc
42 1.0 0.5 WillBroke 13980 14080 17 1409 82171315883210d2
43 1.0 0.5 WillBroke 12620 12720 15 1273 cf5f3536022121f2
44 1.0 0.5 WillBroke 12180 12280 15 1229 c9f7c2acacdc2a4f
45 1.0 0.5 WillBroke 11230 11330 14 1134 e4dcb7f2fca454aa
46 1.0 0.5 WillBroke 13950 14050 17 1406 4f6631c906041c50
47 1.0 0.5 WillBroke 14210 14310 17 1432 94971d9adbcce7f4
48 1.0 0.5 WillBroke 14610 14710 16 1472 52b86bd6f4d01970
49 1.0 0.5 WillBroke 15330 15430 17 1544 b76a0e4f82a8f139
50 1.0 0.5 WillBroke 12690 12790 15 1280 f3859d8ebae145f7
51 1.0 0.5 WillBroke 14540 14640 17 1465 d54f534dbfd8ac98
52 1.0 0.5 WillBroke 13170 13270 16 1328 e3ba704a9ee1a898
53 1.0 0.5 WillBroke 14450 14550 18 1456 09513ed8620db12f
54 1.0 0.5 WillBroke 13500 13600 16 1361 fa700ae33783c44b
55 1.0 0.5 WillBroke 15410 15510 18 1552 37ce852a8984b97a
56 1.0 0.5 WillBroke 12670 12770 15 1278 138a00120ccb00fe
57 1.0 0.5 WillBroke 14630 14730 17 1474 18f604c62fdf14cf
58 1.0 0.5 WillBroke 13760 13860 16 1387 40a380177cc0fb2f
59 1.0 0.5 WillBroke 13150 13250 15 1326 cbb58f0ec6aacce2
60 1.0 0.5 WillBroke 14070 14170 17 1418 fdd65da97d503bea
1 0.6 0.5 WillBroke 18150 18250 16 1826 6ba0eac35d362331
2 0.6 0.5 WillBroke 17970 18070 16 1808 e9a49730ebc3284e
3 0.6 0.5 WillBroke 20530 20630 17 2064 f35e11a268ee6e5b
4 0.6 0.5 WillBroke 18050 18150 16 1816 7f4d381a70594785
5 0.6 0.5 WillBroke 18850 18950 16 1896 2255227b0f0566a4
6 0.6 0.5 WillBroke 18740 18840 18 1885 77671a7b01e433c1
7 0.6 0.5 WillBroke 23130 23230 21 2324 6d6875964a164a26
8 0.6 0.5 WillBroke 18450 18550 17 1856 89995e2334a69fc4
9 0.6 0.5 WillBroke 17630 17730 16 1774 3a57554bfdae952c
10 0.6 0.5 WillBroke 20780 20880 16 2089 92d0d3ee482673bb
11 0.6 0.5 WillBroke 21820 21920 20 2193 499413f37856cc67
12 0.6 0.5 WillBroke 17300 17400 15 1741 cf400e983b9ab384
13 0.6 0.5 WillBroke 19160 19260 18 1927 cc9cd1d981969951
14 0.6 0.5 WillBroke 22520 22620 21 2263 ed6838239b11bc75
15 0.6 0.5 WillBroke 18130 18230 16 1824 d749947d1fa45774
16 0.6 0.5 WillBroke 22710 22810 21 2282 bda734962c5606f0
17 0.6 0.5 WillBroke 20110 20210 18 2022 35e19cd78e4681c5
18 0.6 0.5 WillBroke 20680 20780 16 2079 044b17ae0c8f471d
19 0.6 0.5 WillBroke 20600 20700 20 2071 6bc5d68ea6d37f58
20 0.6 0.5 WillBroke 24210 24310 21 2432 a8ea7744a790f179
21 0.6 0.5 WillBroke 20020 20120 15 2013 024dc742aba6d11e
22 0.6 0.5 WillBroke 16590 16690 16 1670 1ed9990a7a83680d
23 0.6 0.5 WillBroke 17460 17560 17 1757 2f5c8bb3f7fbce51
24 0.6 0.5 WillBroke 18120 18220 17 1823 39e31936bdc74dca
25 0.6 0.5 WillBroke 20980 21080 20 2109 0c545a97c49f67d0
26 0.6 0.5 WillBroke 18610 18710 18 1872 b84cafd2a5e955fd
27 0.6 0.5 WillBroke 18300 18400 17 1841 7610f4a37901d7da
28 0.6 0.5 WillBroke 18190 18290 17 1830 87c68d8444be7fe2
29 0.6 0.5 WillBroke 17520 17620 16 1763 64e7b957cc2182a1
30 0.6 0.5 WillBroke 17850 17950 16 1796 b318302a3ff94a1b
31 0.6 0.5 WillBroke 17100 17200 16 1721 ab156f4dcec9413a
32 0.6 0.5 WillBroke 17430 17530 17 1754 3505a668df088e29
33 0.6 0.5 WillBroke 24030 24130 21 2414 62dad0cd6de6c6ad
34 0.6 0.5 WillBroke 17960 18060 16 1807 468f81ede64f7032
35 0.6 0.5 WillBroke 19990 20090 17 2010 8425b945af3a5546
36 0.6 0.5 WillBroke 18600 18700 18 1871 2ada8cd49c8d5762
37 0.6 0.5 WillBroke 17440 17540 17 1755 a98e38b6442eaf84
38 0.6 0.5 WillBroke 20440 20540 21 2055 7762c24c4c087ea3
39 0.6 0.5 WillBroke 16640 16740 16 1675 948a96907d9eefc0
40 0.6 0.5 WillBroke 18740 18840 15 1885 cf3d3003437065ba
41 0.6 0.5 WillBroke 21260 21360 17 2137 42ef7102a413d1c0
42 0.6 0.5 WillBroke 20280 20380 20 2039 dcf19acb186b9283
43 0.6 0.5 WillBroke 18040 18140 17 1815 a2b7896cebd7012a
44 0.6 0.5 WillBroke 17340 17440 17 1745 ae0d1f06637ac29e
45 0.6 0.5 WillBroke 15820 15920 15 1593 34ed73b3ed021ee4
46 0.6 0.5 WillBroke 20240 20340 20 2035 1327132bbc471b49
47 0.6 0.5 WillBroke 20670 20770 19 2078 6ed62543a7d622f7
48 0.6 0.5 WillBroke 21260 21360 16 2137 7852586cc5440810
49 0.6 0.5 WillBroke 22500 22600 19 2261 e5cb75e99d5282f9
50 0.6 0.5 WillBroke 18130 18230 17 1824 b6ab5edaaf877789
51 0.6 0.5 WillBroke 21210 21310 19 2132 41ac950e5cfaa653
52 0.6 0.5 WillBroke 18990 19090 19 1910 413ccf741adabd38
53 0.6 0.5 WillBroke 21110 21210 21 2122 36abd4e8cfe6083a
54 0.6 0.5 WillBroke 19460 19560 19 1957 cab475fe2176ba46
55 0.6 0.5 WillBroke 22700 22800 21 2281 4621276ba4894fea
56 0.6 0.5 WillBroke 18100 18200 17 1821 ec9a774751bdedbf
57 0.6 0.5 WillBroke 21340 21440 18 2145 5709bbcab913e98c
58 0.6 0.5 WillBroke 19910 20010 18 2002 d16492ba1669abb8
59 0.6 0.5 WillBroke 18890 18990 17 1900 f36f53cb80836d5e
60 0.6 0.5 WillBroke 20450 20550 20 2056 c118dd86c7e0945f
1 0.8 0.0 WillBroke 10070 10170 10 1018 1914ad90455159e8
2 0.8 0.0 WillBroke 9990 10090 10 1010 3d6287598c77d9e3
3 0.8 0.0 WillBroke 11160 11260 10 1127 7476613d96868cc1
4 0.8 0.0 WillBroke 10030 10130 10 1014 50107275381fd7aa
5 0.8 0.0 WillBroke 10400 10500 10 1051 d287687d8bf0078e
6 0.8 0.0 WillBroke 10340 10440 11 1045 6ce913c53b72daf4
7 0.8 0.0 WillBroke 12300 12400 12 1241 bc0a4e85028ea794
8 0.8 0.0 WillBroke 10210 10310 10 1032 9d817ecb6fe288ee
9 0.8 0.0 WillBroke 9820 9920 10 993 92da81d6468ebe82
10 0.8 0.0 WillBroke 11280 11380 10 1139 f2f9c86856025f04
11 0.8 0.0 WillBroke 11730 11830 11 1184 9f0a0926039f3e52
12 0.8 0.0 WillBroke 9690 9790 9 980 33b8c796b8fe56e5
13 0.8 0.0 WillBroke 10530 10630 11 1064 bc70c2da7b3b974c
14 0.8 0.0 WillBroke 12040 12140 12 1215 c95036c6977e1b59
15 0.8 0.0 WillBroke 10080 10180 10 1019 373431a56c7b9101
16 0.8 0.0 WillBroke 12130 12230 12 1224 02dcac6b7da6c93c
17 0.8 0.0 WillBroke 10970 11070 11 1108 baed4dff515bc947
18 0.8 0.0 WillBroke 11220 11320 10 1133 ed5b57045897960d
19 0.8 0.0 WillBroke 11190 11290 11 1130 9e9829f5785c1567
20 0.8 0.0 WillBroke 12780 12880 12 1289 b0ce6f3a04534a83
21 0.8 0.0 WillBroke 10930 11030 10 1104 5f92a1c351fcaade
22 0.8 0.0 WillBroke 9350 9450 9 946 685587a2ecb63f49
23 0.8 0.0 WillBroke 9760 9860 10 987 46ca2993ce13d9b7
24 0.8 0.0 WillBroke 10060 10160 10 1017 8bbb14c9c6edd738
25 0.8 0.0 WillBroke 11360 11460 12 1147 ca7a2943fbf35fa7
26 0.8 0.0 WillBroke 10290 10390 11 1040 c2615398937c44cf
27 0.8 0.0 WillBroke 10140 10240 10 1025 2c11a0e93231978e
28 0.8 0.0 WillBroke 10100 10200 10 1021 02996614f9d1b6ad
29 0.8 0.0 WillBroke 9770 9870 10 988 ee1586d573ca55c9
30 0.8 0.0 WillBroke 9930 10030 10 1004 cb05f8a9a91fd3fa
31 0.8 0.0 WillBroke 9580 9680 10 969 e8ecae5902642a8d
32 0.8 0.0 WillBroke 9740 9840 10 985 f136abd42fb6b90f
33 0.8 0.0 WillBroke 12710 12810 12 1282 87209b5050bf4859
34 0.8 0.0 WillBroke 9980 10080 10 1009 b910622b9c39d291
35 0.8 0.0 WillBroke 10930 11030 10 1104 e910f01456aee3b6
36 0.8 0.0 WillBroke 10290 10390 11 1040 2468ae1f05faa180
37 0.8 0.0 WillBroke 9740 9840 10 985 bf0e779e9243fe83
38 0.8 0.0 WillBroke 11110 11210 12 1122 cd1edafd69f799db
39 0.8 0.0 WillBroke 9360 9460 10 947 0a9c9db826fd6fc3
40 0.8 0.0 WillBroke 10350 10450 9 1046 8a695f2a7b77be08
41 0.8 0.0 WillBroke 11500 11600 10 1161 773e9846d68e4563
42 0.8 0.0 WillBroke 11050 11150 12 1116 971f9792bb5190a5
43 0.8 0.0 WillBroke 10030 10130 10 1014 290e32ab22867eef
44 0.8 0.0 WillBroke 9690 9790 10 980 abf81ab05a0351ab
45 0.8 0.0 WillBroke 8970 9070 9 908 c51f9d6618059105
46 0.8 0.0 WillBroke 11030 11130 11 1114 3eefac78a2ec93b0
47 0.8 0.0 WillBroke 11210 11310 11 1132 c1f575d6e9da5621
48 0.8 0.0 WillBroke 11500 11600 10 1161 cc56a243e423592f
49 0.8 0.0 WillBroke 12040 12140 11 1215 ab73b8cd07be0649
50 0.8 0.0 WillBroke 10080 10180 10 1019 5b3f678f2f519458
51 0.8 0.0 WillBroke 11460 11560 11 1157 49df060130506ba9
52 0.8 0.0 WillBroke 10440 10540 11 1055 a04eaacb8803cb78
53 0.8 0.0 WillBroke 11410 11510 12 1152 47d7de117d48f625
54 0.8 0.0 WillBroke 10700 10800 11 1081 2dc02e576db39ec7
55 0.8 0.0 WillBroke 12120 12220 12 1223 b59afb6f495f92cc
56 0.8 0.0 WillBroke 10050 10150 10 1016 96cd4b621eb75a64
57 0.8 0.0 WillBroke 11520 11620 11 1163 6ace2627157a30f5
58 0.8 0.0 WillBroke 10870 10970 11 1098 d24694742d029864
59 0.8 0.0 WillBroke 10420 10520 10 1053 cb0148bdde051390
60 0.8 0.0 WillBroke 11120 11220 11 1123 89dcecf0208bd4c5
1 0.8 0.8 WillBroke 26100 26200 31 2621 facb758365f7865b
2 0.8 0.8 WillBroke 25850 25950 31 2596 7d282a08b15832e4
3 0.8 0.8 WillBroke 29980 30080 34 3009 f2ded9f2c282d18f
4 0.8 0.8 WillBroke 25990 26090 31 2610 5bb9737062e3e1ff
5 0.8 0.8 WillBroke 27260 27360 32 2737 4bd7db07086983d8
6 0.8 0.8 WillBroke 27040 27140 34 2715 58790a7cd5034891
7 0.8 0.8 WillBroke 34160 34260 43 3427 c3b1132c88b0087b
8 0.8 0.8 WillBroke 26600 26700 32 2671 e4f42c7e9a769659
9 0.8 0.8 WillBroke 25280 25380 31 2539 ae0029cabb1ecb76
10 0.8 0.8 WillBroke 30440 30540 35 3055 075dfb3f39c9f414
11 0.8 0.8 WillBroke 32040 32140 39 3215 6edcb217700a8f7c
12 0.8 0.8 WillBroke 24790 24890 30 2490 f8491701247bcb39
13 0.8 0.8 WillBroke 27710 27810 35 2782 cb475aee74befea5
14 0.8 0.8 WillBroke 33180 33280 41 3329 8af0b8a0fd5e834b
15 0.8 0.8 WillBroke 26070 26170 31 2618 e2fbd7aa00441616
16 0.8 0.8 WillBroke 33480 33580 42 3359 cc06979bd8253d1c
17 0.8 0.8 WillBroke 29220 29320 36 2933 34d06f9996dc6314
18 0.8 0.8 WillBroke 30290 30390 35 3040 f30283d3d1284d9a
19 0.8 0.8 WillBroke 29950 30050 38 3006 ed2ffeeb23e4d2c7
20 0.8 0.8 WillBroke 35990 36090 44 3610 441d34847f7052a3
21 0.8 0.8 WillBroke 29210 29310 33 2932 97b819d64521f3f1
22 0.8 0.8 WillBroke 23650 23750 29 2376 4bece642126eda8e
23 0.8 0.8 WillBroke 24990 25090 31 2510 707aeeeb6326f2a8
24 0.8 0.8 WillBroke 26050 26150 32 2616 e019c2e195081ba6
25 0.8 0.8 WillBroke 30630 30730 39 3074 4193242a4b0f92a4
26 0.8 0.8 WillBroke 26800 26900 34 2691 ea4cd91c79d0dae5
27 0.8 0.8 WillBroke 26360 26460 32 2647 41475b4e3dcc78b5
28 0.8 0.8 WillBroke 26190 26290 32 2630 2812da5c40655627
29 0.8 0.8 WillBroke 25110 25210 31 2522 f5cce351f754c3dc
30 0.8 0.8 WillBroke 25630 25730 31 2574 da101fc4522fbef8
31 0.8 0.8 WillBroke 24440 24540 30 2455 d1ed5841b8f3d2c7
32 0.8 0.8 WillBroke 24950 25050 31 2506 7a853f4af1372d33
33 0.8 0.8 WillBroke 35700 35800 43 3581 c19ba694b20e2224
34 0.8 0.8 WillBroke 25830 25930 31 2594 1fe8515aa980c3e8
35 0.8 0.8 WillBroke 29070 29170 35 2918 b471b626e0a26207
36 0.8 0.8 WillBroke 26760 26860 34 2687 7b47afeb2bda4f09
37 0.8 0.8 WillBroke 24960 25060 31 2507 70611ac9655b4130
38 0.8 0.8 WillBroke 29720 29820 39 2983 29e31c8aedca1b66
39 0.8 0.8 WillBroke 23720 23820 29 2383 e6b672c0d11de53f
40 0.8 0.8 WillBroke 27150 27250 31 2726 228e1e1209860ccf
41 0.8 0.8 WillBroke 31230 31330 36 3134 d8bd943c7794fb4d
42 0.8 0.8 WillBroke 29450 29550 37 2956 99532fe0b5bbd56a
43 0.8 0.8 WillBroke 25920 26020 32 2603 8c12e7bb65f2c9ec
44 0.8 0.8 WillBroke 24790 24890 31 2490 c1e40d8406efd5e9
45 0.8 0.8 WillBroke 22450 22550 28 2256 4ae97c637521edaf
46 0.8 0.8 WillBroke 29410 29510 37 2952 7760a4f76f63ebb5
47 0.8 0.8 WillBroke 30160 30260 37 3027 f062837cb5b49eb0
48 0.8 0.8 WillBroke 31220 31320 36 3133 5e41f3871a485c72
49 0.8 0.8 WillBroke 33200 33300 39 3331 bf6f87e6642eeed9
50 0.8 0.8 WillBroke 26050 26150 32 2616 800841a85e80970f
51 0.8 0.8 WillBroke 31020 31120 38 3113 54d06d44545aa4fb
52 0.8 0.8 WillBroke 27410 27510 35 2752 c545900336cea749
53 0.8 0.8 WillBroke 30780 30880 40 3089 7b14f9d5b0dabe0d
54 0.8 0.8 WillBroke 28150 28250 35 2826 46db795b35f34c5d
55 0.8 0.8 WillBroke 33490 33590 42 3360 c4760d6e42ad2e59
56 0.8 0.8 WillBroke 26030 26130 32 2614 0503e5395eaff483
57 0.8 0.8 WillBroke 31290 31390 37 3140 b7b8ab30e565b2f9
58 0.8 0.8 WillBroke 28940 29040 35 2905 4527feae8a218446
59 0.8 0.8 WillBroke 27310 27410 33 2742 518030c576b6fcbe
60 0.8 0.8 WillBroke 29750 29850 38 2986 53e33f04a6f4a7af
1 0.12 0.5 Endured -1 120000 0 12001 a4d66728d54aad20
2 0.12 0.5 Endured -1 120000 0 12001 0f86d5191fd466e2
3 0.12 0.5 Endured -1 120000 0 12001 842a665c4588e215
4 0.12 0.5 Endured -1 120000 0 12001 930164c1ef89e1d1
5 0.12 0.5 Endured -1 120000 0 12001 a3c5f53000dc35b6
6 0.12 0.5 Endured -1 120000 0 12001 6f2b82eed827ff94
7 0.12 0.5 Endured -1 120000 0 12001 e8ccd63c058aac7e
8 0.12 0.5 Endured -1 120000 0 12001 ce987e8b1ff40739
9 0.12 0.5 Endured -1 120000 0 12001 311b03a75aa8774d
10 0.12 0.5 Endured -1 120000 0 12001 335c11e8d64fdd7a
11 0.12 0.5 Endured -1 120000 0 12001 ec84541c1a1c2b9e
12 0.12 0.5 Endured -1 120000 0 12001 23d1461c11d6eecf
13 0.12 0.5 Endured -1 120000 0 12001 e21fc8da5df2c979
14 0.12 0.5 Endured -1 120000 0 12001 8c16fb1b49916ce9
15 0.12 0.5 Endured -1 120000 0 12001 596e31a87d587289
16 0.12 0.5 Endured -1 120000 0 12001 53e9f6c0cdc92586
17 0.12 0.5 Endured -1 120000 0 12001 32a5669012845805
18 0.12 0.5 Endured -1 120000 0 12001 bf03e03c67b40e3b
19 0.12 0.5 Endured -1 120000 0 12001 178a29a6f8375006
20 0.12 0.5 Endured -1 120000 0 12001 59c536047786a192
21 0.12 0.5 Endured -1 120000 0 12001 b356add08dab94a5
22 0.12 0.5 Endured -1 120000 0 12001 99922c10b6b32d2b
23 0.12 0.5 Endured -1 120000 0 12001 e280c89341344aa7
24 0.12 0.5 Endured -1 120000 0 12001 fa0726e3c32d99d8
25 0.12 0.5 Endured -1 120000 0 12001 f9f241118be9983e
26 0.12 0.5 Endured -1 120000 0 12001 80a50b45c9d799c0
27 0.12 0.5 Endured -1 120000 0 12001 771cfaf72c64438b
28 0.12 0.5 Endured -1 120000 0 12001 fbbd6f2007051076
29 0.12 0.5 Endured -1 120000 0 12001 c08d546694da4a7e
30 0.12 0.5 Endured -1 120000 0 12001 9df481a0c2cdee11
31 0.12 0.5 Endured -1 120000 0 12001 ae9f606dafebfa1e
32 0.12 0.5 Endured -1 120000 0 12001 06e696404e9256de
33 0.12 0.5 Endured -1 120000 0 12001 066aafcddab6ef0e
34 0.12 0.5 Endured -1 120000 0 12001 0833cb592b8138cd
35 0.12 0.5 Endured -1 120000 0 12001 72f9ccaea0637ad4
36 0.12 0.5 Endured -1 120000 0 12001 e0d1c64bc8e0fc48
37 0.12 0.5 Endured -1 120000 0 12001 b70ad94cf12adce0
38 0.12 0.5 Endured -1 120000 0 12001 ff435f0887180b71
39 0.12 0.5 Endured -1 120000 0 12001 8da9c4370b584012
40 0.12 0.5 Endured -1 120000 0 12001 74f9885c1a541501
41 0.12 0.5 Endured -1 120000 0 12001 d4e11eb98b23c59a
42 0.12 0.5 Endured -1 120000 0 12001 4289f6ae3fe60c0d
43 0.12 0.5 Endured -1 120000 0 12001 f9595ac5caec95c2
44 0.12 0.5 Endured -1 120000 0 12001 bc590d5d1b609c7e
45 0.12 0.5 Endured -1 120000 0 12001 efdb32b1f8fb14ca
46 0.12 0.5 Endured -1 120000 0 12001 6b1ed857ef93f9e7
47 0.12 0.5 Endured -1 120000 0 12001 4dcb3fb4a7fb1808
48 0.12 0.5 Endured -1 120000 0 12001 f11072ebdaf3fe06
49 0.12 0.5 Endured -1 120000 0 12001 b2b83bbf20dcb8da
50 0.12 0.5 Endured -1 120000 0 12001 1c976596616ad5bc
51 0.12 0.5 Endured -1 120000 0 12001 3c9322031aac9a32
52 0.12 0.5 Endured -1 120000 0 12001 a96cd8ca41cfa13a
53 0.12 0.5 Endured -1 120000 0 12001 a215b789ed222a7d
54 0.12 0.5 Endured -1 120000 0 12001 3be6e39bfa4d5424
55 0.12 0.5 Endured -1 120000 0 12001 b40fe851ccb51114
56 0.12 0.5 Endured -1 120000 0 12001 3eb672b6f8f9df4b
57 0.12 0.5 Endured -1 120000 0 12001 0cc56de0d1df332a
58 0.12 0.5 Endured -1 120000 0 12001 1c46b092e7a9f5fa
59 0.12 0.5 Endured -1 120000 0 12001 9abf165506073db5
60 0.12 0.5 Endured -1 120000 0 12001 d9913a1ed7920a47
1 0.2 0.5 WillBroke 61550 61650 0 6166 4eb7b5f041058c3a
2 0.2 0.5 WillBroke 60770 60870 0 6088 6adf5a0713405867
3 0.2 0.5 WillBroke 73080 73180 0 7319 3b218fb3f2750d00
4 0.2 0.5 WillBroke 60910 61010 0 6102 e6fc3dd13c4f4f88
5 0.2 0.5 WillBroke 64890 64990 0 6500 13eb57c707621354
6 0.2 0.5 WillBroke 65330 65430 0 6544 5d12aa022ce881c2
7 0.2 0.5 WillBroke 89140 89240 0 8925 722956c2506d94ac
8 0.2 0.5 WillBroke 63320 63420 0 6343 4c8556996b77c4d2
9 0.2 0.5 WillBroke 59100 59200 0 5921 4fdeaa907d37b76a
10 0.2 0.5 WillBroke 74460 74560 0 7457 e6a7d0c99e99df1d
11 0.2 0.5 WillBroke 81360 81460 0 8147 8bb48eff4337aca3
12 0.2 0.5 WillBroke 57220 57320 0 5733 5c1f16f19f35355c
13 0.2 0.5 WillBroke 68020 68120 0 6813 7728601e0be34b58
14 0.2 0.5 WillBroke 85960 86060 0 8607 a16720cf9093a2ba
15 0.2 0.5 WillBroke 61270 61370 0 6138 84ad9eee8ece8cab
16 0.2 0.5 WillBroke 86760 86860 0 8687 f30b663ba19039fa
17 0.2 0.5 WillBroke 72150 72250 0 7226 adb357df88b33dc8
18 0.2 0.5 WillBroke 73890 73990 0 7400 fbfa7d31601e6aa1
19 0.2 0.5 WillBroke 75870 75970 0 7598 e142af5c45ee0be2
20 0.2 0.5 WillBroke 94760 94860 0 9487 4c708580624a1d46
21 0.2 0.5 WillBroke 70030 70130 0 7014 13ad55e6f3130be3
22 0.2 0.5 WillBroke 53850 53950 0 5396 79f3bb316c0eaf85
23 0.2 0.5 WillBroke 58520 58620 0 5863 9f0c6f85419ae6dd
24 0.2 0.5 WillBroke 61550 61650 0 6166 f39221687519b487
25 0.2 0.5 WillBroke 77990 78090 0 7810 10d4fc69f97b26d8
26 0.2 0.5 WillBroke 64630 64730 0 6474 cc05ed3304923a87
27 0.2 0.5 WillBroke 62610 62710 0 6272 39625ac195ca6345
28 0.2 0.5 WillBroke 61980 62080 0 6209 1689dbf84daa149b
29 0.2 0.5 WillBroke 58650 58750 0 5876 63711e804c1fd959
30 0.2 0.5 WillBroke 60210 60310 0 6032 6750a2c42c1feb9b
31 0.2 0.5 WillBroke 56770 56870 0 5688 efe09e0087130ba4
32 0.2 0.5 WillBroke 58580 58680 0 5869 48e0e13604b41a59
33 0.2 0.5 WillBroke 93390 93490 0 9350 0f7b98fadce89c49
34 0.2 0.5 WillBroke 60530 60630 0 6064 7a4f7f1a4f63374c
35 0.2 0.5 WillBroke 70790 70890 0 7090 85f8a9ddf9d30a53
36 0.2 0.5 WillBroke 64920 65020 0 6503 73db5f07ae7671ad
37 0.2 0.5 WillBroke 58250 58350 0 5836 09f7c4eb8062265a
38 0.2 0.5 WillBroke 75920 76020 0 7603 2414eda9e29d7e3e
39 0.2 0.5 WillBroke 54080 54180 0 5419 8668a6e52104341a
40 0.2 0.5 WillBroke 63980 64080 0 6409 9b0483b182117ef2
41 0.2 0.5 WillBroke 77210 77310 0 7732 1177a13eb3cc229b
42 0.2 0.5 WillBroke 74160 74260 0 7427 666d37658845da58
43 0.2 0.5 WillBroke 61350 61450 0 6146 871d25bd76ae94c8
44 0.2 0.5 WillBroke 58190 58290 0 5830 f1e96621098bc360
45 0.2 0.5 WillBroke 50280 50380 0 5039 c2f86a90a197eb00
46 0.2 0.5 WillBroke 73840 73940 0 7395 17cf31b97a0d1671
47 0.2 0.5 WillBroke 75630 75730 0 7574 8538745e7a5e1ff6
48 0.2 0.5 WillBroke 76850 76950 0 7696 b6525c3189927f9a
49 0.2 0.5 WillBroke 84340 84440 0 8445 8590d59e44ff5fd4
50 0.2 0.5 WillBroke 61880 61980 0 6199 2e5718c722577755
51 0.2 0.5 WillBroke 77980 78080 0 7809 8f8ccdb15763c750
52 0.2 0.5 WillBroke 67470 67570 0 6758 ac01f6ce963b5334
53 0.2 0.5 WillBroke 79110 79210 0 7922 6ea0bdfb3703d02a
54 0.2 0.5 WillBroke 69530 69630 0 6964 fb7b9ac715a66a05
55 0.2 0.5 WillBroke 87170 87270 0 8728 07bba7c2cd21b7b7
56 0.2 0.5 WillBroke 61450 61550 0 6156 3136df798ca68e9d
57 0.2 0.5 WillBroke 78000 78100 0 7811 d6a4a321a0936ef2
58 0.2 0.5 WillBroke 71110 71210 0 7122 e7dfb64e0e60fff6
59 0.2 0.5 WillBroke 65890 65990 0 6600 970e46a63d649f1d
60 0.2 0.5 WillBroke 75320 75420 0 7543 cfedd17a42366fca
1 # Generated by tools/pain-box-golden/generate.sh from BadDaySimulator 9f59764 PainBoxSimulation (tick 10 ms, one sample row per tick). Do not edit.
2 # seed intensity pull outcome break_ms end_ms flinches ticks hash
3 1 0.8 0.5 WillBroke 14730 14830 16 1484 1ceb743a21f5ff5a
4 2 0.8 0.5 WillBroke 14600 14700 16 1471 7259484084f5a927
5 3 0.8 0.5 WillBroke 16520 16620 16 1663 1d6bba4a157df7a6
6 4 0.8 0.5 WillBroke 14660 14760 15 1477 e5eebd484761de72
7 5 0.8 0.5 WillBroke 15270 15370 16 1538 3c4747a8445cefd7
8 6 0.8 0.5 WillBroke 15160 15260 17 1527 195b3053e604f362
9 7 0.8 0.5 WillBroke 18400 18500 20 1851 9f21e1a7ce0e8e45
10 8 0.8 0.5 WillBroke 14950 15050 16 1506 70030d48d40f4b19
11 9 0.8 0.5 WillBroke 14330 14430 16 1444 42e87dc3299a52ac
12 10 0.8 0.5 WillBroke 16720 16820 16 1683 ac540aa974f86a3d
13 11 0.8 0.5 WillBroke 17460 17560 18 1757 27c1801dd3b14200
14 12 0.8 0.5 WillBroke 14090 14190 15 1420 319ec304c2b2cc96
15 13 0.8 0.5 WillBroke 15470 15570 17 1558 c5df29d2946eb2d0
16 14 0.8 0.5 WillBroke 17950 18050 20 1806 9ae75b13832bd3e4
17 15 0.8 0.5 WillBroke 14730 14830 16 1484 9d430ea61e812af0
18 16 0.8 0.5 WillBroke 18100 18200 20 1821 8e5fb25cbd4fb1fe
19 17 0.8 0.5 WillBroke 16190 16290 18 1630 05610c511c4d19c1
20 18 0.8 0.5 WillBroke 16630 16730 16 1674 f5e2796f88e62ef6
21 19 0.8 0.5 WillBroke 16540 16640 18 1665 b25f6c3df9d287d6
22 20 0.8 0.5 WillBroke 19200 19300 20 1931 bfd2524973119a17
23 21 0.8 0.5 WillBroke 16150 16250 16 1626 125a8dcf62f71b8a
24 22 0.8 0.5 WillBroke 13550 13650 15 1366 7507771068c765e1
25 23 0.8 0.5 WillBroke 14200 14300 16 1431 3bcf5023b59ce3a8
26 24 0.8 0.5 WillBroke 14710 14810 16 1482 1a491d9500a4ee8a
27 25 0.8 0.5 WillBroke 16820 16920 19 1693 f0830cd17098c811
28 26 0.8 0.5 WillBroke 15070 15170 17 1518 c9e6b86dbee77d05
29 27 0.8 0.5 WillBroke 14840 14940 16 1495 5e57b1ae95415f2d
30 28 0.8 0.5 WillBroke 14770 14870 16 1488 2c0b8e2781a51ee3
31 29 0.8 0.5 WillBroke 14250 14350 16 1436 c32ad3049a90f668
32 30 0.8 0.5 WillBroke 14500 14600 16 1461 4910c161327cdb00
33 31 0.8 0.5 WillBroke 13930 14030 15 1404 1bdcd50e804b9bdd
34 32 0.8 0.5 WillBroke 14180 14280 16 1429 2ab161925bd68a7e
35 33 0.8 0.5 WillBroke 19070 19170 20 1918 5c18119adec71cce
36 34 0.8 0.5 WillBroke 14590 14690 15 1470 64587cd7060ee804
37 35 0.8 0.5 WillBroke 16120 16220 17 1623 78ac045afa3e8511
38 36 0.8 0.5 WillBroke 15050 15150 17 1516 82450899d9167065
39 37 0.8 0.5 WillBroke 14190 14290 16 1430 ae4a4d35b3f54257
40 38 0.8 0.5 WillBroke 16400 16500 19 1651 e0ea8c58df2c29c5
41 39 0.8 0.5 WillBroke 13580 13680 15 1369 6d1697c268835c76
42 40 0.8 0.5 WillBroke 15190 15290 15 1530 3c4a7a8be8eb2453
43 41 0.8 0.5 WillBroke 17060 17160 17 1717 38ae8fdfa2ca5b91
44 42 0.8 0.5 WillBroke 16310 16410 18 1642 3ff1fef4fb1442de
45 43 0.8 0.5 WillBroke 14650 14750 16 1476 19f85bbaf383110c
46 44 0.8 0.5 WillBroke 14110 14210 16 1422 027af17c0ac0fdc7
47 45 0.8 0.5 WillBroke 12960 13060 14 1307 d1fb96d0ee7ba804
48 46 0.8 0.5 WillBroke 16280 16380 18 1639 c8e839df23f5a211
49 47 0.8 0.5 WillBroke 16600 16700 18 1671 e7f53b160c1853ae
50 48 0.8 0.5 WillBroke 17070 17170 16 1718 aeec09055f384b43
51 49 0.8 0.5 WillBroke 17970 18070 18 1808 f212a3419dd45eb8
52 50 0.8 0.5 WillBroke 14720 14820 16 1483 138dc377b6038fc6
53 51 0.8 0.5 WillBroke 17000 17100 18 1711 91bf94bf4f9b80a9
54 52 0.8 0.5 WillBroke 15330 15430 18 1544 479d44543e6d898f
55 53 0.8 0.5 WillBroke 16910 17010 19 1702 23c9ae667a13b1b8
56 54 0.8 0.5 WillBroke 15710 15810 18 1582 5db0798e7430331f
57 55 0.8 0.5 WillBroke 18080 18180 20 1819 bb57883965df4728
58 56 0.8 0.5 WillBroke 14690 14790 16 1480 db298aebc9ac6475
59 57 0.8 0.5 WillBroke 17110 17210 18 1722 a8b179b65459b425
60 58 0.8 0.5 WillBroke 16040 16140 17 1615 9311f9bf9c30c9fa
61 59 0.8 0.5 WillBroke 15280 15380 17 1539 d357274a150ed640
62 60 0.8 0.5 WillBroke 16430 16530 18 1654 dce27d808a54e389
63 1 1.0 0.5 WillBroke 12700 12800 15 1281 3778c1c08b0e4636
64 2 1.0 0.5 WillBroke 12590 12690 15 1270 d2e72be9df803e3d
65 3 1.0 0.5 WillBroke 14160 14260 16 1427 0b18cbb4d9d49fbb
66 4 1.0 0.5 WillBroke 12650 12750 15 1276 da78405420316abd
67 5 1.0 0.5 WillBroke 13140 13240 15 1325 c95a030fe020dd7a
68 6 1.0 0.5 WillBroke 13040 13140 16 1315 44fd3277642c8a9a
69 7 1.0 0.5 WillBroke 15660 15760 19 1577 017b21240992c769
70 8 1.0 0.5 WillBroke 12880 12980 15 1299 599e66b4a1a5921e
71 9 1.0 0.5 WillBroke 12370 12470 15 1248 cb45d1000cf1ea08
72 10 1.0 0.5 WillBroke 14320 14420 16 1443 32fa60bc328344e0
73 11 1.0 0.5 WillBroke 14910 15010 17 1502 fe8e6683df6f44c1
74 12 1.0 0.5 WillBroke 12180 12280 14 1229 d7ceb4d09ec176aa
75 13 1.0 0.5 WillBroke 13290 13390 16 1340 e8036a983b52c1ab
76 14 1.0 0.5 WillBroke 15310 15410 18 1542 0b8a9b1c08492fbe
77 15 1.0 0.5 WillBroke 12700 12800 15 1281 a8ed8929fa4337f0
78 16 1.0 0.5 WillBroke 15430 15530 18 1554 eb95c4903824bb05
79 17 1.0 0.5 WillBroke 13890 13990 16 1400 6db1399b0be214fa
80 18 1.0 0.5 WillBroke 14250 14350 15 1436 535d36145c307a6a
81 19 1.0 0.5 WillBroke 14160 14260 17 1427 547e4a683939cf31
82 20 1.0 0.5 WillBroke 16310 16410 19 1642 0653fd31b3fc42d8
83 21 1.0 0.5 WillBroke 13860 13960 15 1397 abb9fb41943aed14
84 22 1.0 0.5 WillBroke 11720 11820 14 1183 1174869087f230c6
85 23 1.0 0.5 WillBroke 12260 12360 15 1237 d5074ba63114d34f
86 24 1.0 0.5 WillBroke 12680 12780 15 1279 d075ca28021bcb2f
87 25 1.0 0.5 WillBroke 14390 14490 18 1450 ca018f228e141313
88 26 1.0 0.5 WillBroke 12970 13070 16 1308 3c559d5142622b8a
89 27 1.0 0.5 WillBroke 12790 12890 15 1290 04d51fbe35ed5cd5
90 28 1.0 0.5 WillBroke 12730 12830 15 1284 e32fd88365db7019
91 29 1.0 0.5 WillBroke 12300 12400 15 1241 e865da9fc3e136dd
92 30 1.0 0.5 WillBroke 12500 12600 15 1261 ee7b9626cecaa543
93 31 1.0 0.5 WillBroke 12030 12130 15 1214 58cfcc93405f718b
94 32 1.0 0.5 WillBroke 12240 12340 15 1235 4a7a33fc862b87b6
95 33 1.0 0.5 WillBroke 16210 16310 19 1632 a4321c62d0942b51
96 34 1.0 0.5 WillBroke 12580 12680 15 1269 8d8084c506399075
97 35 1.0 0.5 WillBroke 13830 13930 16 1394 80eab6a1a91fe47e
98 36 1.0 0.5 WillBroke 12960 13060 16 1307 a3bf0483a30b9832
99 37 1.0 0.5 WillBroke 12250 12350 15 1236 591a92e077f7fb7e
100 38 1.0 0.5 WillBroke 14040 14140 17 1415 a37a6c6e88296d4c
101 39 1.0 0.5 WillBroke 11750 11850 14 1186 c8e91a1813d1cf7f
102 40 1.0 0.5 WillBroke 13080 13180 14 1319 59ad5f054dacf9b5
103 41 1.0 0.5 WillBroke 14600 14700 16 1471 d6c53c1e324f31bc
104 42 1.0 0.5 WillBroke 13980 14080 17 1409 82171315883210d2
105 43 1.0 0.5 WillBroke 12620 12720 15 1273 cf5f3536022121f2
106 44 1.0 0.5 WillBroke 12180 12280 15 1229 c9f7c2acacdc2a4f
107 45 1.0 0.5 WillBroke 11230 11330 14 1134 e4dcb7f2fca454aa
108 46 1.0 0.5 WillBroke 13950 14050 17 1406 4f6631c906041c50
109 47 1.0 0.5 WillBroke 14210 14310 17 1432 94971d9adbcce7f4
110 48 1.0 0.5 WillBroke 14610 14710 16 1472 52b86bd6f4d01970
111 49 1.0 0.5 WillBroke 15330 15430 17 1544 b76a0e4f82a8f139
112 50 1.0 0.5 WillBroke 12690 12790 15 1280 f3859d8ebae145f7
113 51 1.0 0.5 WillBroke 14540 14640 17 1465 d54f534dbfd8ac98
114 52 1.0 0.5 WillBroke 13170 13270 16 1328 e3ba704a9ee1a898
115 53 1.0 0.5 WillBroke 14450 14550 18 1456 09513ed8620db12f
116 54 1.0 0.5 WillBroke 13500 13600 16 1361 fa700ae33783c44b
117 55 1.0 0.5 WillBroke 15410 15510 18 1552 37ce852a8984b97a
118 56 1.0 0.5 WillBroke 12670 12770 15 1278 138a00120ccb00fe
119 57 1.0 0.5 WillBroke 14630 14730 17 1474 18f604c62fdf14cf
120 58 1.0 0.5 WillBroke 13760 13860 16 1387 40a380177cc0fb2f
121 59 1.0 0.5 WillBroke 13150 13250 15 1326 cbb58f0ec6aacce2
122 60 1.0 0.5 WillBroke 14070 14170 17 1418 fdd65da97d503bea
123 1 0.6 0.5 WillBroke 18150 18250 16 1826 6ba0eac35d362331
124 2 0.6 0.5 WillBroke 17970 18070 16 1808 e9a49730ebc3284e
125 3 0.6 0.5 WillBroke 20530 20630 17 2064 f35e11a268ee6e5b
126 4 0.6 0.5 WillBroke 18050 18150 16 1816 7f4d381a70594785
127 5 0.6 0.5 WillBroke 18850 18950 16 1896 2255227b0f0566a4
128 6 0.6 0.5 WillBroke 18740 18840 18 1885 77671a7b01e433c1
129 7 0.6 0.5 WillBroke 23130 23230 21 2324 6d6875964a164a26
130 8 0.6 0.5 WillBroke 18450 18550 17 1856 89995e2334a69fc4
131 9 0.6 0.5 WillBroke 17630 17730 16 1774 3a57554bfdae952c
132 10 0.6 0.5 WillBroke 20780 20880 16 2089 92d0d3ee482673bb
133 11 0.6 0.5 WillBroke 21820 21920 20 2193 499413f37856cc67
134 12 0.6 0.5 WillBroke 17300 17400 15 1741 cf400e983b9ab384
135 13 0.6 0.5 WillBroke 19160 19260 18 1927 cc9cd1d981969951
136 14 0.6 0.5 WillBroke 22520 22620 21 2263 ed6838239b11bc75
137 15 0.6 0.5 WillBroke 18130 18230 16 1824 d749947d1fa45774
138 16 0.6 0.5 WillBroke 22710 22810 21 2282 bda734962c5606f0
139 17 0.6 0.5 WillBroke 20110 20210 18 2022 35e19cd78e4681c5
140 18 0.6 0.5 WillBroke 20680 20780 16 2079 044b17ae0c8f471d
141 19 0.6 0.5 WillBroke 20600 20700 20 2071 6bc5d68ea6d37f58
142 20 0.6 0.5 WillBroke 24210 24310 21 2432 a8ea7744a790f179
143 21 0.6 0.5 WillBroke 20020 20120 15 2013 024dc742aba6d11e
144 22 0.6 0.5 WillBroke 16590 16690 16 1670 1ed9990a7a83680d
145 23 0.6 0.5 WillBroke 17460 17560 17 1757 2f5c8bb3f7fbce51
146 24 0.6 0.5 WillBroke 18120 18220 17 1823 39e31936bdc74dca
147 25 0.6 0.5 WillBroke 20980 21080 20 2109 0c545a97c49f67d0
148 26 0.6 0.5 WillBroke 18610 18710 18 1872 b84cafd2a5e955fd
149 27 0.6 0.5 WillBroke 18300 18400 17 1841 7610f4a37901d7da
150 28 0.6 0.5 WillBroke 18190 18290 17 1830 87c68d8444be7fe2
151 29 0.6 0.5 WillBroke 17520 17620 16 1763 64e7b957cc2182a1
152 30 0.6 0.5 WillBroke 17850 17950 16 1796 b318302a3ff94a1b
153 31 0.6 0.5 WillBroke 17100 17200 16 1721 ab156f4dcec9413a
154 32 0.6 0.5 WillBroke 17430 17530 17 1754 3505a668df088e29
155 33 0.6 0.5 WillBroke 24030 24130 21 2414 62dad0cd6de6c6ad
156 34 0.6 0.5 WillBroke 17960 18060 16 1807 468f81ede64f7032
157 35 0.6 0.5 WillBroke 19990 20090 17 2010 8425b945af3a5546
158 36 0.6 0.5 WillBroke 18600 18700 18 1871 2ada8cd49c8d5762
159 37 0.6 0.5 WillBroke 17440 17540 17 1755 a98e38b6442eaf84
160 38 0.6 0.5 WillBroke 20440 20540 21 2055 7762c24c4c087ea3
161 39 0.6 0.5 WillBroke 16640 16740 16 1675 948a96907d9eefc0
162 40 0.6 0.5 WillBroke 18740 18840 15 1885 cf3d3003437065ba
163 41 0.6 0.5 WillBroke 21260 21360 17 2137 42ef7102a413d1c0
164 42 0.6 0.5 WillBroke 20280 20380 20 2039 dcf19acb186b9283
165 43 0.6 0.5 WillBroke 18040 18140 17 1815 a2b7896cebd7012a
166 44 0.6 0.5 WillBroke 17340 17440 17 1745 ae0d1f06637ac29e
167 45 0.6 0.5 WillBroke 15820 15920 15 1593 34ed73b3ed021ee4
168 46 0.6 0.5 WillBroke 20240 20340 20 2035 1327132bbc471b49
169 47 0.6 0.5 WillBroke 20670 20770 19 2078 6ed62543a7d622f7
170 48 0.6 0.5 WillBroke 21260 21360 16 2137 7852586cc5440810
171 49 0.6 0.5 WillBroke 22500 22600 19 2261 e5cb75e99d5282f9
172 50 0.6 0.5 WillBroke 18130 18230 17 1824 b6ab5edaaf877789
173 51 0.6 0.5 WillBroke 21210 21310 19 2132 41ac950e5cfaa653
174 52 0.6 0.5 WillBroke 18990 19090 19 1910 413ccf741adabd38
175 53 0.6 0.5 WillBroke 21110 21210 21 2122 36abd4e8cfe6083a
176 54 0.6 0.5 WillBroke 19460 19560 19 1957 cab475fe2176ba46
177 55 0.6 0.5 WillBroke 22700 22800 21 2281 4621276ba4894fea
178 56 0.6 0.5 WillBroke 18100 18200 17 1821 ec9a774751bdedbf
179 57 0.6 0.5 WillBroke 21340 21440 18 2145 5709bbcab913e98c
180 58 0.6 0.5 WillBroke 19910 20010 18 2002 d16492ba1669abb8
181 59 0.6 0.5 WillBroke 18890 18990 17 1900 f36f53cb80836d5e
182 60 0.6 0.5 WillBroke 20450 20550 20 2056 c118dd86c7e0945f
183 1 0.8 0.0 WillBroke 10070 10170 10 1018 1914ad90455159e8
184 2 0.8 0.0 WillBroke 9990 10090 10 1010 3d6287598c77d9e3
185 3 0.8 0.0 WillBroke 11160 11260 10 1127 7476613d96868cc1
186 4 0.8 0.0 WillBroke 10030 10130 10 1014 50107275381fd7aa
187 5 0.8 0.0 WillBroke 10400 10500 10 1051 d287687d8bf0078e
188 6 0.8 0.0 WillBroke 10340 10440 11 1045 6ce913c53b72daf4
189 7 0.8 0.0 WillBroke 12300 12400 12 1241 bc0a4e85028ea794
190 8 0.8 0.0 WillBroke 10210 10310 10 1032 9d817ecb6fe288ee
191 9 0.8 0.0 WillBroke 9820 9920 10 993 92da81d6468ebe82
192 10 0.8 0.0 WillBroke 11280 11380 10 1139 f2f9c86856025f04
193 11 0.8 0.0 WillBroke 11730 11830 11 1184 9f0a0926039f3e52
194 12 0.8 0.0 WillBroke 9690 9790 9 980 33b8c796b8fe56e5
195 13 0.8 0.0 WillBroke 10530 10630 11 1064 bc70c2da7b3b974c
196 14 0.8 0.0 WillBroke 12040 12140 12 1215 c95036c6977e1b59
197 15 0.8 0.0 WillBroke 10080 10180 10 1019 373431a56c7b9101
198 16 0.8 0.0 WillBroke 12130 12230 12 1224 02dcac6b7da6c93c
199 17 0.8 0.0 WillBroke 10970 11070 11 1108 baed4dff515bc947
200 18 0.8 0.0 WillBroke 11220 11320 10 1133 ed5b57045897960d
201 19 0.8 0.0 WillBroke 11190 11290 11 1130 9e9829f5785c1567
202 20 0.8 0.0 WillBroke 12780 12880 12 1289 b0ce6f3a04534a83
203 21 0.8 0.0 WillBroke 10930 11030 10 1104 5f92a1c351fcaade
204 22 0.8 0.0 WillBroke 9350 9450 9 946 685587a2ecb63f49
205 23 0.8 0.0 WillBroke 9760 9860 10 987 46ca2993ce13d9b7
206 24 0.8 0.0 WillBroke 10060 10160 10 1017 8bbb14c9c6edd738
207 25 0.8 0.0 WillBroke 11360 11460 12 1147 ca7a2943fbf35fa7
208 26 0.8 0.0 WillBroke 10290 10390 11 1040 c2615398937c44cf
209 27 0.8 0.0 WillBroke 10140 10240 10 1025 2c11a0e93231978e
210 28 0.8 0.0 WillBroke 10100 10200 10 1021 02996614f9d1b6ad
211 29 0.8 0.0 WillBroke 9770 9870 10 988 ee1586d573ca55c9
212 30 0.8 0.0 WillBroke 9930 10030 10 1004 cb05f8a9a91fd3fa
213 31 0.8 0.0 WillBroke 9580 9680 10 969 e8ecae5902642a8d
214 32 0.8 0.0 WillBroke 9740 9840 10 985 f136abd42fb6b90f
215 33 0.8 0.0 WillBroke 12710 12810 12 1282 87209b5050bf4859
216 34 0.8 0.0 WillBroke 9980 10080 10 1009 b910622b9c39d291
217 35 0.8 0.0 WillBroke 10930 11030 10 1104 e910f01456aee3b6
218 36 0.8 0.0 WillBroke 10290 10390 11 1040 2468ae1f05faa180
219 37 0.8 0.0 WillBroke 9740 9840 10 985 bf0e779e9243fe83
220 38 0.8 0.0 WillBroke 11110 11210 12 1122 cd1edafd69f799db
221 39 0.8 0.0 WillBroke 9360 9460 10 947 0a9c9db826fd6fc3
222 40 0.8 0.0 WillBroke 10350 10450 9 1046 8a695f2a7b77be08
223 41 0.8 0.0 WillBroke 11500 11600 10 1161 773e9846d68e4563
224 42 0.8 0.0 WillBroke 11050 11150 12 1116 971f9792bb5190a5
225 43 0.8 0.0 WillBroke 10030 10130 10 1014 290e32ab22867eef
226 44 0.8 0.0 WillBroke 9690 9790 10 980 abf81ab05a0351ab
227 45 0.8 0.0 WillBroke 8970 9070 9 908 c51f9d6618059105
228 46 0.8 0.0 WillBroke 11030 11130 11 1114 3eefac78a2ec93b0
229 47 0.8 0.0 WillBroke 11210 11310 11 1132 c1f575d6e9da5621
230 48 0.8 0.0 WillBroke 11500 11600 10 1161 cc56a243e423592f
231 49 0.8 0.0 WillBroke 12040 12140 11 1215 ab73b8cd07be0649
232 50 0.8 0.0 WillBroke 10080 10180 10 1019 5b3f678f2f519458
233 51 0.8 0.0 WillBroke 11460 11560 11 1157 49df060130506ba9
234 52 0.8 0.0 WillBroke 10440 10540 11 1055 a04eaacb8803cb78
235 53 0.8 0.0 WillBroke 11410 11510 12 1152 47d7de117d48f625
236 54 0.8 0.0 WillBroke 10700 10800 11 1081 2dc02e576db39ec7
237 55 0.8 0.0 WillBroke 12120 12220 12 1223 b59afb6f495f92cc
238 56 0.8 0.0 WillBroke 10050 10150 10 1016 96cd4b621eb75a64
239 57 0.8 0.0 WillBroke 11520 11620 11 1163 6ace2627157a30f5
240 58 0.8 0.0 WillBroke 10870 10970 11 1098 d24694742d029864
241 59 0.8 0.0 WillBroke 10420 10520 10 1053 cb0148bdde051390
242 60 0.8 0.0 WillBroke 11120 11220 11 1123 89dcecf0208bd4c5
243 1 0.8 0.8 WillBroke 26100 26200 31 2621 facb758365f7865b
244 2 0.8 0.8 WillBroke 25850 25950 31 2596 7d282a08b15832e4
245 3 0.8 0.8 WillBroke 29980 30080 34 3009 f2ded9f2c282d18f
246 4 0.8 0.8 WillBroke 25990 26090 31 2610 5bb9737062e3e1ff
247 5 0.8 0.8 WillBroke 27260 27360 32 2737 4bd7db07086983d8
248 6 0.8 0.8 WillBroke 27040 27140 34 2715 58790a7cd5034891
249 7 0.8 0.8 WillBroke 34160 34260 43 3427 c3b1132c88b0087b
250 8 0.8 0.8 WillBroke 26600 26700 32 2671 e4f42c7e9a769659
251 9 0.8 0.8 WillBroke 25280 25380 31 2539 ae0029cabb1ecb76
252 10 0.8 0.8 WillBroke 30440 30540 35 3055 075dfb3f39c9f414
253 11 0.8 0.8 WillBroke 32040 32140 39 3215 6edcb217700a8f7c
254 12 0.8 0.8 WillBroke 24790 24890 30 2490 f8491701247bcb39
255 13 0.8 0.8 WillBroke 27710 27810 35 2782 cb475aee74befea5
256 14 0.8 0.8 WillBroke 33180 33280 41 3329 8af0b8a0fd5e834b
257 15 0.8 0.8 WillBroke 26070 26170 31 2618 e2fbd7aa00441616
258 16 0.8 0.8 WillBroke 33480 33580 42 3359 cc06979bd8253d1c
259 17 0.8 0.8 WillBroke 29220 29320 36 2933 34d06f9996dc6314
260 18 0.8 0.8 WillBroke 30290 30390 35 3040 f30283d3d1284d9a
261 19 0.8 0.8 WillBroke 29950 30050 38 3006 ed2ffeeb23e4d2c7
262 20 0.8 0.8 WillBroke 35990 36090 44 3610 441d34847f7052a3
263 21 0.8 0.8 WillBroke 29210 29310 33 2932 97b819d64521f3f1
264 22 0.8 0.8 WillBroke 23650 23750 29 2376 4bece642126eda8e
265 23 0.8 0.8 WillBroke 24990 25090 31 2510 707aeeeb6326f2a8
266 24 0.8 0.8 WillBroke 26050 26150 32 2616 e019c2e195081ba6
267 25 0.8 0.8 WillBroke 30630 30730 39 3074 4193242a4b0f92a4
268 26 0.8 0.8 WillBroke 26800 26900 34 2691 ea4cd91c79d0dae5
269 27 0.8 0.8 WillBroke 26360 26460 32 2647 41475b4e3dcc78b5
270 28 0.8 0.8 WillBroke 26190 26290 32 2630 2812da5c40655627
271 29 0.8 0.8 WillBroke 25110 25210 31 2522 f5cce351f754c3dc
272 30 0.8 0.8 WillBroke 25630 25730 31 2574 da101fc4522fbef8
273 31 0.8 0.8 WillBroke 24440 24540 30 2455 d1ed5841b8f3d2c7
274 32 0.8 0.8 WillBroke 24950 25050 31 2506 7a853f4af1372d33
275 33 0.8 0.8 WillBroke 35700 35800 43 3581 c19ba694b20e2224
276 34 0.8 0.8 WillBroke 25830 25930 31 2594 1fe8515aa980c3e8
277 35 0.8 0.8 WillBroke 29070 29170 35 2918 b471b626e0a26207
278 36 0.8 0.8 WillBroke 26760 26860 34 2687 7b47afeb2bda4f09
279 37 0.8 0.8 WillBroke 24960 25060 31 2507 70611ac9655b4130
280 38 0.8 0.8 WillBroke 29720 29820 39 2983 29e31c8aedca1b66
281 39 0.8 0.8 WillBroke 23720 23820 29 2383 e6b672c0d11de53f
282 40 0.8 0.8 WillBroke 27150 27250 31 2726 228e1e1209860ccf
283 41 0.8 0.8 WillBroke 31230 31330 36 3134 d8bd943c7794fb4d
284 42 0.8 0.8 WillBroke 29450 29550 37 2956 99532fe0b5bbd56a
285 43 0.8 0.8 WillBroke 25920 26020 32 2603 8c12e7bb65f2c9ec
286 44 0.8 0.8 WillBroke 24790 24890 31 2490 c1e40d8406efd5e9
287 45 0.8 0.8 WillBroke 22450 22550 28 2256 4ae97c637521edaf
288 46 0.8 0.8 WillBroke 29410 29510 37 2952 7760a4f76f63ebb5
289 47 0.8 0.8 WillBroke 30160 30260 37 3027 f062837cb5b49eb0
290 48 0.8 0.8 WillBroke 31220 31320 36 3133 5e41f3871a485c72
291 49 0.8 0.8 WillBroke 33200 33300 39 3331 bf6f87e6642eeed9
292 50 0.8 0.8 WillBroke 26050 26150 32 2616 800841a85e80970f
293 51 0.8 0.8 WillBroke 31020 31120 38 3113 54d06d44545aa4fb
294 52 0.8 0.8 WillBroke 27410 27510 35 2752 c545900336cea749
295 53 0.8 0.8 WillBroke 30780 30880 40 3089 7b14f9d5b0dabe0d
296 54 0.8 0.8 WillBroke 28150 28250 35 2826 46db795b35f34c5d
297 55 0.8 0.8 WillBroke 33490 33590 42 3360 c4760d6e42ad2e59
298 56 0.8 0.8 WillBroke 26030 26130 32 2614 0503e5395eaff483
299 57 0.8 0.8 WillBroke 31290 31390 37 3140 b7b8ab30e565b2f9
300 58 0.8 0.8 WillBroke 28940 29040 35 2905 4527feae8a218446
301 59 0.8 0.8 WillBroke 27310 27410 33 2742 518030c576b6fcbe
302 60 0.8 0.8 WillBroke 29750 29850 38 2986 53e33f04a6f4a7af
303 1 0.12 0.5 Endured -1 120000 0 12001 a4d66728d54aad20
304 2 0.12 0.5 Endured -1 120000 0 12001 0f86d5191fd466e2
305 3 0.12 0.5 Endured -1 120000 0 12001 842a665c4588e215
306 4 0.12 0.5 Endured -1 120000 0 12001 930164c1ef89e1d1
307 5 0.12 0.5 Endured -1 120000 0 12001 a3c5f53000dc35b6
308 6 0.12 0.5 Endured -1 120000 0 12001 6f2b82eed827ff94
309 7 0.12 0.5 Endured -1 120000 0 12001 e8ccd63c058aac7e
310 8 0.12 0.5 Endured -1 120000 0 12001 ce987e8b1ff40739
311 9 0.12 0.5 Endured -1 120000 0 12001 311b03a75aa8774d
312 10 0.12 0.5 Endured -1 120000 0 12001 335c11e8d64fdd7a
313 11 0.12 0.5 Endured -1 120000 0 12001 ec84541c1a1c2b9e
314 12 0.12 0.5 Endured -1 120000 0 12001 23d1461c11d6eecf
315 13 0.12 0.5 Endured -1 120000 0 12001 e21fc8da5df2c979
316 14 0.12 0.5 Endured -1 120000 0 12001 8c16fb1b49916ce9
317 15 0.12 0.5 Endured -1 120000 0 12001 596e31a87d587289
318 16 0.12 0.5 Endured -1 120000 0 12001 53e9f6c0cdc92586
319 17 0.12 0.5 Endured -1 120000 0 12001 32a5669012845805
320 18 0.12 0.5 Endured -1 120000 0 12001 bf03e03c67b40e3b
321 19 0.12 0.5 Endured -1 120000 0 12001 178a29a6f8375006
322 20 0.12 0.5 Endured -1 120000 0 12001 59c536047786a192
323 21 0.12 0.5 Endured -1 120000 0 12001 b356add08dab94a5
324 22 0.12 0.5 Endured -1 120000 0 12001 99922c10b6b32d2b
325 23 0.12 0.5 Endured -1 120000 0 12001 e280c89341344aa7
326 24 0.12 0.5 Endured -1 120000 0 12001 fa0726e3c32d99d8
327 25 0.12 0.5 Endured -1 120000 0 12001 f9f241118be9983e
328 26 0.12 0.5 Endured -1 120000 0 12001 80a50b45c9d799c0
329 27 0.12 0.5 Endured -1 120000 0 12001 771cfaf72c64438b
330 28 0.12 0.5 Endured -1 120000 0 12001 fbbd6f2007051076
331 29 0.12 0.5 Endured -1 120000 0 12001 c08d546694da4a7e
332 30 0.12 0.5 Endured -1 120000 0 12001 9df481a0c2cdee11
333 31 0.12 0.5 Endured -1 120000 0 12001 ae9f606dafebfa1e
334 32 0.12 0.5 Endured -1 120000 0 12001 06e696404e9256de
335 33 0.12 0.5 Endured -1 120000 0 12001 066aafcddab6ef0e
336 34 0.12 0.5 Endured -1 120000 0 12001 0833cb592b8138cd
337 35 0.12 0.5 Endured -1 120000 0 12001 72f9ccaea0637ad4
338 36 0.12 0.5 Endured -1 120000 0 12001 e0d1c64bc8e0fc48
339 37 0.12 0.5 Endured -1 120000 0 12001 b70ad94cf12adce0
340 38 0.12 0.5 Endured -1 120000 0 12001 ff435f0887180b71
341 39 0.12 0.5 Endured -1 120000 0 12001 8da9c4370b584012
342 40 0.12 0.5 Endured -1 120000 0 12001 74f9885c1a541501
343 41 0.12 0.5 Endured -1 120000 0 12001 d4e11eb98b23c59a
344 42 0.12 0.5 Endured -1 120000 0 12001 4289f6ae3fe60c0d
345 43 0.12 0.5 Endured -1 120000 0 12001 f9595ac5caec95c2
346 44 0.12 0.5 Endured -1 120000 0 12001 bc590d5d1b609c7e
347 45 0.12 0.5 Endured -1 120000 0 12001 efdb32b1f8fb14ca
348 46 0.12 0.5 Endured -1 120000 0 12001 6b1ed857ef93f9e7
349 47 0.12 0.5 Endured -1 120000 0 12001 4dcb3fb4a7fb1808
350 48 0.12 0.5 Endured -1 120000 0 12001 f11072ebdaf3fe06
351 49 0.12 0.5 Endured -1 120000 0 12001 b2b83bbf20dcb8da
352 50 0.12 0.5 Endured -1 120000 0 12001 1c976596616ad5bc
353 51 0.12 0.5 Endured -1 120000 0 12001 3c9322031aac9a32
354 52 0.12 0.5 Endured -1 120000 0 12001 a96cd8ca41cfa13a
355 53 0.12 0.5 Endured -1 120000 0 12001 a215b789ed222a7d
356 54 0.12 0.5 Endured -1 120000 0 12001 3be6e39bfa4d5424
357 55 0.12 0.5 Endured -1 120000 0 12001 b40fe851ccb51114
358 56 0.12 0.5 Endured -1 120000 0 12001 3eb672b6f8f9df4b
359 57 0.12 0.5 Endured -1 120000 0 12001 0cc56de0d1df332a
360 58 0.12 0.5 Endured -1 120000 0 12001 1c46b092e7a9f5fa
361 59 0.12 0.5 Endured -1 120000 0 12001 9abf165506073db5
362 60 0.12 0.5 Endured -1 120000 0 12001 d9913a1ed7920a47
363 1 0.2 0.5 WillBroke 61550 61650 0 6166 4eb7b5f041058c3a
364 2 0.2 0.5 WillBroke 60770 60870 0 6088 6adf5a0713405867
365 3 0.2 0.5 WillBroke 73080 73180 0 7319 3b218fb3f2750d00
366 4 0.2 0.5 WillBroke 60910 61010 0 6102 e6fc3dd13c4f4f88
367 5 0.2 0.5 WillBroke 64890 64990 0 6500 13eb57c707621354
368 6 0.2 0.5 WillBroke 65330 65430 0 6544 5d12aa022ce881c2
369 7 0.2 0.5 WillBroke 89140 89240 0 8925 722956c2506d94ac
370 8 0.2 0.5 WillBroke 63320 63420 0 6343 4c8556996b77c4d2
371 9 0.2 0.5 WillBroke 59100 59200 0 5921 4fdeaa907d37b76a
372 10 0.2 0.5 WillBroke 74460 74560 0 7457 e6a7d0c99e99df1d
373 11 0.2 0.5 WillBroke 81360 81460 0 8147 8bb48eff4337aca3
374 12 0.2 0.5 WillBroke 57220 57320 0 5733 5c1f16f19f35355c
375 13 0.2 0.5 WillBroke 68020 68120 0 6813 7728601e0be34b58
376 14 0.2 0.5 WillBroke 85960 86060 0 8607 a16720cf9093a2ba
377 15 0.2 0.5 WillBroke 61270 61370 0 6138 84ad9eee8ece8cab
378 16 0.2 0.5 WillBroke 86760 86860 0 8687 f30b663ba19039fa
379 17 0.2 0.5 WillBroke 72150 72250 0 7226 adb357df88b33dc8
380 18 0.2 0.5 WillBroke 73890 73990 0 7400 fbfa7d31601e6aa1
381 19 0.2 0.5 WillBroke 75870 75970 0 7598 e142af5c45ee0be2
382 20 0.2 0.5 WillBroke 94760 94860 0 9487 4c708580624a1d46
383 21 0.2 0.5 WillBroke 70030 70130 0 7014 13ad55e6f3130be3
384 22 0.2 0.5 WillBroke 53850 53950 0 5396 79f3bb316c0eaf85
385 23 0.2 0.5 WillBroke 58520 58620 0 5863 9f0c6f85419ae6dd
386 24 0.2 0.5 WillBroke 61550 61650 0 6166 f39221687519b487
387 25 0.2 0.5 WillBroke 77990 78090 0 7810 10d4fc69f97b26d8
388 26 0.2 0.5 WillBroke 64630 64730 0 6474 cc05ed3304923a87
389 27 0.2 0.5 WillBroke 62610 62710 0 6272 39625ac195ca6345
390 28 0.2 0.5 WillBroke 61980 62080 0 6209 1689dbf84daa149b
391 29 0.2 0.5 WillBroke 58650 58750 0 5876 63711e804c1fd959
392 30 0.2 0.5 WillBroke 60210 60310 0 6032 6750a2c42c1feb9b
393 31 0.2 0.5 WillBroke 56770 56870 0 5688 efe09e0087130ba4
394 32 0.2 0.5 WillBroke 58580 58680 0 5869 48e0e13604b41a59
395 33 0.2 0.5 WillBroke 93390 93490 0 9350 0f7b98fadce89c49
396 34 0.2 0.5 WillBroke 60530 60630 0 6064 7a4f7f1a4f63374c
397 35 0.2 0.5 WillBroke 70790 70890 0 7090 85f8a9ddf9d30a53
398 36 0.2 0.5 WillBroke 64920 65020 0 6503 73db5f07ae7671ad
399 37 0.2 0.5 WillBroke 58250 58350 0 5836 09f7c4eb8062265a
400 38 0.2 0.5 WillBroke 75920 76020 0 7603 2414eda9e29d7e3e
401 39 0.2 0.5 WillBroke 54080 54180 0 5419 8668a6e52104341a
402 40 0.2 0.5 WillBroke 63980 64080 0 6409 9b0483b182117ef2
403 41 0.2 0.5 WillBroke 77210 77310 0 7732 1177a13eb3cc229b
404 42 0.2 0.5 WillBroke 74160 74260 0 7427 666d37658845da58
405 43 0.2 0.5 WillBroke 61350 61450 0 6146 871d25bd76ae94c8
406 44 0.2 0.5 WillBroke 58190 58290 0 5830 f1e96621098bc360
407 45 0.2 0.5 WillBroke 50280 50380 0 5039 c2f86a90a197eb00
408 46 0.2 0.5 WillBroke 73840 73940 0 7395 17cf31b97a0d1671
409 47 0.2 0.5 WillBroke 75630 75730 0 7574 8538745e7a5e1ff6
410 48 0.2 0.5 WillBroke 76850 76950 0 7696 b6525c3189927f9a
411 49 0.2 0.5 WillBroke 84340 84440 0 8445 8590d59e44ff5fd4
412 50 0.2 0.5 WillBroke 61880 61980 0 6199 2e5718c722577755
413 51 0.2 0.5 WillBroke 77980 78080 0 7809 8f8ccdb15763c750
414 52 0.2 0.5 WillBroke 67470 67570 0 6758 ac01f6ce963b5334
415 53 0.2 0.5 WillBroke 79110 79210 0 7922 6ea0bdfb3703d02a
416 54 0.2 0.5 WillBroke 69530 69630 0 6964 fb7b9ac715a66a05
417 55 0.2 0.5 WillBroke 87170 87270 0 8728 07bba7c2cd21b7b7
418 56 0.2 0.5 WillBroke 61450 61550 0 6156 3136df798ca68e9d
419 57 0.2 0.5 WillBroke 78000 78100 0 7811 d6a4a321a0936ef2
420 58 0.2 0.5 WillBroke 71110 71210 0 7122 e7dfb64e0e60fff6
421 59 0.2 0.5 WillBroke 65890 65990 0 6600 970e46a63d649f1d
422 60 0.2 0.5 WillBroke 75320 75420 0 7543 cfedd17a42366fca

View file

@ -0,0 +1,518 @@
using Lodur;
using Lodur.Body.Ymir;
using Ymir.Box3D;
namespace Lodur.Tests;
/// <summary>The airway openings the plan carries become liquid sensors in a particle world, and Ragdoll.ReadAirway reads live and pooled volume per opening.</summary>
public sealed class AirwayTests
{
private const float Dt = 1f / 120f;
private const float R = 0.0125f;
private const float DropVolume = (2f * R) * (2f * R) * (2f * R);
private static readonly uint FluidPhase = Box3DSoaPhase.Of(0, fluid: true);
// Bounds, from deterministic-bound-margin (readings are identical run to run), read as max(signed drop, 0) as AirwaySample.Of floors them. Side-lying falls (12 seeds): shipped worst drop 0.01323 m,
// least claimed mutant (the opening's offset rotated about z only) 0.00914 m, separation 1.45: bound sqrt(0.01323 x 0.00914) = 0.0110 m. An opening read from lane 0, a sump read from lane 0, the rim subtracted, the sump offset unrotated or its lane's rotation ignored, the pharynx sump moved and the rim read as a cosine
// (0.00117) are further off; most read 0 on some seed. The zero-reading convention was not needed: the least claimed mutant reads above 0.
private const float SideDropBound = 0.0110f;
// Upright (creation pose -0.04671, welded stool at full strength -0.04615 m): clearance below the sump, shipped worst 0.04615 m, least claimed mutant (the glottis sump 1 cm shallower) 0.03615 m, separation 1.28:
// bound sqrt(0.04615 x 0.03615) = 0.0408 m, so a reading below -0.0408. The 2 cm shallower sump (0.02615) and the mutants reading at or above 0 are further off; the zero-reading convention was not needed.
private const float UprightBound = -0.0408f;
// Limp seated falls (40 seeds): shipped 31 drain, the pelvis-lane mutant 0 (counted as 1): bound sqrt(31 x 1) = 5.6, so at least 6 drain.
private const int SeatedDraining = 6;
private static readonly BodyPlan Plan = BodyPlans.Humanoid();
private static readonly int Mouth = Plan.AirwayIndex("Mouth");
private static readonly int Nose = Plan.AirwayIndex("Nose");
private static Box3DSoaWorld ParticleWorld(int sensors, float gravityZ = 0f, bool extra = false)
{
var (bodies, joints, _) = Ragdoll.Needs(Plan);
return new Box3DSoaWorld(bodies + (extra ? 1 : 0), gravityY: 0f, gravityZ: gravityZ, jointCapacity: joints + (extra ? 1 : 0),
particles: new Box3DSoaParticleCapacities(16, 16, 16, 16, 64, 2, 16, 8, sensors));
}
/// <summary>World position 1.3 cm beyond an opening along its offset direction, from the head's creation pose (no step has run).</summary>
private static (float X, float Y, float Z) Outside(Box3DSoaWorld world, Ragdoll doll, int opening, float beyond)
{
var a = Plan.AirwayOpenings[opening];
var lane = doll.BodyLane(a.Part);
var v = world.View;
var o = a.Offset;
var len = MathF.Sqrt(o.X * o.X + o.Y * o.Y + o.Z * o.Z);
var k = (len + beyond) / len;
return (v.PositionX[lane] + o.X * k, v.PositionY[lane] + o.Y * k, v.PositionZ[lane] + o.Z * k);
}
private static void Drop(Box3DSoaWorld world, (float X, float Y, float Z) at) =>
world.CreateParticles([new Box3DSoaParticleDesc(at, 1000f * DropVolume, R, FluidPhase)]);
private static (float[] Live, float[] Pooled) Read(Ragdoll doll)
{
var live = new float[Plan.AirwayOpenings.Count];
var pooled = new float[Plan.AirwayOpenings.Count];
doll.ReadAirway(live, pooled, new float[Plan.AirwayOpenings.Count], (0f, -1f, 0f));
return (live, pooled);
}
private static float[] DropOf(Ragdoll doll, (float X, float Y, float Z) down)
{
var drop = new float[Plan.AirwayOpenings.Count];
doll.ReadAirway(new float[drop.Length], new float[drop.Length], drop, down);
return drop;
}
[Fact]
public void A_drop_held_at_the_mouth_reads_at_the_mouth_only()
{
using var world = ParticleWorld(Ragdoll.Needs(Plan).Sensors);
var doll = Ragdoll.Build(world, Plan, (0f, 0f), firstStableId: 100);
Drop(world, Outside(world, doll, Mouth, 0.013f));
world.Step(Dt, 4);
var (live, pooled) = Read(doll);
Assert.Equal(DropVolume, live[Mouth], 9);
Assert.Equal(0f, live[Nose]);
Assert.Equal(0f, pooled[Mouth]);
Assert.Equal(0f, pooled[Nose]);
}
[Fact]
public void The_same_drop_at_the_nose_reads_at_the_nose_only_and_behind_the_head_reads_nothing()
{
using var world = ParticleWorld(Ragdoll.Needs(Plan).Sensors);
var doll = Ragdoll.Build(world, Plan, (0f, 0f), firstStableId: 100);
Drop(world, Outside(world, doll, Nose, 0.013f));
world.Step(Dt, 4);
var (live, pooled) = Read(doll);
Assert.Equal(DropVolume, live[Nose], 9);
Assert.Equal(0f, live[Mouth]);
Assert.Equal(0f, pooled[Nose] + pooled[Mouth]);
using var behindWorld = ParticleWorld(Ragdoll.Needs(Plan).Sensors);
var behind = Ragdoll.Build(behindWorld, Plan, (0f, 0f), firstStableId: 100);
var head = behind.BodyLane(Plan.PartIndex("Head"));
var h = behindWorld.View;
Drop(behindWorld, (h.PositionX[head], h.PositionY[head], h.PositionZ[head] - 0.16f)); // 5 cm behind the back of the head
behindWorld.Step(Dt, 4);
var (l2, p2) = Read(behind);
Assert.Equal(0f, l2[Mouth] + l2[Nose] + p2[Mouth] + p2[Nose]);
}
[Fact]
public void A_drop_settled_on_the_face_at_the_mouth_reads_pooled_at_the_mouth()
{
// Gravity pulls toward the face (-z), so the drop presses on the head; the whole body falls with it.
using var world = ParticleWorld(Ragdoll.Needs(Plan).Sensors, gravityZ: -1f);
var doll = Ragdoll.Build(world, Plan, (0f, 0f), firstStableId: 100);
var at = Outside(world, doll, Mouth, R);
world.CreateParticles([new Box3DSoaParticleDesc(at, 1000f * DropVolume, R, FluidPhase)]);
var head = doll.BodyLane(Plan.PartIndex("Head"));
var supported = false;
for (var i = 0; i < 60 && !supported; i++)
{
world.Step(Dt, 4);
supported = world.View.SupportBody[0] == head;
}
Assert.True(supported, "the drop never rested against the head");
world.Settle([new Box3DSoaParticleHandle(0, world.View.ParticleGeneration[0])]);
world.Step(Dt, 4);
var (live, pooled) = Read(doll);
Assert.Equal(DropVolume, pooled[Mouth], 9);
Assert.Equal(0f, live[Mouth]);
Assert.Equal(0f, pooled[Nose]);
}
[Fact]
public void A_world_with_no_particle_system_builds_the_humanoid_and_reads_zeros()
{
var (bodies, joints, sensors) = Ragdoll.Needs(Plan);
Assert.Equal(2, sensors);
using var world = new Box3DSoaWorld(bodies, jointCapacity: joints);
var doll = Ragdoll.Build(world, Plan, (0f, 0f), firstStableId: 100);
world.Step(Dt, 4);
var live = new[] { 7f, 7f };
var pooled = new[] { 7f, 7f };
var drop = new[] { 7f, 7f };
doll.ReadAirway(live, pooled, drop, (0f, 0f, 1f));
Assert.Equal(new[] { 0f, 0f }, live);
Assert.Equal(new[] { 0f, 0f }, pooled);
Assert.Equal(0.0716f, drop[Mouth], 0.002f);
Assert.Equal(0.0718f, drop[Nose], 0.002f);
}
/// <summary>The drop at the creation pose for each down, metres: Mouth, Nose.</summary>
[Theory]
[InlineData(0f, -1f, 0f, -0.0467f, -0.0951f)] // upright: the glottis is the deepest sump, both rims above it
[InlineData(0f, 0f, -1f, -0.0734f, -0.0872f)] // on his back: the oropharynx is the deepest, the lips above it
[InlineData(0f, 0f, 1f, 0.0716f, 0.0718f)] // face down
[InlineData(1f, 0f, 0f, 0.0250f, 0.0250f)] // on his side: the rim, the half-width, lies below the sumps on the midline
[InlineData(-1f, 0f, 0f, 0.0250f, 0.0250f)]
[InlineData(0f, 1f, 0f, 0.0433f, 0.0949f)] // inverted
public void Drop_at_the_creation_pose_follows_down(float x, float y, float z, float mouth, float nose)
{
// Each within 0.002 m. Kills: the offset ignored (nose and mouth swap), the rim ignored (the side poses read 0), the rim taken as a sphere (face down reads 0.094),
// the shallowest sump (upright reads +0.005), and a drop cosine restored (the side poses read 0).
using var world = ParticleWorld(Ragdoll.Needs(Plan).Sensors);
var doll = Ragdoll.Build(world, Plan, (0f, 0f), firstStableId: 100);
var drop = DropOf(doll, (x, y, z));
Assert.Equal(mouth, drop[Mouth], 0.002f);
Assert.Equal(nose, drop[Nose], 0.002f);
}
[Fact]
public void The_length_of_down_does_not_matter()
{
using var world = ParticleWorld(Ragdoll.Needs(Plan).Sensors);
var doll = Ragdoll.Build(world, Plan, (0f, 0f), firstStableId: 100);
var unit = DropOf(doll, (0f, -1f, 0f));
var weight = DropOf(doll, (0f, -9.81f, 0f));
var side = DropOf(doll, (1f, 0f, 0f));
var sideLong = DropOf(doll, (3f, 0f, 0f));
for (var k = 0; k < unit.Length; k++)
{
Assert.Equal(unit[k], weight[k], 1e-6f);
Assert.Equal(side[k], sideLong[k], 1e-6f);
}
}
/// <summary>The humanoid on a ground slab, limp, shoved by a seeded torque on pelvis and torso for six steps, then six seconds: the largest drop over its openings and the torso's face direction y.</summary>
private static (float Drop, float TorsoFaceY) Fall(ulong seed, Action<Ragdoll>? atRest = null)
{
var (bodies, joints, _) = Ragdoll.Needs(Plan);
using var world = new Box3DSoaWorld(capacity: bodies + 1, jointCapacity: joints);
world.AddStaticBox(1, (0f, -0.5f, 0f), (20f, 0.5f, 20f), friction: 0.8f);
var doll = Ragdoll.Build(world, Plan, (0f, 0f), firstStableId: 100);
var strength = new float[Plan.Joints.Count];
var target = new Quat[Plan.Joints.Count];
Array.Fill(target, Quat.Identity);
var v = world.View;
var rng = new SplitMix64(seed);
for (var s = 0; s < 120 * 6; s++)
{
if (s < 6)
{
foreach (var part in new[] { "Pelvis", "Torso" })
{
var i = doll.BodyLane(Plan.PartIndex(part));
v.TorqueX[i] = 200f * rng.NextSigned();
v.TorqueY[i] = 200f * rng.NextSigned();
v.TorqueZ[i] = 200f * rng.NextSigned();
}
}
doll.Drive(strength, target);
world.Step(Dt, 4);
}
var t = doll.BodyLane(Plan.PartIndex("Torso"));
new Quat(v.RotationX[t], v.RotationY[t], v.RotationZ[t], v.RotationW[t]).Rotate(0f, 0f, 1f, out _, out var faceY, out _);
atRest?.Invoke(doll);
var drop = DropOf(doll, (0f, -1f, 0f));
return (MathF.Max(drop[Mouth], drop[Nose]), faceY);
}
/// <summary>The humanoid welded to a stool (the SeatedOrientTests rig): held at the given strength for three seconds, or limp (strength 0) after a seeded torso shove for six: the largest drop over its openings.</summary>
private static float Seated(float strength, ulong seed)
{
var (bodies, joints, _) = Ragdoll.Needs(Plan);
using var world = new Box3DSoaWorld(capacity: bodies + 2, jointCapacity: joints + 1);
world.AddStaticBox(1, (0f, -0.5f, 0f), (20f, 0.5f, 20f), friction: 0.8f);
var stool = world.AddStaticBox(2, (0f, 1.11f, -0.115f), (0.05f, 0.05f, 0.025f), friction: 0.8f);
var doll = Ragdoll.Build(world, Plan, (0f, 0f), firstStableId: 100);
world.AddJoint(Box3DSoaJointKind.Weld, stool, doll.BodyLane(Plan.PartIndex("Pelvis")), (0f, 1.11f, -0.09f), (0f, 1f, 0f));
var held = new float[Plan.Joints.Count];
Array.Fill(held, strength);
var target = new Quat[Plan.Joints.Count];
Array.Fill(target, Quat.Identity);
var v = world.View;
var rng = new SplitMix64(seed);
var steps = 120 * (strength > 0f ? 3 : 6);
for (var s = 0; s < steps; s++)
{
if (strength == 0f && s < 6)
{
var i = doll.BodyLane(Plan.PartIndex("Torso"));
v.TorqueX[i] = 60f * rng.NextSigned();
v.TorqueY[i] = 60f * rng.NextSigned();
v.TorqueZ[i] = 60f * rng.NextSigned();
}
doll.Drive(held, target);
world.Step(Dt, 4);
}
var drop = DropOf(doll, (0f, -1f, 0f));
return MathF.Max(drop[Mouth], drop[Nose]);
}
[Fact]
public void Drop_follows_the_heads_rotation()
{
// One box head created turned 90 degrees about x (its +z face along -y), a sump at its centre: the opening's centre and normal come from the lane's rotation, not the plan's offsets.
// Down (0,-1,0): the mouth's centre lies 0.1025 m below the sump and its rim adds 0.0091 (0.0233 x the sine of the angle
// between down and its normal), the nose 0.1095 and 0.0023; unrotated the mouth would read 0.04 + 0.0233 less the sump. Down (0,0,1): the mouth's centre 0.04 above the sump and its rim 0.0233
// below it, -0.0167. Kills the rotation ignored (the part's identity pose).
var head = new PartDef("Head", Side.Center, PartShape.Box, (0.1f, 0.1f, 0.1f), (0f, 1f, 0f), Quat.FromAxisAngle(1f, 0f, 0f, MathF.PI / 2f), 1000f, 0.5f, 0f);
var turned = new BodyPlan([head], [], [], [.. Plan.AirwayOpenings.Select(o => o with { Part = 0 })], [new AirwaySumpDef("Sump", 0, (0f, 0f, 0f))]);
var (bodies, joints, _) = Ragdoll.Needs(turned);
using var world = new Box3DSoaWorld(bodies, gravityY: 0f, jointCapacity: joints);
var doll = Ragdoll.Build(world, turned, (0f, 0f), firstStableId: 100);
var drop = new float[2];
doll.ReadAirway(new float[2], new float[2], drop, (0f, -1f, 0f));
Assert.Equal(0.1116f, drop[Mouth], 0.002f);
Assert.Equal(0.1118f, drop[Nose], 0.002f);
doll.ReadAirway(new float[2], new float[2], drop, (0f, 0f, 1f));
Assert.Equal(-0.0167f, drop[Mouth], 0.002f);
}
/// <summary>Gravity toward the face (-z); one drop of each given radius rests against the head at each given opening and settles: the pooled patches at those openings.</summary>
private static (Box3DSoaWorld World, Ragdoll Doll) Pooled(params (int Opening, float Radius)[] drops)
{
var world = ParticleWorld(Ragdoll.Needs(Plan).Sensors, gravityZ: -1f, extra: true);
var doll = Ragdoll.Build(world, Plan, (0f, 0f), firstStableId: 100);
var head = doll.BodyLane(Plan.PartIndex("Head"));
var hv = world.View;
var anchor = world.AddStaticBox(2, (hv.PositionX[head], hv.PositionY[head], hv.PositionZ[head] - 0.3f), (0.05f, 0.05f, 0.05f), friction: 0.8f);
world.AddJoint(Box3DSoaJointKind.Weld, anchor, head, (hv.PositionX[head], hv.PositionY[head], hv.PositionZ[head] - 0.1f), (0f, 1f, 0f));
world.CreateParticles([.. drops.Select(d => new Box3DSoaParticleDesc(Outside(world, doll, d.Opening, d.Radius), 8000f * d.Radius * d.Radius * d.Radius, d.Radius, FluidPhase))]);
var settled = new bool[drops.Length];
for (var i = 0; i < 120 && settled.Contains(false); i++)
{
world.Step(Dt, 4);
for (var p = 0; p < drops.Length; p++)
{
if (settled[p] || world.View.SupportBody[p] != head) continue;
world.Settle([new Box3DSoaParticleHandle(p, world.View.ParticleGeneration[p])]);
settled[p] = true;
}
}
Assert.DoesNotContain(false, settled);
world.Step(Dt, 4);
return (world, doll);
}
[Fact]
public void A_take_removes_what_was_drawn_from_the_mouths_pool()
{
var (world, doll) = Pooled((Mouth, R));
using var _ = world;
var before = Read(doll).Pooled[Mouth];
Assert.Equal(DropVolume, before, 9);
var ask = (double)before / 4d;
var taken = doll.TakeDrawn(ask);
Assert.Equal(ask, taken, ask * 1e-6);
world.Step(Dt, 4);
Assert.Equal(before - taken, Read(doll).Pooled[Mouth], before * 1e-5);
}
[Fact]
public void The_take_splits_by_the_openings_readings()
{
var (world, doll) = Pooled((Mouth, 0.005f), (Nose, 0.0075f));
using var _ = world;
var (_, before) = Read(doll);
Assert.True(before[Mouth] > 0f && before[Nose] > 1.5f * before[Mouth], $"readings {before[Mouth]} {before[Nose]}");
var sum = (double)before[Mouth] + before[Nose];
var x = sum / 10d;
var taken = doll.TakeDrawn(x);
Assert.Equal(x, taken, x * 1e-5);
world.Step(Dt, 4);
var (_, after) = Read(doll);
Assert.Equal(x * before[Mouth] / sum, before[Mouth] - after[Mouth], x * 1e-3);
Assert.Equal(x * before[Nose] / sum, before[Nose] - after[Nose], x * 1e-3);
}
[Fact]
public void A_dry_airway_or_a_world_without_particles_takes_nothing()
{
using var world = ParticleWorld(Ragdoll.Needs(Plan).Sensors);
var doll = Ragdoll.Build(world, Plan, (0f, 0f), firstStableId: 100);
world.Step(Dt, 4);
var (live, pooled) = Read(doll);
Assert.Equal(0.0, doll.TakeDrawn(1e-6));
world.Step(Dt, 4);
var (live2, pooled2) = Read(doll);
Assert.Equal(live, live2);
Assert.Equal(pooled, pooled2);
var (bodies, joints, _) = Ragdoll.Needs(Plan);
using var bare = new Box3DSoaWorld(bodies, jointCapacity: joints);
var bareDoll = Ragdoll.Build(bare, Plan, (0f, 0f), firstStableId: 100);
Assert.Equal(0.0, bareDoll.TakeDrawn(1e-6));
Assert.Equal(0.0, doll.TakeDrawn(-1.0));
}
[Fact]
public void A_wet_airway_takes_nothing_for_an_ask_of_zero_below_zero_or_not_a_number()
{
var (world, doll) = Pooled((Mouth, R));
using var _ = world;
var before = Read(doll).Pooled[Mouth];
Assert.Equal(DropVolume, before, 9);
foreach (var ask in new[] { 0.0, -1e-6, -DropVolume, double.NaN, double.NegativeInfinity })
{
Assert.Equal(0.0, doll.TakeDrawn(ask));
world.Step(Dt, 4);
Assert.Equal(before, Read(doll).Pooled[Mouth]);
}
}
[Fact]
public void Liquid_leaves_by_the_lowest_opening()
{
using var world = ParticleWorld(Ragdoll.Needs(Plan).Sensors);
var doll = Ragdoll.Build(world, Plan, (0f, 0f), firstStableId: 100);
Assert.Equal(Mouth, doll.LowestOpening((0f, -1f, 0f)));
Assert.Equal(Mouth, doll.LowestOpening((0f, 0f, -1f)));
Assert.Equal(Nose, doll.LowestOpening((0f, 1f, 0f)));
// A head turned pi about x (a lone box with both openings and a sump at its centre) seen from above.
var head = new PartDef("Head", Side.Center, PartShape.Box, (0.1f, 0.1f, 0.1f), (0f, 1f, 0f), Quat.FromAxisAngle(1f, 0f, 0f, MathF.PI), 1000f, 0.5f, 0f);
var turned = new BodyPlan([head], [], [], [.. Plan.AirwayOpenings.Select(o => o with { Part = 0 })], [new AirwaySumpDef("Sump", 0, (0f, 0f, 0f))]);
var (bodies, joints, _) = Ragdoll.Needs(turned);
using var flipped = new Box3DSoaWorld(bodies, gravityY: 0f, jointCapacity: joints);
var flippedDoll = Ragdoll.Build(flipped, turned, (0f, 0f), firstStableId: 100);
Assert.Equal(Nose, flippedDoll.LowestOpening((0f, -1f, 0f)));
Assert.Equal(Mouth, flippedDoll.LowestOpening((0f, 1f, 0f)));
// Side-lying limp falls: the largest of DropOf, and not always the creation pose's opening.
var seen = new HashSet<int>();
foreach (var seed in new ulong[] { 6, 10, 11, 18, 39, 66, 92, 120, 133, 151, 171, 208 })
Fall(seed, d =>
{
var drop = DropOf(d, (0f, -1f, 0f));
var expect = drop[Nose] > drop[Mouth] ? Nose : Mouth;
Assert.Equal(expect, d.LowestOpening((0f, -1f, 0f)));
seen.Add(expect);
});
Assert.NotEmpty(seen);
}
[Fact]
public void Face_down_the_opening_is_the_larger_drop_at_first_and_then_held_through_the_pitch_sweep()
{
using var world = ParticleWorld(Ragdoll.Needs(Plan).Sensors);
var doll = Ragdoll.Build(world, Plan, (0f, 0f), firstStableId: 100);
var prone = DropOf(doll, (0f, 0f, 1f)); // the two rims are 0.2 mm apart (the nose's lower); a fresh ragdoll takes the larger
Assert.True(prone[Nose] > prone[Mouth] && prone[Nose] - prone[Mouth] < Ragdoll.LowestHysteresis, $"prone drops {prone[Mouth]} {prone[Nose]}");
Assert.Equal(Nose, doll.LowestOpening((0f, 0f, 1f)));
// down (0, sin t, cos t): pitch t from face down.
float Sweep(Ragdoll d, float from, float to, float step, int expectFirst)
{
Assert.Equal(expectFirst, d.LowestOpening((0f, MathF.Sin(from * MathF.PI / 180f), MathF.Cos(from * MathF.PI / 180f))));
for (var deg = from; deg * MathF.Sign(to - from) <= to * MathF.Sign(to - from); deg += step)
if (d.LowestOpening((0f, MathF.Sin(deg * MathF.PI / 180f), MathF.Cos(deg * MathF.PI / 180f))) != expectFirst) return deg;
return float.NaN;
}
using var upWorld = ParticleWorld(Ragdoll.Needs(Plan).Sensors);
using var downWorld = ParticleWorld(Ragdoll.Needs(Plan).Sensors);
var up = Ragdoll.Build(upWorld, Plan, (0f, 0f), firstStableId: 100);
var down = Ragdoll.Build(downWorld, Plan, (0f, 0f), firstStableId: 100);
// Pitching toward the nose, a ragdoll with no memory swaps Mouth for Nose at -5.8 degrees (Soul's sweep, 0.05 degree steps); with the margin it holds Mouth past face down (measured: to +10.4)
// and pitching back it holds Nose past face down (measured: to -26.3), and each still lands the change inside 40 degrees.
var flipUp = Sweep(up, -40f, 40f, 0.05f, Mouth);
var flipDown = Sweep(down, 40f, -40f, -0.05f, Nose);
// The hold is the margin itself (ruling deterministic-bound-margin, readings at 0.05 degree steps): margin 5 mm (shipped) holds Mouth to +10.40 and Nose to -26.35 degrees; 1 mm holds +5.95 and -21.90, 10 mm holds +15.99 and -31.95.
// Mouth bound (7.87, 12.9) = sqrt(10.40 x 5.95) and sqrt(10.40 x 15.99), separation 1.75 and 1.54; Nose bound (-29.0, -24.0) = sqrt(26.35 x 31.95) and sqrt(26.35 x 21.90), separation 1.21 and 1.20.
// Why the Nose separation is 1.20: the Nose reading is 20.8 degrees plus 1.11 per mm of margin, so no margin pair a 5 mm shipped value is held against separates it by more; the Mouth bound (1.75, 1.54) is the pin, and this one claims the same mutants
// (a margin of 2.5 mm or less, 8 mm or more; 3 to 7 mm pass both) on a second axis, 0.05 degree steps, identical on a MinGW and an MSVC native build.
Assert.True(flipUp > 7.87f && flipUp < 12.9f, $"held Mouth to {flipUp} degrees");
Assert.True(flipDown < -24.0f && flipDown > -29.0f, $"held Nose to {flipDown} degrees");
}
[Fact]
public void Two_openings_with_equal_drops_take_the_first()
{
var head = new PartDef("Head", Side.Center, PartShape.Box, (0.1f, 0.1f, 0.1f), (0f, 1f, 0f), Quat.Identity, 1000f, 0.5f, 0f);
var a = Plan.AirwayOpenings[0] with { Part = 0 };
var twin = a with { Label = "Twin" };
var plan = new BodyPlan([head], [], [], [a, twin], [new AirwaySumpDef("Sump", 0, (0f, 0f, 0f))]);
var (bodies, joints, _) = Ragdoll.Needs(plan);
using var world = new Box3DSoaWorld(bodies, gravityY: 0f, jointCapacity: joints);
var doll = Ragdoll.Build(world, plan, (0f, 0f), firstStableId: 100);
Assert.Equal(0, doll.LowestOpening((0f, -1f, 0f)));
Assert.Equal(0, doll.LowestOpening((0f, 1f, 0f)));
}
[Fact]
public void TakeDrawn_allocates_nothing()
{
var (world, doll) = Pooled((Mouth, 0.005f), (Nose, 0.005f));
using var _ = world;
doll.TakeDrawn(1e-12);
var before = GC.GetAllocatedBytesForCurrentThread();
for (var i = 0; i < 100; i++) doll.TakeDrawn(1e-12);
Assert.Equal(before, GC.GetAllocatedBytesForCurrentThread());
}
[Fact]
public void A_side_lying_limp_humanoid_drains()
{
// The twelve falls of the 240-seed sweep that end on the side (torso face y within 0.3 of level) each read a drop above the bound. Kills the opening's offset rotated about z only (least claimed, 0.00914) and the
// mutants further off (a lane read from the pelvis reads 0 on 5 of the 12: the pelvis stays upright).
foreach (var seed in new ulong[] { 6, 10, 11, 18, 39, 66, 92, 120, 133, 151, 171, 208 })
{
var (drop, faceY) = Fall(seed);
Assert.InRange(faceY, -0.3f, 0.3f);
Assert.True(drop > SideDropBound, $"seed {seed}: drop {drop} (face y {faceY})");
}
}
[Fact]
public void Upright_drains_nothing()
{
// The creation pose and the humanoid welded to a stool at full strength: both rims stay above the glottis (readings -0.047 and -0.046).
using var world = ParticleWorld(Ragdoll.Needs(Plan).Sensors);
var doll = Ragdoll.Build(world, Plan, (0f, 0f), firstStableId: 100);
var create = DropOf(doll, (0f, -1f, 0f));
var seated = Seated(1f, 1);
Assert.True(MathF.Max(create[Mouth], create[Nose]) < UprightBound, $"creation {create[Mouth]} {create[Nose]}");
Assert.True(seated < UprightBound, $"seated {seated}");
}
[Fact]
public void A_limp_seated_humanoid_whose_head_hangs_drains()
{
var draining = 0;
for (ulong seed = 1; seed <= 40; seed++)
{
if (Seated(0f, seed) > 0f) draining++;
}
Assert.True(draining >= SeatedDraining, $"{draining} of 40 drain");
}
[Fact]
public void A_particle_world_with_one_sensor_lane_refuses_the_humanoid_at_build()
{
using var world = ParticleWorld(sensors: 1);
Assert.ThrowsAny<Exception>(() => Ragdoll.Build(world, Plan, (0f, 0f), firstStableId: 100));
}
[Fact]
public void ReadAirway_allocates_nothing_and_refuses_spans_not_one_per_opening()
{
using var world = ParticleWorld(Ragdoll.Needs(Plan).Sensors);
var doll = Ragdoll.Build(world, Plan, (0f, 0f), firstStableId: 100);
world.Step(Dt, 4);
var live = new float[2];
var pooled = new float[2];
var drop = new float[2];
var down = (0f, -1f, 0f);
doll.ReadAirway(live, pooled, drop, down);
var before = GC.GetAllocatedBytesForCurrentThread();
for (var i = 0; i < 1000; i++) doll.ReadAirway(live, pooled, drop, down);
Assert.Equal(0L, GC.GetAllocatedBytesForCurrentThread() - before);
Assert.Throws<ArgumentException>(() => doll.ReadAirway(new float[1], pooled, drop, down));
Assert.Throws<ArgumentException>(() => doll.ReadAirway(live, new float[3], drop, down));
Assert.Throws<ArgumentException>(() => doll.ReadAirway(live, pooled, new float[1], down));
Assert.Throws<ArgumentException>(() => doll.ReadAirway(live, pooled, drop, (0f, 0f, 0f)));
}
}

View file

@ -0,0 +1,299 @@
using Lodur;
using Lodur.Body.Ymir;
using Ymir.Box3D;
namespace Lodur.Tests;
/// <summary>
/// The pain box on the real body: a ground, a static stool welded to the pelvis (the PD ragdoll cannot balance for
/// 15 s), the ragdoll, a stimulus box around the right hand's hold point, and an Actor at 1/120 s driving the
/// ragdoll through strengths and targets only. The game (this scenario) owns the world and steps it.
/// </summary>
internal sealed class ConnectedPainBox : IDisposable
{
public const double Dt = 1.0 / 120.0;
/// <summary>
/// The stimulus box's half extent, the smallest in 0.005 m steps that holds the shipped run's hand (seed 1) in the box from 2 s until the break. At e47e3d3 that was 0.125
/// (0.120 let the palm out 4 ticks early). With the gravity feedforward the will's failing sag, which the break no longer outruns, leaves the box earlier. Ticks out,
/// under the subtree-external gate (ruling gravity-support-subtree-external): 0.140 six, 0.145 three, 0.150 two, 0.155 none. At 63444f0 (the count gate) it was 0.145
/// (0.125 eighteen ticks out, 0.140 eight). Limit 0.160: past it the hold no longer holds by intent.
/// </summary>
public const float BoxHalf = 0.155f;
/// <summary>The hold point: where the hold pose is solved to put the strength-1 right palm (the shoulder-right and elbow-right angles below; settled seed 1, 3-4 s, no leak), no longer where the controller sags it to.</summary>
public static readonly (float X, float Y, float Z) Box = (-0.210f, 1.116f, 0.441f);
public readonly Box3DSoaWorld World;
public readonly BodyPlan Plan = BodyPlans.Humanoid();
public readonly Ragdoll Ragdoll;
public readonly Actor Actor;
public readonly BoxStimulus[] Sources = { new BoxStimulus(Box.X, Box.Y, Box.Z, BoxHalf, BoxHalf, BoxHalf) };
public readonly float[] X, Y, Z;
public readonly float[] Strength;
public readonly Quat[] Target;
private readonly int _handR;
private SplitMix64 _rng;
public ConnectedPainBox(ulong seed, HoldParameters? hold = null, DriveParameters? driveTunables = null)
{
var (bodies, joints, _) = Ragdoll.Needs(Plan);
X = new float[Plan.SensePoints.Count]; Y = new float[Plan.SensePoints.Count]; Z = new float[Plan.SensePoints.Count];
Strength = new float[Plan.Joints.Count];
Target = new Quat[Plan.Joints.Count];
_handR = Plan.SenseIndex("Hand", Side.Right);
World = new Box3DSoaWorld(capacity: bodies + 2, jointCapacity: joints + 1);
World.AddStaticBox(1, (0f, -0.5f, 0f), (20f, 0.5f, 20f), friction: 0.8f);
var stool = World.AddStaticBox(2, (0f, 1.11f, -0.115f), (0.05f, 0.05f, 0.025f), friction: 0.8f);
Ragdoll = Ragdoll.Build(World, Plan, (0f, 0f), firstStableId: 100);
World.AddJoint(Box3DSoaJointKind.Weld, stool, Ragdoll.BodyLane(Plan.PartIndex("Pelvis")), (0f, 1.11f, -0.09f), (0f, 1f, 0f));
var holdPose = new Quat[Plan.Joints.Count];
var withdrawPose = new Quat[Plan.Joints.Count];
Array.Fill(holdPose, Quat.Identity);
Array.Fill(withdrawPose, Quat.Identity);
// The hold pose is solved by intent: the shoulder and elbow angles that put the settled strength-1 palm on Box (grid then refine over both, seed 1, 3-4 s,
// box silent): -0.68 and -0.25, 0.15 cm off. At 63444f0 (the count gate) the fit was -0.70 and -0.36, 0.34 cm off; under the subtree-external gate that pose settles
// the palm 4.74 cm out, because the right thumb and fingers now load the arm (the grid at 0.04 gives -0.68, -0.24 at 0.19 cm, the refine at 0.01 -0.68, -0.25: the fit is a ridge).
// At e47e3d3 the same fit was -1.0 and -0.6, a pose that gravity sagged onto Box; with the feedforward the controller no longer sags, and -1.0, -0.6 would hold the palm well above it.
holdPose[Plan.JointIndex("Shoulder", Side.Right)] = Quat.FromAxisAngle(1f, 0f, 0f, -0.68f);
holdPose[Plan.JointIndex("Elbow", Side.Right)] = Quat.FromAxisAngle(0f, 0f, 1f, -0.25f);
withdrawPose[Plan.JointIndex("Shoulder", Side.Right)] = Quat.FromAxisAngle(1f, 0f, 0f, 0.3f);
withdrawPose[Plan.JointIndex("Elbow", Side.Right)] = Quat.FromAxisAngle(0f, 0f, 1f, -2.0f);
_rng = new SplitMix64(seed);
var gain = 1.0 + 0.2 * _rng.NextSigned();
var drain = 1.0 + 0.2 * _rng.NextSigned();
// The pain box as a Brain: hold against the reflex until the will breaks, then release into the withdraw pose.
var tunables = hold ?? new HoldParameters();
var brain = new Brain
{
Goals = new[]
{
new GoalSpec
{
Id = "objective", Priority = 0.0, Pull = 0.5,
Behaviour = new PoseBehaviour { Keys = new[] { holdPose }, FlinchPose = withdrawPose, Hold = tunables },
},
new GoalSpec
{
Id = "release", Priority = 1.0, Pull = 0.5, InvoluntarySeconds = double.PositiveInfinity,
When = new[] { new Condition(DriveQuantity.Breaks, ConditionOp.AtLeast, 1.0) },
Behaviour = new PoseBehaviour
{
Keys = new[] { withdrawPose }, FlinchPose = withdrawPose,
Hold = tunables with { FlinchGain = 0.0, StrainShake = 0.0 },
},
},
},
};
Actor = new Actor(Dt, Plan.SensePoints.Count, new NerveParameters { Gain = gain }, new WithdrawalParameters(),
(driveTunables ?? new DriveParameters()) with { DrainTrait = drain }, brain);
}
public Box3DSoaView View => World.View;
/// <summary>Right hand point now.</summary>
public (float X, float Y, float Z) Hand
{
get { Ragdoll.ReadSensePoints(X, Y, Z); return (X[_handR], Y[_handR], Z[_handR]); }
}
public bool HandInBox => Sources[0].Contains(Hand.X, Hand.Y, Hand.Z);
/// <summary>One tick: the game writes the box intensity, the body reports its regions, the Actor decides, the body is driven, the world steps.</summary>
public TickEvents Tick()
{
var tick = Actor.TickCount;
var ramp = Math.Min(1.0, tick * Dt / 2.0);
Sources[0].Intensity = Math.Max(0.0, 0.8 * ramp * (1.0 + 0.1 * _rng.NextSigned()));
Ragdoll.ReadSensePoints(X, Y, Z);
var events = Actor.Tick(X, Y, Z, Sources, Strength, Target);
Ragdoll.Drive(Strength, Target);
World.Step((float)Dt, 4);
return events;
}
public void Dispose() => World.Dispose();
}
public sealed class ConnectedPainBoxTests
{
private static float Dist((float X, float Y, float Z) a, (float X, float Y, float Z) b) =>
MathF.Sqrt((a.X - b.X) * (a.X - b.X) + (a.Y - b.Y) * (a.Y - b.Y) + (a.Z - b.Z) * (a.Z - b.Z));
[Fact]
public void ReadSensePoints_puts_the_hands_at_the_palms_at_the_creation_pose()
{
using var s = new RagdollScenario(seed: 1);
var x = new float[3]; var y = new float[3]; var z = new float[3];
s.Ragdoll.ReadSensePoints(x, y, z);
Assert.Equal(0.21f, x[s.Plan.SenseIndex("Hand", Side.Left)], 3);
Assert.Equal(-0.21f, x[s.Plan.SenseIndex("Hand", Side.Right)], 3);
Assert.Equal(0.93f, y[s.Plan.SenseIndex("Hand", Side.Right)], 3);
Assert.Equal(0f, z[s.Plan.SenseIndex("Hand", Side.Right)], 3);
Assert.Equal(0f, x[s.Plan.SenseIndex("Head")], 3); // the head body's centre, within a millimetre
Assert.Equal(1.74f, y[s.Plan.SenseIndex("Head")], 3);
Assert.Equal(0f, z[s.Plan.SenseIndex("Head")], 3);
Assert.Throws<ArgumentException>(() => s.Ragdoll.ReadSensePoints(new float[1], y, z));
}
[Fact]
public void ReadSensePoints_allocates_nothing()
{
using var s = new RagdollScenario(seed: 1);
var x = new float[3]; var y = new float[3]; var z = new float[3];
s.Ragdoll.ReadSensePoints(x, y, z);
var before = GC.GetAllocatedBytesForCurrentThread();
for (var i = 0; i < 1000; i++) s.Ragdoll.ReadSensePoints(x, y, z);
Assert.Equal(0L, GC.GetAllocatedBytesForCurrentThread() - before);
}
private sealed record Timeline(List<long> Flinches, long Broke, long Withdrew, List<(long Tick, (float X, float Y, float Z) Hand, bool InBox)> Hand, ulong Hash);
private static Timeline Run(ulong seed, HoldParameters? hold = null, double maxSeconds = 25.0, DriveParameters? drive = null)
{
using var s = new ConnectedPainBox(seed, hold, drive);
var t = new Timeline(new List<long>(), -1, -1, new List<(long, (float, float, float), bool)>(), 0);
long broke = -1, withdrew = -1;
var max = (long)(maxSeconds / ConnectedPainBox.Dt);
for (long i = 0; i < max && withdrew < 0; i++)
{
var e = s.Tick();
if ((e & TickEvents.Flinch) != 0) t.Flinches.Add(i);
if ((e & TickEvents.WillBroke) != 0) broke = i;
if ((e & TickEvents.GoalChanged) != 0) withdrew = i;
t.Hand.Add((i, s.Hand, s.HandInBox));
}
// Keep running a little so the broken will has time to pull the arm out.
for (var k = 0; k < 60; k++)
{
s.Tick();
t.Hand.Add((t.Hand.Count, s.Hand, s.HandInBox));
}
return t with { Broke = broke, Withdrew = withdrew, Hash = RagdollScenario.HashOf(s.World) };
}
private static readonly (float X, float Y, float Z) Centre = ConnectedPainBox.Box;
private const int Hz = 120;
[Fact]
public void The_reflex_leaks_through_real_muscle_strength_and_the_broken_will_pulls_the_arm_out()
{
var t = Run(seed: 1);
Assert.True(t.Broke > 0, "the will never broke");
Assert.True(t.Flinches.Count > 0);
// The hand stays in the box until the will breaks (from 2 s on: before that the arm is still swinging up into it).
for (var i = 2 * Hz; i < t.Broke; i++) Assert.True(t.Hand[i].InBox, $"hand left the box at tick {i}, will broke at {t.Broke}");
// A flinch moves it: within 200 ms of some Flinch the hand is over 2.3 cm from its hold point (the box centre).
var moved = t.Flinches.Any(f => t.Hand.Skip((int)f).Take(Hz / 5 + 1).Any(h => Dist(h.Hand, Centre) > 0.023f));
Assert.True(moved, "no flinch moved the hand over 2.3 cm from the hold point");
// The broken will pulls it out within 300 ms.
Assert.Contains(t.Hand.Skip((int)t.Broke).Take(Hz * 3 / 10 + 1), h => !h.InBox);
}
[Fact]
public void The_movement_is_the_leak_not_the_body_without_it_the_hand_holds_still_and_with_it_the_hand_is_pulled_away_by_the_last_flinch()
{
// Both runs hold at full strength until the will is nearly gone (a WillCurve this small weights by ~1): the will's own
// sag of the hold, which would move even a leak-free arm, is pinned in the next test, so this isolates the leak.
var flat = new DriveParameters { WillCurve = 0.001 };
var plain = Run(seed: 1, new HoldParameters { FlinchGain = 0.0, StrainShake = 0.0 }, maxSeconds: 16.0, flat);
var full = Run(seed: 1, drive: flat);
Assert.Equal(full.Flinches, plain.Flinches); // the nervous state does not depend on the arm while the hand is in the box
// No leak, no shake: after settling, the hand stays within 2.3 cm of the hold point until the will breaks.
for (var i = 3 * Hz; i < plain.Broke; i++) Assert.True(Dist(plain.Hand[i].Hand, Centre) <= 0.023f, $"drift {Dist(plain.Hand[i].Hand, Centre)} at tick {i}");
// With the leak, at the last flinch the hand is over 2.3 cm from where the leak-free arm is at the same tick.
var last = (int)full.Flinches[^1];
Assert.True(Dist(full.Hand[last].Hand, plain.Hand[last].Hand) > 0.023f);
}
[Fact]
public void A_failing_will_sags_the_hold_even_with_no_leak_and_no_shake_while_a_strong_will_holds_still()
{
var plain = Run(seed: 1, new HoldParameters { FlinchGain = 0.0, StrainShake = 0.0 }, maxSeconds: 16.0);
// Early, resolve is high and the weight near 1: the hand stays within 2.3 cm of the hold point (seed 1 measured 0.1-1.7 cm over 3-6 s with the gravity feedforward; 0.2-2.0 cm to 8 s at e47e3d3).
for (var i = 3 * Hz; i < 6 * Hz; i++) Assert.True(Dist(plain.Hand[i].Hand, Centre) <= 0.023f, $"drift {Dist(plain.Hand[i].Hand, Centre)} at tick {i}");
// Late, the will is nearly gone: the voluntary hold has gone slack and the arm sags well out of the box before the break (measured 0.199 m at 14.3 s with the gravity feedforward, the will's weakness the only sag left; 0.155 m at e47e3d3).
Assert.True(Dist(plain.Hand[(int)plain.Broke - 60].Hand, Centre) > 0.1f);
}
[Fact]
public void The_hold_pose_puts_the_settled_palm_on_the_box_centre_at_full_strength()
{
// The pose is solved for this (0.15 cm at the fit): with a flat will and no leak the palm's mean from 3 to 4 s is within 0.5 cm of the hold point (0.15 cm measured; 0.24 at 63444f0).
var t = Run(seed: 1, new HoldParameters { FlinchGain = 0.0, StrainShake = 0.0 }, maxSeconds: 5.0, new DriveParameters { WillCurve = 0.001 });
var settled = t.Hand.Skip(3 * Hz).Take(Hz).ToList();
var mean = (X: settled.Average(h => h.Hand.X), Y: settled.Average(h => h.Hand.Y), Z: settled.Average(h => h.Hand.Z));
Assert.True(Dist(mean, Centre) <= 0.005f, $"settled palm {Dist(mean, Centre) * 100f:F2} cm from the hold point");
}
private const float ShakeLine = 0.0202f;
private static float VerticalPeakToPeak(Timeline t, int fromSecond)
{
var seg = t.Hand.Skip(fromSecond * Hz).Take(Hz).Select(h => h.Hand.Y).ToList();
return seg.Max() - seg.Min();
}
[Fact]
public void Strain_shows_as_a_visible_shake_of_the_hand_which_the_shipped_amplitude_makes_and_zero_does_not()
{
// Seconds 8 to 13 of seed 1: strain is about 3, the will has not broken (it breaks at 14.75 s). Measured at the
// palm with the shipped StrainShake 0.08 / ShakeHz 3.5: 2.68-4.84 cm peak to peak in hand height per second; at 0, 0.15-1.52 cm (3.3-4.6 and 0.2-1.4 cm at 63444f0; 3.2-5.5 and 0.6-1.2 cm at e47e3d3).
// The floor and the still cap are one line, ShakeLine, the geometric midpoint (deterministic-bound-margin) of the shipped least (2.68) and the zero-shake worst (1.52): 2.02 cm, separation 1.76.
// (The shake was 0.03 on the forearm-tip hand, 3.9-4.7 cm there; the hands' mass damps the arm and the default rose to keep the rule.)
var shaking = Run(seed: 1, new HoldParameters(), maxSeconds: 16.0);
var still = Run(seed: 1, new HoldParameters { StrainShake = 0.0 }, maxSeconds: 16.0);
for (var s = 8; s <= 13; s++)
{
Assert.True(VerticalPeakToPeak(shaking, s) > ShakeLine, $"shipped shake only {VerticalPeakToPeak(shaking, s)} m peak to peak in second {s}");
Assert.True(VerticalPeakToPeak(shaking, s) < 0.07f, $"shipped shake is {VerticalPeakToPeak(shaking, s)} m peak to peak in second {s}, more than a strain tremor");
Assert.True(VerticalPeakToPeak(still, s) < ShakeLine, $"no shake still moved {VerticalPeakToPeak(still, s)} m in second {s}");
}
}
[Fact]
public void The_same_seed_twice_gives_the_same_events_and_the_same_world_state_hash()
{
var a = Run(seed: 1);
var b = Run(seed: 1);
Assert.Equal(a.Flinches, b.Flinches);
Assert.Equal(a.Broke, b.Broke);
Assert.Equal(a.Withdrew, b.Withdrew);
Assert.Equal(a.Hash, b.Hash);
Assert.NotEqual(a.Hash, Run(seed: 2).Hash);
}
private static ulong HandTrackHash(Timeline t)
{
var h = 14695981039346656037ul;
foreach (var (tick, hand, inBox) in t.Hand)
{
foreach (var f in new[] { hand.X, hand.Y, hand.Z })
{
h ^= (uint)BitConverter.SingleToInt32Bits(f);
h *= 1099511628211ul;
}
h ^= inBox ? 1ul : 0ul;
h *= 1099511628211ul;
}
return h;
}
[Fact]
public void Seed_1_to_16_seconds_replays_the_world_the_break_and_the_deliberate_switch_recorded_at_the_will_mix()
{
// Recorded with the subtree-external gravity support (ruling gravity-support-subtree-external) and the hold re-solved under it (pose -0.68, -0.25, box half 0.155).
// The line before was recorded at 63444f0, the count gate (pose -0.70, -0.36, box half 0.145): broke=1773 withdrew=1785 flinches=16 hand=6db1f8d175e3e635 world=348765d9a09a27cf.
// The line before that was recorded at e47e3d3, the ragdoll hands (palm region, hand-mass damping, StrainShake 0.08, box half 0.125, pose -1.0, -0.6):
// broke=1772 withdrew=1784 flinches=16 hand=17416bc7c2d12853 world=9f710f8186aff900. The break moved one tick each time, the flinch count never; the hand and the world moved
// because the muscles carry the arm's weight, and again because the thumb and fingers resting on each other now load the arm.
var t = Run(seed: 1, maxSeconds: 16.0);
Assert.Equal("broke=1774 withdrew=1786 flinches=16 hand=27e153fde720075e world=8998d8f0fca463ec",
$"broke={t.Broke} withdrew={t.Withdrew} flinches={t.Flinches.Count} hand={HandTrackHash(t):x16} world={t.Hash:x16}");
}
}

View file

@ -0,0 +1,305 @@
using Lodur;
using Lodur.Body.Ymir;
using Ymir.Box3D;
namespace Lodur.Tests;
public sealed class HandTests
{
private static int[] HandBodies(RagdollScenario s) =>
new[] { "Palm", "Thumb", "Fingers" }.SelectMany(l => new[] { s.Plan.PartIndex(l, Side.Left), s.Plan.PartIndex(l, Side.Right) }).ToArray();
/// <summary>FNV-1a 64 over the creation lanes of the 13 base bodies (world lanes 1..13) and the 12 base joints.</summary>
private static ulong BaseCreationHash(Box3DSoaWorld world)
{
var v = world.View;
var h = 14695981039346656037ul;
void U(ulong x) { for (var k = 0; k < 8; k++) { h ^= (byte)(x >> (8 * k)); h *= 1099511628211ul; } }
void F(float f) => U((uint)BitConverter.SingleToInt32Bits(f));
for (var i = 1; i <= 13; i++)
{
U(v.StableId[i]); U(v.Kind[i]); U((ulong)v.Parent[i]); U((ulong)v.Limb[i]);
F(v.Size0[i]); F(v.Size1[i]); F(v.Size2[i]);
F(v.PositionX[i]); F(v.PositionY[i]); F(v.PositionZ[i]);
F(v.RotationX[i]); F(v.RotationY[i]); F(v.RotationZ[i]); F(v.RotationW[i]);
}
for (var j = 0; j < 12; j++)
{
U(v.JointKind[j]); U((ulong)v.JointBodyA[j]); U((ulong)v.JointBodyB[j]);
F(v.JointFrameX[j]); F(v.JointFrameY[j]); F(v.JointFrameZ[j]); F(v.JointFrameW[j]);
F(v.JointOriginX[j]); F(v.JointOriginY[j]); F(v.JointOriginZ[j]);
}
return h;
}
/// <summary>
/// Re-recorded at the BodyPlan cut: the Limb lane now carries plan part ordinals (it carried the old Limb enum values, which differ
/// from LowerArmL on). With the Limb term left out the function gives 0x65216f91ffc63d24 on both Lodur d7a626b and this cut.
/// </summary>
private const ulong BaseHash = 0xbbcc7aff6c088398ul;
[Fact]
public void Hands_are_appended_after_the_base_bodies_and_joints_and_leave_them_as_they_were()
{
using var s = new RagdollScenario(seed: 1);
var v = s.World.View;
var r = s.Ragdoll;
Assert.Equal(1 + 19, v.Count);
Assert.Equal(18, v.JointCount);
Assert.Equal(BaseHash, BaseCreationHash(s.World));
Assert.Equal(new ulong[] { 113, 114, 115, 116, 117, 118 }, Enumerable.Range(14, 6).Select(i => v.StableId[i]).ToArray());
Assert.All(HandBodies(s), l => Assert.InRange(r.BodyLane(l), 14, 19));
foreach (var m in new[] { "Wrist", "Thumb", "Fingers" }.SelectMany(l => new[] { s.Plan.JointIndex(l, Side.Left), s.Plan.JointIndex(l, Side.Right) })) Assert.InRange(r.JointLane(m), 12, 17);
foreach (var side in new[] { Side.Left, Side.Right })
{
var palm = r.BodyLane(s.Plan.PartIndex("Palm", side));
var thumb = r.BodyLane(s.Plan.PartIndex("Thumb", side));
var fingers = r.BodyLane(s.Plan.PartIndex("Fingers", side));
Assert.Equal(r.BodyLane(s.Plan.PartIndex("LowerArm", side)), v.Parent[palm]);
Assert.Equal(palm, v.Parent[thumb]);
Assert.Equal(palm, v.Parent[fingers]);
Assert.Equal(((uint)Box3DSoaKind.Box, (uint)Box3DSoaKind.Capsule, (uint)Box3DSoaKind.Box), (v.Kind[palm], v.Kind[thumb], v.Kind[fingers]));
Assert.Equal((0.014f, 0.045f, 0.040f), (v.Size0[palm], v.Size1[palm], v.Size2[palm]));
Assert.Equal((0.011f, 0.03f), (v.Size0[thumb], v.Size1[thumb]));
Assert.Equal((0.011f, 0.0425f, 0.038f), (v.Size0[fingers], v.Size1[fingers], v.Size2[fingers]));
Assert.Equal((r.BodyLane(s.Plan.PartIndex("LowerArm", side)), palm), (v.JointBodyA[r.JointLane(s.Plan.JointIndex("Wrist", side))], v.JointBodyB[r.JointLane(s.Plan.JointIndex("Wrist", side))]));
Assert.Equal((palm, thumb), (v.JointBodyA[r.JointLane(s.Plan.JointIndex("Thumb", side))], v.JointBodyB[r.JointLane(s.Plan.JointIndex("Thumb", side))]));
Assert.Equal((palm, fingers), (v.JointBodyA[r.JointLane(s.Plan.JointIndex("Fingers", side))], v.JointBodyB[r.JointLane(s.Plan.JointIndex("Fingers", side))]));
}
}
[Fact]
public void The_hand_region_is_the_palm_body_wherever_the_palm_goes()
{
using var s = new RagdollScenario(seed: 2);
Array.Clear(s.Strength);
s.Run(1.0f); // falling: the palms are nowhere near the creation pose
var x = new float[3]; var y = new float[3]; var z = new float[3];
s.Ragdoll.ReadSensePoints(x, y, z);
var v = s.World.View;
foreach (var (region, limb) in new[] { (s.Plan.SenseIndex("Hand", Side.Left), s.Plan.PartIndex("Palm", Side.Left)), (s.Plan.SenseIndex("Hand", Side.Right), s.Plan.PartIndex("Palm", Side.Right)) })
{
var i = s.Ragdoll.BodyLane(limb);
Assert.Equal((v.PositionX[i], v.PositionY[i], v.PositionZ[i]), (x[region], y[region], z[region]));
}
}
/// <summary>Runs <paramref name="runSeconds"/>, then one more second step by step; the fastest the limbs turn and move in that second.</summary>
private static (float Angular, float Linear) LastSecond(RagdollScenario s, float runSeconds, IEnumerable<int> limbs)
{
s.Run(runSeconds);
float ang = 0f, lin = 0f;
var watched = limbs.ToArray();
for (var step = 0; step < 120; step++)
{
s.Run(RagdollScenario.Dt);
foreach (var l in watched)
{
var sp = s.Speeds(l);
ang = MathF.Max(ang, sp.Angular);
lin = MathF.Max(lin, sp.Linear);
}
}
return (ang, lin);
}
[Theory]
[InlineData(1ul)]
[InlineData(2ul)]
[InlineData(3ul)]
public void Hands_rest_standing_palm_thumb_and_fingers_alike(ulong seed)
{
using var s = new RagdollScenario(seed);
var (ang, _) = LastSecond(s, 5f, HandBodies(s));
Assert.True(ang < 0.05f, $"seed {seed}: a hand body (thumbs included: a free thumb twist spins) still turns at {ang} rad/s in the last second of 6");
}
[Fact]
public void Limp_hands_settle_instead_of_ringing()
{
for (ulong seed = 1; seed <= 20; seed++)
{
using var s = new RagdollScenario(seed);
Array.Clear(s.Strength);
var (ang, lin) = LastSecond(s, 7f, HandBodies(s));
Assert.True(ang < 1f && lin < 0.1f, $"seed {seed}: a limp hand still moves at {lin} m/s, {ang} rad/s in the last second of 8");
}
}
/// <summary>Distance between the two bodies' copies of a joint's anchor, each carried by its own body from creation.</summary>
private sealed class JointSeparation
{
private readonly (int A, int B, (float X, float Y, float Z) LocalA, (float X, float Y, float Z) LocalB)[] _joints;
public JointSeparation(Box3DSoaWorld world, IEnumerable<int> jointLanes)
{
var v = world.View;
_joints = jointLanes.Select(j =>
{
int a = v.JointBodyA[j], b = v.JointBodyB[j];
return (a, b, Local(v, a, v.JointOriginX[j], v.JointOriginY[j], v.JointOriginZ[j]), Local(v, b, v.JointOriginX[j], v.JointOriginY[j], v.JointOriginZ[j]));
}).ToArray();
}
private static (float, float, float) Local(Box3DSoaView v, int i, float x, float y, float z)
{
new Quat(v.RotationX[i], v.RotationY[i], v.RotationZ[i], v.RotationW[i]).Conjugate()
.Rotate(x - v.PositionX[i], y - v.PositionY[i], z - v.PositionZ[i], out var lx, out var ly, out var lz);
return (lx, ly, lz);
}
private static (float X, float Y, float Z) World(Box3DSoaView v, int i, (float X, float Y, float Z) p)
{
new Quat(v.RotationX[i], v.RotationY[i], v.RotationZ[i], v.RotationW[i]).Rotate(p.X, p.Y, p.Z, out var x, out var y, out var z);
return (x + v.PositionX[i], y + v.PositionY[i], z + v.PositionZ[i]);
}
/// <summary>The worst separation among the joints from index <paramref name="firstHand"/> on, and among those before it.</summary>
public (float AtOrAfter, float Before) MaxBy(Box3DSoaView v, int firstHand)
{
float after = 0f, before = 0f;
for (var k = 0; k < _joints.Length; k++)
{
var (a, b, la, lb) = _joints[k];
var p = World(v, a, la); var q = World(v, b, lb);
var d = MathF.Sqrt((p.X - q.X) * (p.X - q.X) + (p.Y - q.Y) * (p.Y - q.Y) + (p.Z - q.Z) * (p.Z - q.Z));
if (k >= firstHand) after = MathF.Max(after, d); else before = MathF.Max(before, d);
}
return (after, before);
}
}
/// <summary>
/// The slam flail's worst joint-anchor separations over seeds 1..20 and strike/wind-up half-periods of 15, 30 and 60 ticks,
/// 6 s each: [0] the hand joints (wrist, thumb, fingers), [1] the body joints. Runs are independent worlds, taken in parallel.
/// </summary>
private static (float Hand, float Body) FlailWorst(out int runs)
{
var cases = new List<(ulong Seed, int Half)>();
foreach (var half in new[] { 15, 30, 60 }) for (ulong seed = 1; seed <= 20; seed++) cases.Add((seed, half));
runs = cases.Count;
var results = new (float Hand, float Body)[cases.Count];
Parallel.For(0, cases.Count, k =>
{
var (seed, half) = cases[k];
using var s = new RagdollScenario(seed);
var all = Enumerable.Range(0, s.Plan.Joints.Count).ToArray();
var sep = new JointSeparation(s.World, all.Select(m => s.Ragdoll.JointLane(m)));
float hand = 0f, body = 0f;
for (var i = 0; i < 6 * 120; i++)
{
var strike = (i / half) % 2 == 0;
foreach (var (sh, el) in new[] { (s.Plan.JointIndex("Shoulder", Side.Left), s.Plan.JointIndex("Elbow", Side.Left)), (s.Plan.JointIndex("Shoulder", Side.Right), s.Plan.JointIndex("Elbow", Side.Right)) })
{
s.Target[sh] = Quat.FromAxisAngle(1f, 0f, 0f, strike ? -1.5f : -0.5f);
s.Target[el] = Quat.FromAxisAngle(0f, 0f, 1f, strike ? 0f : -2.2f);
}
s.Target[s.Plan.JointIndex("Fingers", Side.Left)] = s.Target[s.Plan.JointIndex("Fingers", Side.Right)] = Quat.FromAxisAngle(0f, 0f, 1f, strike ? -1.5f : 0f);
s.Target[s.Plan.JointIndex("Wrist", Side.Left)] = s.Target[s.Plan.JointIndex("Wrist", Side.Right)] = Quat.FromAxisAngle(1f, 0f, 0f, strike ? 0.8f : -0.8f);
s.Run(RagdollScenario.Dt);
var v = s.World.View;
for (var b = 0; b < v.Count; b++)
{
Assert.True(float.IsFinite(v.PositionX[b] + v.PositionY[b] + v.PositionZ[b] + v.RotationW[b] + v.VelocityX[b] + v.AngularVelocityX[b]), $"seed {seed} half {half}: body {b} is finite at step {i}");
}
var (h, bo) = sep.MaxBy(v, s.Plan.JointIndex("Wrist", Side.Left));
hand = MathF.Max(hand, h);
body = MathF.Max(body, bo);
}
results[k] = (hand, body);
});
return (results.Max(r => r.Hand), results.Max(r => r.Body));
}
[Fact]
public void Joints_hold_together_under_a_slam_flail_across_seeds_and_cadences_within_their_measured_bars()
{
// The bars are MEASURED, not targets (ruling flail-bar-honest-multiseed). Over these 60 runs the worst hand joint stretched
// 57.4 mm (thumb) and the worst body joint 37.4 mm (elbow); the bars sit just above, so a worse hand or body fails.
// A soft joint stretches by the slam's acceleration over its stiffness, whatever the gains; the real tightening is
// follow-up ymir-joint-softness-and-filter (joint softness and collision filtering in Ymir's SoA world).
var (hand, body) = FlailWorst(out _);
Assert.True(hand <= 0.060f, $"a hand joint came apart by {hand * 1000f} mm (bar 60)");
Assert.True(body <= 0.045f, $"a body joint came apart by {body * 1000f} mm (bar 45)");
}
/// <summary>Swing of a joint's rotation off its axis, radians (the twist about the joint z removed).</summary>
private static float Swing(RagdollScenario s, int m)
{
var v = s.World.View;
var j = s.Ragdoll.JointLane(m);
var along = MathF.Sqrt(v.JointRotationW[j] * v.JointRotationW[j] + v.JointRotationZ[j] * v.JointRotationZ[j]);
return 2f * MathF.Acos(MathF.Min(1f, along));
}
/// <summary>How far the fingers are curled from straight (palm-frame), radians; curl is positive for both hands.</summary>
private static float Curl(RagdollScenario s, Side side)
{
var v = s.World.View;
var palm = s.Ragdoll.BodyLane(s.Plan.PartIndex("Palm", side));
var fingers = s.Ragdoll.BodyLane(s.Plan.PartIndex("Fingers", side));
var relative = new Quat(v.RotationX[palm], v.RotationY[palm], v.RotationZ[palm], v.RotationW[palm]).Conjugate()
* new Quat(v.RotationX[fingers], v.RotationY[fingers], v.RotationZ[fingers], v.RotationW[fingers]);
var sx = side == Side.Left ? 1f : -1f;
var angleAboutZ = 2f * MathF.Atan2(relative.Z, relative.W);
return -sx * angleAboutZ;
}
[Theory]
[InlineData(Side.Left)]
[InlineData(Side.Right)]
public void The_fingers_rest_relaxed_at_creation_and_stay_there_while_nothing_grips(Side side)
{
using var s = new RagdollScenario(seed: 1);
Assert.Equal(0.35f, Curl(s, side), 0.01f); // ruling hand-rest-curl-relaxed
s.Run(3f);
Assert.Equal(0.35f, Curl(s, side), 0.05f);
}
[Theory]
[InlineData(Side.Left)]
[InlineData(Side.Right)]
public void The_knuckle_curls_to_1_6_rad_from_straight_and_extends_0_35_rad_past_it_and_no_further(Side side)
{
float Reach(float target)
{
using var s = new RagdollScenario(seed: 1);
s.Target[s.Plan.JointIndex("Fingers", side)] = Quat.FromAxisAngle(0f, 0f, 1f, target);
s.Run(2f);
return Curl(s, side);
}
Assert.InRange(Reach(-3f), 1.5f, 1.72f); // the limit is 1.6 from straight (a soft stop gives a little), whatever the creation curl
Assert.InRange(Reach(3f), -0.45f, -0.30f); // 0.35 past straight, a soft stop gives a little
}
/// <summary>
/// How far past its cone a hand joint may swing, at the geometric midpoint (deterministic-bound-margin) of the shipped worst and the least claimed mutant:
/// 0.0684 rad (wrist, both sides, four directions; 0.0528 thumb) against 0.0970 (the wrist cone 0.03 rad wider than its plan; 0.0874 at 0.02, 0.1065 at 0.04, the cone limit off
/// 1.47), separation 1.42, margin 1.19 each side. The gravity feedforward lets the muscle press its full torque on Box3D's soft limit, which gives 0.0684 where the controller at
/// e47e3d3 sagged off it (0.0587; 0.0621 under the count gate at 63444f0, whose bound was 0.194 against the cone-less mutant 0.6048: three times looser than the old 0.06, a limit
/// 0.1 rad wider would have passed). Claiming a limit 1.7 degrees wide keeps the bound under 0.082 rad.
/// </summary>
private const float ConeOvershoot = 0.0815f;
[Theory]
[InlineData("Wrist", Side.Left, 1.0f)]
[InlineData("Wrist", Side.Right, 1.0f)]
[InlineData("Thumb", Side.Left, 0.7f)]
[InlineData("Thumb", Side.Right, 0.7f)]
public void A_hand_joint_swings_to_its_cone_and_no_further_whichever_way_it_is_told(string label, Side side, float cone)
{
var reached = 0f;
foreach (var (ax, ay) in new[] { (1f, 0f), (-1f, 0f), (0f, 1f), (0f, -1f) })
{
using var s = new RagdollScenario(seed: 1);
var joint = s.Plan.JointIndex(label, side);
s.Target[joint] = Quat.FromAxisAngle(ax, ay, 0f, 2.5f);
s.Run(2f);
var swing = Swing(s, joint);
Assert.True(swing < cone + ConeOvershoot, $"{label} {side} swung {swing} past its cone {cone} toward ({ax}, {ay})");
reached = MathF.Max(reached, swing);
}
Assert.True(reached > cone - 0.15f, $"{label} {side} only swung {reached} of its cone {cone} in any direction");
}
}

View file

@ -0,0 +1,159 @@
using Lodur;
using Lodur.Body.Ymir;
using Xunit.Abstractions;
using Ymir.Box3D;
namespace Lodur.Tests;
/// <summary>The IK solve against the physical ragdoll: Ymir's joint frame is the one Ik.JointFrame mirrors, and a solved arm lands the wrist.</summary>
public sealed class IkReachTests
{
private const float Dt = 1f / 120f;
private const float Seconds = 4f;
private static readonly BodyPlan Plan = BodyPlans.Humanoid();
// Shoulder plus these offsets (body fact 9).
private static readonly (float X, float Y, float Z)[] Targets = { (0f, -0.25f, 0.35f), (-0.15f, -0.3f, 0.25f), (0f, 0.05f, 0.45f) };
private readonly ITestOutputHelper _out;
public IkReachTests(ITestOutputHelper output) => _out = output;
/// <summary>
/// Wrist error bound at the geometric midpoint (deterministic-bound-margin) of the shipped worst, 2.98 cm over the three free-floating targets
/// (probe 3.0, 2.3, 1.0 cm), and the least claimed mutant, 4.78 cm (the parent rotation conjugate dropped in the creation-frame transform): margin 1.27 each side.
/// Also killed: swing order flipped, 5.29 cm (5.22 before the arm held its swivel across ticks); the joint frame applied the wrong way round,
/// 5.58 cm. A flipped elbow flex reads 33 cm.
/// Twist is not this metric's mutant (the arm tracks twist weakly); the Core twist test claims it.
/// </summary>
private const float FreeBound = 0.0377f;
/// <summary>Runs the right arm toward shoulder + offset for four seconds and returns the wrist error, the final state hash and the torso drift.</summary>
private static (float Error, ulong Hash) Reach((float X, float Y, float Z) offset, float gravity, bool weldPelvis, float strengthValue = 1f)
{
var (bodies, joints, _) = Ragdoll.Needs(Plan);
using var world = new Box3DSoaWorld(capacity: bodies + (weldPelvis ? 1 : 0), gravityY: gravity, jointCapacity: joints + (weldPelvis ? 1 : 0));
var ragdoll = Ragdoll.Build(world, Plan, (0f, 0f), firstStableId: 100);
if (weldPelvis)
{
var stool = world.AddStaticBox(2, (0f, 1.11f, -0.115f), (0.05f, 0.05f, 0.025f), friction: 0.8f);
world.AddJoint(Box3DSoaJointKind.Weld, stool, ragdoll.BodyLane(Plan.PartIndex("Pelvis")), (0f, 1.11f, -0.09f), (0f, 1f, 0f));
}
var arm = ArmChain.Of(Plan, Side.Right, Dt);
var strength = new float[Plan.Joints.Count];
var target = new Quat[Plan.Joints.Count];
Array.Fill(strength, strengthValue);
Array.Fill(target, Quat.Identity);
var goal = (X: arm.ShoulderAnchor.X + offset.X, Y: arm.ShoulderAnchor.Y + offset.Y, Z: arm.ShoulderAnchor.Z + offset.Z);
var torso = ragdoll.BodyLane(arm.ParentPart);
var v = world.View;
for (var i = 0; i < (int)MathF.Round(Seconds / Dt); i++)
{
var rotation = new Quat(v.RotationX[torso], v.RotationY[torso], v.RotationZ[torso], v.RotationW[torso]);
arm.Solve(rotation, v.PositionX[torso], v.PositionY[torso], v.PositionZ[torso], goal.X, goal.Y, goal.Z, out target[arm.ShoulderJoint], out target[arm.ElbowJoint]);
ragdoll.Drive(strength, target);
world.Step(Dt, 4);
}
// The wrist anchor: the forearm body's position plus its rotation applied to the anchor's creation-pose offset.
var wristJoint = Plan.Joints[Plan.JointIndex("Wrist", Side.Right)];
var fore = ragdoll.BodyLane(wristJoint.Parent);
var centre = Plan.Parts[wristJoint.Parent].Position;
new Quat(v.RotationX[fore], v.RotationY[fore], v.RotationZ[fore], v.RotationW[fore])
.Rotate(wristJoint.Anchor.X - centre.X, wristJoint.Anchor.Y - centre.Y, wristJoint.Anchor.Z - centre.Z, out var ox, out var oy, out var oz);
var dx = v.PositionX[fore] + ox - goal.X;
var dy = v.PositionY[fore] + oy - goal.Y;
var dz = v.PositionZ[fore] + oz - goal.Z;
return (MathF.Sqrt(dx * dx + dy * dy + dz * dz), RagdollScenario.HashOf(world));
}
[Fact]
public void Core_joint_frames_match_Ymir()
{
var (bodies, joints, _) = Ragdoll.Needs(Plan);
using var world = new Box3DSoaWorld(capacity: bodies, jointCapacity: joints);
var ragdoll = Ragdoll.Build(world, Plan, (0f, 0f), firstStableId: 100);
var v = world.View;
Assert.Equal(18, Plan.Joints.Count);
for (var j = 0; j < Plan.Joints.Count; j++)
{
var lane = ragdoll.JointLane(j);
var ymir = new Quat(v.JointFrameX[lane], v.JointFrameY[lane], v.JointFrameZ[lane], v.JointFrameW[lane]);
var core = Ik.JointFrame(Plan.Joints[j]);
var dot = MathF.Abs(core.X * ymir.X + core.Y * ymir.Y + core.Z * ymir.Z + core.W * ymir.W);
Assert.True(dot > 1f - 1e-5f, $"joint {Plan.Joints[j].Label} {Plan.Joints[j].Side}: Core frame {core} against Ymir {ymir}");
}
}
[Fact]
public void Zero_gravity_reach_lands_the_wrist()
{
// State hashes recorded at origin/main e47e3d3, before the gravity feedforward: in zero gravity Drive writes the PD torque only, so they never move.
var recorded = new ulong[] { 2780975657960733482ul, 1878696821643337211ul, 486659158273771449ul };
var worst = 0f;
for (var k = 0; k < Targets.Length; k++)
{
var offset = Targets[k];
var (error, hash) = Reach(offset, gravity: 0f, weldPelvis: false);
_out.WriteLine($"zero gravity, offset {offset}: wrist error {error * 100f:F2} cm, hash {hash}");
Assert.Equal(recorded[k], hash);
worst = MathF.Max(worst, error);
Assert.True(error < FreeBound, $"wrist error {error * 100f:F2} cm at {offset} exceeds {FreeBound * 100f:F1} cm");
}
_out.WriteLine($"shipped worst {worst * 100f:F2} cm, bound {FreeBound * 100f:F1} cm");
}
/// <summary>
/// Gravity reach bound at the geometric midpoint (deterministic-bound-margin) of the shipped worst, 0.77 cm over the three targets with the pelvis welded (0.77, 0.16, 0.72),
/// and the least claimed mutant, 3.97 cm (the count gate, any touch carries the body's weight at no joint: 3.01, 3.16, 3.97): 1.75 cm, margin 2.27 each side, separation 5.2.
/// Also killed: a deposit at the touched body instead of the common ancestor, 5.84 cm; the feedforward off, 24.01 cm (13.69, 10.16, 24.01). Not claimed here: no gate at all reads
/// 0.89 cm and a touch outside the ragdoll ignored 0.77 cm, 1.16 and 1.00 times the shipped worst; the hand-rest tests in HandTests kill both. The controller no longer sags: zero
/// gravity reads 0.89 cm. Only a touch outside a joint's subtree supports it (ruling gravity-support-subtree-external), so the right hand's thumb on its fingers no longer lifts the arm's load.
/// At 63444f0 this bound was 9.76 cm, pinned to the count gate's own self-contact cost.
/// </summary>
private const float GravityBound = 0.0175f;
[Fact]
public void Gravity_reach_lands_the_wrist_at_full_strength()
{
var worst = 0f;
foreach (var offset in Targets)
{
var (error, _) = Reach(offset, gravity: -10f, weldPelvis: true);
_out.WriteLine($"gravity on, pelvis welded, offset {offset}: wrist error {error * 100f:F2} cm");
worst = MathF.Max(worst, error);
Assert.True(error < GravityBound, $"wrist error {error * 100f:F2} cm at {offset} exceeds {GravityBound * 100f:F2} cm");
}
_out.WriteLine($"shipped worst {worst * 100f:F2} cm, bound {GravityBound * 100f:F2} cm");
}
/// <summary>
/// The least a half-strength arm sags at any target, at the geometric midpoint of the shipped least (13.85 cm; 19.00, 13.85, 22.79) and the least claimed mutant (0.88 cm:
/// the feedforward without its strength factor, which holds the weight up at half strength; 0.88, 0.89, 12.78): 3.49 cm, margin 3.97 each side. A weak will sags (strength 0.5 is
/// weakness, not the controller), and the feedforward off reads 22.45, 17.18, 38.77 there. At 63444f0 the bound was 4.43 cm (shipped least 13.38, mutant 1.47).
/// </summary>
private const float WeakSag = 0.0349f;
[Fact]
public void A_half_strength_arm_still_sags_under_gravity_at_every_target()
{
foreach (var offset in Targets)
{
var (error, _) = Reach(offset, gravity: -10f, weldPelvis: true, strengthValue: 0.5f);
_out.WriteLine($"gravity on, pelvis welded, half strength, offset {offset}: wrist error {error * 100f:F2} cm");
Assert.True(error > WeakSag, $"half strength landed within {error * 100f:F2} cm at {offset}, under {WeakSag * 100f:F2} cm: weakness did not sag");
}
}
[Fact]
public void Reach_is_deterministic()
{
var a = Reach(Targets[0], gravity: 0f, weldPelvis: false);
var b = Reach(Targets[0], gravity: 0f, weldPelvis: false);
Assert.Equal(a.Hash, b.Hash);
Assert.Equal(a.Error, b.Error);
}
}

View file

@ -0,0 +1,24 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<IsPackable>false</IsPackable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.14.1" />
<PackageReference Include="xunit" Version="2.9.3" />
<PackageReference Include="xunit.runner.visualstudio" Version="3.1.4" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\src\Lodur.Core\Lodur.Core.csproj" />
<ProjectReference Include="..\..\src\Lodur.Body.Ymir\Lodur.Body.Ymir.csproj" />
</ItemGroup>
<ItemGroup>
<Using Include="Xunit" />
</ItemGroup>
</Project>

View file

@ -0,0 +1,105 @@
using Lodur;
namespace Lodur.Tests;
public sealed class PdMuscleTests
{
private static (float X, float Y, float Z) Torque(Quat rotation, (float X, float Y, float Z) w, Quat target, float kp, float kd, float strength, float? twistKp = null, float? twistKd = null)
{
PdMuscle.Torque(rotation, w.X, w.Y, w.Z, target, new MuscleGains(kp, kd, twistKp ?? kp, twistKd ?? kd), strength, out var x, out var y, out var z);
return (x, y, z);
}
[Fact]
public void At_the_target_and_at_rest_there_is_no_torque()
{
var q = Quat.FromAxisAngle(0f, 1f, 0f, 0.7f);
var t = Torque(q, (0f, 0f, 0f), q, 100f, 10f, 1f);
Assert.Equal((0f, 0f, 0f), (MathF.Abs(t.X) < 1e-4f ? 0f : t.X, MathF.Abs(t.Y) < 1e-4f ? 0f : t.Y, MathF.Abs(t.Z) < 1e-4f ? 0f : t.Z));
}
[Fact]
public void Torque_turns_the_child_toward_the_target_in_proportion_to_the_error()
{
var near = Torque(Quat.Identity, default, Quat.FromAxisAngle(0f, 0f, 1f, 0.1f), 100f, 0f, 1f);
var far = Torque(Quat.Identity, default, Quat.FromAxisAngle(0f, 0f, 1f, 0.2f), 100f, 0f, 1f);
Assert.Equal(10f, near.Z, 1e-2f); // kp * angle about +z
Assert.Equal(20f, far.Z, 1e-2f);
Assert.Equal(0f, near.X, 1e-4f);
Assert.Equal(0f, near.Y, 1e-4f);
var back = Torque(Quat.FromAxisAngle(0f, 0f, 1f, 0.3f), default, Quat.Identity, 100f, 0f, 1f);
Assert.Equal(-30f, back.Z, 1e-2f); // the error is a rotation, so it flips sign with direction
}
[Fact]
public void Damping_opposes_the_relative_angular_velocity()
{
var t = Torque(Quat.Identity, (1f, -2f, 3f), Quat.Identity, 100f, 5f, 1f);
Assert.Equal((-5f, 10f, -15f), (t.X, t.Y, t.Z));
}
[Fact]
public void Strength_scales_the_whole_law_and_zero_is_limp()
{
var target = Quat.FromAxisAngle(1f, 0f, 0f, 0.4f);
var full = Torque(Quat.Identity, (0.5f, 0f, 0f), target, 100f, 10f, 1f);
var half = Torque(Quat.Identity, (0.5f, 0f, 0f), target, 100f, 10f, 0.5f);
Assert.Equal(full.X * 0.5f, half.X, 1e-4f);
var limp = Torque(Quat.Identity, (0.5f, 0f, 0f), target, 100f, 10f, 0f);
Assert.Equal((0f, 0f, 0f), limp);
Assert.Equal((0f, 0f, 0f), Torque(Quat.Identity, (0.5f, 0f, 0f), target, 100f, 10f, -1f));
}
[Fact]
public void Passive_damping_survives_limp_and_stiffness_does_not()
{
var target = Quat.FromAxisAngle(1f, 0f, 0f, 0.4f);
var w = (1f, -2f, 3f);
PdMuscle.Torque(Quat.Identity, w.Item1, w.Item2, w.Item3, target, new MuscleGains(100f, 5f, 100f, 2f, passive: 1f), 0f, out var x, out var y, out var z);
Assert.Equal((-5f, 10f, -6f), (x, y, z)); // exactly -kd * omega per axis, nothing toward the target
PdMuscle.Torque(Quat.Identity, w.Item1, w.Item2, w.Item3, target, new MuscleGains(100f, 5f, 100f, 2f, passive: 0f), 0f, out x, out y, out z);
Assert.Equal((0f, 0f, 0f), (x, y, z));
// A half passive floor under a quarter strength damps at the floor, stiffens at the strength.
PdMuscle.Torque(Quat.Identity, w.Item1, 0f, 0f, target, new MuscleGains(100f, 5f, 100f, 2f, passive: 0.5f), 0.25f, out x, out y, out z);
var stiffOnly = Torque(Quat.Identity, default, target, 100f, 5f, 0.25f).X;
Assert.Equal(stiffOnly - 0.5f * 5f * 1f, x, 1e-3f);
// Above the floor strength rules: the whole law, as without Passive.
PdMuscle.Torque(Quat.Identity, w.Item1, w.Item2, w.Item3, target, new MuscleGains(100f, 5f, 100f, 2f, passive: 0.5f), 1f, out x, out y, out z);
var plain = Torque(Quat.Identity, w, target, 100f, 5f, 1f, twistKp: 100f, twistKd: 2f);
Assert.Equal((plain.X, plain.Y, plain.Z), (x, y, z));
}
[Fact]
public void The_error_takes_the_shorter_way_round_even_when_the_quaternions_are_opposite_signs()
{
// 350 degrees about z is 10 degrees the other way.
var rotation = Quat.FromAxisAngle(0f, 0f, 1f, 350f * MathF.PI / 180f);
var t = Torque(rotation, default, Quat.Identity, 100f, 0f, 1f);
Assert.Equal(100f * 10f * MathF.PI / 180f, t.Z, 1e-2f);
// The same rotation written with every sign flipped gives the same torque.
var flipped = new Quat(-rotation.X, -rotation.Y, -rotation.Z, -rotation.W);
var t2 = Torque(flipped, default, Quat.Identity, 100f, 0f, 1f);
Assert.Equal(t.Z, t2.Z, 1e-3f);
}
[Fact]
public void Twist_gains_act_on_z_only_and_swing_gains_on_x_and_y()
{
var w = (1f, 1f, 1f);
var t = Torque(Quat.Identity, w, Quat.Identity, 100f, 10f, 1f, twistKp: 100f, twistKd: 1f);
Assert.Equal((-10f, -10f, -1f), (t.X, t.Y, t.Z));
var e = Torque(Quat.Identity, default, Quat.FromAxisAngle(1f, 0f, 0f, 0.1f), 100f, 0f, 1f, twistKp: 5f, twistKd: 0f);
Assert.Equal(10f, e.X, 1e-2f);
var z = Torque(Quat.Identity, default, Quat.FromAxisAngle(0f, 0f, 1f, 0.1f), 100f, 0f, 1f, twistKp: 5f, twistKd: 0f);
Assert.Equal(0.5f, z.Z, 1e-3f);
}
[Fact]
public void Quaternion_rotate_matches_the_axis_angle()
{
Quat.FromAxisAngle(0f, 0f, 1f, MathF.PI / 2).Rotate(1f, 0f, 0f, out var x, out var y, out var z);
Assert.Equal(0f, x, 1e-5f);
Assert.Equal(1f, y, 1e-5f);
Assert.Equal(0f, z, 1e-5f);
}
}

View file

@ -0,0 +1,121 @@
using Lodur;
using Lodur.Body.Ymir;
using Ymir.Box3D;
namespace Lodur.Tests;
/// <summary>The builder assumes no species: a six-part quadruped builds and steps beside the humanoid in one caller world.</summary>
public sealed class QuadrupedPlanTests
{
private static BodyPlan Quadruped()
{
PartDef Part(string label, Side side, PartShape shape, (float, float, float) size, (float, float, float) at) =>
new(label, side, shape, size, at, Quat.Identity, 1000f, 0.8f, 0f);
JointDef Joint(string label, Side side, JointKind kind, int parent, int child, (float, float, float) at, (float, float, float) axis, float lower, float upper, float cone) =>
new(label, side, kind, parent, child, at, axis, lower, upper, cone, new MuscleGains(10f, 1f, 5f, 0.5f));
var parts = new[]
{
Part("Trunk", Side.Center, PartShape.Box, (0.4f, 0.15f, 0.12f), (0f, 0.6f, 0f)),
Part("Head", Side.Center, PartShape.Sphere, (0.12f, 0f, 0f), (0.55f, 0.8f, 0f)),
Part("Foreleg", Side.Left, PartShape.Capsule, (0.04f, 0.2f, 0f), (0.3f, 0.25f, 0.1f)),
Part("Foreleg", Side.Right, PartShape.Capsule, (0.04f, 0.2f, 0f), (0.3f, 0.25f, -0.1f)),
Part("Hindleg", Side.Left, PartShape.Capsule, (0.04f, 0.2f, 0f), (-0.3f, 0.25f, 0.1f)),
Part("Hindleg", Side.Right, PartShape.Capsule, (0.04f, 0.2f, 0f), (-0.3f, 0.25f, -0.1f)),
};
var joints = new[]
{
Joint("Neck", Side.Center, JointKind.Spherical, 0, 1, (0.45f, 0.7f, 0f), (0f, 1f, 0f), -0.5f, 0.5f, 0.5f),
Joint("Shoulder", Side.Left, JointKind.Revolute, 0, 2, (0.3f, 0.5f, 0.1f), (0f, 0f, 1f), -1f, 1f, 0f),
Joint("Shoulder", Side.Right, JointKind.Revolute, 0, 3, (0.3f, 0.5f, -0.1f), (0f, 0f, 1f), -1f, 1f, 0f),
Joint("Hip", Side.Left, JointKind.Revolute, 0, 4, (-0.3f, 0.5f, 0.1f), (0f, 0f, 1f), -1f, 1f, 0f),
Joint("Hip", Side.Right, JointKind.Revolute, 0, 5, (-0.3f, 0.5f, -0.1f), (0f, 0f, 1f), -1f, 1f, 0f),
};
return new BodyPlan(parts, joints, new[] { new SensePointDef("Muzzle", Side.Center, 1, (0.12f, 0f, 0f)) });
}
[Fact]
public void A_quadruped_builds_after_the_humanoid_in_one_world_in_its_own_plan_order_and_steps_finite()
{
var humanoidPlan = BodyPlans.Humanoid();
var quadPlan = Quadruped();
var (hb, hj, hs) = Ragdoll.Needs(humanoidPlan);
var (qb, qj, qs) = Ragdoll.Needs(quadPlan);
Assert.Equal((6, 5, 0), (qb, qj, qs));
Assert.Equal(2, hs);
using var world = new Box3DSoaWorld(capacity: hb + qb + 1, jointCapacity: hj + qj);
world.AddStaticBox(1, (0f, -0.5f, 0f), (20f, 0.5f, 20f), friction: 0.8f);
var human = Ragdoll.Build(world, humanoidPlan, (0f, 0f), firstStableId: 100);
var quad = Ragdoll.Build(world, quadPlan, (2f, 0f), firstStableId: 200);
var v = world.View;
Assert.Equal(1 + hb + qb, v.Count);
Assert.Equal(hj + qj, v.JointCount);
for (var i = 0; i < qb; i++)
{
var lane = quad.BodyLane(i);
Assert.Equal(1 + hb + i, lane); // contiguous, right after the humanoid
Assert.Equal(200ul + (ulong)i, v.StableId[lane]); // stable id = first + plan ordinal
Assert.Equal(i, v.Limb[lane]); // limb lane = plan ordinal
Assert.Equal(quadPlan.ParentOf(i) < 0 ? -1 : quad.BodyLane(quadPlan.ParentOf(i)), v.Parent[lane]);
}
for (var j = 0; j < qj; j++)
{
var lane = quad.JointLane(j);
Assert.Equal(hj + j, lane);
Assert.Equal((quad.BodyLane(quadPlan.Joints[j].Parent), quad.BodyLane(quadPlan.Joints[j].Child)), (v.JointBodyA[lane], v.JointBodyB[lane]));
}
Assert.Equal((uint)Box3DSoaKind.Box, v.Kind[quad.BodyLane(quadPlan.PartIndex("Trunk"))]);
Assert.Equal((uint)Box3DSoaKind.Sphere, v.Kind[quad.BodyLane(quadPlan.PartIndex("Head"))]);
Assert.Equal((uint)Box3DSoaKind.Capsule, v.Kind[quad.BodyLane(quadPlan.PartIndex("Hindleg", Side.Right))]);
Assert.Equal(2.3f, v.PositionX[quad.BodyLane(quadPlan.PartIndex("Foreleg", Side.Left))], 4); // origin x 2 + plan x 0.3
var humanStrength = new float[humanoidPlan.Joints.Count]; var humanTarget = new Quat[humanoidPlan.Joints.Count];
var quadStrength = new float[qj]; var quadTarget = new Quat[qj];
Array.Fill(humanTarget, Quat.Identity); Array.Fill(quadTarget, Quat.Identity);
for (var tick = 0; tick < 60; tick++)
{
human.Drive(humanStrength, humanTarget);
quad.Drive(quadStrength, quadTarget);
world.Step(1f / 120f, 4);
}
for (var i = 0; i < v.Count; i++)
{
Assert.True(float.IsFinite(v.PositionX[i] + v.PositionY[i] + v.PositionZ[i] + v.RotationW[i]), $"body {i} finite");
}
var x = new float[1]; var y = new float[1]; var z = new float[1];
quad.ReadSensePoints(x, y, z);
var head = quad.BodyLane(quadPlan.PartIndex("Head"));
Assert.True(MathF.Abs(x[0] - v.PositionX[head]) < 0.2f); // the muzzle sits within its offset of the head
Assert.Throws<ArgumentException>(() => quad.ReadSensePoints(new float[3], new float[3], new float[3]));
Assert.Throws<ArgumentException>(() => quad.Drive(new float[3], quadTarget));
}
private const float SenseTolerance = 3.5e-4f; // geometric mean of the shipped worst (one float ulp at 3, 2.4e-7) and the weakest mutant (0.5)
[Fact]
public void A_sense_point_reads_its_parts_position_plus_the_parts_rotation_applied_to_its_offset()
{
// Root turned 90 degrees about z: the offset (0.5, 0.2, 0.1) lands at (-0.2, 0.5, 0.1) from the part, not at (0.5, 0.2, 0.1) and not at 0.
var turned = Quat.FromAxisAngle(0f, 0f, 1f, MathF.PI / 2f);
var parts = new[]
{
new PartDef("Root", Side.Center, PartShape.Box, (0.2f, 0.1f, 0.1f), (0f, 1f, 0f), turned, 1000f, 0.8f, 0f),
new PartDef("Tip", Side.Center, PartShape.Sphere, (0.05f, 0f, 0f), (0f, 1.5f, 0f), Quat.Identity, 1000f, 0.8f, 0f),
};
var joints = new[] { new JointDef("J", Side.Center, JointKind.Spherical, 0, 1, (0f, 1.2f, 0f), (0f, 1f, 0f), -1f, 1f, 0.5f, new MuscleGains(1f, 1f, 1f, 1f)) };
var plan = new BodyPlan(parts, joints, new[] { new SensePointDef("Probe", Side.Center, 0, (0.5f, 0.2f, 0.1f)) });
var (bodies, jointCount, _) = Ragdoll.Needs(plan);
using var world = new Box3DSoaWorld(capacity: bodies, jointCapacity: jointCount);
var ragdoll = Ragdoll.Build(world, plan, (3f, 0f), firstStableId: 1);
var x = new float[1]; var y = new float[1]; var z = new float[1];
ragdoll.ReadSensePoints(x, y, z);
var error = MathF.Max(MathF.Abs(x[0] - 2.8f), MathF.Max(MathF.Abs(y[0] - 1.5f), MathF.Abs(z[0] - 0.1f)));
Assert.True(error < SenseTolerance, $"sense point ({x[0]}, {y[0]}, {z[0]}) is {error} from (2.8, 1.5, 0.1)");
}
}

View file

@ -0,0 +1,124 @@
using Lodur;
using Lodur.Body.Ymir;
using Ymir.Box3D;
namespace Lodur.Tests;
/// <summary>One ragdoll on a ground slab, stepped at 120 Hz, with caller-owned strength and target arrays.</summary>
internal sealed class RagdollScenario : IDisposable
{
public const float Dt = 1f / 120f;
public readonly Box3DSoaWorld World;
public readonly BodyPlan Plan = BodyPlans.Humanoid();
public readonly Ragdoll Ragdoll;
public readonly float[] Strength;
public readonly Quat[] Target;
private int _steps;
public RagdollScenario(ulong seed, float gravityY = -10f)
{
var (bodies, joints, _) = Ragdoll.Needs(Plan);
Strength = new float[Plan.Joints.Count];
Target = new Quat[Plan.Joints.Count];
World = new Box3DSoaWorld(capacity: bodies + 1, gravityY: gravityY, jointCapacity: joints);
World.AddStaticBox(1, (0f, -0.5f, 0f), (20f, 0.5f, 20f), friction: 0.8f);
Ragdoll = Ragdoll.Build(World, Plan, (0f, 0f), firstStableId: 100);
Array.Fill(Target, Quat.Identity);
Array.Fill(Strength, 1f);
Shove(seed);
}
/// <summary>The seed's only effect: one step of random torque on pelvis and torso, up to 30 N m per axis.</summary>
private void Shove(ulong seed)
{
var rng = new SplitMix64(seed);
var v = World.View;
foreach (var limb in new[] { Plan.PartIndex("Pelvis"), Plan.PartIndex("Torso") })
{
var i = Ragdoll.BodyLane(limb);
v.TorqueX[i] = 30f * rng.NextSigned();
v.TorqueY[i] = 30f * rng.NextSigned();
v.TorqueZ[i] = 30f * rng.NextSigned();
}
}
public void Run(float seconds)
{
var n = (int)MathF.Round(seconds / Dt);
for (var i = 0; i < n; i++)
{
Ragdoll.Drive(Strength, Target);
World.Step(Dt, 4);
_steps++;
}
}
public float HeadHeight => World.View.PositionY[Ragdoll.BodyLane(Plan.PartIndex("Head"))];
public float PelvisHeight => World.View.PositionY[Ragdoll.BodyLane(Plan.PartIndex("Pelvis"))];
/// <summary>Linear and angular speed of one limb's body.</summary>
public (float Linear, float Angular) Speeds(int part)
{
var v = World.View;
var i = Ragdoll.BodyLane(part);
return (MathF.Sqrt(v.VelocityX[i] * v.VelocityX[i] + v.VelocityY[i] * v.VelocityY[i] + v.VelocityZ[i] * v.VelocityZ[i]),
MathF.Sqrt(v.AngularVelocityX[i] * v.AngularVelocityX[i] + v.AngularVelocityY[i] * v.AngularVelocityY[i] + v.AngularVelocityZ[i] * v.AngularVelocityZ[i]));
}
/// <summary>The fastest linear and angular speed of any ragdoll body.</summary>
public (float Linear, float Angular) MaxSpeeds()
{
var v = World.View;
float lin = 0f, ang = 0f;
for (var i = 1; i < v.Count; i++)
{
lin = MathF.Max(lin, MathF.Sqrt(v.VelocityX[i] * v.VelocityX[i] + v.VelocityY[i] * v.VelocityY[i] + v.VelocityZ[i] * v.VelocityZ[i]));
ang = MathF.Max(ang, MathF.Sqrt(v.AngularVelocityX[i] * v.AngularVelocityX[i] + v.AngularVelocityY[i] * v.AngularVelocityY[i] + v.AngularVelocityZ[i] * v.AngularVelocityZ[i]));
}
return (lin, ang);
}
/// <summary>FNV-1a 64 over every body and joint state lane of this scenario's world.</summary>
public ulong StateHash() => HashOf(World);
/// <summary>FNV-1a 64 over every body and joint state lane of any world.</summary>
public static ulong HashOf(Box3DSoaWorld world)
{
var v = world.View;
var h = 14695981039346656037ul;
void Bytes(ReadOnlySpan<byte> b)
{
foreach (var x in b) { h ^= x; h *= 1099511628211ul; }
}
void F(ReadOnlySpan<float> lane) => Bytes(System.Runtime.InteropServices.MemoryMarshal.AsBytes(lane));
Bytes(System.Runtime.InteropServices.MemoryMarshal.AsBytes(BitConverter.GetBytes(world.StepCount).AsSpan()));
F(v.PositionX); F(v.PositionY); F(v.PositionZ);
F(v.RotationX); F(v.RotationY); F(v.RotationZ); F(v.RotationW);
F(v.VelocityX); F(v.VelocityY); F(v.VelocityZ);
F(v.AngularVelocityX); F(v.AngularVelocityY); F(v.AngularVelocityZ);
F(v.JointAngle);
F(v.JointRotationX); F(v.JointRotationY); F(v.JointRotationZ); F(v.JointRotationW);
F(v.JointAngularVelocityX); F(v.JointAngularVelocityY); F(v.JointAngularVelocityZ);
return h;
}
public void Dispose() => World.Dispose();
}
/// <summary>SplitMix64: a seedable generator whose sequence is the same on every platform.</summary>
internal struct SplitMix64
{
private ulong _s;
public SplitMix64(ulong seed) => _s = seed;
public ulong Next()
{
var z = _s += 0x9E3779B97F4A7C15ul;
z = (z ^ (z >> 30)) * 0xBF58476D1CE4E5B9ul;
z = (z ^ (z >> 27)) * 0x94D049BB133111EBul;
return z ^ (z >> 31);
}
/// <summary>Uniform in [-1, 1).</summary>
public float NextSigned() => (Next() >> 40) / (float)(1 << 23) - 1f;
}

View file

@ -0,0 +1,280 @@
using Lodur;
using Lodur.Body.Ymir;
using Ymir.Box3D;
namespace Lodur.Tests;
public sealed class RagdollTests
{
private const float StandingHead = 1.74f;
[Theory]
[InlineData(1ul)]
[InlineData(2ul)]
[InlineData(3ul)]
public void A_ragdoll_with_full_strength_stands_through_a_shove(ulong seed)
{
using var s = new RagdollScenario(seed);
s.Run(1.5f);
Assert.InRange(s.HeadHeight, StandingHead - 0.1f, StandingHead + 0.05f);
Assert.True(s.PelvisHeight > 1.05f);
var (linear, angular) = s.MaxSpeeds();
Assert.True(linear < 0.6f && angular < 1.0f, $"settled upright: {linear} m/s, {angular} rad/s");
}
/// <summary>The trunk is at rest; extremities may still rock a little (a head resting on an arm chatters at a few rad/s for seconds).</summary>
private static void AssertResting(RagdollScenario s, string label)
{
foreach (var (limb, name) in new[] { (s.Plan.PartIndex("Pelvis"), "Pelvis"), (s.Plan.PartIndex("Torso"), "Torso") })
{
var (linear, angular) = s.Speeds(limb);
Assert.True(linear < 0.05f && angular < 0.2f, $"{label}: {name} at {linear} m/s, {angular} rad/s");
}
var (maxLinear, maxAngular) = s.MaxSpeeds();
Assert.True(maxLinear < 0.6f && maxAngular < 6f, $"{label}: an extremity still moves at {maxLinear} m/s, {maxAngular} rad/s");
Assert.True(s.HeadHeight < 0.4f && s.PelvisHeight < 0.3f, $"{label}: lying down");
var v = s.World.View;
for (var i = 1; i < v.Count; i++)
{
Assert.True(v.PositionY[i] > 0f && float.IsFinite(v.PositionY[i]), $"{label}: body {i} above the ground");
}
}
[Theory]
[InlineData(1ul)]
[InlineData(2ul)]
[InlineData(3ul)]
public void Without_strength_the_same_ragdoll_falls_and_comes_to_rest(ulong seed)
{
using var s = new RagdollScenario(seed);
Array.Clear(s.Strength);
s.Run(1.0f);
Assert.True(s.HeadHeight < 0.6f, $"limp joints cannot hold it up: head at {s.HeadHeight}");
s.Run(5.0f);
AssertResting(s, $"seed {seed}");
}
[Fact]
public void Stand_then_go_limp_falls_from_height_and_rests()
{
using var s = new RagdollScenario(seed: 7);
s.Run(1.5f);
Assert.True(s.HeadHeight > 1.6f);
Array.Clear(s.Strength); // will gives out: the caller's array is the only thing that changed
s.Run(1.0f);
Assert.True(s.HeadHeight < 1.0f, $"falling after strength drops: head at {s.HeadHeight}");
s.Run(5.0f);
AssertResting(s, "after standing");
}
[Fact]
public void Strength_is_per_muscle_zeroing_one_knee_changes_that_knee_and_not_the_other_arrays_entries()
{
static (float Left, float Right) Knees(float leftStrength)
{
using var s = new RagdollScenario(seed: 1);
// Both knees are told to flex 0.5 rad about their hinge (the joint frame's z axis).
s.Target[s.Plan.JointIndex("Knee", Side.Left)] = Quat.FromAxisAngle(0f, 0f, 1f, 0.5f);
s.Target[s.Plan.JointIndex("Knee", Side.Right)] = Quat.FromAxisAngle(0f, 0f, 1f, 0.5f);
s.Strength[s.Plan.JointIndex("Knee", Side.Left)] = leftStrength; // a caller-owned element, written in place
s.Run(0.5f);
var v = s.World.View;
return (v.JointAngle[s.Ragdoll.JointLane(s.Plan.JointIndex("Knee", Side.Left))], v.JointAngle[s.Ragdoll.JointLane(s.Plan.JointIndex("Knee", Side.Right))]);
}
var (strongL, strongR) = Knees(1f);
var (limpL, limpR) = Knees(0f);
Assert.InRange(strongL, 0.35f, 1.2f); // both follow the target, plus the sag of the body's weight
Assert.True(MathF.Abs(strongL - strongR) < 0.15f, $"symmetric when both are strong: {strongL} {strongR}");
Assert.True(MathF.Abs(limpL - limpR) > 0.3f, $"the limp knee no longer tracks: left {limpL}, right {limpR}");
}
[Fact]
public void Same_seed_gives_the_same_state_hash_at_every_checkpoint_and_other_seeds_differ()
{
static List<ulong> Hashes(ulong seed, int strengthElementToFlip = -1)
{
using var s = new RagdollScenario(seed);
if (strengthElementToFlip >= 0) s.Strength[strengthElementToFlip] = 0.5f;
var hashes = new List<ulong>();
for (var i = 0; i < 6; i++) { s.Run(0.5f); hashes.Add(s.StateHash()); }
Array.Clear(s.Strength); // stand, then fall
for (var i = 0; i < 8; i++) { s.Run(0.5f); hashes.Add(s.StateHash()); }
return hashes;
}
var a = Hashes(42);
Assert.Equal(a, Hashes(42));
Assert.Equal(a.Count, a.Distinct().Count()); // the hash moves every checkpoint: the ragdoll is not frozen
Assert.NotEqual(a[0], Hashes(43)[0]); // the seed matters
Assert.NotEqual(a[0], Hashes(42, BodyPlans.Humanoid().JointIndex("Hip", Side.Left))[0]); // and so does one strength element
}
[Fact]
public void Muscle_torques_are_equal_and_opposite_on_parent_and_child()
{
using var s = new RagdollScenario(seed: 1);
var v = s.World.View;
v.TorqueX.Clear(); v.TorqueY.Clear(); v.TorqueZ.Clear(); // drop the shove
Array.Clear(s.Strength);
s.Strength[s.Plan.JointIndex("Elbow", Side.Left)] = 1f;
s.Strength[s.Plan.JointIndex("Hip", Side.Right)] = 1f;
s.Target[s.Plan.JointIndex("Elbow", Side.Left)] = Quat.FromAxisAngle(0f, 0f, 1f, -0.5f);
s.Target[s.Plan.JointIndex("Hip", Side.Right)] = Quat.FromAxisAngle(1f, 0f, 0f, 0.4f);
s.Ragdoll.Drive(s.Strength, s.Target);
float sx = 0f, sy = 0f, sz = 0f;
for (var i = 0; i < v.Count; i++) { sx += v.TorqueX[i]; sy += v.TorqueY[i]; sz += v.TorqueZ[i]; }
Assert.Equal(0f, sx, 1e-3f); Assert.Equal(0f, sy, 1e-3f); Assert.Equal(0f, sz, 1e-3f);
// Only the four bodies of those two joints were touched, and the elbow child got the hinge torque.
var touched = Enumerable.Range(0, v.Count).Where(i => v.TorqueX[i] != 0f || v.TorqueY[i] != 0f || v.TorqueZ[i] != 0f).ToHashSet();
Assert.Equal(new HashSet<int>
{
s.Ragdoll.BodyLane(s.Plan.PartIndex("UpperArm", Side.Left)), s.Ragdoll.BodyLane(s.Plan.PartIndex("LowerArm", Side.Left)),
s.Ragdoll.BodyLane(s.Plan.PartIndex("Pelvis")), s.Ragdoll.BodyLane(s.Plan.PartIndex("Thigh", Side.Right)),
}, touched);
Assert.NotEqual(0f, v.TorqueX[s.Ragdoll.BodyLane(s.Plan.PartIndex("LowerArm", Side.Left))]);
}
private static float TorqueNorm(RagdollScenario s, int part)
{
var v = s.World.View;
var i = s.Ragdoll.BodyLane(part);
return MathF.Sqrt(v.TorqueX[i] * v.TorqueX[i] + v.TorqueY[i] * v.TorqueY[i] + v.TorqueZ[i] * v.TorqueZ[i]);
}
private static void ClearTorques(RagdollScenario s)
{
var v = s.World.View;
v.TorqueX.Clear(); v.TorqueY.Clear(); v.TorqueZ.Clear();
}
[Fact]
public void A_fractional_strength_scales_the_written_torque_linearly()
{
using var s = new RagdollScenario(seed: 1);
Array.Clear(s.Strength);
s.Target[s.Plan.JointIndex("Hip", Side.Left)] = Quat.FromAxisAngle(1f, 0f, 0f, 0.3f);
ClearTorques(s);
s.Strength[s.Plan.JointIndex("Hip", Side.Left)] = 1f;
s.Ragdoll.Drive(s.Strength, s.Target);
var full = TorqueNorm(s, s.Plan.PartIndex("Thigh", Side.Left));
ClearTorques(s);
s.Strength[s.Plan.JointIndex("Hip", Side.Left)] = 0.25f;
s.Ragdoll.Drive(s.Strength, s.Target);
Assert.True(full > 1f);
Assert.Equal(full * 0.25f, TorqueNorm(s, s.Plan.PartIndex("Thigh", Side.Left)), full * 1e-3f);
}
[Fact]
public void A_hinge_takes_torque_about_its_own_axis_only_and_a_ball_joint_takes_any()
{
// The gravity feedforward is the same under either target, so what differs is the PD term alone: the hinge turns what it can (its target's off-axis part changes nothing,
// bit for bit) and the ball joint takes the swing it is told.
using var s = new RagdollScenario(seed: 1);
Array.Clear(s.Strength);
var elbow = s.Plan.JointIndex("Elbow", Side.Left);
var hip = s.Plan.JointIndex("Hip", Side.Left);
var forearm = s.Plan.PartIndex("LowerArm", Side.Left);
var thigh = s.Plan.PartIndex("Thigh", Side.Left);
s.Strength[elbow] = 1f;
s.Strength[hip] = 1f;
(float X, float Y, float Z) Torque(int part) { var v = s.World.View; var i = s.Ragdoll.BodyLane(part); return (v.TorqueX[i], v.TorqueY[i], v.TorqueZ[i]); }
s.Target[elbow] = Quat.Identity;
s.Target[hip] = Quat.Identity;
ClearTorques(s);
s.Ragdoll.Drive(s.Strength, s.Target);
var straightForearm = Torque(forearm);
var straightThigh = Torque(thigh);
var offAxis = Quat.FromAxisAngle(1f, 0f, 0f, 0.3f); // about the joint frame's x: not the hinge axis (z)
s.Target[elbow] = offAxis;
s.Target[hip] = offAxis;
ClearTorques(s);
s.Ragdoll.Drive(s.Strength, s.Target);
Assert.Equal(straightForearm, Torque(forearm)); // the hinge ignores what it cannot turn
var t = Torque(thigh);
var change = MathF.Sqrt((t.X - straightThigh.X) * (t.X - straightThigh.X) + (t.Y - straightThigh.Y) * (t.Y - straightThigh.Y) + (t.Z - straightThigh.Z) * (t.Z - straightThigh.Z));
Assert.True(change > 1f, $"the ball joint's thigh torque moved {change} N m"); // the ball joint does not
}
[Fact]
public void The_gravity_feedforward_on_a_hinge_acts_about_its_axis_only()
{
// A forearm held out of the vertical (shoulder raised, elbow bent, everything at full strength for 1 s), then only the elbow strong: the load's torque about the elbow
// is not zero there, and what the forearm gets is along the elbow's axis, though the load's own torque is not (the hinge has twist gains only).
using var s = new RagdollScenario(seed: 1);
var shoulder = s.Plan.JointIndex("Shoulder", Side.Left);
var elbow = s.Plan.JointIndex("Elbow", Side.Left);
s.Target[shoulder] = Quat.FromAxisAngle(1f, 0f, 0f, -1.2f);
s.Target[elbow] = Quat.FromAxisAngle(0f, 0f, 1f, 0.8f);
s.Run(1f);
var forearm = s.Plan.PartIndex("LowerArm", Side.Left);
Array.Clear(s.Strength);
ClearTorques(s);
s.Ragdoll.Drive(s.Strength, s.Target);
var v = s.World.View;
var i = s.Ragdoll.BodyLane(forearm);
var (x0, y0, z0) = (v.TorqueX[i], v.TorqueY[i], v.TorqueZ[i]); // the wrist's and the elbow's tissue damping alone, which the difference below removes
s.Strength[elbow] = 1f;
ClearTorques(s);
s.Ragdoll.Drive(s.Strength, s.Target);
var (dx, dy, dz) = (v.TorqueX[i] - x0, v.TorqueY[i] - y0, v.TorqueZ[i] - z0);
var j = s.Ragdoll.JointLane(elbow);
new Quat(v.JointFrameX[j], v.JointFrameY[j], v.JointFrameZ[j], v.JointFrameW[j]).Rotate(0f, 0f, 1f, out var ax, out var ay, out var az);
var total = MathF.Sqrt(dx * dx + dy * dy + dz * dz);
var along = dx * ax + dy * ay + dz * az;
Assert.True(total > 0.5f, $"the held-out forearm gets {total} N m");
Assert.True(MathF.Abs(along) > total * 0.99999f, $"{total} N m on the forearm, {along} of it along the elbow axis");
}
/// <summary>
/// Zero gravity: Drive writes the PD torque and nothing else (the feedforward is skipped), so the 2 s state hash of a free ragdoll, seeds 1-3, is the one recorded at
/// origin/main e47e3d3, before the gravity feedforward. Goldens move only where a ruling says; this one pins that the feedforward is zero where gravity is.
/// </summary>
[Fact]
public void A_zero_gravity_world_replays_the_hash_recorded_before_the_gravity_feedforward()
{
var recorded = new ulong[] { 4596821165163159072ul, 2187121869401780341ul, 2995211072229544614ul };
var got = new ulong[3];
for (var k = 0; k < 3; k++)
{
using var s = new RagdollScenario((ulong)(k + 1), gravityY: 0f);
s.Run(2f);
got[k] = s.StateHash();
}
Assert.True(recorded.SequenceEqual(got), string.Join(", ", got));
}
[Fact]
public void Driving_a_tick_allocates_nothing()
{
using var s = new RagdollScenario(seed: 1);
s.Ragdoll.Drive(s.Strength, s.Target); // warm
var before = GC.GetAllocatedBytesForCurrentThread();
for (var i = 0; i < 1000; i++) s.Ragdoll.Drive(s.Strength, s.Target);
Assert.Equal(0L, GC.GetAllocatedBytesForCurrentThread() - before);
}
[Fact]
public void The_world_carries_the_limb_tree_and_the_arrays_must_have_one_entry_per_muscle()
{
using var s = new RagdollScenario(seed: 1);
var v = s.World.View;
var r = s.Ragdoll;
Assert.Equal(-1, v.Parent[r.BodyLane(s.Plan.PartIndex("Pelvis"))]);
Assert.Equal(r.BodyLane(s.Plan.PartIndex("Pelvis")), v.Parent[r.BodyLane(s.Plan.PartIndex("Torso"))]);
Assert.Equal(r.BodyLane(s.Plan.PartIndex("Thigh", Side.Left)), v.Parent[r.BodyLane(s.Plan.PartIndex("Shin", Side.Left))]);
Assert.Equal(r.BodyLane(s.Plan.PartIndex("Shin", Side.Right)), v.Parent[r.BodyLane(s.Plan.PartIndex("Foot", Side.Right))]);
Assert.Equal(s.Plan.PartIndex("LowerArm", Side.Right), v.Limb[r.BodyLane(s.Plan.PartIndex("LowerArm", Side.Right))]);
Assert.Equal((uint)Box3DSoaKind.Capsule, v.Kind[r.BodyLane(s.Plan.PartIndex("Thigh", Side.Left))]);
Assert.Equal((uint)Box3DSoaKind.Box, v.Kind[r.BodyLane(s.Plan.PartIndex("Torso"))]);
Assert.Equal((uint)Box3DSoaKind.Sphere, v.Kind[r.BodyLane(s.Plan.PartIndex("Head"))]);
Assert.Equal(s.Plan.Joints.Count, v.JointCount);
Assert.Throws<ArgumentException>(() => r.Drive(new float[3], s.Target));
Assert.Throws<ArgumentException>(() => r.Drive(s.Strength, new Quat[3]));
}
}

View file

@ -0,0 +1,223 @@
using Lodur;
using Lodur.Body.Ymir;
using Xunit.Abstractions;
using Ymir.Box3D;
namespace Lodur.Tests;
/// <summary>
/// The orient layers on the real body: a ragdoll seated on a stool welded to the pelvis, without and with gravity, a sound at one side. An Actor whose goal looks
/// at it and wards it off drives the ragdoll through strengths and targets only; the game (this scenario) reads the part poses, owns the world and steps it.
/// </summary>
public sealed class SeatedOrientTests
{
private const float Dt = 1f / 120f;
private const uint Thing = 7;
private const float WardDistance = 0.3f;
private const float Spread = 0.15f;
private static readonly BodyPlan Plan = BodyPlans.Humanoid();
/// <summary>Where the sound sits for each case: well to one side and a little ahead, at head height and beyond the arms reach.</summary>
private static readonly (float X, float Y, float Z)[] Sounds = { (0.4f, 1.74f, 0.7f), (-0.4f, 1.74f, 0.7f) };
/// <summary>
/// A lower sound to the left, whose ward goals the near (left) arm reaches with zero shoulder twist. The far arm's goal crosses the midline and the
/// straight wrist path to it touches the trunk, so the far arm follows the hand path through the clearance via point (ruling
/// lodur:ruling:reach-clears-body-by-via-point): forward first, then across.
/// </summary>
private static readonly (float X, float Y, float Z) LowSound = (0.4f, 1.2f, 0.9f);
/// <summary>
/// Without gravity, bound on the far (right) wrist's distance to its ward goal at the low sound after 2 s, metres: the geometric midpoint of the shipped
/// 6.97 cm and the least claimed mutant, 34.92 cm (the via point at the trunk front, clearance 0). Also killed: the via point's x at the midpoint of wrist
/// and goal, 39.31 cm; every reach solved directly (blocked forced false), 44.90 cm; the wedge before the path, 44.6 cm.
/// </summary>
private const float FarArmBound = 0.1560f;
/// <summary>
/// Head forward error bound after 2 s, degrees, set at the geometric midpoint (deterministic-bound-margin) of the shipped worst then, 1.030 deg, and the
/// least claimed mutant, 15.233 deg (the look blended at half weight), and not loosened since: the shipped worst is now 1.946 deg over the two sounds under gravity (1.080 without it; the
/// feedforward lifts the head's look to 1.946 from 0.814), the half-weight mutant 15.729 deg. Layers off reads 29.7 deg.
/// </summary>
private const float LookBoundDegrees = 3.961f;
/// <summary>
/// Without gravity, bound on each wrist's distance to its own ward goal after 2 s at the head-height sounds, metres: the geometric midpoint of the shipped
/// worst, 8.11 cm (the arm that the other sound's side blocks, on its via path), and the least claimed mutant, 11.45 cm (the via point's x at the midpoint).
/// Also killed: no spread, 13.25 cm; the wrists sent sideways of the head by the ward distance, 35.02 cm; the arms blended at half weight, 46.09 cm. Layers off reads the start,
/// 81.3 and 83.5 cm. Not re-measured: spread halved and offset, and the clamped zero-twist swivel (64.94 cm before the hand path), each far above the bound.
/// </summary>
private const float WardBound = 0.0964f;
/// <summary>
/// Without gravity, bound on the near (left) wrist's distance to its ward goal at the low sound, the geometric midpoint of the shipped worst, 4.34 cm,
/// and the least claimed mutant, 7.65 cm (the via point's x at the midpoint). Also killed: the arms at half weight, 36.48 cm; sideways, 25.90 cm; Not killed: no spread reads
/// 2.95 cm, the look at half weight 5.01 cm, every reach solved directly 5.19 cm.
/// </summary>
private const float NearWardBound = 0.0576f;
/// <summary>
/// Under gravity, the head-height bound on each wrist: the geometric midpoint of the shipped worst, 7.03 cm, and the least claimed mutant, 9.81 cm (the arm's path never
/// blocked by the trunk: 9.81 and 3.76 cm): 8.30 cm, margin 1.18 each side, separation 1.40. Also killed, re-measured under the subtree-external gate (ruling
/// gravity-support-subtree-external): the gravity feedforward off, 18.68 cm; no spread, 21.21 cm; the via point's x at the midpoint, 26.77 cm; the wrists sent sideways of
/// the head, 34.25 cm; the via point at the trunk front with clearance 0, 34.30 cm (15.52 at 63444f0, where the count gate left the arm lighter); the arms at half weight, 52.17 cm.
/// Not killed: every reach solved directly, 7.20 cm at 63444f0, not re-measured. The ward is not limited by gravity or by the gate: zero gravity reads 8.11 cm, the count gate
/// 6.00, no gate 7.59, the subtree-external gate 7.03, so the reading rests on the planner's own residual. At 63444f0 the bound was 9.65 cm (shipped worst 6.00, least claimed
/// mutant 15.52); the shipped reading rose to 7.03 and the path-never-blocked mutant, 9.81, is separated from it by 1.40, so it is claimed and the bound fell. The bound at e47e3d3, before the feedforward, was 21.78 cm (shipped worst 18.68, least claimed mutant
/// 25.41). Not re-measured: spread halved and offset, and the clamped zero-twist swivel.
/// </summary>
private const float GravityWardBound = 0.0830f;
private readonly ITestOutputHelper _out;
public SeatedOrientTests(ITestOutputHelper output) => _out = output;
private static float Dist((float X, float Y, float Z) a, (float X, float Y, float Z) b) =>
MathF.Sqrt((a.X - b.X) * (a.X - b.X) + (a.Y - b.Y) * (a.Y - b.Y) + (a.Z - b.Z) * (a.Z - b.Z));
private static (float X, float Y, float Z) Unit((float X, float Y, float Z) v)
{
var l = MathF.Sqrt(v.X * v.X + v.Y * v.Y + v.Z * v.Z);
return (v.X / l, v.Y / l, v.Z / l);
}
private static Quat[] Held()
{
var pose = new Quat[Plan.Joints.Count];
Array.Fill(pose, Quat.Identity);
return pose;
}
private static Brain Watching() => new()
{
Goals = new[]
{
new GoalSpec { Id = "sit", Priority = 0.0, Behaviour = new PoseBehaviour { Keys = new[] { Held() }, FlinchPose = Held() } },
new GoalSpec
{
Id = "watch", Priority = 1.0, Target = new TargetFilter { Kinds = new[] { Thing } },
Considerations = new[] { new Consideration(ConsiderationInput.Distance, 0.0, 60.0, 1.0, 0.0) },
Behaviour = new PoseBehaviour
{
Keys = new[] { Held() }, FlinchPose = Held(),
Look = new LookLayer(),
Arms = new ArmLayer { Mode = ArmMode.WardOff, Side = ArmSide.Both, Distance = WardDistance, Spread = Spread },
},
},
},
};
/// <summary>Seats the body, sounds the emitter for two seconds and returns the head forward's error to the sound bearing (radians) and each wrist's distance to its ward goal at the end and at the start.</summary>
private static (float Look, float Left, float Right, float LeftStart, float RightStart, ulong Target) Run((float X, float Y, float Z) sound, float gravity)
{
var (bodies, joints, _) = Ragdoll.Needs(Plan);
using var world = new Box3DSoaWorld(capacity: bodies + 2, gravityY: gravity, jointCapacity: joints + 1);
world.AddStaticBox(1, (0f, -0.5f, 0f), (20f, 0.5f, 20f), friction: 0.8f);
var stool = world.AddStaticBox(2, (0f, 1.11f, -0.115f), (0.05f, 0.05f, 0.025f), friction: 0.8f);
var ragdoll = Ragdoll.Build(world, Plan, (0f, 0f), firstStableId: 100);
world.AddJoint(Box3DSoaJointKind.Weld, stool, ragdoll.BodyLane(Plan.PartIndex("Pelvis")), (0f, 1.11f, -0.09f), (0f, 1f, 0f));
var senseHead = Plan.SenseIndex("Head");
var actor = new Actor(Dt, Plan.SensePoints.Count, new NerveParameters(), new WithdrawalParameters(), new DriveParameters(), Watching(),
new NerveParameters { Threshold = 0.05, SensitisationGrowth = 0.0, ConductionDelaySeconds = 0.0 }, senseHead,
new PerceptParameters { Capacity = 4, MemorySeconds = 5.0 }, body: Plan);
var x = new float[Plan.SensePoints.Count]; var y = new float[x.Length]; var z = new float[x.Length];
var strength = new float[Plan.Joints.Count];
var target = new Quat[Plan.Joints.Count];
var parts = new PartPose[Plan.Parts.Count];
var emitters = new[] { new Emitter { Channel = Channel.Audio, X = sound.X, Y = sound.Y, Z = sound.Z, Radius = 40f, Intensity = 1.0, Id = 1, Kind = Thing } };
var head = Plan.PartIndex("Head");
var wrists = new[] { Plan.JointIndex("Wrist", Side.Left), Plan.JointIndex("Wrist", Side.Right) };
var torso = Plan.PartIndex("Torso");
// Each wrist's distance to its own ward-off goal: the head centre plus Distance toward the sound plus Spread along the torso's left
// axis, the left wrist to the left. The goal is rebuilt from the measured head and torso, as the layer builds it.
float WristError(int k)
{
var h = parts[head];
var u = Unit((sound.X - h.X, sound.Y - h.Y, sound.Z - h.Z));
parts[torso].Rotation.Rotate(1f, 0f, 0f, out var lx, out var ly, out var lz);
var across = k == 0 ? Spread : -Spread;
var goal = (h.X + u.X * WardDistance + lx * across, h.Y + u.Y * WardDistance + ly * across, h.Z + u.Z * WardDistance + lz * across);
var j = Plan.Joints[wrists[k]];
var fore = parts[j.Parent];
var c = Plan.Parts[j.Parent].Position;
fore.Rotation.Rotate(j.Anchor.X - c.X, j.Anchor.Y - c.Y, j.Anchor.Z - c.Z, out var ox, out var oy, out var oz);
return Dist((fore.X + ox, fore.Y + oy, fore.Z + oz), goal);
}
ragdoll.ReadPartPoses(parts);
var (leftStart, rightStart) = (WristError(0), WristError(1));
for (var i = 0; i < (int)MathF.Round(2f / Dt); i++)
{
ragdoll.ReadSensePoints(x, y, z);
ragdoll.ReadPartPoses(parts);
actor.Tick(x, y, z, Array.Empty<BoxStimulus>(), strength, target, emitters, parts: parts);
ragdoll.Drive(strength, target);
world.Step(Dt, 4);
}
ragdoll.ReadPartPoses(parts);
var hp = parts[head];
hp.Rotation.Rotate(0f, 0f, 1f, out var fx, out var fy, out var fz);
var bearing = Unit((sound.X - hp.X, sound.Y - hp.Y, sound.Z - hp.Z));
var cos = Math.Clamp(fx * bearing.X + fy * bearing.Y + fz * bearing.Z, -1f, 1f);
return (MathF.Acos(cos), WristError(0), WristError(1), leftStart, rightStart, actor.TargetId);
}
[Fact]
public void ReadPartPoses_reports_each_part_at_its_creation_pose_and_allocates_nothing()
{
var (bodies, joints, _) = Ragdoll.Needs(Plan);
using var world = new Box3DSoaWorld(capacity: bodies, jointCapacity: joints);
var ragdoll = Ragdoll.Build(world, Plan, (0f, 0f), firstStableId: 100);
var poses = new PartPose[Plan.Parts.Count];
ragdoll.ReadPartPoses(poses);
for (var p = 0; p < poses.Length; p++)
{
var d = Plan.Parts[p];
Assert.Equal(d.Position.X, poses[p].X, 3);
Assert.Equal(d.Position.Y, poses[p].Y, 3);
Assert.Equal(d.Position.Z, poses[p].Z, 3);
var dot = MathF.Abs(d.Rotation.X * poses[p].Rotation.X + d.Rotation.Y * poses[p].Rotation.Y + d.Rotation.Z * poses[p].Rotation.Z + d.Rotation.W * poses[p].Rotation.W);
Assert.True(dot > 1f - 1e-5f, $"part {d.Label} {d.Side} rotation {poses[p].Rotation} against {d.Rotation}");
}
Assert.Throws<ArgumentException>(() => ragdoll.ReadPartPoses(new PartPose[poses.Length - 1]));
var before = GC.GetAllocatedBytesForCurrentThread();
for (var i = 0; i < 1000; i++) ragdoll.ReadPartPoses(poses);
Assert.Equal(0L, GC.GetAllocatedBytesForCurrentThread() - before);
}
[Fact]
public void Without_gravity_a_seated_body_looks_at_the_sound_and_its_wrists_meet_the_ward_goals()
{
for (var s = 0; s < Sounds.Length; s++)
{
var r = Run(Sounds[s], gravity: 0f);
_out.WriteLine($"sound {s}: head error {r.Look * 57.2958f:F3} deg, wrists to their goals {r.Left * 100f:F2} and {r.Right * 100f:F2} cm (start {r.LeftStart * 100f:F2} and {r.RightStart * 100f:F2}), target {r.Target}");
Assert.Equal(1UL, r.Target);
Assert.True(r.Look * 57.2958f < LookBoundDegrees, $"head forward is {r.Look * 57.2958f:F2} deg off the sound, bound {LookBoundDegrees} deg");
Assert.True(r.Left < WardBound && r.Right < WardBound, $"wrists are {r.Left * 100f:F1} and {r.Right * 100f:F1} cm from their goals, bound {WardBound * 100f:F1} cm");
}
var low = Run(LowSound, gravity: 0f);
_out.WriteLine($"low sound: wrists to their goals {low.Left * 100f:F2} and {low.Right * 100f:F2} cm");
Assert.True(low.Left < NearWardBound, $"the near wrist is {low.Left * 100f:F1} cm from its goal, bound {NearWardBound * 100f:F1} cm");
Assert.True(low.Right < FarArmBound, $"the far wrist is {low.Right * 100f:F1} cm from its goal, bound {FarArmBound * 100f:F1} cm");
}
[Fact]
public void Under_gravity_a_seated_body_looks_at_the_sound_and_its_wrists_rise_toward_the_ward_goals()
{
for (var s = 0; s < Sounds.Length; s++)
{
var r = Run(Sounds[s], gravity: -10f);
_out.WriteLine($"sound {s}: head error {r.Look * 57.2958f:F3} deg, wrists to their goals {r.Left * 100f:F2} and {r.Right * 100f:F2} cm (start {r.LeftStart * 100f:F2} and {r.RightStart * 100f:F2}), target {r.Target}");
Assert.Equal(1UL, r.Target);
Assert.True(r.Look * 57.2958f < LookBoundDegrees, $"head forward is {r.Look * 57.2958f:F2} deg off the sound, bound {LookBoundDegrees} deg");
Assert.True(r.Left < GravityWardBound && r.Right < GravityWardBound, $"wrists are {r.Left * 100f:F1} and {r.Right * 100f:F1} cm from their goals, bound {GravityWardBound * 100f:F1} cm");
}
}
}

View file

@ -0,0 +1,16 @@
<Project Sdk="Microsoft.NET.Sdk">
<!-- Generator of tests/Lodur.Core.Tests/pain-box-golden.tsv from Bad Day Simulator's own pain box.
Not a product target (not in Lodur.slnx); run tools/pain-box-golden/generate.sh. -->
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net10.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>disable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<Compile Include="$(BdsRoot)\src\BadDay.Core\*.cs" />
</ItemGroup>
</Project>

View file

@ -0,0 +1,46 @@
using System;
using System.Globalization;
using System.IO;
using BadDay.Core;
// One row per (intensity, pull, seed): the outcome of BadDaySimulator's PainBoxSimulation at 9f59764 with
// SampleEverySeconds 0.01, so the timeline holds one Sample row per tick, and an FNV-1a 64 hash of that
// per-tick stream (stimulus, pain, strain, resolve as raw double bits, then the goal byte).
var settings = new (double Intensity, double Pull)[]
{
(0.8, 0.5), (1.0, 0.5), (0.6, 0.5), (0.8, 0.0), (0.8, 0.8), (0.12, 0.5), (0.2, 0.5),
};
const int Seeds = 60;
using var w = new StreamWriter(args[0], false, new System.Text.UTF8Encoding(false)) { NewLine = "\n" };
w.WriteLine("# Generated by tools/pain-box-golden/generate.sh from BadDaySimulator 9f59764 PainBoxSimulation (tick 10 ms, one sample row per tick). Do not edit.");
w.WriteLine("# seed intensity pull outcome break_ms end_ms flinches ticks hash");
foreach (var (intensity, pull) in settings)
{
for (ulong seed = 1; seed <= Seeds; seed++)
{
var p = new PainBoxParameters { BoxIntensity = intensity, ObjectivePull = pull, SampleEverySeconds = 0.01 };
var r = PainBoxSimulation.Run(p, seed);
var h = 14695981039346656037ul;
void Byte(byte b) { h ^= b; h *= 1099511628211ul; }
void Double(double d) { foreach (var b in BitConverter.GetBytes(BitConverter.DoubleToInt64Bits(d))) Byte(b); }
long ticks = 0;
foreach (var e in r.Timeline)
{
if (e.Kind != EntryKind.Sample) continue;
ticks++;
Double(e.Stimulus); Double(e.Pain); Double(e.Strain); Double(e.Resolve);
Byte((byte)e.Goal);
}
w.WriteLine(string.Join(' ',
seed.ToString(CultureInfo.InvariantCulture),
intensity.ToString("0.0#", CultureInfo.InvariantCulture),
pull.ToString("0.0#", CultureInfo.InvariantCulture),
r.Outcome,
(r.TimeToBreakMs ?? -1).ToString(CultureInfo.InvariantCulture),
r.EndMs.ToString(CultureInfo.InvariantCulture),
r.Flinches.ToString(CultureInfo.InvariantCulture),
ticks.ToString(CultureInfo.InvariantCulture),
h.ToString("x16", CultureInfo.InvariantCulture)));
}
}

View file

@ -0,0 +1,11 @@
#!/usr/bin/env bash
# Regenerates tests/Lodur.Core.Tests/pain-box-golden.tsv from Bad Day Simulator's pain box at 9f59764.
# Usage: tools/pain-box-golden/generate.sh <path to a BadDaySimulator checkout at 9f59764>
set -euo pipefail
bds="${1:?path to a BadDaySimulator checkout at 9f59764}"
want=9f597647a608a6c6e44473cc9f1399983de14616
have="$(git -C "$bds" rev-parse HEAD)"
[ "$have" = "$want" ] || { echo "BadDaySimulator is at $have, need $want" >&2; exit 1; }
[ -z "$(git -C "$bds" status --porcelain -- src)" ] || { echo "BadDaySimulator has local changes under src/; the table must come from $want as committed" >&2; exit 1; }
here="$(cd "$(dirname "$0")" && pwd)"
dotnet run --project "$here/PainBoxGolden.csproj" -p:BdsRoot="$(cd "$bds" && pwd -W 2>/dev/null || pwd)" -- "$here/../../tests/Lodur.Core.Tests/pain-box-golden.tsv"