#include "evo/processes/feeding.hpp" #include #include #include #include namespace evo::processes { namespace { bool fits(const accounting::Inventory& amount, const accounting::Inventory& available) noexcept { if (amount.energy > available.energy) { return false; } for (std::size_t index = 0; index < 4; ++index) { if (amount.matter[index] > available.matter[index]) { return false; } } return true; } std::uint64_t portion(std::uint64_t quantity, std::uint16_t efficiency) noexcept { return (quantity / 1000) * efficiency + (quantity % 1000) * efficiency / 1000; } accounting::ReservoirId reservoir(std::uint32_t actor) noexcept { return {actor == 1 ? 3U : actor + 3U}; } } // namespace FeedingCommunity::FeedingCommunity(ProducerProcess producer, std::vector consumers, DecompositionConfig decomposition, ReproductionConfig reproduction, std::uint32_t living) : producer_{std::move(producer)}, consumers_{std::move(consumers)}, states_(consumers_.size() + 1, State::unborn), parents_(consumers_.size() + 1, 0), origins_(consumers_.size() + 1, Tick{}), decomposition_{decomposition}, reproduction_{reproduction} { // Index zero is the producer; reserved slots stay unborn until a funded birth. for (std::size_t index = 0; index <= living; ++index) { states_[index] = State::active; } } std::expected FeedingCommunity::create(ProducerConfig producer, accounting::Picojoules source, std::array nutrients, std::span consumers, DecompositionConfig decomposition, ReproductionConfig reproduction) { if (consumers.empty() || consumers.size() > max_consumers || reproduction.capacity > max_consumers - consumers.size() || reproduction.construction_per_thousand > 1000 || std::ranges::any_of(consumers, [](const auto& c) { return c.assimilation_per_thousand > 1000; })) { return std::unexpected{FeedingError::invalid_config}; } auto isolated = ProducerProcess::create(producer, source, nutrients); if (!isolated) { return std::unexpected{FeedingError::invalid_config}; } std::vector opening{isolated->balances().begin(), isolated->balances().end()}; for (const auto& consumer : consumers) { opening.push_back(consumer.opening); } // Reserved reservoirs precede waste, so the waste index remains last. opening.insert(opening.end(), reproduction.capacity, accounting::Inventory{}); opening.emplace_back(); // Waste is owned matter, not destroyed inventory. auto ledger = accounting::Ledger::create(opening); if (!ledger) { return std::unexpected{FeedingError::accounting_failure}; } isolated->ledger_ = std::move(*ledger); std::vector slots{consumers.begin(), consumers.end()}; slots.resize(consumers.size() + reproduction.capacity); return FeedingCommunity{std::move(*isolated), std::move(slots), decomposition, reproduction, static_cast(consumers.size())}; } std::expected FeedingCommunity::state(std::uint32_t id) const noexcept { if (id == 0 || id > states_.size()) { return std::unexpected{FeedingError::invalid_actor}; } return states_[id - 1]; } std::expected FeedingCommunity::active(std::uint32_t id) const noexcept { const auto current = state(id); if (!current) { return std::unexpected{current.error()}; } return *current == State::active; } std::expected FeedingCommunity::born(std::uint32_t id) const noexcept { const auto current = state(id); if (!current) { return std::unexpected{current.error()}; } return *current != State::unborn; } std::expected FeedingCommunity::parent(std::uint32_t id) const noexcept { const auto exists = born(id); if (!exists) { return std::unexpected{exists.error()}; } if (!*exists) { return std::unexpected{FeedingError::unborn_actor}; } return parents_[id - 1]; } std::expected FeedingCommunity::origin(std::uint32_t id) const noexcept { const auto exists = born(id); if (!exists) { return std::unexpected{exists.error()}; } if (!*exists) { return std::unexpected{FeedingError::unborn_actor}; } return origins_[id - 1]; } std::expected FeedingCommunity::corpse(std::uint32_t id) const noexcept { const auto current = state(id); if (!current) { return std::unexpected{current.error()}; } if (*current == State::unborn) { return std::unexpected{FeedingError::unborn_actor}; } if (*current == State::active) { return std::unexpected{FeedingError::not_corpse}; } return balances()[reservoir(id).value - 1]; } std::expected FeedingCommunity::feed(const FeedIntent& input) { if (input.consumer < 2 || input.consumer > states_.size() || input.target == 0 || input.target > states_.size() || input.target == input.consumer) { return std::unexpected{FeedingError::invalid_actor}; } for (const auto actor : {input.consumer, input.target}) { if (states_[actor - 1] == State::unborn) { return std::unexpected{FeedingError::unborn_actor}; } if (states_[actor - 1] != State::active) { return std::unexpected{FeedingError::inactive_actor}; } } const auto& config = consumers_[input.consumer - 2]; if (input.amount == accounting::Inventory{} || !fits(input.amount, config.intake_limit)) { return std::unexpected{FeedingError::intake_limit}; } const auto from = reservoir(input.target); if (!fits(input.amount, balances()[from.value - 1])) { return std::unexpected{FeedingError::insufficient_inventory}; } accounting::Inventory assimilated{}, heat{}, waste{}; assimilated.energy.value = portion(input.amount.energy.value, config.assimilation_per_thousand); heat.energy.value = input.amount.energy.value - assimilated.energy.value; for (std::size_t index = 0; index < 4; ++index) { assimilated.matter[index].value = portion(input.amount.matter[index].value, config.assimilation_per_thousand); waste.matter[index].value = input.amount.matter[index].value - assimilated.matter[index].value; } const std::array legs{ accounting::Transfer{from, reservoir(input.consumer), assimilated}, accounting::Transfer{from, {4}, heat}, accounting::Transfer{from, {static_cast(balances().size())}, waste}}; auto& ledger = producer_.ledger_; if (ledger.last_action() == std::numeric_limits::max() || !ledger.transfer(ledger.last_action() + 1, legs)) { return std::unexpected{FeedingError::accounting_failure}; } const bool depleted = balances()[from.value - 1] == accounting::Inventory{}; if (depleted) { states_[input.target - 1] = State::corpse; } return FeedReceipt{input.sequence, assimilated, depleted}; } std::expected FeedingCommunity::reproduce(const ReproduceIntent& input, Tick target) { // The producer is funded by capture; treating it as a parent would conflate the two. if (input.parent < 2 || input.parent > states_.size()) { return std::unexpected{FeedingError::invalid_actor}; } if (states_[input.parent - 1] == State::unborn) { return std::unexpected{FeedingError::unborn_actor}; } if (states_[input.parent - 1] != State::active) { return std::unexpected{FeedingError::inactive_actor}; } if (input.investment == accounting::Inventory{}) { return std::unexpected{FeedingError::invalid_endowment}; } const auto from = reservoir(input.parent); if (!fits(input.investment, balances()[from.value - 1])) { return std::unexpected{FeedingError::insufficient_inventory}; } const auto slot = std::ranges::find(states_, State::unborn); if (slot == states_.end()) { return std::unexpected{FeedingError::no_capacity}; } const auto child = static_cast(slot - states_.begin()) + 1; accounting::Inventory endowment{}, heat{}, waste{}; endowment.energy.value = portion(input.investment.energy.value, reproduction_.construction_per_thousand); heat.energy.value = input.investment.energy.value - endowment.energy.value; for (std::size_t index = 0; index < 4; ++index) { endowment.matter[index].value = portion(input.investment.matter[index].value, reproduction_.construction_per_thousand); waste.matter[index].value = input.investment.matter[index].value - endowment.matter[index].value; } if (!fits(reproduction_.minimum_endowment, endowment)) { return std::unexpected{FeedingError::invalid_endowment}; } const std::array legs{ accounting::Transfer{from, reservoir(child), endowment}, accounting::Transfer{from, {4}, heat}, accounting::Transfer{from, {static_cast(balances().size())}, waste}}; auto& ledger = producer_.ledger_; if (ledger.last_action() == std::numeric_limits::max() || !ledger.transfer(ledger.last_action() + 1, legs)) { return std::unexpected{FeedingError::accounting_failure}; } *slot = State::active; // No genome exists yet, so a child duplicates the configuration of its parent. consumers_[child - 2] = consumers_[input.parent - 2]; parents_[child - 1] = input.parent; origins_[child - 1] = target; return ReproduceReceipt{input.sequence, child, endowment, {heat.energy, waste.matter}}; } std::expected FeedingCommunity::decompose() { auto remaining = decomposition_.per_tick_limit; // Final iteration is waste, after all corpse reservoirs. Unborn slots are skipped. for (std::size_t index = 0; index <= states_.size(); ++index) { if (index < states_.size() && states_[index] != State::corpse) { continue; } const auto from = index == states_.size() ? accounting::ReservoirId{static_cast(balances().size())} : reservoir(static_cast(index + 1)); const auto available = balances()[from.value - 1]; accounting::Inventory heat{}, nutrients{}; heat.energy.value = std::min(remaining.energy.value, available.energy.value); for (std::size_t channel = 0; channel < 4; ++channel) { nutrients.matter[channel].value = std::min(remaining.matter[channel].value, available.matter[channel].value); } if (heat == accounting::Inventory{} && nutrients == accounting::Inventory{}) { continue; } const std::array legs{accounting::Transfer{from, {4}, heat}, accounting::Transfer{from, {2}, nutrients}}; auto& ledger = producer_.ledger_; if (ledger.last_action() == std::numeric_limits::max() || !ledger.transfer(ledger.last_action() + 1, legs)) { return std::unexpected{FeedingError::accounting_failure}; } remaining.energy.value -= heat.energy.value; for (std::size_t channel = 0; channel < 4; ++channel) { remaining.matter[channel].value -= nutrients.matter[channel].value; } } last_decomposed_.energy.value = decomposition_.per_tick_limit.energy.value - remaining.energy.value; for (std::size_t channel = 0; channel < 4; ++channel) { last_decomposed_.matter[channel].value = decomposition_.per_tick_limit.matter[channel].value - remaining.matter[channel].value; } return {}; } std::expected, FeedingError> FeedingCommunity::advance(Tick target, std::span inputs, std::span terminal_events, std::span births) { if (progress().tick.value == std::numeric_limits::max() || target.value != progress().tick.value + 1) { return std::unexpected{FeedingError::wrong_tick}; } if (inputs.size() > max_consumers || states_.empty() || terminal_events.size() > states_.size() || births.size() > max_consumers) { return std::unexpected{FeedingError::invalid_batch}; } std::vector ordered{inputs.begin(), inputs.end()}; std::ranges::sort(ordered, {}, &FeedIntent::sequence); std::array seen{}; std::uint64_t previous{}; for (const auto& input : ordered) { if (input.sequence == 0 || input.sequence == previous || input.consumer < 2 || input.consumer > consumers_.size() + 1 || seen[input.consumer]) { return std::unexpected{FeedingError::invalid_batch}; } seen[input.consumer] = true; previous = input.sequence; } // Reproduction sequences form a separate space; a consumer may feed and then reproduce. std::vector ordered_births{births.begin(), births.end()}; std::ranges::sort(ordered_births, {}, &ReproduceIntent::sequence); std::array expecting{}; previous = 0; for (const auto& birth : ordered_births) { if (birth.sequence == 0 || birth.sequence == previous || birth.parent < 2 || birth.parent > consumers_.size() + 1 || expecting[birth.parent]) { return std::unexpected{FeedingError::invalid_batch}; } expecting[birth.parent] = true; previous = birth.sequence; } auto candidate = *this; std::array terminated{}; for (const auto event : terminal_events) { if (event.actor == 0 || event.actor > states_.size() || terminated[event.actor]) { return std::unexpected{FeedingError::invalid_batch}; } if (candidate.states_[event.actor - 1] == State::unborn) { return std::unexpected{FeedingError::unborn_actor}; } if (candidate.states_[event.actor - 1] != State::active) { return std::unexpected{FeedingError::inactive_actor}; } terminated[event.actor] = true; candidate.states_[event.actor - 1] = State::corpse; } if (candidate.states_[0] == State::active) { if (!candidate.producer_.advance(target)) { return std::unexpected{FeedingError::accounting_failure}; } } else { candidate.producer_.progress_.tick = target; } std::vector receipts; receipts.reserve(ordered.size()); for (const auto& input : ordered) { const auto result = candidate.feed(input); if (!result) { return std::unexpected{result.error()}; } receipts.push_back(*result); } // Eligibility is fixed on entry to this phase, after terminal facts and feeding. // Applying a birth activates a slot, so a child must not become a parent here. for (const auto& birth : ordered_births) { if (candidate.states_[birth.parent - 1] == State::unborn) { return std::unexpected{FeedingError::unborn_actor}; } if (candidate.states_[birth.parent - 1] != State::active) { return std::unexpected{FeedingError::inactive_actor}; } } std::vector delivered; delivered.reserve(ordered_births.size()); for (const auto& birth : ordered_births) { const auto result = candidate.reproduce(birth, target); if (!result) { return std::unexpected{result.error()}; } delivered.push_back(*result); } candidate.last_births_ = std::move(delivered); if (const auto result = candidate.decompose(); !result) { return std::unexpected{result.error()}; } static_assert(std::is_nothrow_move_assignable_v); *this = std::move(candidate); return receipts; } } // namespace evo::processes