feat(cellular): rules 13 feeding, matter as energy, spent pool and predation
Foundation / checks (checks) (push) Successful in 5s
Foundation / checks (client) (push) Successful in 4s
Foundation / checks (ecs) (push) Successful in 4s
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 4m29s
Foundation / postgres-tools (push) Successful in 31s
Foundation / server-image (push) Successful in 4m24s
Foundation / image (push) Successful in 5m3s

Phase 2 of the cellular revamp build plan (ADR-0179), server half.

- Matter as energy: when an energy cost exceeds the reserve's energy, reserve
  matter stands in for the rest at each channel's burn rate (pJ per 1,000 fg,
  scaled by the genome's burn efficiency), largest channel first. Upkeep may
  burn any channel; thrust only channels the player has not excluded. Burned
  matter adds no heat; it goes to the region's spent pool. A cell dies only when
  nothing can pay its upkeep.
- Collection: per-channel limits scaled by the genome's collection indices, a
  shared limit on all matter, a tunable cost per membrane point, and only the
  genome's kept share (energy conversion) of bubble energy reaching the reserve.
- Predation: engulf mass carries a tunable share of reserve matter, the
  predator's engulf capacity scales its side and the prey's membrane (now in
  nanometres) its own; kill absorption scales the predator's intake; the kill's
  remainder is split between bubbles at the prey and the spent pool, and a full
  habitat sends overflow to the pool.
- The spent pool is owner format 11 state, counted in conservation, and drips
  back as seeded random bubbles every interval tick.
- Reserve matter is carried as load: slower thrust and turning, costlier thrust.
- Channel exclusions are a 4-bit step intent field, trace byte 14; only owned
  lives under rules 13 may send them.

