feat(biology): rules 13 mutation catalog, behaviour triggers and offer draw
Foundation / checks (checks) (push) Successful in 5s
Foundation / checks (client) (push) Successful in 5s
Foundation / checks (ecs) (push) Successful in 5s
Foundation / checks (network) (push) Successful in 4s
Foundation / checks (postgres) (push) Successful in 4s
Foundation / checks (tsan) (push) Successful in 4s
Foundation / checks (deploy) (push) Successful in 4m30s
Foundation / postgres-tools (push) Successful in 22s
Foundation / server-image (push) Successful in 4m10s
Foundation / image (push) Successful in 4m46s

Phase 3 of the cellular revamp build plan (ADR-0179), first part: the headless
pieces the owner will use.

- The named catalog: all 49 mutations of Cellular_mutation_plan.md as data
  (stable ids and tuning keys, name, pro, con, effect, availability, increase
  and decrease triggers, base weight). Applying one edits a schema-7 plan by
  fixed reference points (a point is a hundredth of the founder's value), with
  paired edits, spreads across a channel group, recipe shifts, photosynthesis
  acquire and shed, and Adhesion; bounds, gates (carbon burned, buds made) and
  the enabled switch close it. 43 mutations are open at birth, as planned.
- Triggers: per-tick activity signals and eight trigger kinds (accumulate,
  absence, count in a window, event, share over a window, regular recurrence,
  straight heading, sharp turns) move each mutation's affinity score within
  bounds; integer state only, so replay reproduces scores.
- Offers: weight = base x a score multiplier; chances clamp(k x weight, floor,
  cap) summing to the options, in parts per million (floor 0.001%, cap 70%),
  found exactly by water-filling over sorted weights; a systematic draw picks
  distinct mutations whose inclusion frequencies equal their chances exactly.

Tests cover the catalog's identities, the pool at birth, every kind of edit,
bounds and gates; every trigger kind; score bounds; weights; a 300-seed chance
ensemble; and an exhaustive draw over all million draws. Refreshes the DEV
session window.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
dingo
2026-10-22 18:46:21 -04:00
co-authored by Claude Opus 5.5
parent 76d21b4815
commit 732d008aa1
10 changed files with 1513 additions and 2 deletions
+508
View File
@@ -0,0 +1,508 @@
#include "evo/biology/cellular_catalog.hpp"
#include "evo/biology/founder.hpp"
#include "evo/biology/mutation.hpp"
#include <algorithm>
#include <limits>
namespace evo::biology {
namespace {
using T = CellularTrait;
using S = CellularSignal;
using K = CellularTriggerKind;
using E = CellularEffect;
using A = CellularAvailability;
using P = CellularSpread;
constexpr std::uint32_t second = 20; // Ticks.
constexpr std::uint32_t minute = 60 * second;
constexpr std::uint16_t right_angle = 16'384; // 90 degrees.
constexpr std::uint16_t twenty_degrees = 3'641;
constexpr CellularTriggerSpec accumulate(S signal, std::uint32_t ticks) {
return {K::accumulate, signal, ticks};
}
constexpr CellularTriggerSpec absence(S signal, std::uint32_t ticks) {
return {K::absence, signal, ticks};
}
constexpr CellularTriggerSpec count(S signal, std::uint32_t times, std::uint32_t ticks) {
return {K::count, signal, ticks, times};
}
constexpr CellularTriggerSpec event(S signal) {
return {K::event, signal};
}
constexpr CellularTriggerSpec share(S part, S whole, std::uint32_t ticks) {
return {K::share, part, ticks, 0, whole, 500};
}
constexpr CellularTriggerSpec regular(std::uint32_t gap, std::uint32_t ticks) {
return {K::regular, S::thrust, ticks, 0, {}, 0, gap};
}
constexpr CellularTriggerSpec straight(std::uint32_t ticks) {
return {K::straight, S::thrust, ticks, 0, {}, 0, 0, twenty_degrees};
}
constexpr CellularTriggerSpec turns(std::uint32_t times, std::uint32_t ticks) {
return {K::turns, S::thrust, ticks, times, {}, 0, 0, right_angle};
}
struct Entry {
std::uint16_t id;
std::string_view key, name, pro, con;
E effect;
T primary;
std::int8_t primary_sign;
T paired;
std::int8_t paired_sign;
P spread;
A available;
CellularTriggerSpec increase, decrease;
std::uint32_t base_weight = 100, primary_step = 5;
};
constexpr CellularMutationSpec spec(const Entry& e) {
return {e.id, e.key, e.name, e.pro, e.con, e.effect,
e.primary, e.paired, e.primary_sign, e.paired_sign, e.spread, e.available,
e.increase, e.decrease, e.base_weight, e.primary_step};
}
// Cellular_mutation_plan.md sections 5-9. Mirrors take their core mutation's triggers swapped.
constexpr std::array<CellularMutationSpec, cellular_catalog_size> catalog{
// Movement (section 5).
spec({1, "strong_propulsion", "Strong Propulsion", "Top speed and acceleration +5%",
"More energy per second at full thrust, and per distance", E::adjust, T::move_output, 1,
T::move_efficiency, -1, P::none, A::always, accumulate(S::thrust, 10 * second),
absence(S::thrust, 30 * minute)}),
spec({2, "economical_propulsion", "Economical Propulsion",
"Drifts further after letting go; top speed +5%",
"Stops more slowly; slides more in turns", E::adjust, T::move_coasting, 1, T::none, 0,
P::none, A::always, regular(15 * second, minute), absence(S::thrust, 2 * minute)}),
spec({3, "efficient_propulsion", "Efficient Propulsion", "Less energy per distance",
"Top speed and acceleration -2%", E::adjust, T::move_efficiency, 1, T::move_output, -1,
P::none, A::always, share(S::energy_movement, S::energy_spent, minute),
absence(S::thrust, 5 * minute)}),
spec({4, "agile_steering", "Agile Steering", "Turns 5% faster",
"Top speed and acceleration -2%", E::adjust, T::move_steering, 1, T::move_output, -1,
P::none, A::always, turns(5, 20 * second), straight(minute)}),
spec({5, "streamlined_body", "Streamlined Body", "Top speed +5% and longer forward glide",
"Turns 2% slower", E::adjust, T::move_streamlining, 1, T::move_steering, -1, P::none,
A::always, straight(20 * second), turns(5, 20 * second)}),
spec({6, "strong_brakes", "Strong Brakes", "Stops and reverses 5% faster",
"Top speed -2%; each brake draws more energy", E::adjust, T::move_braking, 1,
T::move_output, -1, P::none, A::always, count(S::brake_press, 5, minute),
absence(S::brake_press, 10 * minute)}),
spec({7, "light_propulsion", "Light Propulsion", "Less energy per second and per distance",
"Top speed -5%", E::adjust, T::move_output, -1, T::move_efficiency, 1, P::none, A::always,
absence(S::thrust, 30 * minute), accumulate(S::thrust, 10 * second)}),
spec({8, "damped_body", "Damped Body", "Stops sooner, slides less",
"Top speed -5%; more energy per distance", E::adjust, T::move_coasting, -1, T::none, 0,
P::none, A::always, absence(S::thrust, 2 * minute), regular(15 * second, minute)}),
spec({9, "overdriven_propulsion", "Overdriven Propulsion", "Top speed +2%",
"More energy per second and per distance", E::adjust, T::move_efficiency, -1,
T::move_output, 1, P::none, A::always, absence(S::thrust, 5 * minute),
share(S::energy_movement, S::energy_spent, minute)}),
spec({10, "forward_drive", "Forward Drive", "Top speed +2%", "Turns 5% slower", E::adjust,
T::move_steering, -1, T::move_output, 1, P::none, A::always, straight(minute),
turns(5, 20 * second)}),
spec({11, "rounded_body", "Rounded Body", "Turns 2% faster", "Top speed -5%", E::adjust,
T::move_streamlining, -1, T::move_steering, 1, P::none, A::always, turns(5, 20 * second),
straight(20 * second)}),
spec({12, "light_brakes", "Light Brakes", "Top speed +2%", "Stops 5% slower", E::adjust,
T::move_braking, -1, T::move_output, 1, P::none, A::always,
absence(S::brake_press, 10 * minute), count(S::brake_press, 5, minute)}),
// Feeding (section 6).
spec({13, "carbon_gatherer", "Carbon Gatherer", "Collects carbon 5% faster",
"Collects N, P and other matter 1% slower each", E::adjust, T::collect_carbon, 1, T::none,
0, P::collect_matter, A::always, share(S::collected_carbon, S::collected_matter, minute),
absence(S::collected_carbon, 5 * minute)}),
spec({14, "nitrogen_gatherer", "Nitrogen Gatherer", "Collects nitrogen 5% faster",
"Collects C, P and other matter 1% slower each", E::adjust, T::collect_nitrogen, 1,
T::none, 0, P::collect_matter, A::always,
share(S::collected_nitrogen, S::collected_matter, minute),
absence(S::collected_nitrogen, 5 * minute)}),
spec({15, "phosphorus_gatherer", "Phosphorus Gatherer", "Collects phosphorus 5% faster",
"Collects C, N and other matter 1% slower each", E::adjust, T::collect_phosphorus, 1,
T::none, 0, P::collect_matter, A::always,
share(S::collected_phosphorus, S::collected_matter, minute),
absence(S::collected_phosphorus, 5 * minute)}),
spec({16, "other_matter_gatherer", "Other Matter Gatherer", "Collects other matter 5% faster",
"Collects C, N and P 1% slower each", E::adjust, T::collect_other, 1, T::none, 0,
P::collect_matter, A::always, share(S::collected_other, S::collected_matter, minute),
absence(S::collected_other, 5 * minute)}),
spec({17, "big_appetite", "Big Appetite", "Takes in 5% more per second at rich food",
"More upkeep", E::adjust, T::intake, 1, T::upkeep_efficiency, -1, P::none, A::always,
accumulate(S::intake_limited, 10 * second), absence(S::fed, 5 * minute)}),
spec({18, "small_appetite", "Small Appetite", "Less upkeep", "Takes in 5% less at rich food",
E::adjust, T::intake, -1, T::upkeep_efficiency, 1, P::none, A::always,
absence(S::fed, 5 * minute), accumulate(S::intake_limited, 10 * second)}),
// Energy (section 6).
spec({19, "thorough_extraction", "Thorough Extraction", "More energy from each energy bubble",
"Drains energy bubbles 2% slower", E::adjust, T::energy_kept, 1, T::collect_energy, -1,
P::none, A::always, accumulate(S::burned_matter, 30 * second),
absence(S::burned_matter, 10 * minute)}),
spec({20, "rapid_extraction", "Rapid Extraction", "Drains energy bubbles 5% faster",
"Keeps slightly less of each", E::adjust, T::collect_energy, 1, T::energy_kept, -1,
P::none, A::always, accumulate(S::energy_limited, 10 * second),
absence(S::energy_collected, 5 * minute)}),
spec({21, "carbon_metabolism", "Carbon Metabolism", "Carbon covers 5% more energy when burned",
"N, P and other matter cover 1% less each", E::adjust, T::burn_carbon, 1, T::none, 0,
P::burn, A::always, accumulate(S::burned_carbon, 30 * second),
absence(S::burned_carbon, 10 * minute)}),
spec({22, "nitrogen_metabolism", "Nitrogen Metabolism", "Nitrogen covers 5% more energy",
"C, P and other matter cover 1% less each", E::adjust, T::burn_nitrogen, 1, T::none, 0,
P::burn, A::always, accumulate(S::burned_nitrogen, 30 * second),
absence(S::burned_nitrogen, 10 * minute)}),
spec({23, "phosphorus_metabolism", "Phosphorus Metabolism", "Phosphorus covers 5% more energy",
"C, N and other matter cover 1% less each", E::adjust, T::burn_phosphorus, 1, T::none, 0,
P::burn, A::always, accumulate(S::burned_phosphorus, 30 * second),
absence(S::burned_phosphorus, 10 * minute)}),
spec({24, "other_matter_metabolism", "Other Matter Metabolism",
"Other matter covers 5% more energy", "C, N and P cover 1% less each", E::adjust,
T::burn_other, 1, T::none, 0, P::burn, A::always,
accumulate(S::burned_other, 30 * second), absence(S::burned_other, 10 * minute)}),
// Photosynthesis (section 6).
spec({25, "acquire_photosynthesis", "Acquire Photosynthesis", "Steady energy from light",
"Producer tissue adds mass and upkeep; drains energy bubbles slower", E::acquire_light,
T::light, 1, T::collect_energy, -1, P::none, A::light_absent_after_carbon,
accumulate(S::burned_carbon, 30 * second),
accumulate(S::burned_not_carbon, 30 * second)}),
spec({26, "expand_photosynthesis", "Expand Photosynthesis", "5% more energy from light",
"More tissue mass and upkeep; drains energy bubbles slower", E::adjust, T::light, 1,
T::collect_energy, -1, P::none, A::light_present, accumulate(S::drifting, minute),
accumulate(S::thrust, 2 * minute)}),
spec({27, "reduce_photosynthesis", "Reduce Photosynthesis",
"Less tissue, lighter; drains energy bubbles faster", "Less energy from light", E::adjust,
T::light, -1, T::collect_energy, 1, P::none, A::light_present,
accumulate(S::thrust, 2 * minute), accumulate(S::drifting, minute)}),
spec({28, "shed_photosynthesis", "Shed Photosynthesis", "No producer mass or upkeep",
"No light energy", E::shed_light, T::light, -1, T::none, 0, P::none, A::light_present,
accumulate(S::thrust, 5 * minute), accumulate(S::drifting, minute), 25}),
// Predation and defense (section 7).
spec({29, "reinforced_membrane", "Reinforced Membrane",
"Predators need 5% more mass to engulf you",
"More membrane mass and upkeep, slower collection, heavier", E::adjust, T::membrane, 1,
T::none, 0, P::none, A::always, accumulate(S::larger_contact, 5 * second),
absence(S::larger_contact, 10 * minute)}),
spec({30, "thin_membrane", "Thin Membrane", "Faster collection, less mass and upkeep",
"Easier to engulf", E::adjust, T::membrane, -1, T::none, 0, P::none, A::always,
absence(S::larger_contact, 10 * minute), accumulate(S::larger_contact, 5 * second)}),
spec({31, "expanding_chamber", "Expanding Chamber", "Can engulf prey 5% bigger",
"Stretched wall: slightly easier to engulf yourself", E::adjust, T::engulf_capacity, 1,
T::membrane, -1, P::none, A::always, count(S::engulf_too_large_or_membrane, 3, 0),
absence(S::engulf_attempt, 10 * minute)}),
spec({32, "small_mouth", "Small Mouth", "Tougher wall", "Only smaller prey", E::adjust,
T::engulf_capacity, -1, T::membrane, 1, P::none, A::always,
absence(S::engulf_attempt, 10 * minute), count(S::engulf_too_large, 3, 0)}),
spec({33, "rapid_digestion", "Rapid Digestion", "Takes 5% more from a kill straight away",
"Slower everyday feeding", E::adjust, T::kill_absorption, 1, T::intake, -1, P::none,
A::always, event(S::engulf_success), absence(S::engulf_success, 15 * minute)}),
spec({34, "grazers_gut", "Grazer's Gut", "Faster everyday feeding", "Takes less from kills",
E::adjust, T::kill_absorption, -1, T::intake, 1, P::none, A::always,
absence(S::engulf_success, 15 * minute), event(S::engulf_success)}),
// Body and maintenance (section 8).
spec({35, "larger_body", "Larger Body",
"Harder to engulf, can engulf bigger prey, touches more food",
"More upkeep, costlier buds and regrowth, heavier and slower", E::adjust, T::size, 1,
T::none, 0, P::none, A::always, accumulate(S::reserve_over_body, minute),
accumulate(S::burned_matter, 30 * second)}),
spec({36, "smaller_body", "Smaller Body", "Less upkeep, cheaper buds and regrowth, quicker",
"Easier to engulf, smaller prey only", E::adjust, T::size, -1, T::none, 0, P::none,
A::always, accumulate(S::burned_matter, 30 * second),
accumulate(S::reserve_over_body, minute)}),
spec({37, "carbon_thrifty_body", "Carbon-Thrifty Body",
"Building, regrowth and buds need less carbon", "Need more N, P and other matter",
E::recipe, T::recipe_carbon, -1, T::none, 0, P::none, A::always,
accumulate(S::blocked_carbon, 10 * second),
share(S::collected_carbon, S::collected_matter, minute), 100, 20}),
spec({38, "nitrogen_thrifty_body", "Nitrogen-Thrifty Body", "Need less nitrogen",
"Need more C, P and other matter", E::recipe, T::recipe_nitrogen, -1, T::none, 0, P::none,
A::always, accumulate(S::blocked_nitrogen, 10 * second),
share(S::collected_nitrogen, S::collected_matter, minute), 100, 20}),
spec({39, "phosphorus_thrifty_body", "Phosphorus-Thrifty Body", "Need less phosphorus",
"Need more C, N and other matter", E::recipe, T::recipe_phosphorus, -1, T::none, 0,
P::none, A::always, accumulate(S::blocked_phosphorus, 10 * second),
share(S::collected_phosphorus, S::collected_matter, minute), 100, 20}),
spec({40, "other_thrifty_body", "Other-Thrifty Body", "Need less other matter",
"Need more C, N and P", E::recipe, T::recipe_other, -1, T::none, 0, P::none, A::always,
accumulate(S::blocked_other, 10 * second),
share(S::collected_other, S::collected_matter, minute), 100, 20}),
spec({41, "efficient_upkeep", "Efficient Upkeep",
"Lower upkeep, never below the essential floor", "Regrows 2% slower", E::adjust,
T::upkeep_efficiency, 1, T::growth_speed, -1, P::none, A::always,
share(S::energy_upkeep, S::energy_spent, 5 * minute), accumulate(S::regrowing, minute)}),
spec({42, "rapid_growth", "Rapid Growth", "Regrows 5% faster", "More upkeep", E::adjust,
T::growth_speed, 1, T::upkeep_efficiency, -1, P::none, A::always,
accumulate(S::regrowing, minute), accumulate(S::fully_grown, 10 * minute)}),
spec({43, "dense_tissue", "Dense Tissue",
"Smaller footprint for the same mass, lighter membrane, less upkeep",
"Less surface: slower collection, touches less food", E::adjust, T::density, 1, T::none,
0, P::none, A::always, accumulate(S::larger_contact, 5 * second),
accumulate(S::fed, minute)}),
spec({44, "light_tissue", "Light Tissue",
"Larger surface: faster collection, touches more food",
"More membrane mass and upkeep, bigger target", E::adjust, T::density, -1, T::none, 0,
P::none, A::always, accumulate(S::fed, minute),
accumulate(S::larger_contact, 5 * second)}),
// Reproduction (section 9).
spec({45, "bigger_buds", "Bigger Buds", "Buds start 5% larger and survive more often",
"Each bud costs 5% more", E::adjust, T::bud_share, 1, T::none, 0, P::none, A::always,
event(S::bud_lost_early), event(S::bud_refused)}),
spec({46, "smaller_buds", "Smaller Buds", "Each bud is cheaper",
"Buds start smaller and more vulnerable", E::adjust, T::bud_share, -1, T::none, 0,
P::none, A::always, event(S::bud_refused), event(S::bud_lost_early)}),
spec({47, "twinning", "Twinning", "More offspring per bud",
"Each offspring starts smaller and more vulnerable", E::adjust, T::litter, 1, T::none, 0,
P::none, A::always, event(S::bud_with_surplus), event(S::bud_lost_early), 100, 25}),
spec({48, "single_bud", "Single Bud", "Each offspring starts larger", "Fewer offspring per bud",
E::adjust, T::litter, -1, T::none, 0, P::none, A::always, event(S::bud_lost_early),
event(S::bud_with_surplus), 100, 25}),
spec({49, "adhesion", "Adhesion",
"Become a multicellular organism: the path to emerging into the world",
"Permanent: no more splits, one shared reserve, engulfed whole, heavier",
E::acquire_adhesion, T::none, 0, T::none, 0, P::none, A::adhesion_absent_after_buds,
event(S::bud_done), absence(S::bud_done, 15 * minute), 50}),
};
// The founder's value of a point-based trait over 100: one point in the trait's units.
std::uint64_t unit_of(T trait) noexcept {
const auto& f = primitive_founder_parameters;
switch (trait) {
case T::intake:
return f.ingestion / 100;
case T::energy_kept:
return f.energy_conversion / 100;
case T::light:
return photosynthesis_acquired_start / 100;
case T::membrane:
return founder_membrane_nanometres / 100;
case T::size:
return f.target_size / 100;
case T::bud_share:
return f.reproduction / 100;
default:
return 1; // Indices are points already; recipe and litter move in their own units.
}
}
std::optional<Capability> capability_of(T trait) noexcept {
switch (trait) {
case T::intake:
return Capability::ingestion;
case T::energy_kept:
return Capability::energy_conversion;
case T::light:
return Capability::photosynthesis;
case T::membrane:
return Capability::membrane;
case T::size:
return Capability::target_size;
case T::bud_share:
return Capability::reproduction;
default:
return std::nullopt;
}
}
// The trait's slot in the draft; null when absent (a capability the plan does not carry).
std::uint16_t* index_of(GenomeDraft& draft, T trait) noexcept {
if (!draft.movement_arrangement || !draft.cellular_traits)
return nullptr;
auto& a = *draft.movement_arrangement;
auto& t = *draft.cellular_traits;
switch (trait) {
case T::move_output:
return &a.output;
case T::move_efficiency:
return &a.efficiency;
case T::move_steering:
return &a.steering;
case T::move_streamlining:
return &a.streamlining;
case T::move_braking:
return &a.braking;
case T::move_coasting:
return &a.coasting;
case T::collect_energy:
return &t.collection[0];
case T::collect_carbon:
return &t.collection[1];
case T::collect_nitrogen:
return &t.collection[2];
case T::collect_phosphorus:
return &t.collection[3];
case T::collect_other:
return &t.collection[4];
case T::burn_carbon:
return &t.burn[0];
case T::burn_nitrogen:
return &t.burn[1];
case T::burn_phosphorus:
return &t.burn[2];
case T::burn_other:
return &t.burn[3];
case T::engulf_capacity:
return &t.engulf_capacity;
case T::kill_absorption:
return &t.kill_absorption;
case T::upkeep_efficiency:
return &t.upkeep_efficiency;
case T::growth_speed:
return &t.growth_speed;
case T::density:
return &t.density;
case T::litter:
return &t.litter;
default:
return nullptr;
}
}
// Moves one trait by `units` (its own units) in direction `sign`, within bounds. False when
// the trait is absent or the move would leave its bounds.
bool move(GenomeDraft& draft, T trait, std::int8_t sign, std::uint64_t units,
const CellularCatalogBounds& bounds) {
if (trait == T::none || sign == 0 || units == 0)
return trait == T::none || units == 0;
const auto unit = unit_of(trait);
const bool litter = trait == T::litter;
const auto lowest = litter ? 0 : std::uint64_t{bounds.min_points} * unit;
const auto highest =
litter ? std::uint64_t{bounds.max_litter} : std::uint64_t{bounds.max_points} * unit;
const auto step = litter ? units : units * unit;
const auto shifted = [&](std::uint64_t value) -> std::optional<std::uint64_t> {
if (sign > 0)
return value > highest || step > highest - value ? std::nullopt
: std::optional{value + step};
return value < lowest + step ? std::nullopt : std::optional{value - step};
};
if (const auto capability = capability_of(trait)) {
const auto record =
std::ranges::find(draft.capabilities, *capability, &CapabilityRecord::kind);
if (record == draft.capabilities.end())
return false;
const auto next = shifted(record->parameter);
const auto& limits =
(*capability_schema_for(draft.schema_version))[static_cast<std::size_t>(*capability)];
if (!next || *next < limits.minimum || *next > limits.maximum)
return false;
record->parameter = static_cast<std::uint32_t>(*next);
return true;
}
auto* slot = index_of(draft, trait);
if (slot == nullptr)
return false;
const auto next = shifted(*slot);
if (!next || *next > std::numeric_limits<std::uint16_t>::max())
return false;
*slot = static_cast<std::uint16_t>(*next);
return true;
}
} // namespace
std::span<const CellularMutationSpec> cellular_catalog() noexcept {
return catalog;
}
const CellularMutationSpec* cellular_mutation(std::uint16_t id) noexcept {
const auto found = std::ranges::find(catalog, id, &CellularMutationSpec::id);
return found == catalog.end() ? nullptr : &*found;
}
CellularMutationTuning cellular_default_tuning(const CellularMutationSpec& spec) noexcept {
CellularMutationTuning tuning{};
tuning.base_weight = spec.base_weight;
tuning.primary_step = spec.primary_step;
return tuning;
}
std::optional<GenomeDraft>
apply_cellular_mutation(const Genome& plan, const CellularMutationSpec& spec,
const CellularMutationTuning& tuning, const CellularCatalogBounds& bounds,
const CellularLineageProgress& progress, std::uint64_t successor_id,
std::uint64_t origin_event) {
if (plan.schema_version() < genome_schema_v7 || !plan.cellular_traits() ||
!plan.movement_arrangement() || !tuning.enabled)
return std::nullopt;
GenomeDraft draft;
draft.schema_version = plan.schema_version();
draft.id = successor_id;
draft.origin_event = origin_event;
draft.development_version = plan.development_version();
draft.parents = {plan.id()};
draft.capabilities.assign(plan.capabilities().begin(), plan.capabilities().end());
draft.movement_arrangement = plan.movement_arrangement();
draft.cellular_traits = plan.cellular_traits();
if (!draft.cellular_traits)
return std::nullopt;
auto& traits = *draft.cellular_traits;
const bool producer = plan.carries(Capability::photosynthesis);
switch (spec.available) {
case A::always:
break;
case A::light_absent_after_carbon:
if (producer || progress.carbon_burned < bounds.carbon_for_light)
return std::nullopt;
break;
case A::light_present:
if (!producer)
return std::nullopt;
break;
case A::adhesion_absent_after_buds:
if (traits.adhesion != 0 || progress.buds < bounds.buds_for_adhesion)
return std::nullopt;
break;
}
switch (spec.effect) {
case E::adjust:
if (!move(draft, spec.primary, spec.primary_sign, tuning.primary_step, bounds) ||
!move(draft, spec.paired, spec.paired_sign, tuning.paired_step, bounds))
return std::nullopt;
if (spec.spread != P::none) {
const auto group = spec.spread == P::burn
? std::array{T::burn_carbon, T::burn_nitrogen,
T::burn_phosphorus, T::burn_other}
: std::array{T::collect_carbon, T::collect_nitrogen,
T::collect_phosphorus, T::collect_other};
for (const auto other : group)
if (other != spec.primary &&
!move(draft, other, static_cast<std::int8_t>(-spec.primary_sign),
tuning.spread_step, bounds))
return std::nullopt;
}
break;
case E::recipe: {
auto& recipe = traits.recipe;
const auto own =
static_cast<std::size_t>(spec.primary) - static_cast<std::size_t>(T::recipe_carbon);
const auto step = tuning.primary_step;
if (own >= recipe.size() || recipe[own] < bounds.recipe_min_share + step)
return std::nullopt;
recipe[own] = static_cast<std::uint16_t>(recipe[own] - step);
// The other three share the step; the first of them takes the remainder.
auto share = step / 3;
auto remainder = step - share * 3;
for (std::size_t c = 0; c < recipe.size(); ++c) {
if (c == own)
continue;
recipe[c] = static_cast<std::uint16_t>(recipe[c] + share + remainder);
remainder = 0;
}
break;
}
case E::acquire_light:
if (producer)
return std::nullopt;
draft.capabilities.push_back(
{Capability::photosynthesis, photosynthesis_acquired_start, 0});
if (!move(draft, spec.paired, spec.paired_sign, tuning.paired_step, bounds))
return std::nullopt;
break;
case E::shed_light:
std::erase_if(draft.capabilities, [](const CapabilityRecord& record) {
return record.kind == Capability::photosynthesis;
});
break;
case E::acquire_adhesion:
traits.adhesion = 1;
break;
}
// The genome's own validation (ranges, prerequisites) decides the rest.
if (!Genome::create(draft))
return std::nullopt;
return draft;
}
} // namespace evo::biology
+118
View File
@@ -0,0 +1,118 @@
#include "evo/biology/cellular_offers.hpp"
#include <algorithm>
#include <numeric>
namespace evo::biology {
namespace {
// Weights above this keep every product below 2^63 (weights x 10^7 targets).
constexpr std::uint64_t max_weight = 1'000'000'000;
} // namespace
std::uint64_t cellular_offer_weight(std::uint32_t base_weight, std::int32_t score,
const CellularOfferRules& rules) noexcept {
std::int64_t multiplier = 1'000;
if (score > 0 && rules.score_max > 0)
multiplier += (static_cast<std::int64_t>(rules.max_multiplier_per_mille) - 1'000) *
std::min(score, rules.score_max) / rules.score_max;
if (score < 0 && rules.score_min < 0)
multiplier -= (1'000 - static_cast<std::int64_t>(rules.min_multiplier_per_mille)) *
std::max(score, rules.score_min) / rules.score_min;
multiplier = std::max<std::int64_t>(multiplier, 0);
return std::uint64_t{base_weight} * static_cast<std::uint64_t>(multiplier);
}
std::optional<std::vector<std::uint32_t>>
cellular_offer_chances(std::span<const std::uint64_t> weights, const CellularOfferRules& rules) {
const std::uint64_t m = weights.size();
const std::uint64_t target = std::uint64_t{rules.options} * cellular_chance_whole;
const std::uint64_t floor = rules.floor_ppm, cap = rules.cap_ppm;
if (m == 0 || rules.options == 0 || floor > cap || cap > cellular_chance_whole ||
m * floor > target || m * cap < target ||
std::ranges::any_of(weights, [](std::uint64_t w) { return w > max_weight; }))
return std::nullopt;
// Ascending by weight (stable on the given order): the lightest sit at the floor, the
// heaviest at the cap, and the middle share what is left in proportion to weight.
std::vector<std::size_t> order(weights.size());
std::iota(order.begin(), order.end(), 0);
std::ranges::stable_sort(order, {}, [&](std::size_t i) { return weights[i]; });
std::vector<std::uint64_t> prefix(m + 1, 0);
for (std::size_t i = 0; i < m; ++i)
prefix[i + 1] = prefix[i] + weights[order[i]];
for (std::uint64_t low = 0; low <= m; ++low) {
for (std::uint64_t high = 0; low + high <= m; ++high) {
const auto fixed = low * floor + high * cap;
const auto mid_begin = low, mid_end = m - high;
if (mid_begin == mid_end) {
if (fixed != target)
continue;
std::vector<std::uint32_t> chances(m);
for (std::size_t i = 0; i < m; ++i)
chances[order[i]] = static_cast<std::uint32_t>(i < low ? floor : cap);
return chances;
}
if (fixed > target)
continue;
const auto num = target - fixed; // <= 10^7 for at most 10 options.
const auto den = prefix[mid_end] - prefix[mid_begin];
if (den == 0)
continue;
// Middle within [floor, cap]; the floor group below it and the cap group above.
const auto w_first = weights[order[mid_begin]];
const auto w_last = weights[order[mid_end - 1]];
if (num * w_first < floor * den || num * w_last > cap * den)
continue;
if (low > 0 && num * weights[order[low - 1]] > floor * den)
continue;
if (high > 0 && num * weights[order[mid_end]] < cap * den)
continue;
std::vector<std::uint32_t> chances(m);
std::vector<std::uint64_t> remainder(m, 0);
std::uint64_t total = fixed;
for (std::size_t i = 0; i < m; ++i) {
if (i < low || i >= mid_end) {
chances[order[i]] = static_cast<std::uint32_t>(i < low ? floor : cap);
continue;
}
const auto product = num * weights[order[i]];
chances[order[i]] = static_cast<std::uint32_t>(product / den);
remainder[i] = product % den;
total += product / den;
}
// Rounding: the largest remainders (then the lighter order) take one ppm each.
std::vector<std::size_t> middle;
for (auto i = mid_begin; i < mid_end; ++i)
middle.push_back(static_cast<std::size_t>(i));
std::ranges::stable_sort(middle, std::ranges::greater{},
[&](std::size_t i) { return remainder[i]; });
for (std::size_t k = 0; total < target && k < middle.size(); ++k) {
auto& chance = chances[order[middle[k]]];
if (chance < cap) {
++chance;
++total;
}
}
if (total != target)
continue;
return chances;
}
}
return std::nullopt;
}
std::vector<std::size_t> cellular_systematic_draw(std::span<const std::uint32_t> chances,
std::uint32_t options, std::uint32_t u) noexcept {
std::vector<std::size_t> picked;
std::uint64_t point = u % cellular_chance_whole;
std::uint64_t cumulative = 0;
for (std::size_t i = 0; i < chances.size() && picked.size() < options; ++i) {
cumulative += chances[i];
// A chance of at most 100% can cover at most one point.
if (point < cumulative) {
picked.push_back(i);
point += cellular_chance_whole;
}
}
return picked;
}
} // namespace evo::biology
+152
View File
@@ -0,0 +1,152 @@
#include "evo/biology/cellular_triggers.hpp"
#include <algorithm>
#include <limits>
namespace evo::biology {
namespace {
// The smaller angle between two headings.
std::uint16_t deviation(std::uint16_t a, std::uint16_t b) noexcept {
const auto forward = static_cast<std::uint16_t>(a - b);
const auto back = static_cast<std::uint16_t>(b - a);
return std::min(forward, back);
}
std::uint64_t saturating_add(std::uint64_t a, std::uint64_t b) noexcept {
return b > std::numeric_limits<std::uint64_t>::max() - a
? std::numeric_limits<std::uint64_t>::max()
: a + b;
}
// a * 1000 >= b * k, exactly, for a, b below 2^54.
bool share_at_least(std::uint64_t part, std::uint64_t whole, std::uint32_t per_thousand) noexcept {
constexpr std::uint64_t limit = 1ULL << 54U;
if (part >= limit || whole >= limit) {
part >>= 10U;
whole >>= 10U;
}
return part * 1'000 >= whole * per_thousand;
}
} // namespace
bool cellular_trigger_tick(const CellularTriggerSpec& spec, std::uint32_t threshold,
CellularTriggerState& state, const CellularActivity& activity) noexcept {
const auto ticks = threshold != 0 ? threshold : spec.ticks;
const auto value = activity[spec.signal];
const bool present = value != 0;
switch (spec.kind) {
case CellularTriggerKind::accumulate:
if (present && ++state.first >= ticks) {
state.first = 0;
return true;
}
return false;
case CellularTriggerKind::absence:
state.first = present ? 0 : state.first + 1;
if (state.first >= ticks) {
state.first = 0;
return true;
}
return false;
case CellularTriggerKind::count:
// A window opens at the first counted event; `ticks` 0 keeps it open forever.
if (state.first != 0 && ticks != 0 && ++state.ticks >= ticks) {
state.first = 0;
state.ticks = 0;
}
if (present) {
if (state.first == 0)
state.ticks = 0;
if (++state.first >= spec.count) {
state.first = 0;
state.ticks = 0;
return true;
}
}
return false;
case CellularTriggerKind::event:
return present;
case CellularTriggerKind::share: {
state.first = saturating_add(state.first, value);
state.second = saturating_add(state.second, activity[spec.denominator]);
if (++state.ticks < ticks)
return false;
const bool fired =
state.second != 0 && share_at_least(state.first, state.second, spec.per_thousand);
state = {};
return fired;
}
case CellularTriggerKind::regular:
// A run starts at the signal and breaks after a gap longer than `gap`.
state.first = present ? 0 : state.first + 1;
if (present && state.running == 0) {
state.running = 1;
state.ticks = 0;
}
if (state.running == 0)
return false;
if (state.first > spec.gap) {
state.running = 0;
return false;
}
if (++state.ticks >= ticks) {
state.ticks = 0;
return true;
}
return false;
case CellularTriggerKind::straight:
if (!present)
return false;
if (state.running == 0 || deviation(activity.heading, state.heading) > spec.angle) {
state.running = 1;
state.heading = activity.heading;
state.first = 0;
}
if (++state.first >= ticks) {
state.first = 0;
return true;
}
return false;
case CellularTriggerKind::turns: {
if (state.running == 0) {
state.running = 1;
state.heading = activity.heading;
return false;
}
if (state.first != 0 && ++state.ticks >= ticks) {
state.first = 0;
state.ticks = 0;
}
if (deviation(activity.heading, state.heading) <= spec.angle)
return false;
state.heading = activity.heading;
if (state.first == 0)
state.ticks = 0;
if (++state.first >= spec.count) {
state.first = 0;
state.ticks = 0;
return true;
}
return false;
}
}
return false;
}
void cellular_affinity_tick(CellularAffinity& affinity, const CellularActivity& activity,
std::span<const CellularMutationTuning> tuning,
CellularScoreBounds bounds) noexcept {
const auto catalog = cellular_catalog();
for (std::size_t i = 0; i < catalog.size() && i < tuning.size(); ++i) {
const auto& t = tuning[i];
if (!t.enabled)
continue;
std::int32_t score = affinity.score[i];
if (cellular_trigger_tick(catalog[i].increase, t.increase_ticks, affinity.increase[i],
activity))
score += t.increase_points;
if (cellular_trigger_tick(catalog[i].decrease, t.decrease_ticks, affinity.decrease[i],
activity))
score -= t.decrease_points;
affinity.score[i] = static_cast<std::int16_t>(std::clamp(score, bounds.min, bounds.max));
}
}
} // namespace evo::biology