diff --git a/CMakeLists.txt b/CMakeLists.txt index 1565f31..241beed 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -77,6 +77,7 @@ add_library(evo_biology STATIC src/biology/mutation.cpp src/biology/lineage.cpp src/biology/founder.cpp src/biology/cellular_motion.cpp src/biology/cellular_kinematics.cpp src/biology/cellular_tuning.cpp src/biology/cellular_revamp_tuning.cpp + src/biology/cellular_burn.cpp src/biology/cellular_currents.cpp src/biology/cellular_deposit_motion.cpp src/biology/cellular_uptake.cpp @@ -500,6 +501,14 @@ if(BUILD_TESTING) else() add_test(NAME cellular-tuning-contracts COMMAND evo-cellular-tuning-tests) endif() + add_executable(evo-cellular-revamp-step-tests tests/cellular_revamp_step_tests.cpp) + target_link_libraries(evo-cellular-revamp-step-tests PRIVATE evo::biology) + evo_owned_target(evo-cellular-revamp-step-tests) + add_test(NAME cellular-revamp-step-contracts COMMAND evo-cellular-revamp-step-tests) + add_executable(evo-cellular-burn-tests tests/cellular_burn_tests.cpp) + target_link_libraries(evo-cellular-burn-tests PRIVATE evo::biology) + evo_owned_target(evo-cellular-burn-tests) + add_test(NAME cellular-burn-contracts COMMAND evo-cellular-burn-tests) add_executable(evo-cellular-revamp-tuning-tests tests/cellular_revamp_tuning_tests.cpp) target_link_libraries(evo-cellular-revamp-tuning-tests PRIVATE evo::biology) evo_owned_target(evo-cellular-revamp-tuning-tests) diff --git a/Cellular_Revamp_Build_Plan.md b/Cellular_Revamp_Build_Plan.md index 7f0367e..413a375 100644 --- a/Cellular_Revamp_Build_Plan.md +++ b/Cellular_Revamp_Build_Plan.md @@ -21,13 +21,17 @@ rules 12. - **One revamp tuning file.** Every new tunable goes in `deploy/kubernetes/region/dev/tuning/cellular-revamp.tuning`, beside the rules-12 `cellular.tuning`, with the same format and validation. -- **Client and server together** in every phase. +- **Server phases first, then one session version.** Phases 1-5 build and test the + server halves. The wire changes in every one of them (body values, offers, bud + choices, organisms), so session v14 and the client screens for all of them are one + step after phase 5, rather than a protocol revision per phase. Nothing deploys before + that step anyway. - **Shared biology.** Derivations stay in the headless library, so the client predictor and the server agree. ## Phases -### Phase 1: genome and body (rules 13 foundation) +### Phase 1: genome and body (rules 13 foundation) - done Server: - Genome schema 7: every heritable value the plans name, in points (founder 100) @@ -44,13 +48,12 @@ Server: from points; no legacy photosynthesis speed penalty. - Rules 13 owner skeleton (new owner format) and tuning keys for every body value. -Client: none in this phase. Showing the new body values needs them on the wire, which -session v14 adds in phase 2. +Client: in the session v14 step. Verify: founder 6 derives the same body as founder 5 where the plans say "today's value"; the essential floor holds; encode/decode and bound checks for schema 7. -### Phase 2: feeding, energy and predation +### Phase 2: feeding, energy and predation - server done Server: - Collection per channel with the shared intake limit; the membrane collection penalty. @@ -61,10 +64,11 @@ Server: - Reserve matter in mass for handling and movement energy, not upkeep. - Engulf check with engulf capacity and `engulf_reserve_mass_percent`; kill absorption; the kill remainder split between bubbles and the spent pool. -- Session v14 for the new perception fields and the exclusion control. +- Channel exclusions are a 4-bit step intent field, carried in the trace's byte 14. -Client: energy display including what matter can stand in for; channel exclusion -toggles; spent-pool drips drawn like infall; hover and HUD show the phase 1 body values. +Client (session v14 step): energy display including what matter can stand in for; +channel exclusion toggles; spent-pool drips drawn like infall; hover and HUD show the +phase 1 body values. Verify: conservation per channel and energy across burning, the pool, kills and drips; no burn of excluded matter except for upkeep; replay determinism. @@ -124,6 +128,13 @@ Client: organism drawn as its member cells; Emerge button at the threshold. Verify: one reserve and one genome across members; whole engulfment conserves; the Emerge action only at the threshold. +### Session v14 and the client + +- Session v14: the phase 1 body values in perception; payable energy; the exclusion + control; named offers with pro, con, chance, cost and Stay / Become; the bud choice; + organisms and the Emerge action. +- Client screens for all of the above. + ### Phase 6: wildlife, instrumentation and the playtest - Wildlife controller: matter-as-energy aware, budding with litter, engulfing with the diff --git a/Cellular_feeding_energy_plan.md b/Cellular_feeding_energy_plan.md index c0474ff..e2180dc 100644 --- a/Cellular_feeding_energy_plan.md +++ b/Cellular_feeding_energy_plan.md @@ -54,9 +54,10 @@ with **reserve matter** instead. The matter is not converted into energy; it sta for it. It covers every energy cost: upkeep, thrust, growth and bud construction, and the energy part of mutation costs. -- **Burn rate:** each channel has a tunable rate in femtograms per picojoule, divided - by the cell's burn efficiency for that channel (founder 100). Matter pays at a higher - rate than pure energy, so burning matter is always the expensive way to stay alive. +- **Burn rate:** each channel has a tunable rate, the picojoules 1,000 fg of it stands in + for, scaled by the cell's burn efficiency for that channel (founder 100). Matter pays + at a worse rate than the energy bubbles carry, so burning matter is always the + expensive way to stay alive (trial: 2,000 pJ per 1,000 fg). - **Only reserve matter burns.** The body is never burned. - **Death:** a cell dies when its upkeep cannot be paid by energy or any reserve matter. @@ -138,7 +139,7 @@ the energy in bubbles must be retuned when this is turned on. | --- | --- | | Founder collection rate per channel | From today's derived limits | | Shared ingestion limit | Founder ingestion capability | -| Burn rate per channel (fg per pJ) | To be selected in playtesting | +| Burn rate per channel (pJ per 1,000 fg) | 2,000 | | Spent-pool drip rate | To be selected in playtesting | | Carbon burned before photosynthesis is offered | To be selected in playtesting | diff --git a/deploy/kubernetes/region/dev-session-route/listener.yaml b/deploy/kubernetes/region/dev-session-route/listener.yaml index 478db2d..3402f4d 100644 --- a/deploy/kubernetes/region/dev-session-route/listener.yaml +++ b/deploy/kubernetes/region/dev-session-route/listener.yaml @@ -12,7 +12,7 @@ spec: env: - {name: REGION_SESSION, value: "dev"} - {name: REGION_SESSION_LISTEN, value: "0.0.0.0:7400"} - - {name: REGION_SESSION_WINDOW, value: "dev-20261022T221857-44422cf1:1792721937"} + - {name: REGION_SESSION_WINDOW, value: "dev-20261022T223519-812afd47:1792722919"} - {name: REGION_M10_MAX_GRANT_LIFETIME, value: "14400"} ports: # QUIC (ADR-0090): UDP only; nothing listens on TCP 7400. diff --git a/deploy/kubernetes/region/dev/tuning/cellular-revamp.tuning b/deploy/kubernetes/region/dev/tuning/cellular-revamp.tuning index e00e2d4..e488e0d 100644 --- a/deploy/kubernetes/region/dev/tuning/cellular-revamp.tuning +++ b/deploy/kubernetes/region/dev/tuning/cellular-revamp.tuning @@ -6,3 +6,26 @@ tuning.version = 1 # Body (body and maintenance plan). body.essential_upkeep_per_mille = 250 # share of upkeep no upkeep-efficiency trait reduces +body.reserve_load_per_mille = 1_000 # reserve matter carried as load (slower, costlier thrust) + +# Energy (feeding and energy plan): what 1,000 fg of reserve matter stands in for when the +# reserve's energy runs out. Bubbles carry ~17 pJ of energy per fg of matter, so 2 pJ per fg +# makes burning matter the expensive way to stay alive (a founder burns a carbon bubble in +# about 80 s of upkeep). +energy.burn_carbon_pj_per_kfg = 2_000 +energy.burn_nitrogen_pj_per_kfg = 2_000 +energy.burn_phosphorus_pj_per_kfg = 2_000 +energy.burn_other_pj_per_kfg = 2_000 + +# Feeding: collection lost per membrane point above the founder's 100 (5 points: -1%). +feeding.membrane_collection_per_mille_per_point = 2 + +# Predation (predation and defense plan). +predation.engulf_ratio_milli = 1_500 # a predator needs 1.5x the prey's engulf mass +predation.engulf_reserve_percent = 100 # share of reserve matter in engulf mass +predation.kill_bubble_per_mille = 500 # a kill's remainder left as bubbles; the rest is spent + +# The spent pool drips back as bubbles at random spots. +spent.drip_interval_ticks = 20 # once a second +spent.drip_bubble_pj = 20_000_000 # largest energy bubble per drip +spent.drip_bubble_fg = 1_000_000 # largest matter bubble per drip and channel diff --git a/include/evo/biology/cellular_burn.hpp b/include/evo/biology/cellular_burn.hpp new file mode 100644 index 0000000..239dd77 --- /dev/null +++ b/include/evo/biology/cellular_burn.hpp @@ -0,0 +1,52 @@ +#pragma once + +#include "evo/accounting/ledger.hpp" + +#include +#include +#include +#include + +// Matter as energy (rules 13, ADR-0179; Cellular_feeding_energy_plan.md section 3). When an +// energy cost is larger than the reserve's energy, reserve matter stands in for the rest at +// each channel's burn rate. The matter is not converted: it leaves the cell as spent matter, +// which the region owner keeps in its spent pool. No energy is created, so a cost paid with +// matter adds no heat. +namespace evo::biology { +inline constexpr std::size_t cellular_matter_channels = 4; // C, N, P, other. + +struct CellularBurn { + // Picojoules 1,000 fg of each matter channel stands in for, after the cell's burn + // efficiency. Zero means the channel cannot be burned. + std::array pj_per_kfg{}; + // Bit c set: the player keeps channel c (C = bit 0). Upkeep may override it. + std::uint8_t excluded{}; + auto operator<=>(const CellularBurn&) const = default; +}; + +// The burn rates of a cell: each base rate times its burn efficiency index over 100. +[[nodiscard]] CellularBurn +cellular_burn(const std::array& base_pj_per_kfg, + const std::array& efficiency, + std::uint8_t excluded) noexcept; + +// Energy the reserve could pay: its energy plus what its burnable matter stands in for. +// `override_exclusions` also counts excluded channels (upkeep). +[[nodiscard]] std::uint64_t cellular_payable_energy(const accounting::Inventory& reserve, + const CellularBurn& burn, + bool override_exclusions) noexcept; + +// Pays `cost` from `reserve`: its energy first, then matter from the largest burnable channel +// (ties C, N, P, O), the next largest when that runs out. Returns the energy paid and the +// matter spent, and leaves `reserve` debited; nothing changes when the whole cost cannot be +// paid. A channel pays whole femtograms, so matter may cover slightly more than the cost. +struct CellularPayment { + std::uint64_t energy{}; + accounting::Inventory spent{}; // Matter only. + auto operator<=>(const CellularPayment&) const = default; +}; +[[nodiscard]] std::optional cellular_pay(accounting::Inventory& reserve, + std::uint64_t cost, + const CellularBurn& burn, + bool override_exclusions) noexcept; +} // namespace evo::biology diff --git a/include/evo/biology/cellular_region_step.hpp b/include/evo/biology/cellular_region_step.hpp index 5bab61f..310b512 100644 --- a/include/evo/biology/cellular_region_step.hpp +++ b/include/evo/biology/cellular_region_step.hpp @@ -2,10 +2,12 @@ #include "evo/biology/cellular_step.hpp" +#include #include #include #include #include +#include #include #include @@ -16,6 +18,30 @@ inline constexpr std::size_t max_cellular_tick_lives = 256; // ratio in thousandths per micrometre of prey membrane (tunable; 1.5 for 1 um). inline constexpr std::uint64_t cellular_engulf_ratio_milli_per_membrane_um = 1'500; +// Rules 13 (ADR-0179; feeding and energy, predation and defense plans): region-declared +// feeding, energy and predation values. All trial values from the revamp tuning file. +struct CellularRevampStepRules { + // Collection changes by this many per mille per membrane point away from the founder's 100 + // (thicker collects slower), bounded to 10%-200%. + std::uint32_t membrane_collection_per_mille_per_point{}; + // A predator needs engulf mass x capacity / 100 >= prey engulf mass x ratio / 1000 x prey + // membrane points / 100. + std::uint32_t engulf_ratio_milli{1'500}; + // Share of reserve matter that counts toward engulf mass, per cent. + std::uint32_t engulf_reserve_percent{100}; + // Share of a kill's remainder left as bubbles at the prey; the rest goes to the spent pool. + std::uint32_t kill_bubble_per_thousand{500}; + auto operator<=>(const CellularRevampStepRules&) const = default; +}; +// Rules 13: one life's heritable feeding, energy and predation values, from its genome. +struct CellularRevampLifeInput { + CellularBurn burn{}; + std::array collection{100, 100, 100, 100, 100}; // E, C, N, P, O. + std::uint32_t energy_kept_per_thousand{1'000}; // Of each energy bubble; the rest is heat. + std::uint32_t membrane_nm{1'000}; + std::uint16_t engulf_capacity{100}, kill_absorption{100}; + auto operator<=>(const CellularRevampLifeInput&) const = default; +}; struct CellularRegionRules { // Rules 3: engulfment, and every corpse's inventory deposited as patch detritus. // Rules 2 (false) is the original trial: engulf intents are ignored and starvation @@ -25,6 +51,8 @@ struct CellularRegionRules { // its intake rate, with no intake target; pools yield at most a quarter of that rate. // A dead life's detritus becomes one bubble per non-empty channel. bool contact_feeding{}; + // Rules 13: present exactly when every life carries its revamp input. + std::optional revamp{}; auto operator<=>(const CellularRegionRules&) const = default; }; @@ -42,6 +70,8 @@ struct CellularLifeStepInput { // Rules 12: liquid motion, required exactly when the habitat is format 3. The movement // intent becomes the propulsion command. std::optional liquid{}; + // Rules 13 (ADR-0179), required exactly when the region rules declare revamp. + std::optional revamp{}; auto operator<=>(const CellularLifeStepInput&) const = default; }; enum class CellularEngulfStatus : std::uint8_t { @@ -88,6 +118,9 @@ struct CellularRegionStepCandidate { // Rules 3 detritus patches created at empty cells, sorted by address. std::vector new_patches; accounting::Picojoules heat_released{}; + // Rules 13: everything for the region's spent pool this tick: matter every life burned in + // place of energy (also in its own step candidate) and the spent share of kill remainders. + accounting::Inventory spent{}; auto operator<=>(const CellularRegionStepCandidate&) const = default; }; enum class CellularRegionStepError : std::uint8_t { diff --git a/include/evo/biology/cellular_revamp_tuning.hpp b/include/evo/biology/cellular_revamp_tuning.hpp index 684a576..c504768 100644 --- a/include/evo/biology/cellular_revamp_tuning.hpp +++ b/include/evo/biology/cellular_revamp_tuning.hpp @@ -21,6 +21,18 @@ struct CellularRevampTuning { std::int64_t version{}; // Body: the share of upkeep no upkeep-efficiency trait reduces. std::int64_t body_essential_upkeep_per_mille{}; + // Body: share of reserve matter carried as load on handling and thrust costs. + std::int64_t body_reserve_load_per_mille{}; + // Energy: picojoules 1,000 fg of each matter channel stand in for (burn efficiency 100). + std::int64_t energy_burn_carbon_pj_per_kfg{}, energy_burn_nitrogen_pj_per_kfg{}, + energy_burn_phosphorus_pj_per_kfg{}, energy_burn_other_pj_per_kfg{}; + // Feeding: per mille of collection lost per membrane point above the founder's 100. + std::int64_t feeding_membrane_collection_per_mille_per_point{}; + // Predation. + std::int64_t predation_engulf_ratio_milli{}, predation_engulf_reserve_percent{}, + predation_kill_bubble_per_mille{}; + // The spent pool's drip back into the region. + std::int64_t spent_drip_interval_ticks{}, spent_drip_bubble_pj{}, spent_drip_bubble_fg{}; auto operator<=>(const CellularRevampTuning&) const = default; }; diff --git a/include/evo/biology/cellular_step.hpp b/include/evo/biology/cellular_step.hpp index 8cef71d..988ef00 100644 --- a/include/evo/biology/cellular_step.hpp +++ b/include/evo/biology/cellular_step.hpp @@ -1,5 +1,6 @@ #pragma once +#include "evo/biology/cellular_burn.hpp" #include "evo/biology/cellular_habitat.hpp" #include "evo/biology/cellular_kinematics.hpp" @@ -21,6 +22,9 @@ struct CellularStepIntent { bool frozen{}; // Rules 12: oppose relative velocity instead of following `movement`. bool brake{}; + // Rules 13 (ADR-0179): matter channels the player keeps from being burned for anything but + // upkeep, bit 0 carbon to bit 3 other matter. Wildlife keeps nothing. + std::uint8_t exclude{}; auto operator<=>(const CellularStepIntent&) const = default; }; @@ -54,6 +58,9 @@ struct CellularStepCandidate { // Rules 12 (liquid motion): the motion state after the tick and the path travelled. CellularMotionState motion{}; std::uint64_t path_um{}; + // Rules 13 (ADR-0179): reserve matter burned in place of energy, for the region's spent + // pool. Costs paid this way add no heat. + accounting::Inventory spent{}; auto operator<=>(const CellularStepCandidate&) const = default; }; // Rules 12: liquid-relative motion inputs for one life (Cellular_Region_Movement_Plan.md). @@ -72,10 +79,12 @@ propose_cellular_step(std::uint64_t begin_tick, CellularArea area, CellularPosit const MetabolicBudget& budget, const CellularHabitat& habitat) noexcept; // Rules 12: maintenance first, then one kinematic tick funded from what is left; thrust it // cannot fund is not applied and the cell coasts with the flow. No targeted intake: liquid -// regions feed by contact in the region step. +// regions feed by contact in the region step. Rules 13 pass `burn`: reserve matter stands in +// for missing energy, any channel for maintenance and only unexcluded ones for thrust. [[nodiscard]] std::expected 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; + accounting::Inventory heat, const MetabolicBudget& budget, + const CellularBurn* burn = nullptr) noexcept; } // namespace evo::biology diff --git a/include/evo/server/lifecycle/cellular_revamp.hpp b/include/evo/server/lifecycle/cellular_revamp.hpp index 3353689..284611d 100644 --- a/include/evo/server/lifecycle/cellular_revamp.hpp +++ b/include/evo/server/lifecycle/cellular_revamp.hpp @@ -1,9 +1,13 @@ #pragma once +#include "evo/biology/cellular_habitat.hpp" +#include "evo/biology/cellular_region_step.hpp" #include "evo/biology/cellular_revamp_tuning.hpp" #include "evo/biology/development.hpp" +#include #include +#include // Rules 13 (ADR-0179, Cellular_Revamp_Build_Plan.md): what a cellular owner declares when it // upgrades to owner format 11. Taken from the Git tuning file when the region opens and @@ -12,10 +16,36 @@ namespace evo::server { struct CellularRevampRules { biology::BodyTuning body{}; + // Picojoules 1,000 fg of C, N, P and other matter stand in for at burn efficiency 100. + std::array burn_pj_per_kfg{}; + biology::CellularRevampStepRules step{}; + // The spent pool drips back as bubbles every `drip_interval_ticks` ticks (0: never), one + // bubble per non-empty channel of at most these amounts, at seeded random spots. + std::uint32_t drip_interval_ticks{}; + std::uint64_t drip_bubble_pj{}, drip_bubble_fg{}; + // Share of reserve matter carried as load, per mille: it slows thrust and turning and makes + // thrust costlier, in proportion to the body's mass. Upkeep stays on the body. + std::uint32_t reserve_load_per_thousand{}; auto operator<=>(const CellularRevampRules&) const = default; }; [[nodiscard]] bool cellular_revamp_valid(const CellularRevampRules& rules) noexcept; +// The spent pool's drip for the tick ending at `tick`: on every `drip_interval_ticks`-th tick, +// one bubble per non-empty channel of at most the declared size, taken from `spent`, at a +// seeded random spot (nudged east past taken addresses) with the next deposit id and `source`. +// A habitat at its deposit limit keeps the rest waiting. False only on identity overflow, with +// `config` and `spent` then unusable. +[[nodiscard]] 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); +// A body's handling carrying reserve matter: thrust, reverse thrust and turning scale by +// body / (body + load), full-output costs by (body + load) / body, where load is the declared +// share of `carried` matter. Drag is unchanged. No load leaves the handling as it is. +[[nodiscard]] biology::CellularHandling +cellular_loaded_handling(const biology::CellularHandling& handling, std::uint64_t body_mass, + std::uint64_t carried, const CellularRevampRules& rules) noexcept; // Rules from the revamp tuning file. [[nodiscard]] CellularRevampRules cellular_revamp_rules(const biology::CellularRevampTuning& tuning); diff --git a/src/biology/cellular_burn.cpp b/src/biology/cellular_burn.cpp new file mode 100644 index 0000000..81c708f --- /dev/null +++ b/src/biology/cellular_burn.cpp @@ -0,0 +1,96 @@ +#include "evo/biology/cellular_burn.hpp" + +#include +#include + +namespace evo::biology { +namespace { +constexpr auto u64_max = std::numeric_limits::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& base_pj_per_kfg, + const std::array& 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(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 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 diff --git a/src/biology/cellular_region_step.cpp b/src/biology/cellular_region_step.cpp index 7f029b0..76d2fa8 100644 --- a/src/biology/cellular_region_step.cpp +++ b/src/biology/cellular_region_step.cpp @@ -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 channel{}; + std::uint64_t shared{}; +}; +std::optional revamp_limits(const CellularLifeStepInput& life, + const CellularRevampStepRules& rules) { + if (!life.revamp) + return std::nullopt; + const auto& own = *life.revamp; + const auto points = static_cast(own.membrane_nm / 10); + const auto mult = std::clamp( + 1'000 - static_cast(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(mult) / 1'000; + if (channel != 0) + shared += *base; + } + limits.shared = shared * static_cast(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 @@ -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 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 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); diff --git a/src/biology/cellular_revamp_tuning.cpp b/src/biology/cellular_revamp_tuning.cpp index 2de046e..ebed8e8 100644 --- a/src/biology/cellular_revamp_tuning.cpp +++ b/src/biology/cellular_revamp_tuning.cpp @@ -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; } diff --git a/src/biology/cellular_step.cpp b/src/biology/cellular_step.cpp index cf3eb6e..a5b4547 100644 --- a/src/biology/cellular_step.cpp +++ b/src/biology/cellular_step.cpp @@ -97,11 +97,10 @@ propose_cellular_step(std::uint64_t begin_tick, CellularArea area, CellularPosit return candidate; } -std::expected -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 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::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; diff --git a/src/server/lifecycle/cellular_batch.cpp b/src/server/lifecycle/cellular_batch.cpp index 7de5854..b785068 100644 --- a/src/server/lifecycle/cellular_batch.cpp +++ b/src/server/lifecycle/cellular_batch.cpp @@ -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 ticks) { std::set identities; @@ -167,7 +168,9 @@ void put_intent(std::vector& out, const CellularLifeIntent& life) // player action records keep it zero: the trace alone carries a brake. out.push_back( static_cast((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 bytes) { step.lives.reserve(static_cast(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 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}; diff --git a/src/server/lifecycle/cellular_lives.cpp b/src/server/lifecycle/cellular_lives.cpp index f9c74ee..c7775c5 100644 --- a/src/server/lifecycle/cellular_lives.cpp +++ b/src/server/lifecycle/cellular_lives.cpp @@ -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* plans = nullptr) { + const std::vector* 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 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 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{new CellularLives{std::make_unique( @@ -877,13 +887,13 @@ CellularLives::exchange_boundary(std::span 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 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 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(in.get(4)); - if (in.get(4) != 0 || !cellular_revamp_valid(revamp)) + const auto u32 = [&in] { return static_cast(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 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 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 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 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 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 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 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 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 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> lit_lives; diff --git a/src/server/lifecycle/cellular_revamp.cpp b/src/server/lifecycle/cellular_revamp.cpp index 93f3b0c..2cebd5f 100644 --- a/src/server/lifecycle/cellular_revamp.cpp +++ b/src/server/lifecycle/cellular_revamp.cpp @@ -1,12 +1,108 @@ #include "evo/server/lifecycle/cellular_revamp.hpp" +#include "evo/core/random.hpp" + +#include +#include + 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(slower(handling.thrust_q10)); + loaded.reverse_thrust_q10 = static_cast(slower(handling.reverse_thrust_q10)); + loaded.turn = static_cast(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(x % config.width_um), + static_cast(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::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(t.body_essential_upkeep_per_mille)}}; + const auto u32 = [](std::int64_t value) { return static_cast(value); }; + const auto u64 = [](std::int64_t value) { return static_cast(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 diff --git a/tests/cellular_burn_tests.cpp b/tests/cellular_burn_tests.cpp new file mode 100644 index 0000000..2e4650e --- /dev/null +++ b/tests/cellular_burn_tests.cpp @@ -0,0 +1,133 @@ +#include "evo/biology/cellular_burn.hpp" + +#include +#include +#include +#include + +// Matter as energy (rules 13, ADR-0179): energy first, then the largest burnable channel at its +// rate; exclusions hold except for upkeep; nothing changes when the cost cannot be paid. +namespace { +using namespace evo; +using namespace evo::biology; +void check(bool condition, std::source_location at = std::source_location::current()) { + if (!condition) + throw std::runtime_error("cellular burn line " + std::to_string(at.line())); +} +#define CHECK(expression) check(static_cast(expression)) + +accounting::Inventory reserve(std::uint64_t energy, std::uint64_t c, std::uint64_t n, + std::uint64_t p, std::uint64_t o) { + return {{energy}, + {accounting::Femtograms{c}, accounting::Femtograms{n}, accounting::Femtograms{p}, + accounting::Femtograms{o}}}; +} +// 10 pJ per 1,000 fg on every channel unless stated. +CellularBurn flat(std::uint8_t excluded = 0) { + return cellular_burn({10, 10, 10, 10}, {100, 100, 100, 100}, excluded); +} + +void energy_first() { + auto r = reserve(500, 1'000, 1'000, 1'000, 1'000); + const auto paid = cellular_pay(r, 300, flat(), false); + CHECK(paid && paid->energy == 300 && paid->spent == accounting::Inventory{}); + CHECK(r == reserve(200, 1'000, 1'000, 1'000, 1'000)); +} + +void largest_channel_then_next() { + // 100 pJ of energy, then 150 pJ from matter: carbon (largest) covers 100 pJ with 10,000 fg, + // then nitrogen (now largest) covers the last 50 pJ with 5,000 fg. + auto r = reserve(100, 10'000, 8'000, 1'000, 2'000); + const auto paid = cellular_pay(r, 250, flat(), false); + CHECK(paid && paid->energy == 100 && paid->spent == reserve(0, 10'000, 5'000, 0, 0)); + CHECK(r == reserve(0, 0, 3'000, 1'000, 2'000)); + // Ties go to the lower channel. + auto tie = reserve(0, 3'000, 3'000, 0, 0); + const auto first = cellular_pay(tie, 10, flat(), false); + CHECK(first && first->spent == reserve(0, 1'000, 0, 0, 0)); +} + +void whole_femtograms_round_up() { + // 1 pJ at 10 pJ per 1,000 fg needs 100 fg; 1 pJ at 3 pJ per 1,000 fg needs 334 fg. + auto r = reserve(0, 1'000, 0, 0, 0); + const auto paid = cellular_pay(r, 1, flat(), false); + CHECK(paid && paid->spent.matter[0].value == 100); + auto odd = reserve(0, 1'000, 0, 0, 0); + const auto thirds = + cellular_pay(odd, 1, cellular_burn({3, 3, 3, 3}, {100, 100, 100, 100}, 0), false); + CHECK(thirds && thirds->spent.matter[0].value == 334); +} + +void exclusions_and_upkeep_override() { + // Carbon excluded: nitrogen pays, though carbon is larger. + auto r = reserve(0, 10'000, 2'000, 0, 0); + const auto paid = cellular_pay(r, 10, flat(0b0001), false); + CHECK(paid && paid->spent == reserve(0, 0, 1'000, 0, 0)); + // Only excluded matter left: refused for thrust, paid for upkeep. + auto kept = reserve(0, 10'000, 0, 0, 0); + CHECK(cellular_payable_energy(kept, flat(0b0001), false) == 0); + CHECK(!cellular_pay(kept, 10, flat(0b0001), false) && kept == reserve(0, 10'000, 0, 0, 0)); + const auto upkeep = cellular_pay(kept, 10, flat(0b0001), true); + CHECK(upkeep && upkeep->spent == reserve(0, 1'000, 0, 0, 0)); +} + +void refusal_changes_nothing() { + // 5 pJ of energy plus 10 pJ of matter cannot pay 16 pJ. + auto r = reserve(5, 1'000, 0, 0, 0); + CHECK(cellular_payable_energy(r, flat(), false) == 15); + CHECK(!cellular_pay(r, 16, flat(), false) && r == reserve(5, 1'000, 0, 0, 0)); + const auto exact = cellular_pay(r, 15, flat(), false); + CHECK(exact && exact->energy == 5 && exact->spent == reserve(0, 1'000, 0, 0, 0) && + r == reserve(0, 0, 0, 0, 0)); +} + +void efficiency_scales_rates() { + const auto burn = cellular_burn({10, 10, 10, 10}, {105, 99, 100, 100}, 0xFF); + CHECK(burn.pj_per_kfg[0] == 10 && burn.pj_per_kfg[1] == 9 && burn.excluded == 0x0F); + const auto finer = cellular_burn({10'000, 10'000, 0, 10'000}, {105, 99, 100, 100}, 0); + CHECK(finer.pj_per_kfg[0] == 10'500 && finer.pj_per_kfg[1] == 9'900); + // A zero rate cannot be burned. + auto r = reserve(0, 0, 0, 5'000, 0); + CHECK(cellular_payable_energy(r, finer, true) == 0 && !cellular_pay(r, 1, finer, true)); +} + +// Every femtogram and picojoule is accounted: reserve before = reserve after + paid. +void conservation_property() { + for (std::uint64_t seed = 1; seed < 400; ++seed) { + const auto x = seed * 2'654'435'761ULL; + const auto before = + reserve(x % 997, x % 50'021, (x >> 8) % 40'009, (x >> 16) % 3'001, (x >> 24) % 70'001); + const auto burn = cellular_burn({7 + seed % 13, 9, 11 + seed % 5, 13}, + {100, static_cast(80 + seed % 40), 100, 120}, + static_cast(seed % 16)); + auto after = before; + const auto cost = (x >> 32) % 2'000; + const auto paid = cellular_pay(after, cost, burn, seed % 3 == 0); + if (!paid) { + CHECK(after == before); + continue; + } + CHECK(after.energy.value + paid->energy == before.energy.value); + for (std::size_t c = 0; c < 4; ++c) + CHECK(after.matter[c].value + paid->spent.matter[c].value == before.matter[c].value); + CHECK(paid->spent.energy.value == 0); + } +} +} // namespace + +int main() { + try { + energy_first(); + largest_channel_then_next(); + whole_femtograms_round_up(); + exclusions_and_upkeep_override(); + refusal_changes_nothing(); + efficiency_scales_rates(); + conservation_property(); + } catch (const std::exception& error) { + std::fprintf(stderr, "%s\n", error.what()); + return 1; + } + std::puts("PASS cellular matter-as-energy payments"); + return 0; +} diff --git a/tests/cellular_revamp_owner_tests.cpp b/tests/cellular_revamp_owner_tests.cpp index 6e01ed3..1933a94 100644 --- a/tests/cellular_revamp_owner_tests.cpp +++ b/tests/cellular_revamp_owner_tests.cpp @@ -25,8 +25,41 @@ CellularLiquidRules liquid() { .bubble_radius_um = biology::cellular_mote_radius_um}}; } +// The trial revamp rules (deploy/kubernetes/region/dev/tuning/cellular-revamp.tuning). CellularRevampRules revamp(std::uint32_t essential = 250) { - return {.body = {.essential_upkeep_per_thousand = essential}}; + return {.body = {.essential_upkeep_per_thousand = essential}, + .burn_pj_per_kfg = {2'000, 2'000, 2'000, 2'000}, + .step = {.membrane_collection_per_mille_per_point = 2, + .engulf_ratio_milli = 1'500, + .engulf_reserve_percent = 100, + .kill_bubble_per_thousand = 500}, + .drip_interval_ticks = 20, + .drip_bubble_pj = 20'000'000, + .drip_bubble_fg = 1'000'000, + .reserve_load_per_thousand = 1'000}; +} + +// Reserve matter slows thrust and turning and raises thrust costs in proportion to the body. +void carried_matter_is_load() { + const biology::CellularHandling base{.thrust_q10 = 20'480, + .reverse_thrust_q10 = 10'240, + .forward_drag_ppm = 95'163, + .lateral_drag_ppm = 95'163, + .turn = 3'276, + .thrust_cost = {1'000}, + .reverse_cost = {500}}; + require(cellular_loaded_handling(base, 8'000'000, 0, revamp()) == base, + "an empty reserve changed the handling"); + const auto heavy = cellular_loaded_handling(base, 8'000'000, 8'000'000, revamp()); + require(heavy.thrust_q10 == 10'240 && heavy.reverse_thrust_q10 == 5'120 && + heavy.turn == 1'638 && heavy.thrust_cost.value == 2'000 && + heavy.reverse_cost.value == 1'000 && + heavy.forward_drag_ppm == base.forward_drag_ppm, + "carrying the body's mass again did not halve thrust and double its cost"); + auto none = revamp(); + none.reserve_load_per_thousand = 0; + require(cellular_loaded_handling(base, 8'000'000, 8'000'000, none) == base, + "a zero load share still loaded the cell"); } LifeAccount account(std::uint8_t last) { @@ -67,11 +100,13 @@ Owner revamp_region(std::uint32_t essential = 250) { return state; } -std::vector swim(const CellularLives& state, biology::CellularIntent movement) { +std::vector swim(const CellularLives& state, biology::CellularIntent movement, + std::uint8_t exclude = 0) { std::vector result; for (const auto& life : state.lives()) { CellularLifeIntent input{life.identity.life, {}}; input.intent.movement = movement; + input.intent.exclude = exclude; result.push_back(input); } return result; @@ -118,6 +153,93 @@ void mixed_generations_tick_and_continue() { closed(*continuous); } +// The spent pool drips back one bubble per non-empty channel on every interval tick, at +// seeded spots, without losing or creating anything; a full habitat keeps it waiting. +void the_spent_pool_drips_back() { + const auto rules = revamp(); + biology::CellularHabitatConfig config{7, 9, 11, 48'000, 48'000, {}}; + config.format = biology::cellular_habitat_liquid_format; + config.next_deposit = 1; + accounting::Inventory spent{{50'000'000}, {{{2'500'000}, {0}, {300}, {1'000'000}}}}; + auto off = config; + auto kept = spent; + require(cellular_drip_spent(off, kept, rules, 1, 2, 19, 5) && off == config && kept == spent, + "the pool dripped between intervals"); + auto once = config; + auto left = spent; + require(cellular_drip_spent(once, left, rules, 1, 2, 20, 5), "drip refused"); + require(once.patches.size() == 4 && once.next_deposit == 5, + "a drip is one bubble per non-empty channel"); + accounting::Inventory dripped{}; + for (const auto& bubble : once.patches) { + require(bubble.kind == biology::CellularDepositKind::mote && bubble.merged == 1 && + bubble.source == 5 && bubble.address.x_um < 48'000 && + bubble.address.y_um < 48'000, + "a drip bubble is malformed"); + dripped.energy.value += bubble.stock.energy.value; + for (std::size_t c = 0; c < 4; ++c) + dripped.matter[c].value += bubble.stock.matter[c].value; + } + require(dripped == + accounting::Inventory{{20'000'000}, {{{1'000'000}, {0}, {300}, {1'000'000}}}} && + left == accounting::Inventory{{30'000'000}, {{{1'500'000}, {0}, {0}, {0}}}}, + "the drip did not move the capped amounts exactly"); + auto again = config; + auto same = spent; + require(cellular_drip_spent(again, same, rules, 1, 2, 20, 5) && again == once, + "the drip is not deterministic"); + auto full = config; + for (std::uint32_t i = 0; i < biology::max_cellular_liquid_deposits; ++i) { + biology::CellularPatch filler{{i % 48'000, i / 48'000}, + 5, + {{1}, {}}, + ++full.next_deposit, + biology::cellular_mote_radius_um, + biology::CellularDepositKind::mote}; + filler.merged = 1; + full.patches.push_back(filler); + } + const auto packed = full; + auto waiting = spent; + require(cellular_drip_spent(full, waiting, rules, 1, 2, 20, 5) && full == packed && + waiting == spent, + "a full habitat took a drip"); +} + +// Exclusions belong to owned lives under rules 13 and travel in the trace. +void exclusions_are_checked_and_replayed() { + auto state = revamp_region(); + require(state->advance_tick(swim(*state, {300, 0}, 0b0101)).has_value(), + "an owned life's exclusions were refused"); + require(!state->advance_tick(swim(*state, {}, 0x10)).has_value(), + "an exclusion outside the four matter channels was accepted"); + auto older = opening(7, true, 2, false); + checked(older->advance_tick({}), "genesis tick"); + older = checked(older->migration_upgrade_candidate(), "boundary upgrade"); + older = checked(older->maturation_upgrade_candidate(), "maturation upgrade"); + older = checked(older->inheritance_upgrade_candidate(), "inheritance upgrade"); + older = checked(older->photosynthesis_upgrade_candidate({0, 1, {0}}), "light upgrade"); + older = checked(older->liquid_upgrade_candidate(liquid()), "liquid upgrade"); + older = checked(older->birth_candidate({account(1), 1}, {100, 100, 100, 100, {older->tick()}}), + "founder 5 birth"); + require(!older->advance_tick(swim(*older, {}, 0b0001)).has_value(), + "a rules-12 owner accepted exclusions"); +} + +// A rules-13 region runs long enough for founders to spend their endowment, keeping closure, +// and restores with its rules and spent pool exactly. +void a_long_run_keeps_closure_and_restores() { + auto state = revamp_region(); + for (int tick = 0; tick < 700; ++tick) { + const auto x = static_cast((tick / 50) % 2 == 0 ? 900 : -900); + checked(state->advance_tick(swim(*state, {x, 400}, 0b0010)), "long-run tick"); + } + closed(*state); + const auto copy = restore(*state); + require(copy->snapshot() == state->snapshot() && copy->revamp_rules() == revamp(), + "format 11 did not restore the rules and spent pool exactly"); +} + // A recorded trace replays to the exact live result under rules 13. void trace_replays() { auto live = revamp_region(); @@ -128,7 +250,8 @@ void trace_replays() { batch.header.predecessor.fill(1); batch.header.predecessor_digest.fill(2); for (int tick = 0; tick < 24; ++tick) { - const auto intents = swim(*live, {static_cast(tick < 12 ? 1'000 : -400), 0}); + const auto intents = swim(*live, {static_cast(tick < 12 ? 1'000 : -400), 0}, + static_cast(tick % 16)); checked(live->advance_tick(intents), "recorded tick"); batch.ticks.push_back({intents, {}, {}}); } @@ -137,12 +260,18 @@ void trace_replays() { const auto decoded = checked(decode_cellular_batch(bytes), "trace decodes"); const auto replayed = checked(replay_cellular_batch(*base, decoded), "trace replays"); require(replayed->snapshot() == live->snapshot(), "replay diverged from the live run"); + require(decoded.ticks.back().lives.front().intent.exclude == 23 % 16, + "exclusions did not survive the trace"); } } // namespace int main() try { upgrade_and_restore(); mixed_generations_tick_and_continue(); + the_spent_pool_drips_back(); + carried_matter_is_load(); + exclusions_are_checked_and_replayed(); + a_long_run_keeps_closure_and_restores(); trace_replays(); std::puts("PASS rules 13 owner: upgrade, founder 6, restore and replay"); return 0; diff --git a/tests/cellular_revamp_step_tests.cpp b/tests/cellular_revamp_step_tests.cpp new file mode 100644 index 0000000..4216410 --- /dev/null +++ b/tests/cellular_revamp_step_tests.cpp @@ -0,0 +1,271 @@ +#include "evo/biology/cellular_region_step.hpp" + +#include +#include +#include +#include +#include +#include +#include + +// Rules 13 region step (ADR-0179; feeding and energy, predation and defense plans): per-channel +// collection with a shared limit, the membrane's collection cost, the kept share of bubble +// energy, matter standing in for energy, engulf eligibility with reserve mass and capacity, and +// the kill remainder split between bubbles and the spent pool. Everything conserves. +namespace { +using namespace evo::biology; +using evo::accounting::Inventory; + +void check(bool value, std::source_location at = std::source_location::current()) { + if (!value) + throw std::runtime_error("cellular revamp step line " + std::to_string(at.line())); +} +#define CHECK(...) check(static_cast(__VA_ARGS__)) + +constexpr CellularArea area{3'000, 2'000}; +constexpr CellularRegionRules plain{true, true, CellularRevampStepRules{}}; + +Inventory inv(std::uint64_t e, std::uint64_t c, std::uint64_t n, std::uint64_t p, std::uint64_t o) { + return {{e}, {{{c}, {n}, {p}, {o}}}}; +} +void add(Inventory& to, const Inventory& from) { + to.energy.value += from.energy.value; + for (std::size_t i = 0; i < to.matter.size(); ++i) + to.matter[i].value += from.matter[i].value; +} + +// One bubble at (100, 100), or none. +std::unique_ptr liquid_map(const Inventory& stock, bool bubble = true) { + CellularHabitatConfig config{7, 9, 11, area.width_um, area.height_um, {}}; + config.format = cellular_habitat_liquid_format; + config.next_deposit = 2; + if (bubble) { + CellularPatch mote{ + {100, 100}, 51, stock, 1, cellular_mote_radius_um, CellularDepositKind::mote}; + mote.merged = 1; + config.patches.push_back(mote); + } + auto made = CellularHabitat::create(std::move(config)); + CHECK(made); + return std::move(*made); +} + +// Intake limits of 1,000 per second on every channel: 50 per 50 ms tick. +MetabolicBudget budget(std::uint64_t mass, std::uint64_t maintenance = 0) { + MetabolicBudget value{}; + value.rate_microseconds = 1'000'000; + value.intake_limit = inv(1'000, 1'000, 1'000, 1'000, 1'000); + value.phenotype.total_mass = mass; + value.maintenance.value = maintenance; + return value; +} + +CellularRevampLifeInput founder_input() { + CellularRevampLifeInput input{}; + input.burn = cellular_burn({10, 10, 10, 10}, {100, 100, 100, 100}, 0); + return input; +} + +// A still cell; no thrust, no current. +CellularLifeStepInput cell(std::uint64_t id, CellularPosition at, std::uint64_t mass, + const Inventory& reserve, bool engulf = false, + CellularRevampLifeInput revamp = founder_input(), + std::uint64_t maintenance = 0) { + CellularLifeStepInput life{}; + life.life_id = id; + life.position = at; + life.extent_um = 20; + life.intent.engulf = engulf; + life.body = inv(0, 10, 10, 10, 10); + life.reserve = reserve; + life.budget = budget(mass, maintenance); + life.membrane_um = 1; + life.source = 51; + life.liquid = CellularLiquidInput{}; + life.revamp = revamp; + return life; +} + +// Everything the region holds after a candidate: lives (body, reserve, heat), deposits, corpses, +// heat released and the spent pool. +Inventory total(const CellularRegionStepCandidate& c, const CellularHabitat& map, + std::span lives) { + Inventory sum{}; + for (std::size_t i = 0; i < map.patches().size(); ++i) { + const auto update = std::ranges::find(c.patches, map.patches()[i].address, + &CellularPatchStockUpdate::address); + add(sum, update == c.patches.end() ? map.patches()[i].stock : update->stock); + } + for (const auto& patch : c.new_patches) + add(sum, patch.stock); + for (const auto& corpse : c.starved) + add(sum, corpse.inventory); + for (const auto& life : c.lives) { + add(sum, life.candidate.reserve_after); + add(sum, life.candidate.heat_after); + for (const auto& input : lives) + if (input.life_id == life.life_id) + add(sum, input.body); + } + sum.energy.value += c.heat_released.value; + add(sum, c.spent); + return sum; +} +Inventory before(const CellularHabitat& map, std::span lives) { + Inventory sum{}; + for (const auto& patch : map.patches()) + add(sum, patch.stock); + for (const auto& life : lives) { + add(sum, life.reserve); + add(sum, life.body); + add(sum, life.heat); + } + return sum; +} + +void collection_per_channel_with_a_shared_limit() { + const auto map = liquid_map(inv(1'000, 1'000, 1'000, 1'000, 1'000)); + auto input = founder_input(); + input.collection = {100, 200, 100, 100, 100}; + input.energy_kept_per_thousand = 400; + const std::array lives{cell(1, {95, 95}, 1'000, {}, false, input)}; + const auto result = propose_cellular_region_step(4, area, lives, *map, plain); + CHECK(result && result->lives.size() == 1); + const auto& reserve = result->lives[0].candidate.reserve_after; + // Carbon at 200 takes 100 of the shared 200; N and P take their 50; other matter gets none. + CHECK(reserve.matter[0].value == 100 && reserve.matter[1].value == 50 && + reserve.matter[2].value == 50 && reserve.matter[3].value == 0); + // 50 pJ drained, 40% kept, the rest heat. + CHECK(reserve.energy.value == 20 && result->lives[0].candidate.heat_after.energy.value == 30); + CHECK(total(*result, *map, lives) == before(*map, lives)); +} + +void a_thicker_membrane_collects_slower() { + const auto map = liquid_map(inv(1'000, 1'000, 1'000, 1'000, 1'000)); + auto input = founder_input(); + input.membrane_nm = 1'100; // 110 points. + CellularRevampStepRules costly{}; + costly.membrane_collection_per_mille_per_point = 20; // 10 points: -20%. + const CellularRegionRules rules{true, true, costly}; + const std::array lives{cell(1, {95, 95}, 1'000, {}, false, input)}; + const auto result = propose_cellular_region_step(4, area, lives, *map, rules); + CHECK(result); + const auto& reserve = result->lives[0].candidate.reserve_after; + CHECK(reserve.matter[0].value == 40 && reserve.energy.value == 40); + CHECK(total(*result, *map, lives) == before(*map, lives)); +} + +void matter_pays_upkeep_and_nothing_left_starves() { + const auto map = liquid_map({}, false); + // 20 pJ per second is 1 pJ per tick; 10 pJ per 1,000 fg makes that 100 fg of carbon. + const std::array lives{ + cell(1, {500, 500}, 1'000, inv(0, 1'000, 0, 0, 0), false, founder_input(), 20), + cell(2, {900, 900}, 1'000, {}, false, founder_input(), 20)}; + const auto result = propose_cellular_region_step(4, area, lives, *map, plain); + CHECK(result && result->lives.size() == 1 && result->lives[0].life_id == 1); + CHECK(result->lives[0].candidate.reserve_after == inv(0, 900, 0, 0, 0)); + CHECK(result->lives[0].candidate.spent == inv(0, 100, 0, 0, 0)); + CHECK(result->lives[0].candidate.heat_after.energy.value == 0); // Matter adds no heat. + CHECK(result->spent == inv(0, 100, 0, 0, 0)); + CHECK(result->starved.size() == 1 && result->starved[0].life_id == 2); + CHECK(total(*result, *map, lives) == before(*map, lives)); +} + +void reserve_mass_and_capacity_decide_engulfment() { + const auto map = liquid_map({}, false); + // Predator 3,000; prey body 1,000 plus 1,000 fg of reserve matter: exactly 1.5 times. + const auto prey_reserve = inv(100, 250, 250, 250, 250); + { + const std::array lives{cell(1, {500, 500}, 3'000, {}, true), + cell(2, {510, 500}, 1'000, prey_reserve)}; + const auto result = propose_cellular_region_step(4, area, lives, *map, plain); + CHECK(result && result->lives.size() == 1 && + result->lives[0].engulf == CellularEngulfStatus::engulfed); + CHECK(total(*result, *map, lives) == before(*map, lives)); + } + { + // One more femtogram of reserve makes the prey too large. + const std::array lives{cell(1, {500, 500}, 3'000, {}, true), + cell(2, {510, 500}, 1'000, inv(100, 251, 250, 250, 250))}; + const auto result = propose_cellular_region_step(4, area, lives, *map, plain); + CHECK(result && result->lives.size() == 2 && + result->lives[0].engulf == CellularEngulfStatus::prey_too_large); + // Counting no reserve, or a bigger chamber, makes it eligible again. + CellularRevampStepRules unladen{}; + unladen.engulf_reserve_percent = 0; + const CellularRegionRules light{true, true, unladen}; + const auto again = propose_cellular_region_step(4, area, lives, *map, light); + CHECK(again && again->lives.size() == 1); + auto chamber = founder_input(); + chamber.engulf_capacity = 105; + const std::array bigger{cell(1, {500, 500}, 3'000, {}, true, chamber), lives[1]}; + const auto wider = propose_cellular_region_step(4, area, bigger, *map, plain); + CHECK(wider && wider->lives.size() == 1); + } + { + // A thicker membrane defends: reported as the membrane, not the size. + auto tough = founder_input(); + tough.membrane_nm = 1'200; + const std::array lives{cell(1, {500, 500}, 3'000, {}, true), + cell(2, {510, 500}, 1'000, prey_reserve, false, tough)}; + const auto result = propose_cellular_region_step(4, area, lives, *map, plain); + CHECK(result && result->lives.size() == 2 && + result->lives[0].engulf == CellularEngulfStatus::membrane_too_thick); + } +} + +void a_kill_splits_its_remainder() { + const auto map = liquid_map({}, false); + auto hunter = founder_input(); + hunter.energy_kept_per_thousand = 500; + hunter.kill_absorption = 200; // Twice the 50-per-tick limit: 100 per channel. + const std::array lives{cell(1, {500, 500}, 4'000, {}, true, hunter), + cell(2, {510, 500}, 1'000, inv(1'000, 290, 290, 290, 290))}; + const auto result = propose_cellular_region_step(4, area, lives, *map, plain); + CHECK(result && result->lives.size() == 1); + const auto& predator = result->lives[0].candidate; + // Prey: 1,000 pJ and 300 fg per channel (290 reserve + 10 body). Absorbed: 100 each; + // half of the 100 pJ kept, half heat. + CHECK(predator.reserve_after == inv(50, 100, 100, 100, 100)); + CHECK(predator.heat_after.energy.value == 50); + // Remainder 900 pJ and 200 fg per channel: half as bubbles, half to the spent pool. + CHECK(result->spent == inv(450, 100, 100, 100, 100)); + Inventory bubbles{}; + for (const auto& patch : result->new_patches) + add(bubbles, patch.stock); + CHECK(bubbles == inv(450, 100, 100, 100, 100)); + CHECK(total(*result, *map, lives) == before(*map, lives)); +} + +void every_life_needs_a_revamp_input() { + const auto map = liquid_map({}, false); + auto bare = cell(1, {500, 500}, 1'000, {}); + bare.revamp.reset(); + const std::array lives{bare}; + CHECK(!propose_cellular_region_step(4, area, lives, *map, plain)); + auto greedy = founder_input(); + greedy.energy_kept_per_thousand = 1'001; + const auto kept = cell(1, {500, 500}, 1'000, {}, false, greedy); + const std::array bad{kept}; + CHECK(!propose_cellular_region_step(4, area, bad, *map, plain)); + // And none without rules 13. + const std::array revamped{cell(1, {500, 500}, 1'000, {})}; + CHECK(!propose_cellular_region_step(4, area, revamped, *map, CellularRegionRules{true, true})); +} +} // namespace + +int main() { + try { + collection_per_channel_with_a_shared_limit(); + a_thicker_membrane_collects_slower(); + matter_pays_upkeep_and_nothing_left_starves(); + reserve_mass_and_capacity_decide_engulfment(); + a_kill_splits_its_remainder(); + every_life_needs_a_revamp_input(); + } catch (const std::exception& error) { + std::fprintf(stderr, "%s\n", error.what()); + return 1; + } + std::puts("PASS rules 13 region step: collection, energy, matter as energy and engulfment"); + return 0; +} diff --git a/tests/cellular_revamp_tuning_tests.cpp b/tests/cellular_revamp_tuning_tests.cpp index 0fb5278..d9ddb71 100644 --- a/tests/cellular_revamp_tuning_tests.cpp +++ b/tests/cellular_revamp_tuning_tests.cpp @@ -18,7 +18,20 @@ void check(bool condition, std::source_location at = std::source_location::curre #define CHECK(expression) check(static_cast(expression)) CellularRevampTuning trial() { - return {.version = 1, .body_essential_upkeep_per_mille = 250}; + return {.version = 1, + .body_essential_upkeep_per_mille = 250, + .body_reserve_load_per_mille = 1'000, + .energy_burn_carbon_pj_per_kfg = 2'000, + .energy_burn_nitrogen_pj_per_kfg = 2'000, + .energy_burn_phosphorus_pj_per_kfg = 2'000, + .energy_burn_other_pj_per_kfg = 2'000, + .feeding_membrane_collection_per_mille_per_point = 2, + .predation_engulf_ratio_milli = 1'500, + .predation_engulf_reserve_percent = 100, + .predation_kill_bubble_per_mille = 500, + .spent_drip_interval_ticks = 20, + .spent_drip_bubble_pj = 20'000'000, + .spent_drip_bubble_fg = 1'000'000}; } std::string with(std::string text, const std::string& key, const std::string& value) { @@ -60,6 +73,10 @@ void refusals() { const auto parsed = parse_cellular_revamp_tuning(missing); CHECK(!parsed && parsed.error().kind == CellularTuningErrorKind::missing_key && parsed.error().key == "body.essential_upkeep_per_mille"); + CHECK(error_of(with(base, "spent.drip_bubble_fg", "0")) == + CellularTuningErrorKind::inconsistent); + CHECK(error_of(with(base, "predation.engulf_reserve_percent", "101")) == + CellularTuningErrorKind::out_of_range); // Rules-12 keys belong in the other file. CHECK(error_of(base + "region.width_um = 60000\n") == CellularTuningErrorKind::unknown_key); CHECK(error_of(std::string(max_cellular_revamp_tuning_bytes + 1, '#')) ==