All values come from the revamp tuning file. Rules up to 12 are unchanged. Tests
cover payments and their conservation over 400 seeds, the rules-13 region step
(collection, membrane, kept energy, burning, engulfment and kill splits with
closure), the drip, load, exclusions, a 700-tick run with closure and exact
restore, and trace replay with exclusions. Session v14 and the client follow
the server phases (build plan). 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:35:31 -04:00
co-authored by Claude Opus 5.5
parent c7b4846901
commit 76d21b4815
21 changed files with 1307 additions and 72 deletions
+96
View File
@@ -0,0 +1,96 @@
#include "evo/biology/cellular_burn.hpp"
#include <algorithm>
#include <limits>
namespace evo::biology {
namespace {
constexpr auto u64_max = std::numeric_limits<std::uint64_t>::max();
constexpr std::uint64_t kilo = 1'000;
bool burnable(const CellularBurn& burn, std::size_t channel, bool override_exclusions) noexcept {
return burn.pj_per_kfg[channel] != 0 &&
(override_exclusions || (burn.excluded & (1U << channel)) == 0);
}
// floor(mass * rate / 1000), saturating; exact while mass * rate fits.
std::uint64_t covered(std::uint64_t mass, std::uint64_t rate) noexcept {
const auto whole = mass / kilo;
const auto part = mass % kilo;
if (rate != 0 && whole > u64_max / rate)
return u64_max;
const auto head = whole * rate;
const auto tail = part * rate / kilo; // part < 1000 and rate < 2^54 in practice.
return tail > u64_max - head ? u64_max : head + tail;
}
// Smallest mass whose cover reaches `cost`: ceil(cost * 1000 / rate).
std::uint64_t needed(std::uint64_t cost, std::uint64_t rate) noexcept {
const auto whole = cost / rate;
const auto part = cost % rate;
if (whole > (u64_max - kilo) / kilo)
return u64_max;
return whole * kilo + (part * kilo + rate - 1) / rate;
}
} // namespace
CellularBurn
cellular_burn(const std::array<std::uint64_t, cellular_matter_channels>& base_pj_per_kfg,
const std::array<std::uint16_t, cellular_matter_channels>& efficiency,
std::uint8_t excluded) noexcept {
CellularBurn burn{};
for (std::size_t c = 0; c < cellular_matter_channels; ++c)
burn.pj_per_kfg[c] =
base_pj_per_kfg[c] > u64_max / 1'000 ? 0 : base_pj_per_kfg[c] * efficiency[c] / 100;
burn.excluded = static_cast<std::uint8_t>(excluded & 0x0FU);
return burn;
}
std::uint64_t cellular_payable_energy(const accounting::Inventory& reserve,
const CellularBurn& burn, bool override_exclusions) noexcept {
auto total = reserve.energy.value;
for (std::size_t c = 0; c < cellular_matter_channels; ++c) {
if (!burnable(burn, c, override_exclusions))
continue;
const auto cover = covered(reserve.matter[c].value, burn.pj_per_kfg[c]);
total = cover > u64_max - total ? u64_max : total + cover;
}
return total;
}
std::optional<CellularPayment> cellular_pay(accounting::Inventory& reserve, std::uint64_t cost,
const CellularBurn& burn,
bool override_exclusions) noexcept {
if (cellular_payable_energy(reserve, burn, override_exclusions) < cost)
return std::nullopt;
CellularPayment payment{};
payment.energy = std::min(cost, reserve.energy.value);
auto remaining = cost - payment.energy;
auto after = reserve;
after.energy.value -= payment.energy;
while (remaining != 0) {
// The largest burnable channel; ties go to the lower channel (C, N, P, O).
std::size_t pick = cellular_matter_channels;
for (std::size_t c = 0; c < cellular_matter_channels; ++c)
if (burnable(burn, c, override_exclusions) && after.matter[c].value != 0 &&
(pick == cellular_matter_channels ||
after.matter[c].value > after.matter[pick].value))
pick = c;
if (pick == cellular_matter_channels)
return std::nullopt; // Unreachable: payable energy covered the cost.
auto& mass = after.matter[pick].value;
const auto rate = burn.pj_per_kfg[pick];
const auto cover = covered(mass, rate);
if (cover >= remaining) {
const auto take = std::min(mass, needed(remaining, rate));
mass -= take;
payment.spent.matter[pick].value += take;
remaining = 0;
} else {
payment.spent.matter[pick].value += mass;
remaining -= cover;
mass = 0;
}
}
reserve = after;
return payment;
}
} // namespace evo::biology
+188 -9
View File
@@ -55,6 +55,60 @@ struct Deposit {
std::uint64_t& channel_of(accounting::Inventory& value, std::size_t channel) noexcept {
return channel == 0 ? value.energy.value : value.matter[channel - 1].value;
}
std::uint64_t value_of(const accounting::Inventory& value, std::size_t channel) noexcept {
return channel == 0 ? value.energy.value : value.matter[channel - 1].value;
}
std::uint64_t matter_of(const accounting::Inventory& value) noexcept {
std::uint64_t total{};
for (const auto& channel : value.matter)
total = channel.value > u64_max - total ? u64_max : total + channel.value;
return total;
}
// Rules 13: a life's per-tick collection limits: the budget's founder-composed limits scaled by
// its collection indices and its membrane, and the shared limit on all matter together.
struct Limits {
std::array<std::uint64_t, 5> channel{};
std::uint64_t shared{};
};
std::optional<Limits> revamp_limits(const CellularLifeStepInput& life,
const CellularRevampStepRules& rules) {
if (!life.revamp)
return std::nullopt;
const auto& own = *life.revamp;
const auto points = static_cast<std::int64_t>(own.membrane_nm / 10);
const auto mult = std::clamp<std::int64_t>(
1'000 - static_cast<std::int64_t>(rules.membrane_collection_per_mille_per_point) *
(points - 100),
100, 2'000);
Limits limits{};
std::uint64_t shared{};
for (std::size_t channel = 0; channel < limits.channel.size(); ++channel) {
const auto per_second = channel == 0 ? life.budget.intake_limit.energy.value
: life.budget.intake_limit.matter[channel - 1].value;
const auto base = accounting::per_tick(per_second, cellular_motion_tick_microseconds,
accounting::Rounding::down);
if (!base || *base > u64_max / 2'000)
return std::nullopt;
limits.channel.at(channel) = *base / 100 * own.collection.at(channel) +
*base % 100 * own.collection.at(channel) / 100;
if (limits.channel.at(channel) > u64_max / 2'000)
return std::nullopt;
limits.channel.at(channel) =
limits.channel.at(channel) * static_cast<std::uint64_t>(mult) / 1'000;
if (channel != 0)
shared += *base;
}
limits.shared = shared * static_cast<std::uint64_t>(mult) / 1'000;
return limits;
}
// Rules 13: engulf mass is the body plus the declared share of reserve matter.
std::uint64_t engulf_mass(const CellularLifeStepInput& life, const accounting::Inventory& reserve,
const CellularRevampStepRules& rules) noexcept {
const auto carried = matter_of(reserve) / 100 * rules.engulf_reserve_percent +
matter_of(reserve) % 100 * rules.engulf_reserve_percent / 100;
const auto body = life.budget.phenotype.total_mass;
return carried > u64_max - body ? u64_max : body + carried;
}
} // namespace
std::expected<CellularRegionStepCandidate, CellularRegionStepError>
@@ -84,6 +138,11 @@ propose_cellular_region_step(std::uint64_t begin_tick, CellularArea area,
if (rules.engulf_and_detritus && (life.membrane_um == 0 || life.source == 0 ||
(life.intent.engulf && life.intent.intake_target)))
return std::unexpected{CellularRegionStepError::invalid_intent};
// Rules 13: a revamp input for every life, only in a liquid contact-feeding region.
if (life.revamp.has_value() != rules.revamp.has_value() ||
(rules.revamp && (!liquid || !rules.contact_feeding || life.revamp->membrane_nm == 0 ||
life.revamp->energy_kept_per_thousand > 1'000)))
return std::unexpected{CellularRegionStepError::invalid_intent};
ordered.push_back(&life);
}
std::ranges::sort(ordered, {}, [](const auto* life) { return life->life_id; });
@@ -132,7 +191,8 @@ propose_cellular_region_step(std::uint64_t begin_tick, CellularArea area,
life->liquid
? propose_liquid_cellular_step(begin_tick, area, life->position, life->extent_um,
intent.movement, *life->liquid, life->reserve,
life->heat, life->budget)
life->heat, life->budget,
life->revamp ? &life->revamp->burn : nullptr)
: propose_cellular_step(begin_tick, area, life->position, life->extent_um, intent,
life->reserve, life->heat, life->budget, habitat);
if (!step && step.error() == CellularStepError::insufficient_maintenance) {
@@ -159,6 +219,8 @@ propose_cellular_region_step(std::uint64_t begin_tick, CellularArea area,
if (!step)
return std::unexpected{CellularRegionStepError::life_step};
auto result = *step;
if (!add(candidate.spent, result.spent))
return std::unexpected{CellularRegionStepError::overflow};
if (target) {
const auto index = habitat.find(*target);
if (!index) {
@@ -181,7 +243,60 @@ propose_cellular_region_step(std::uint64_t begin_tick, CellularArea area,
}
}
}
if (rules.contact_feeding) {
if (rules.contact_feeding && rules.revamp) {
// Rules 13: per-channel collection scaled by the genome and membrane, a shared limit
// on all matter, and only the kept share of bubble energy reaching the reserve.
const auto limits = revamp_limits(*life, *rules.revamp);
if (!limits)
return std::unexpected{CellularRegionStepError::overflow};
accounting::Inventory drained{}, acquired{};
std::optional<std::size_t> first;
for (std::size_t index = 0; index < patch_stock.size(); ++index) {
const auto& deposit = habitat.patches()[index];
if (!cellular_path_contact(life->position, result.position, life->extent_um,
deposit))
continue;
bool took = false;
for (std::size_t channel = 0; channel < limits->channel.size(); ++channel) {
auto& stock = channel_of(patch_stock[index], channel);
auto& taken = channel_of(drained, channel);
auto allowance = limits->channel.at(channel) - taken;
if (channel != 0) {
const auto matter = matter_of(drained);
allowance = std::min(allowance,
limits->shared > matter ? limits->shared - matter : 0);
}
if (deposit.kind == CellularDepositKind::pool)
allowance =
std::min(allowance, limits->channel.at(channel) *
cellular_pool_yield_per_thousand / 1000);
auto& reserve = channel_of(result.reserve_after, channel);
const auto take = std::min({stock, allowance, u64_max - reserve});
if (take == 0)
continue;
stock -= take;
taken += take;
auto kept = take;
if (channel == 0) {
kept = take / 1'000 * life->revamp->energy_kept_per_thousand +
take % 1'000 * life->revamp->energy_kept_per_thousand / 1'000;
if (!add(result.heat_after.energy.value, take - kept))
return std::unexpected{CellularRegionStepError::overflow};
}
reserve += kept;
channel_of(acquired, channel) += kept;
took = true;
}
if (took && !first)
first = index;
}
if (first) {
result.intake_status = CellularIntakeStatus::acquired;
result.intake = CellularPatchUptakeProposal{
habitat.patches()[*first].address,
{patch_stock[*first], result.reserve_after, acquired}};
}
} else if (rules.contact_feeding) {
// ADR-0136: drain every touched deposit (ascending address) up to the per-tick
// intake limit; a pool gives at most a quarter of that limit.
std::array<std::uint64_t, 5> limit{};
@@ -260,15 +375,26 @@ propose_cellular_region_step(std::uint64_t begin_tick, CellularArea area,
if (!cellular_footprints_contact(predator.candidate.position, hunter->extent_um,
prey_step.position, prey->extent_um))
continue;
if (!product_at_least(hunter->budget.phenotype.total_mass, 1'000,
prey->budget.phenotype.total_mass,
cellular_engulf_ratio_milli_per_membrane_um *
prey->membrane_um)) {
// Rules 13: engulf masses carry reserve matter, the predator's capacity scales
// its side and the prey's membrane (nanometres; 1,000 is the founder) its own.
const auto& revamp = rules.revamp;
const auto hunter_mass =
revamp ? engulf_mass(*hunter, predator.candidate.reserve_after, *revamp)
: hunter->budget.phenotype.total_mass;
const auto prey_mass = revamp ? engulf_mass(*prey, prey_step.reserve_after, *revamp)
: prey->budget.phenotype.total_mass;
const auto hunter_scale =
revamp ? std::uint64_t{hunter->revamp->engulf_capacity} * 10'000 : 1'000;
const auto prey_scale =
revamp ? std::uint64_t{revamp->engulf_ratio_milli} * prey->revamp->membrane_nm
: cellular_engulf_ratio_milli_per_membrane_um * prey->membrane_um;
const auto founder_scale = revamp
? std::uint64_t{revamp->engulf_ratio_milli} * 1'000
: cellular_engulf_ratio_milli_per_membrane_um;
if (!product_at_least(hunter_mass, hunter_scale, prey_mass, prey_scale)) {
membrane_blocked =
membrane_blocked ||
product_at_least(hunter->budget.phenotype.total_mass, 1'000,
prey->budget.phenotype.total_mass,
cellular_engulf_ratio_milli_per_membrane_um);
product_at_least(hunter_mass, hunter_scale, prey_mass, founder_scale);
predator.engulf = membrane_blocked ? CellularEngulfStatus::membrane_too_thick
: CellularEngulfStatus::prey_too_large;
continue;
@@ -292,6 +418,52 @@ propose_cellular_region_step(std::uint64_t begin_tick, CellularArea area,
? predator.candidate.intake->transfer.acquired
: accounting::Inventory{};
accounting::Inventory taken_in{};
if (revamp) {
// Rules 13: the collection limits scaled by kill absorption; only the kept
// share of the prey's energy reaches the reserve, the rest is heat.
const auto limits = revamp_limits(*hunter, *revamp);
if (!limits)
return std::unexpected{CellularRegionStepError::overflow};
for (std::size_t channel = 0; channel < 5; ++channel) {
const auto limit =
limits->channel.at(channel) / 100 * hunter->revamp->kill_absorption +
limits->channel.at(channel) % 100 * hunter->revamp->kill_absorption /
100;
const auto already = value_of(acquired, channel);
channel_of(taken_in, channel) = std::min(
value_of(whole, channel), limit > already ? limit - already : 0);
}
auto kept_in = taken_in;
kept_in.energy.value =
taken_in.energy.value / 1'000 * hunter->revamp->energy_kept_per_thousand +
taken_in.energy.value % 1'000 * hunter->revamp->energy_kept_per_thousand /
1'000;
if (!add(predator.candidate.heat_after.energy.value,
taken_in.energy.value - kept_in.energy.value) ||
!add(predator.candidate.reserve_after, kept_in))
return std::unexpected{CellularRegionStepError::overflow};
accounting::Inventory bubbles = whole;
accounting::Inventory spent{};
for (std::size_t channel = 0; channel < 5; ++channel) {
const auto rest = value_of(bubbles, channel) - value_of(taken_in, channel);
const auto left = rest / 1'000 * revamp->kill_bubble_per_thousand +
rest % 1'000 * revamp->kill_bubble_per_thousand / 1'000;
channel_of(bubbles, channel) = left;
channel_of(spent, channel) = rest - left;
}
if (!add(candidate.spent, spent))
return std::unexpected{CellularRegionStepError::overflow};
deposits.push_back({prey->life_id, prey->source, prey_step.position, bubbles,
prey->extent_um});
CellularCorpseCandidate eaten{prey->life_id, prey_step.position, {}};
eaten.cause = CellularDeathCause::engulfed;
eaten.predator_id = hunter->life_id;
candidate.starved.push_back(eaten);
predator.engulf = CellularEngulfStatus::engulfed;
predator.prey_id = prey->life_id;
taken[q] = true;
break;
}
const auto energy_room =
remaining(hunter->budget.intake_limit.energy.value, acquired.energy.value);
if (!energy_room)
@@ -380,6 +552,13 @@ propose_cellular_region_step(std::uint64_t begin_tick, CellularArea area,
}
}
deposits = std::move(overflow); // A full habitat: the nearest deposit takes it.
if (rules.revamp) {
// Rules 13: the spent pool takes it instead, so it seeps back elsewhere.
for (const auto& deposit : deposits)
if (!add(candidate.spent, deposit.inventory))
return std::unexpected{CellularRegionStepError::overflow};
deposits.clear();
}
}
for (const auto& deposit : deposits) {
const auto address = cell_of(deposit.position);
+29
View File
@@ -10,11 +10,35 @@ struct Field {
std::int64_t minimum, maximum;
};
constexpr std::int64_t rate_limit = 1'000'000'000'000; // pJ per 1,000 fg.
constexpr std::int64_t amount_limit = 1'000'000'000'000'000'000; // pJ or fg per bubble.
// Schema order is the canonical encoding order.
constexpr std::array fields{
Field{"tuning.version", &CellularRevampTuning::version, 1, 1'000},
Field{"body.essential_upkeep_per_mille", &CellularRevampTuning::body_essential_upkeep_per_mille,
0, 1'000},
Field{"body.reserve_load_per_mille", &CellularRevampTuning::body_reserve_load_per_mille, 0,
1'000},
Field{"energy.burn_carbon_pj_per_kfg", &CellularRevampTuning::energy_burn_carbon_pj_per_kfg, 0,
rate_limit},
Field{"energy.burn_nitrogen_pj_per_kfg", &CellularRevampTuning::energy_burn_nitrogen_pj_per_kfg,
0, rate_limit},
Field{"energy.burn_phosphorus_pj_per_kfg",
&CellularRevampTuning::energy_burn_phosphorus_pj_per_kfg, 0, rate_limit},
Field{"energy.burn_other_pj_per_kfg", &CellularRevampTuning::energy_burn_other_pj_per_kfg, 0,
rate_limit},
Field{"feeding.membrane_collection_per_mille_per_point",
&CellularRevampTuning::feeding_membrane_collection_per_mille_per_point, 0, 1'000},
Field{"predation.engulf_ratio_milli", &CellularRevampTuning::predation_engulf_ratio_milli, 1,
1'000'000},
Field{"predation.engulf_reserve_percent",
&CellularRevampTuning::predation_engulf_reserve_percent, 0, 100},
Field{"predation.kill_bubble_per_mille", &CellularRevampTuning::predation_kill_bubble_per_mille,
0, 1'000},
Field{"spent.drip_interval_ticks", &CellularRevampTuning::spent_drip_interval_ticks, 0, 72'000},
Field{"spent.drip_bubble_pj", &CellularRevampTuning::spent_drip_bubble_pj, 0, amount_limit},
Field{"spent.drip_bubble_fg", &CellularRevampTuning::spent_drip_bubble_fg, 0, amount_limit},
};
CellularTuningError error(CellularTuningErrorKind kind, std::size_t line, std::string_view key) {
@@ -53,6 +77,11 @@ parse_cellular_revamp_tuning(std::string_view text) {
if (tuning.version != cellular_revamp_tuning_version)
return std::unexpected{
error(CellularTuningErrorKind::unsupported_version, 0, "tuning.version")};
// A drip needs a bubble size on both kinds of channel.
if (tuning.spent_drip_interval_ticks != 0 &&
(tuning.spent_drip_bubble_pj == 0 || tuning.spent_drip_bubble_fg == 0))
return std::unexpected{
error(CellularTuningErrorKind::inconsistent, 0, "spent.drip_interval_ticks")};
return tuning;
}
+27 -12
View File
@@ -97,11 +97,10 @@ propose_cellular_step(std::uint64_t begin_tick, CellularArea area, CellularPosit
return candidate;
}
std::expected<CellularStepCandidate, CellularStepError>
propose_liquid_cellular_step(std::uint64_t begin_tick, CellularArea area, CellularPosition position,
std::uint32_t extent_um, CellularIntent movement,
const CellularLiquidInput& liquid, accounting::Inventory reserve,
accounting::Inventory heat, const MetabolicBudget& budget) noexcept {
std::expected<CellularStepCandidate, CellularStepError> propose_liquid_cellular_step(
std::uint64_t begin_tick, CellularArea area, CellularPosition position, std::uint32_t extent_um,
CellularIntent movement, const CellularLiquidInput& liquid, accounting::Inventory reserve,
accounting::Inventory heat, const MetabolicBudget& budget, const CellularBurn* burn) noexcept {
if (begin_tick == std::numeric_limits<std::uint64_t>::max())
return std::unexpected{CellularStepError::invalid_tick};
if (budget.rate_microseconds != rate_period_microseconds)
@@ -110,20 +109,35 @@ propose_liquid_cellular_step(std::uint64_t begin_tick, CellularArea area, Cellul
budget.maintenance.value, cellular_motion_tick_microseconds, accounting::Rounding::up);
if (!maintenance)
return std::unexpected{CellularStepError::overflow};
if (reserve.energy.value < *maintenance)
accounting::Inventory spent{};
// Energy goes to heat; matter standing in for it goes to the spent pool (rules 13).
const auto pay = [&](std::uint64_t cost, bool upkeep) {
if (burn == nullptr) {
if (reserve.energy.value < cost)
return false;
reserve.energy.value -= cost;
return credit_heat(heat, cost);
}
const auto paid = cellular_pay(reserve, cost, *burn, upkeep);
if (!paid)
return false;
for (std::size_t c = 0; c < spent.matter.size(); ++c)
spent.matter[c].value += paid->spent.matter[c].value;
return credit_heat(heat, paid->energy);
};
if (!pay(*maintenance, true))
return std::unexpected{CellularStepError::insufficient_maintenance};
if (!credit_heat(heat, *maintenance))
return std::unexpected{CellularStepError::overflow};
reserve.energy.value -= *maintenance;
// Thrust may draw on unexcluded matter too, but never on excluded matter.
const accounting::Picojoules offered{
burn == nullptr ? reserve.energy.value : cellular_payable_energy(reserve, *burn, false)};
const auto motion =
step_cellular_kinematics(area, position, extent_um, liquid.motion, {movement, liquid.brake},
liquid.handling, liquid.flow, reserve.energy);
liquid.handling, liquid.flow, offered);
if (!motion)
return std::unexpected{CellularStepError::motion};
if (!credit_heat(heat, motion->cost.value))
if (!pay(motion->cost.value, false))
return std::unexpected{CellularStepError::overflow};
reserve.energy.value -= motion->cost.value;
CellularStepCandidate candidate{};
candidate.begin_tick = begin_tick;
@@ -135,6 +149,7 @@ propose_liquid_cellular_step(std::uint64_t begin_tick, CellularArea area, Cellul
candidate.movement_cost = motion->cost;
candidate.motion = motion->state;
candidate.path_um = motion->path_um;
candidate.spent = spent;
switch (motion->thrust) {
case CellularThrustStatus::idle:
candidate.movement_status = CellularMovementStatus::not_requested;
+7 -3
View File
@@ -57,7 +57,8 @@ bool valid_intent(const CellularLifeIntent& life) {
step.movement.y <= movement_limit && !(step.engulf && step.intake_target) &&
!(step.bud && (step.intake_target || step.engulf)) &&
!(step.frozen && (step.movement != biology::CellularIntent{} || step.intake_target ||
step.engulf || step.bud || step.brake));
step.engulf || step.bud || step.brake || step.exclude != 0)) &&
step.exclude <= 0x0F;
}
bool valid_ticks(std::span<const CellularTickIntents> ticks) {
std::set<std::uint64_t> identities;
@@ -167,7 +168,9 @@ void put_intent(std::vector<std::uint8_t>& out, const CellularLifeIntent& life)
// player action records keep it zero: the trace alone carries a brake.
out.push_back(
static_cast<std::uint8_t>((life.intent.frozen ? 1U : 0U) | (life.intent.brake ? 2U : 0U)));
put(out, 0, 2);
// Byte 14 (rules 13): kept matter channels, bits 0-3; byte 15 stays zero.
out.push_back(life.intent.exclude);
out.push_back(0);
put(out, life.intent.intake_target ? life.intent.intake_target->x_um : 0, 4);
put(out, life.intent.intake_target ? life.intent.intake_target->y_um : 0, 4);
}
@@ -305,7 +308,7 @@ decode_cellular_batch(std::span<const std::uint8_t> bytes) {
step.lives.reserve(static_cast<std::size_t>(count));
for (std::uint64_t i = 0; i < count; ++i) {
const auto record = bytes.subspan(offset, cellular_batch_intent_bytes);
if (record[12] > 3 || record[13] > 3 || !all_zero(record.subspan(14, 2)))
if (record[12] > 3 || record[13] > 3 || record[14] > 0x0F || record[15] != 0)
return std::unexpected{CellularBatchError::format};
CellularLifeIntent life;
life.life_id = get(record, 0, 8);
@@ -324,6 +327,7 @@ decode_cellular_batch(std::span<const std::uint8_t> bytes) {
life.intent.bud = record[12] == 3; // ADR-0125.
life.intent.frozen = (record[13] & 1U) != 0; // ADR-0128.
life.intent.brake = (record[13] & 2U) != 0; // Rules 12; owners below refuse it.
life.intent.exclude = record[14]; // Rules 13; owners below refuse it.
if (!valid_intent(life) ||
(!step.lives.empty() && step.lives.back().life_id >= life.life_id))
return std::unexpected{CellularBatchError::format};
+112 -26
View File
@@ -52,9 +52,13 @@ constexpr std::size_t cellular_lives_v9_header_bytes = cellular_lives_v8_header_
// its motion state (two velocities, heading, reserved, two carries), 20 bytes.
constexpr std::size_t cellular_lives_v10_header_bytes = cellular_lives_v9_header_bytes + 88;
constexpr std::size_t cellular_life_motion_bytes = 20;
// Format 11 (rules 13, ADR-0179): the revamp rules, so far the essential upkeep share (4) and a
// reserved zero (4). Later build phases extend this block before format 11 is deployed.
constexpr std::size_t cellular_lives_v11_header_bytes = cellular_lives_v10_header_bytes + 8;
// Format 11 (rules 13, ADR-0179): the revamp rules and the spent pool. Essential upkeep share and
// a reserved zero (8), four burn rates (32), membrane collection cost, engulf ratio, engulf
// reserve share and kill bubble share (16), drip interval and a reserved zero (8), drip bubble
// energy and matter (16), and the spent pool (40): 120 bytes. The word after the drip interval
// is the reserve load share. Later build phases extend this
// block before format 11 is deployed.
constexpr std::size_t cellular_lives_v11_header_bytes = cellular_lives_v10_header_bytes + 120;
bool valid_motion(const biology::CellularMotionState& m) noexcept {
constexpr std::int64_t carry = biology::cellular_velocity_q10_per_um_s * 1'000'000;
@@ -395,7 +399,8 @@ validate_state(std::uint64_t world, std::uint64_t region, std::uint64_t frame,
accounting::Inventory opening_total, bool detritus_rules = false,
bool bud_rules = false, std::uint64_t next_bud_sequence = 1,
bool presence_rules = false, const CellularBoundaryLedger* boundary = nullptr,
const std::vector<CellularOffspringRevision>* plans = nullptr) {
const std::vector<CellularOffspringRevision>* plans = nullptr,
const accounting::Inventory& spent = {}) {
// A bud's identity lies in this region's namespace below the next sequence; anything
// else is an allocated identity, below the namespace (ADR-0125).
const auto bud_identity = [&](std::uint64_t identity) noexcept {
@@ -568,9 +573,12 @@ validate_state(std::uint64_t world, std::uint64_t region, std::uint64_t frame,
if (plans && !validate_plans(lives, corpses, archive, *plans, config.tick))
return std::unexpected{CellularLivesError::invalid_life};
const auto current = sum_state(nursery, heat, habitat, lives, corpses);
auto current = sum_state(nursery, heat, habitat, lives, corpses);
if (!current)
return std::unexpected{current.error()};
// Rules 13: the spent pool is region stock until it drips back.
if (!add_inventory(*current, spent))
return std::unexpected{CellularLivesError::overflow};
auto expected = opening_total;
if (boundary) {
accounting::Inventory credit{}, debit{};
@@ -616,6 +624,7 @@ struct CellularLives::State {
accounting::Picojoules captured{}; // Format 9: light credited to reserves so far.
CellularLiquidRules liquid{}; // Format 10 (rules 12).
CellularRevampRules revamp{}; // Format 11 (rules 13).
accounting::Inventory spent{}; // Format 11: matter and energy waiting to drip back.
std::shared_ptr<const biology::CellularFlowField> field; // Generated from `liquid`.
State(std::uint64_t world_id, std::uint64_t region_id, std::uint64_t frame_id,
@@ -812,10 +821,11 @@ CellularLives::migration_replacement(std::vector<CellularOwnedLife> living,
state_->region, state_->frame);
if (!habitat)
return std::unexpected(CellularLivesError::habitat);
const auto total = validate_state(state_->world, state_->region, state_->frame, state_->config,
state_->nursery_config, **habitat, living, state_->corpses,
archive, state_->nursery, state_->heat, state_->opening_total,
true, true, state_->next_bud_sequence, true, &boundary);
const auto total =
validate_state(state_->world, state_->region, state_->frame, state_->config,
state_->nursery_config, **habitat, living, state_->corpses, archive,
state_->nursery, state_->heat, state_->opening_total, true, true,
state_->next_bud_sequence, true, &boundary, nullptr, state_->spent);
if (!total)
return std::unexpected(total.error());
auto replacement = std::unique_ptr<CellularLives>{new CellularLives{std::make_unique<State>(
@@ -877,13 +887,13 @@ CellularLives::exchange_boundary(std::span<const biology::CellularPatch> deposit
habitat = std::move(*created);
}
const auto rules = state_->rules_version;
const auto total =
validate_state(state_->world, state_->region, state_->frame, state_->config,
state_->nursery_config, *habitat, state_->lives, state_->corpses,
state_->archive, state_->nursery, heat, state_->opening_total,
rules >= cellular_lives_engulf_rules, rules >= cellular_lives_bud_rules,
state_->next_bud_sequence, rules >= cellular_lives_presence_rules, &boundary,
cellular_retained_plans(rules) ? &state_->offspring_revisions : nullptr);
const auto total = validate_state(
state_->world, state_->region, state_->frame, state_->config, state_->nursery_config,
*habitat, state_->lives, state_->corpses, state_->archive, state_->nursery, heat,
state_->opening_total, rules >= cellular_lives_engulf_rules,
rules >= cellular_lives_bud_rules, state_->next_bud_sequence,
rules >= cellular_lives_presence_rules, &boundary,
cellular_retained_plans(rules) ? &state_->offspring_revisions : nullptr, state_->spent);
if (!total)
return std::unexpected(total.error());
BoundarySavepoint savepoint{std::move(state_->habitat), state_->heat, state_->current_total,
@@ -1152,8 +1162,20 @@ std::vector<std::uint8_t> CellularLives::snapshot() const {
out.put(cost == 1'000 ? 0 : cost, 4);
}
if (revamp) {
out.put(state_->revamp.body.essential_upkeep_per_thousand, 4);
const auto& r = state_->revamp;
out.put(r.body.essential_upkeep_per_thousand, 4);
out.put(0, 4);
for (const auto rate : r.burn_pj_per_kfg)
out.put(rate);
out.put(r.step.membrane_collection_per_mille_per_point, 4);
out.put(r.step.engulf_ratio_milli, 4);
out.put(r.step.engulf_reserve_percent, 4);
out.put(r.step.kill_bubble_per_thousand, 4);
out.put(r.drip_interval_ticks, 4);
out.put(r.reserve_load_per_thousand, 4);
out.put(r.drip_bubble_pj);
out.put(r.drip_bubble_fg);
out.inventory(state_->spent);
}
for (const auto site : state_->nursery_config.sites)
out.site(site);
@@ -1469,7 +1491,8 @@ CellularLives::birth_candidate(LifeRequest request, LifeAllocation allocation) c
state_->rules_version >= cellular_lives_presence_rules,
state_->format_version >= cellular_lives_migration_format ? &state_->boundary : nullptr,
state_->format_version >= cellular_lives_inheritance_format ? &state_->offspring_revisions
: nullptr);
: nullptr,
state_->spent);
if (!current)
return std::unexpected{current.error()};
@@ -1486,6 +1509,7 @@ CellularLives::birth_candidate(LifeRequest request, LifeAllocation allocation) c
candidate->state_->liquid = state_->liquid;
candidate->state_->field = state_->field;
candidate->state_->revamp = state_->revamp;
candidate->state_->spent = state_->spent;
return candidate;
}
@@ -1660,9 +1684,23 @@ CellularLives::restore(std::span<const std::uint8_t> bytes, std::uint64_t world,
field = std::move(*generated);
}
CellularRevampRules revamp{};
accounting::Inventory spent{};
if (revamp_version) {
revamp.body.essential_upkeep_per_thousand = static_cast<std::uint32_t>(in.get(4));
if (in.get(4) != 0 || !cellular_revamp_valid(revamp))
const auto u32 = [&in] { return static_cast<std::uint32_t>(in.get(4)); };
revamp.body.essential_upkeep_per_thousand = u32();
const auto reserved = in.get(4);
for (auto& rate : revamp.burn_pj_per_kfg)
rate = in.get();
revamp.step.membrane_collection_per_mille_per_point = u32();
revamp.step.engulf_ratio_milli = u32();
revamp.step.engulf_reserve_percent = u32();
revamp.step.kill_bubble_per_thousand = u32();
revamp.drip_interval_ticks = u32();
revamp.reserve_load_per_thousand = u32();
revamp.drip_bubble_pj = in.get();
revamp.drip_bubble_fg = in.get();
spent = in.inventory();
if (reserved != 0 || !cellular_revamp_valid(revamp))
return std::unexpected{CellularLivesError::format};
}
const auto life_bytes = liquid_version ? cellular_life_v6_bytes + 8 + cellular_life_motion_bytes
@@ -1886,7 +1924,7 @@ CellularLives::restore(std::span<const std::uint8_t> bytes, std::uint64_t world,
saved_world, saved_region, saved_frame, config, nursery_config, **habitat, lives, corpses,
*archive, nursery, heat, opening_total, engulf_version, bud_version, next_bud_sequence,
presence_version, migration_version ? &boundary : nullptr,
inheritance_version ? &plan_history : nullptr);
inheritance_version ? &plan_history : nullptr, spent);
if (!current)
return std::unexpected{current.error()};
@@ -1901,6 +1939,7 @@ CellularLives::restore(std::span<const std::uint8_t> bytes, std::uint64_t world,
restored->state_->liquid = liquid;
restored->state_->field = std::move(field);
restored->state_->revamp = revamp;
restored->state_->spent = spent;
if (!std::ranges::equal(bytes, restored->snapshot()))
return std::unexpected{CellularLivesError::noncanonical};
return restored;
@@ -1938,6 +1977,7 @@ CellularLives::advance_tick_with_mutations(std::span<const CellularLifeIntent> i
const bool presence_rules = state_->rules_version >= cellular_lives_presence_rules;
const bool inheritance_rules = cellular_retained_plans(state_->rules_version);
const bool liquid_rules = state_->rules_version >= cellular_lives_liquid_rules;
const bool revamp_rules = state_->rules_version >= cellular_lives_revamp_rules;
if (liquid_rules && !state_->field)
return std::unexpected{CellularLivesError::invalid_config};
for (std::size_t i = 0; i < ordered.size(); ++i) {
@@ -1953,6 +1993,10 @@ CellularLives::advance_tick_with_mutations(std::span<const CellularLifeIntent> i
return std::unexpected{CellularLivesError::invalid_intents};
if (intent.brake && !liquid_rules)
return std::unexpected{CellularLivesError::invalid_intents};
// Rules 13: exclusions are an owned life's setting, never wildlife's or a frozen cell's.
if (intent.exclude != 0 && (!revamp_rules || intent.exclude > 0x0F || intent.frozen ||
state_->lives[i].account == LifeAccount{}))
return std::unexpected{CellularLivesError::invalid_intents};
}
for (std::size_t i = 0; i < selections.size(); ++i) {
const auto& selection = selections[i];
@@ -2018,18 +2062,50 @@ CellularLives::advance_tick_with_mutations(std::span<const CellularLifeIntent> i
*membrane,
life.source});
if (liquid_rules) {
const auto handling = cellular_liquid_handling(*genome, *budget, state_->liquid);
auto handling = cellular_liquid_handling(*genome, *budget, state_->liquid);
if (!handling)
return std::unexpected{CellularLivesError::biology};
if (revamp_rules) {
// Rules 13: reserve matter is carried as load.
std::uint64_t carried{};
for (const auto& channel : life.reserve.matter)
carried += channel.value;
*handling = cellular_loaded_handling(*handling, budget->phenotype.total_mass,
carried, state_->revamp);
}
inputs.back().liquid = biology::CellularLiquidInput{
life.motion, *handling,
state_->field->at_footprint(life.position, budget->phenotype.extent),
ordered[i].intent.brake};
}
if (revamp_rules) {
// Rules 13: the genome's traits; a life from before the upgrade (no traits, the
// membrane in micrometres) feeds and burns as a founder and keeps all bubble energy.
biology::CellularRevampLifeInput revamp{};
const auto& traits = genome->cellular_traits();
const auto kept = genome->parameter(biology::Capability::energy_conversion);
if (traits) {
revamp.burn = biology::cellular_burn(state_->revamp.burn_pj_per_kfg, traits->burn,
ordered[i].intent.exclude);
revamp.collection = traits->collection;
revamp.energy_kept_per_thousand = kept ? *kept : 1'000;
revamp.membrane_nm = *membrane;
revamp.engulf_capacity = traits->engulf_capacity;
revamp.kill_absorption = traits->kill_absorption;
} else {
revamp.burn =
biology::cellular_burn(state_->revamp.burn_pj_per_kfg, {100, 100, 100, 100},
ordered[i].intent.exclude);
revamp.membrane_nm = *membrane * 1'000;
}
inputs.back().revamp = revamp;
}
}
auto proposal =
biology::propose_cellular_region_step(state_->config.tick, state_->config.area, inputs,
*state_->habitat, {engulf_rules, contact_rules});
biology::CellularRegionRules region_rules{engulf_rules, contact_rules};
if (revamp_rules)
region_rules.revamp = state_->revamp.step;
auto proposal = biology::propose_cellular_region_step(state_->config.tick, state_->config.area,
inputs, *state_->habitat, region_rules);
if (!proposal)
return std::unexpected{CellularLivesError::region_step};
@@ -2038,6 +2114,9 @@ CellularLives::advance_tick_with_mutations(std::span<const CellularLifeIntent> i
auto next_archive = state_->archive;
auto next_offspring_revisions = state_->offspring_revisions;
auto next_heat = state_->heat;
auto next_spent = state_->spent;
if (!add_inventory(next_spent, proposal->spent))
return std::unexpected{CellularLivesError::overflow};
auto habitat_config = state_->habitat->config();
for (const auto& result : proposal->lives) {
const auto found = std::ranges::lower_bound(
@@ -2428,6 +2507,11 @@ CellularLives::advance_tick_with_mutations(std::span<const CellularLifeIntent> i
}
habitat_config.patches.insert(at, made);
}
// Rules 13: the spent pool drips back as bubbles at seeded random spots.
if (revamp_rules &&
!cellular_drip_spent(habitat_config, next_spent, state_->revamp, state_->world,
state_->region, proposal->end_tick, state_->nursery_config.source))
return std::unexpected{CellularLivesError::overflow};
if (deposits)
std::erase_if(habitat_config.patches, [](const biology::CellularPatch& patch) {
return patch.stock == accounting::Inventory{};
@@ -2466,7 +2550,7 @@ CellularLives::advance_tick_with_mutations(std::span<const CellularLifeIntent> i
state_->nursery, next_heat, state_->opening_total, engulf_rules, bud_rules,
next_bud_sequence, presence_rules,
state_->format_version >= cellular_lives_migration_format ? &state_->boundary : nullptr,
inheritance_rules ? &next_offspring_revisions : nullptr);
inheritance_rules ? &next_offspring_revisions : nullptr, next_spent);
if (!total)
return std::unexpected{total.error()};
@@ -2483,6 +2567,8 @@ CellularLives::advance_tick_with_mutations(std::span<const CellularLifeIntent> i
next->captured = state_->captured;
next->liquid = state_->liquid;
next->field = state_->field;
next->revamp = state_->revamp;
next->spent = next_spent;
// ADR-0175: light, from this tick's own intentions, credited to every active,
// unfrozen photosynthetic survivor's reserve and to the boundary inflow together.
std::vector<std::pair<std::uint64_t, std::uint64_t>> lit_lives;
+99 -3
View File
@@ -1,12 +1,108 @@
#include "evo/server/lifecycle/cellular_revamp.hpp"
#include "evo/core/random.hpp"
#include <algorithm>
#include <limits>
namespace evo::server {
bool cellular_revamp_valid(const CellularRevampRules& rules) noexcept {
return rules.body.essential_upkeep_per_thousand <= 1'000;
constexpr std::uint64_t most = 1'000'000'000'000'000ULL;
const auto& step = rules.step;
for (const auto rate : rules.burn_pj_per_kfg)
if (rate > 1'000'000'000'000ULL)
return false;
return rules.body.essential_upkeep_per_thousand <= 1'000 &&
step.membrane_collection_per_mille_per_point <= 1'000 && step.engulf_ratio_milli >= 1 &&
step.engulf_ratio_milli <= 1'000'000 && step.engulf_reserve_percent <= 100 &&
step.kill_bubble_per_thousand <= 1'000 && rules.drip_interval_ticks <= 72'000 &&
rules.drip_bubble_pj <= most && rules.drip_bubble_fg <= most &&
(rules.drip_interval_ticks == 0 ||
(rules.drip_bubble_pj != 0 && rules.drip_bubble_fg != 0)) &&
rules.reserve_load_per_thousand <= 1'000;
}
biology::CellularHandling cellular_loaded_handling(const biology::CellularHandling& handling,
std::uint64_t body_mass, std::uint64_t carried,
const CellularRevampRules& rules) noexcept {
// Masses stay far below 2^40 fg, so these products fit in 64 bits.
const auto load = carried / 1'000 * rules.reserve_load_per_thousand +
carried % 1'000 * rules.reserve_load_per_thousand / 1'000;
if (load == 0 || body_mass == 0 || body_mass > (1ULL << 40U) || load > (1ULL << 40U))
return handling;
const auto total = body_mass + load;
const auto slower = [&](std::uint64_t value) { return value * body_mass / total; };
const auto dearer = [&](std::uint64_t value) {
return value > (1ULL << 23U) ? value / body_mass * total
: (value * total + body_mass - 1) / body_mass;
};
auto loaded = handling;
loaded.thrust_q10 = static_cast<std::uint32_t>(slower(handling.thrust_q10));
loaded.reverse_thrust_q10 = static_cast<std::uint32_t>(slower(handling.reverse_thrust_q10));
loaded.turn = static_cast<std::uint16_t>(slower(handling.turn));
loaded.thrust_cost.value = dearer(handling.thrust_cost.value);
loaded.reverse_cost.value = dearer(handling.reverse_cost.value);
return loaded;
}
bool cellular_drip_spent(biology::CellularHabitatConfig& config, accounting::Inventory& spent,
const CellularRevampRules& rules, std::uint64_t world,
std::uint64_t region, std::uint64_t tick, std::uint64_t source) {
if (rules.drip_interval_ticks == 0 || tick % rules.drip_interval_ticks != 0)
return true;
Random random{world * 0x9e3779b97f4a7c15ULL ^ region * 0xc2b2ae3d27d4eb4fULL ^ tick};
const auto by_address = [](const biology::CellularPatch& patch) { return patch.address; };
for (std::size_t channel = 0; channel < 5; ++channel) {
auto& pool = channel == 0 ? spent.energy.value : spent.matter[channel - 1].value;
const auto cap = channel == 0 ? rules.drip_bubble_pj : rules.drip_bubble_fg;
// Both draws happen for every channel, so a channel's spot never depends on another's.
const auto x = random.next();
const auto y = random.next();
if (pool == 0 || config.patches.size() >= biology::max_cellular_liquid_deposits)
continue;
biology::CellularPatchAddress address{static_cast<std::uint32_t>(x % config.width_um),
static_cast<std::uint32_t>(y % config.height_um)};
auto at = std::ranges::lower_bound(config.patches, address, {}, by_address);
while (at != config.patches.end() && at->address == address) {
address.x_um = address.x_um + 1 < config.width_um ? address.x_um + 1 : 0;
at = std::ranges::lower_bound(config.patches, address, {}, by_address);
}
if (config.next_deposit == std::numeric_limits<std::uint32_t>::max())
return false;
const auto amount = std::min(pool, cap);
biology::CellularPatch bubble{address,
source,
{},
config.next_deposit++,
biology::cellular_mote_radius_um,
biology::CellularDepositKind::mote};
bubble.merged = 1;
if (channel == 0)
bubble.stock.energy.value = amount;
else
bubble.stock.matter[channel - 1].value = amount;
pool -= amount;
config.patches.insert(at, bubble);
}
return true;
}
CellularRevampRules cellular_revamp_rules(const biology::CellularRevampTuning& t) {
return {.body = {.essential_upkeep_per_thousand =
static_cast<std::uint32_t>(t.body_essential_upkeep_per_mille)}};
const auto u32 = [](std::int64_t value) { return static_cast<std::uint32_t>(value); };
const auto u64 = [](std::int64_t value) { return static_cast<std::uint64_t>(value); };
return {.body = {.essential_upkeep_per_thousand = u32(t.body_essential_upkeep_per_mille)},
.burn_pj_per_kfg = {u64(t.energy_burn_carbon_pj_per_kfg),
u64(t.energy_burn_nitrogen_pj_per_kfg),
u64(t.energy_burn_phosphorus_pj_per_kfg),
u64(t.energy_burn_other_pj_per_kfg)},
.step = {.membrane_collection_per_mille_per_point =
u32(t.feeding_membrane_collection_per_mille_per_point),
.engulf_ratio_milli = u32(t.predation_engulf_ratio_milli),
.engulf_reserve_percent = u32(t.predation_engulf_reserve_percent),
.kill_bubble_per_thousand = u32(t.predation_kill_bubble_per_mille)},
.drip_interval_ticks = u32(t.spent_drip_interval_ticks),
.drip_bubble_pj = u64(t.spent_drip_bubble_pj),
.drip_bubble_fg = u64(t.spent_drip_bubble_fg),
.reserve_load_per_thousand = u32(t.body_reserve_load_per_mille)};
}
} // namespace evo::server