Files
aevolution/src/biology/metabolism.cpp
T
dingoandClaude Opus 5.5 108f29eda5
Foundation / checks (ecs) (push) Successful in 2m25s
Foundation / checks (deploy) (push) Successful in 5m15s
Foundation / checks (network) (push) Successful in 21m56s
Foundation / checks (client) (push) Successful in 22m54s
Foundation / checks (tsan) (push) Successful in 47m4s
Foundation / checks (postgres) (push) Successful in 1h15m49s
Foundation / checks (checks) (push) Failing after 1h30m4s
Foundation / postgres-tools (push) Skipped
Foundation / server-image (push) Skipped
Foundation / image (push) Skipped
feat(biology): evolve photosynthetic producers that capture light
ADR-0175 implements ADR-0136 step C with trial costs to be balanced after
playtesting. Genome schema 5 adds a photosynthesis efficiency (empty in
schemas 1-4, so earlier offers and draws are unchanged; mutation operators
29-32 are appended). Development version 5 builds the organelles as
internal membrane (p/4 of structure, upkept twice) and slows movement by
p/2 per thousand. Founder 4 and cellular rules 11 let lineages earn the
capability as an offspring plan that children express.

Owner format 9 declares the region's light. Inside each tick's detached
candidate, active unfrozen producers capture cross-section x irradiance x
efficiency (a quarter while moving), credited to the reserve and boundary
inflow together and replayed from recorded intentions. Well-lit wildlife
producers hold still. The joint owner keeps infall, water and radiation and
nests a rules-11 owner unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 18:06:02 -04:00

267 lines
12 KiB
C++

