#include "evo/processes/ecosystem.hpp" #include #include #include namespace evo::processes { namespace { constexpr std::size_t slot_limit = max_consumers + 2; std::size_t balance_index(std::uint32_t actor) noexcept { return actor == 1 ? 2 : static_cast(actor) + 2; } bool covers(const accounting::Inventory& need, const accounting::Inventory& have) noexcept { if (need.energy > have.energy) { return false; } for (std::size_t index = 0; index < 4; ++index) { if (need.matter[index] > have.matter[index]) { return false; } } return true; } // Cumulative diagnostics saturate; they are reported totals, not owned inventory. void accumulate(accounting::Inventory& total, const accounting::Inventory& amount) noexcept { constexpr auto maximum = std::numeric_limits::max(); total.energy.value = amount.energy.value > maximum - total.energy.value ? maximum : total.energy.value + amount.energy.value; for (std::size_t index = 0; index < 4; ++index) { total.matter[index].value = amount.matter[index].value > maximum - total.matter[index].value ? maximum : total.matter[index].value + amount.matter[index].value; } } // Non-cryptographic combiner, used only to compare results across platforms. std::uint64_t mix(std::uint64_t hash, std::uint64_t value) noexcept { return hash ^ (value + 0x9e3779b97f4a7c15ULL + (hash << 6U) + (hash >> 2U)); } } // namespace EcosystemEpisode::EcosystemEpisode(FeedingCommunity community, std::vector founders, EcosystemConfig config, std::uint64_t seed) : community_{std::move(community)}, founders_{std::move(founders)}, config_{config}, random_{seed}, seed_{seed} {} std::expected EcosystemEpisode::create(EcosystemConfig config, std::span founders, std::uint64_t seed) { if (founders.empty() || founders.size() > max_strategies || config.tick_limit == 0) { return std::unexpected{EcosystemError::invalid_config}; } for (const auto& founder : founders) { // A zero lifespan would retire a founder before it ever acted; a zero // investment would request a birth the community rejects outright. if (founder.lifespan == 0 || founder.investment == accounting::Inventory{} || founder.assimilation_per_thousand > 1000) { return std::unexpected{EcosystemError::invalid_config}; } } std::vector consumers; consumers.reserve(founders.size()); for (const auto& founder : founders) { consumers.push_back( {founder.opening, founder.intake_limit, founder.assimilation_per_thousand}); } auto community = FeedingCommunity::create( config.producer, config.source, config.nutrients, consumers, config.decomposition, {config.capacity, config.construction_per_thousand, {}}); if (!community) { return std::unexpected{EcosystemError::invalid_config}; } return EcosystemEpisode{ std::move(*community), {founders.begin(), founders.end()}, config, seed}; } std::uint32_t EcosystemEpisode::lineage(std::uint32_t id) const noexcept { if (id < 2) { return 0; } // A child always occupies a higher slot than its parent, so this terminates. auto current = id; while (true) { const auto exists = community_.born(current); if (!exists || !*exists) { return 0; } const auto ancestor = community_.parent(current); if (!ancestor) { return 0; } if (*ancestor == 0) { return current; } current = *ancestor; } } const StrategyConfig& EcosystemEpisode::strategy(std::uint32_t id) const noexcept { const auto root = lineage(id); // Every born consumer descends from a founder; index zero is a safe fallback. const auto offset = root >= 2 && static_cast(root - 2) < founders_.size() ? static_cast(root - 2) : 0U; return founders_[offset]; } std::expected EcosystemEpisode::step() { if (finished_) { return false; } const auto slots = static_cast(founders_.size() + config_.capacity + 1); const auto tick = community_.progress().tick.value + 1; // Lifespan retirement is decided from age alone, before any activity this tick. std::vector terminal; for (std::uint32_t id = 2; id <= slots; ++id) { const auto alive = community_.active(id); const auto born = community_.origin(id); if (!alive || !*alive || !born) { continue; } if (tick - born->value >= strategy(id).lifespan) { terminal.push_back({id}); } } // Probe a discarded copy so bites are sized against the state feeding will see: // terminal facts and producer capture/growth both land before any feeding. auto probe = community_; if (!probe.advance(Tick{tick}, {}, terminal)) { return std::unexpected{EcosystemError::community_failure}; } std::array target{}; std::array claimed{}; for (std::uint32_t consumer = 2; consumer <= slots; ++consumer) { const auto alive = probe.active(consumer); // A consumer that cannot bite must not claim a target away from one that can. if (!alive || !*alive || strategy(consumer).intake_limit == accounting::Inventory{}) { continue; } std::array available{}; std::size_t count = 0; for (std::uint32_t candidate = 1; candidate <= slots; ++candidate) { const auto living = probe.active(candidate); if (candidate == consumer || claimed[candidate] || !living || !*living) { continue; } if (probe.balances()[balance_index(candidate)] == accounting::Inventory{}) { continue; } available[count++] = candidate; } if (count == 0) { continue; } // One feeder per target removes contention rejection from the batch. const auto chosen = available[random_.next() % count]; target[consumer] = chosen; claimed[chosen] = true; } // A consumer bitten this tick may be retired by that bite, so it does not act. for (std::uint32_t consumer = 2; consumer <= slots; ++consumer) { if (target[consumer] != 0 && claimed[consumer]) { target[consumer] = 0; } } claimed.fill(false); std::vector meals; for (std::uint32_t consumer = 2; consumer <= slots; ++consumer) { if (target[consumer] == 0) { continue; } const auto& cap = strategy(consumer).intake_limit; const auto& balance = probe.balances()[balance_index(target[consumer])]; accounting::Inventory bite{}; bite.energy.value = std::min(cap.energy.value, balance.energy.value); for (std::size_t channel = 0; channel < 4; ++channel) { bite.matter[channel].value = std::min(cap.matter[channel].value, balance.matter[channel].value); } if (bite == accounting::Inventory{}) { continue; } claimed[target[consumer]] = true; meals.push_back( {static_cast(meals.size()) + 1, consumer, target[consumer], bite}); } std::size_t free_slots = 0; for (std::uint32_t id = 2; id <= slots; ++id) { const auto exists = probe.born(id); if (exists && !*exists) { ++free_slots; } } std::vector newborn; for (std::uint32_t parent = 2; parent <= slots && newborn.size() < free_slots; ++parent) { const auto alive = probe.active(parent); if (!alive || !*alive || claimed[parent]) { continue; } const auto& plan = strategy(parent); const auto& balance = probe.balances()[balance_index(parent)]; // Feeding only adds to an unbitten parent, so this bound stays valid. if (!covers(plan.reproduction_threshold, balance) || !covers(plan.investment, balance)) { continue; } newborn.push_back( {static_cast(newborn.size()) + 1, parent, plan.investment}); } const auto receipts = community_.advance(Tick{tick}, meals, terminal, newborn); if (!receipts) { return std::unexpected{EcosystemError::community_failure}; } lifespan_deaths_ += terminal.size(); for (const auto& receipt : *receipts) { if (receipt.target_depleted) { ++predation_deaths_; } } births_ += community_.last_births().size(); accumulate(decomposed_, community_.last_decomposed()); bool surviving = false; for (std::uint32_t id = 2; id <= slots; ++id) { const auto alive = community_.active(id); if (alive && *alive) { surviving = true; break; } } if (!surviving) { extinction_tick_ = tick; finished_ = true; } else if (tick >= config_.tick_limit) { finished_ = true; } return true; } std::expected EcosystemEpisode::run() { while (true) { const auto stepped = step(); if (!stepped) { return std::unexpected{stepped.error()}; } if (!*stepped) { return report(); } } } EcosystemReport EcosystemEpisode::report() const noexcept { const auto slots = static_cast(founders_.size() + config_.capacity + 1); EcosystemReport summary{}; summary.seed = seed_; summary.ticks = community_.progress().tick.value; summary.births = births_; summary.predation_deaths = predation_deaths_; summary.lifespan_deaths = lifespan_deaths_; summary.extinction_tick = extinction_tick_; summary.founders = static_cast(founders_.size()); std::array represented{}; for (std::uint32_t id = 2; id <= slots; ++id) { const auto alive = community_.active(id); if (!alive || !*alive) { continue; } const auto root = lineage(id); if (root != 0 && !represented[root]) { represented[root] = true; ++summary.surviving_lineages; } } summary.decomposed = decomposed_; // The ledger validated at creation that every channel total fits u64. for (const auto& balance : community_.balances()) { summary.conserved.energy.value += balance.energy.value; for (std::size_t channel = 0; channel < 4; ++channel) { summary.conserved.matter[channel].value += balance.matter[channel].value; } } std::uint64_t hash = 0; for (const auto value : {summary.ticks, summary.births, summary.predation_deaths, summary.lifespan_deaths, summary.extinction_tick}) { hash = mix(hash, value); } for (const auto& balance : community_.balances()) { hash = mix(hash, balance.energy.value); for (const auto& mass : balance.matter) { hash = mix(hash, mass.value); } } for (std::uint32_t id = 1; id <= slots; ++id) { const auto exists = community_.born(id); const auto alive = community_.active(id); hash = mix(hash, (exists && *exists ? 2U : 0U) + (alive && *alive ? 1U : 0U)); hash = mix(hash, lineage(id)); } summary.fingerprint = hash; return summary; } } // namespace evo::processes