#include "evo/biology/metabolism.hpp"
#include "evo/accounting/rates.hpp"
#include <algorithm>
#include <limits>
namespace evo::biology {
namespace {
constexpr std::uint64_t thousand = 1000;
// Membrane is the more carbon-rich compartment, so a thicker one changes what a
// body is made of and not only how much of it there is.
constexpr Composition structure_shares{500, 150, 50, 300};
constexpr Composition membrane_shares{700, 50, 100, 150};
constexpr std::uint32_t total_share(const Composition& shares) noexcept {
std::uint32_t sum = 0;
for (const auto share : shares) {
sum += share;
}
return sum;
}
static_assert(total_share(structure_shares) == thousand);
static_assert(total_share(membrane_shares) == thousand);
bool multiply(std::uint64_t& result, std::uint64_t left, std::uint64_t right) noexcept {
if (left != 0 && right > std::numeric_limits<std::uint64_t>::max() / left) {
return false;
}
result = left * right;
return true;
}
bool add(std::uint64_t& result, std::uint64_t left, std::uint64_t right) noexcept {
if (right > std::numeric_limits<std::uint64_t>::max() - left) {
return false;
}
result = left + right;
return true;
}
// Declared flooring, matching ADR-0031's derivation.
std::uint64_t scaled(std::uint64_t value, std::uint64_t numerator) noexcept {
return value / thousand * numerator + value % thousand * numerator / thousand;
}
// Splits a mass across the ledger's channels. The last channel takes whatever the
// first three left, so the parts always sum back to the whole.
accounting::Inventory compose(std::uint64_t mass, const Composition& shares) noexcept {
accounting::Inventory parts{};
std::uint64_t assigned = 0;
for (std::size_t index = 0; index + 1 < shares.size(); ++index) {
const auto part = scaled(mass, shares[index]);
parts.matter[index].value = part;
assigned += part;
}
parts.matter[shares.size() - 1].value = mass - assigned;
return parts;
}
bool combine(accounting::Inventory& total, const accounting::Inventory& amount) noexcept {
if (!add(total.energy.value, total.energy.value, amount.energy.value)) {
return false;
}
for (std::size_t index = 0; index < total.matter.size(); ++index) {
if (!add(total.matter[index].value, total.matter[index].value,
amount.matter[index].value)) {
return false;
}
}
return true;
}
// Every channel and the energy must fit: a surplus of one element never pays for
// a shortfall of another.
bool fits(const accounting::Inventory& needed, const accounting::Inventory& available) noexcept {
if (needed.energy > available.energy) {
return false;
}
for (std::size_t index = 0; index < needed.matter.size(); ++index) {
if (needed.matter[index] > available.matter[index]) {
return false;
}
}
return true;
}
std::uint64_t matter_total(const accounting::Inventory& inventory) noexcept {
std::uint64_t sum = 0;
for (const auto& mass : inventory.matter) {
sum += mass.value;
}
return sum;
}
// Scales an inventory's matter while keeping its composition. The last channel
// again takes the remainder, so the parts sum to the scaled whole exactly.
accounting::Inventory fraction_of(const accounting::Inventory& source,
std::uint64_t numerator) noexcept {
accounting::Inventory parts{};
const auto whole = scaled(matter_total(source), numerator);
std::uint64_t assigned = 0;
for (std::size_t index = 0; index + 1 < source.matter.size(); ++index) {
const auto part = scaled(source.matter[index].value, numerator);
parts.matter[index].value = part;
assigned += part;
}
parts.matter[source.matter.size() - 1].value = whole - assigned;
return parts;
}
} // namespace
std::expected<MetabolicRules, DevelopmentError>
metabolic_rules_for(std::uint32_t development_version) {
if (development_version == 1) {
return MetabolicRules{structure_shares, membrane_shares, 20, 50'000};
}
// Version 2: per second; movement at 1000 um/s costs 50 pJ/s per 1000 fg (tunable).
// Versions 3, 4 and 5: the same metabolism.
if (development_version >= 2 && development_version <= 5) {
return MetabolicRules{structure_shares, membrane_shares, 50, 50'000};
}
return std::unexpected{DevelopmentError::unsupported_rules};
}
std::expected<MetabolicBudget, DevelopmentError>
metabolic_budget(const Genome& genome, GrowthState growth, EnvironmentState environment,
std::uint32_t max_growth_per_thousand) {
const auto phenotype = derive_phenotype(genome, growth, environment);
if (!phenotype) {
return std::unexpected{phenotype.error()};
}
const auto rules = metabolic_rules_for(genome.development_version());
if (!rules) {
return std::unexpected{rules.error()};
}
const auto shape = rules_for(genome.development_version());
if (!shape) {
return std::unexpected{shape.error()};
}
MetabolicBudget budget;
budget.phenotype = *phenotype;
budget.rate_microseconds = development_rate_microseconds(genome.development_version());
budget.assimilation_per_thousand =
static_cast<std::uint16_t>(phenotype->conversion_per_thousand);
budget.body = compose(phenotype->structural_mass, rules->structure);
if (!combine(budget.body, compose(phenotype->membrane_mass, rules->membrane))) {
return std::unexpected{DevelopmentError::overflow};
}
budget.maintenance.value = phenotype->maintenance;
// Moving a larger body costs more, so a thicker membrane is paid for twice.
std::uint64_t haulage{};
if (!multiply(haulage, scaled(phenotype->total_mass, rules->movement_per_kilogram),
phenotype->movement_speed)) {
return std::unexpected{DevelopmentError::overflow};
}
budget.movement.value = haulage / thousand;
if (!add(budget.demand.value, budget.maintenance.value, budget.movement.value)) {
return std::unexpected{DevelopmentError::overflow};
}
// Intake funds structure, so it arrives in the proportions structure needs.
budget.intake_limit = compose(phenotype->ingestion_rate, rules->structure);
budget.intake_limit.energy.value =
scaled(phenotype->ingestion_rate, rules->intake_energy_per_kilogram);
const auto plan = plan_development(genome, growth, environment);
if (!plan) {
return std::unexpected{plan.error()};
}
// A plan bounds by total mass, which cannot tell whether the elements a step
// consumes are actually there: released matter never substitutes for an
// element the step needs. Narrow the proposal to the largest step whose own
// intake fits channel by channel.
budget.construction.after = growth;
const auto proposed = plan->after.realized_per_thousand - growth.realized_per_thousand;
for (std::uint32_t attempt = std::min(proposed, max_growth_per_thousand); attempt > 0;
--attempt) {
const GrowthState candidate{growth.realized_per_thousand + attempt,
growth.damage_per_thousand};
const auto grown = derive_phenotype(genome, candidate, environment);
if (!grown) {
return std::unexpected{grown.error()};
}
// Compose the grown body and difference it against the current one.
// Composing the mass difference instead would discard the rounding this
// body already carries, and the budget could not then reproduce the
// derived body channel by channel. Each compartment is still composed
// separately: the two differ in what they cost.
auto reached = compose(grown->structural_mass, rules->structure);
if (!combine(reached, compose(grown->membrane_mass, rules->membrane))) {
return std::unexpected{DevelopmentError::overflow};
}
ConstructionTransition move{};
move.after = candidate;
std::uint64_t acquired = 0, freed = 0;
for (std::size_t index = 0; index < reached.matter.size(); ++index) {
const auto held = budget.body.matter[index].value;
const auto wanted = reached.matter[index].value;
if (wanted >= held) {
move.intake.matter[index].value = wanted - held;
acquired += wanted - held;
} else {
move.release.matter[index].value = held - wanted;
freed += held - wanted;
}
}
// Energy is priced on the net mass change, as the plan prices it.
move.intake.energy.value = scaled(acquired - freed, shape->construction_per_kilogram);
if (!fits(move.intake, environment.available)) {
continue;
}
budget.construction = move;
break;
}
if (genome.carries(Capability::reproduction)) {
const auto value = *genome.parameter(Capability::reproduction);
// Version 4 (ADR-0137): a bud is always half the body, and reproduction is skill:
// it takes up to half off the bud's construction energy (value / 2000). Matter is
// never discounted (ADR-0118). Earlier versions invest `value` per thousand.
const bool skill = genome.development_version() >= 4; // Versions 4 and 5.
const auto fraction = skill ? bud_body_per_thousand_v4 : value;
// A parent divides the body it has, so the investment keeps its composition.
budget.reproduction_investment = fraction_of(budget.body, fraction);
// Offspring tissue is priced at what the parent's own tissue costs.
const auto construction =
scaled(matter_total(budget.reproduction_investment), shape->construction_per_kilogram);
// Discount = construction * skill / 2000, split to stay within 64 bits.
const std::uint64_t level = std::min<std::uint32_t>(value, 1000);
const auto discount = construction / 2000 * level + construction % 2000 * level / 2000;
budget.reproduction_investment.energy.value =
skill ? construction - discount : construction;
}
return budget;
}
std::optional<std::uint64_t> bud_funding_seconds(const MetabolicBudget& budget,
std::uint32_t feeding_per_thousand) noexcept {
const auto period = budget.rate_microseconds;
if (period == 0 || accounting::microseconds_per_second % period != 0 ||
feeding_per_thousand == 0 || feeding_per_thousand > thousand ||
matter_total(budget.reproduction_investment) == 0)
return std::nullopt;
const auto periods_per_second = accounting::microseconds_per_second / period;
// Per-second amounts; ceil(need / rate) seconds for each.
const auto seconds = [&](std::uint64_t need,
std::uint64_t per_period) -> std::optional<std::uint64_t> {
if (need == 0)
return std::uint64_t{0};
std::uint64_t per_second{};
if (!multiply(per_second, scaled(per_period, feeding_per_thousand), periods_per_second) ||
per_second == 0)
return std::nullopt;
return need / per_second + (need % per_second != 0 ? 1 : 0);
};
std::uint64_t longest = 0;
for (std::size_t c = 0; c < budget.reproduction_investment.matter.size(); ++c) {
const auto t = seconds(budget.reproduction_investment.matter[c].value,
budget.intake_limit.matter[c].value);
if (!t)
return std::nullopt;
longest = std::max(longest, *t);
}
// Energy: the fed share of intake, less the whole demand, all per period.
const auto fed = scaled(budget.intake_limit.energy.value, feeding_per_thousand);
if (fed <= budget.demand.value)
return std::nullopt;
std::uint64_t surplus{};
if (!multiply(surplus, fed - budget.demand.value, periods_per_second) || surplus == 0)
return std::nullopt;
const auto need = budget.reproduction_investment.energy.value;
longest = std::max(longest, need / surplus + (need % surplus != 0 ? 1 : 0));
return longest;
}
} // namespace evo::biology