diff --git a/Cellular_Revamp_Build_Plan.md b/Cellular_Revamp_Build_Plan.md index 2abfe0d..3f4e3d2 100644 --- a/Cellular_Revamp_Build_Plan.md +++ b/Cellular_Revamp_Build_Plan.md @@ -113,10 +113,10 @@ refusal reasons. Verify: control transfer is one way and exactly once across retries and restarts; splits and litters conserve; a refused split spends nothing. -### Phase 5: multicellular organisms and emergence +### Phase 5: multicellular organisms and emergence - server done -Blocked on the maintainer's confirmation of the locked-requirement question in -ADR-0179 (whole-organism mutations). +Unblocked 2026-10-23: the maintainer accepted whole-organism mutations and the +playtest form of Emerge (ADR-0179). Server: - Adhesion forms the organism at once. The organism is one life with a member count, @@ -126,6 +126,23 @@ Server: - Emergence threshold (members, mass, reserve energy) and the Emerge action; the wildlife member limit as a safeguard. +As built: +- An organism develops as its genome with the target size times its members, so mass, + footprint, upkeep, intake and engulf mass all follow from it. Its corpse records the + single-cell extent. +- Adhesion ends the single cell's life as `merged` (an empty corpse) and starts the + organism as a new life (bud identity, two members) holding the whole body and reserve, + at the cell's spot and with its account, affinity and progress. +- An organism's mutation is recorded as a direct expression (no split); its changed + tissue is paid from the reserve with construction energy. Unaffordable keeps the offer. +- An organism's bud pays the bud fee and adds litter members at the current growth. + Wildlife organisms stop one member short of the threshold. An organism cannot become + its bud. +- Handling adds `organism.load_per_mille` of the extra members' mass as load. +- Emerge (intent bit, exclusive with bud, engulf, intake and frozen) at the threshold + exports the body and reserve through the boundary ledger and ends the life as + `emerged`. Below the threshold the request is ignored. + Client: organism drawn as its member cells; Emerge button at the threshold. Verify: one reserve and one genome across members; whole engulfment conserves; the @@ -154,9 +171,10 @@ Emerge action only at the threshold. | Item | Phase | | --- | --- | -| Whole-organism mutations versus the locked "structural changes are expressed in offspring" requirement | 5 | -| What Emerge does before the 3D world exists | 5 | | Retuning bubble energy or founder `energy_conversion` (keep 40% vs today's 100%) | 2 | +| Organism pace: in tests a two-member organism at half growth swims about 7.5 µm per tick and needed about 5,000 ticks on a rich mote to fund one internal member | 6 | +| Region migration does not carry rules-13 per-life state (affinity, members); an organism's move would be refused | 6 | +| The life-ended message has no `emerged` reason yet (reported as unrecorded) | v14 | ## Risks diff --git a/apps/evo-server/cellular_bridge.hpp b/apps/evo-server/cellular_bridge.hpp index 4a5d430..f22590e 100644 --- a/apps/evo-server/cellular_bridge.hpp +++ b/apps/evo-server/cellular_bridge.hpp @@ -450,6 +450,10 @@ class CellularBridge { return l.identity.life; }) != state.lives().end()) continue; + // Rules 13: control moved to another life (succession, or a merge into an organism). + if (std::ranges::find(state.lives(), account, &server::CellularOwnedLife::account) != + state.lives().end()) + continue; const auto corpse = std::ranges::find(state.corpses(), life_id, &server::CellularOwnedCorpse::life_id); if (corpse == state.corpses().end()) diff --git a/deploy/kubernetes/region/dev-session-route/listener.yaml b/deploy/kubernetes/region/dev-session-route/listener.yaml index 4b14c98..36210d5 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-20261023T021936-96b9c651:1792736376"} + - {name: REGION_SESSION_WINDOW, value: "dev-20261023T104955-41ebed4e:1792766995"} - {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 c2985ed..4db2dfc 100644 --- a/deploy/kubernetes/region/dev/tuning/cellular-revamp.tuning +++ b/deploy/kubernetes/region/dev/tuning/cellular-revamp.tuning @@ -58,6 +58,12 @@ reproduction.bud_fee_o_fg = 0 reproduction.bud_fee_scale_percent = 0 reproduction.organism_cap = 256 # births refused at this many lives (an organism counts once) +# Multicellular organisms (reproduction plan section 6). +organism.load_per_mille = 500 # share of the extra members' mass loading one cell's thrust +organism.emerge_members = 8 # Emerge needs at least this many cells, +organism.emerge_mass_fg = 100_000_000 # this much body and reserve mass, +organism.emerge_reserve_pj = 0 # and this much reserve energy + # Per-mutation overrides are optional: `mutation.. = value`, with fields enabled, # base_weight, increase_points, decrease_points, primary_step, paired_step, spread_step, # increase_ticks, decrease_ticks, cost_e_pj, cost_c_fg, cost_n_fg, cost_p_fg, cost_o_fg and diff --git a/docs/PROJECT_VISION.md b/docs/PROJECT_VISION.md index bad6702..1c22bcf 100644 --- a/docs/PROJECT_VISION.md +++ b/docs/PROJECT_VISION.md @@ -21,7 +21,7 @@ requirements. See [the architecture](architecture/SYSTEM_OVERVIEW.md), |---|---| | Absolute permadeath | Dead organisms never resume. A fresh life after death starts as a primitive cell with no account-age advantage. Voluntary one-way succession into living newborn offspring at birth is distinct from a fresh life; no return to the NPC parent or fallback after the child's death. | | Persistent ancestry | At birth the player stays as the parent or continues as the child; the other organism is independent wildlife. A relinquished parent retains its established behavior and reproductive plan. Independent relatives survive player logout/death and face ordinary ecology. Extinct genomes remain in history. | -| Structural inheritance | Body-plan changes are expressed in offspring; retain the parent's existing anatomy separately from its heritable offspring plan. Capability and construction costs remain real. | +| Structural inheritance | Body-plan changes of a single cell are expressed in offspring; retain the parent's existing anatomy separately from its heritable offspring plan. A multicellular organism, one body of many cells, expresses an accepted change as a whole, funded from its reserve (maintainer, 2026-10-23; ADR-0179). Capability and construction costs remain real. | | Player-origin biology | A world can start with geology and chemistry but no life. Every lineage must ultimately reference a player-influenced founder. Do not silently seed prebuilt wildlife. | | Ecological progression | No classes, mandatory intelligence endgame, linear mutation tree, or cell-to-human ladder. Mixed and unfamiliar strategies are valid. | | Biological costs | Traits change physical/developmental parameters. Energy, matter, nutrients and environmental constraints determine consequences. | diff --git a/docs/adr/0179-cellular-gameplay-revamp.md b/docs/adr/0179-cellular-gameplay-revamp.md index 9cb4d1f..6bb7509 100644 --- a/docs/adr/0179-cellular-gameplay-revamp.md +++ b/docs/adr/0179-cellular-gameplay-revamp.md @@ -43,22 +43,18 @@ The system plans are the decision. In summary: - **Postponed:** temperature, sensing, multicellular mutations, damage, draft groups 071-150. -## Conflicts with locked requirements +## Conflicts with locked requirements (resolved 2026-10-23) -The project vision is the product authority. Two decisions need the maintainer's -explicit confirmation before the affected code (build plan phase 5) is written: +The project vision is the product authority. The maintainer settled both conflicts: -1. **Whole-organism mutations.** The vision locks "structural mutations are expressed - in offspring rather than rebuilding the parent's existing body". The reproduction - plan has a multicellular organism express an accepted mutation directly. Proposed - resolution: amend the vision so that the rule applies to single cells, and a - multicellular organism, being one body grown from many cells, re-expresses its plan - as a whole. Alternative: an organism's mutation is expressed only by members added - after it. -2. **Emergence before the 3D world.** ADR-0177's emergence needs the 3D world, which - does not exist. Proposed for the playtest: Emerge records the organism's matter as an - export from the region and ends the cellular life with an "emerged" outcome; the - player then starts a fresh life. +1. **Whole-organism mutations: accepted.** The vision's structural-inheritance rule now + applies to single cells. A multicellular organism, one body grown from many cells, + expresses an accepted mutation as a whole, funded from its shared reserve + ([PROJECT_VISION.md](../PROJECT_VISION.md) amended). +2. **Emergence before the 3D world: accepted.** Emerge records the organism's matter as + an export from the region and ends the cellular life with an "emerged" outcome; the + player then starts a fresh life. This lets the full cellular loop be played several + times before work on the 3D space. ## Alternatives diff --git a/include/evo/biology/budding.hpp b/include/evo/biology/budding.hpp index f031b48..4e8716d 100644 --- a/include/evo/biology/budding.hpp +++ b/include/evo/biology/budding.hpp @@ -5,6 +5,7 @@ #include #include #include +#include // M11.5 budding (ADR-0098 decision 1, ADR-0125): a funded proposal, detached from any // owner. The parent pays its ADR-0032 reproduction investment and a starting provision @@ -66,6 +67,13 @@ split_cell(const Genome& parent, const Genome& child, GrowthState growth, const accounting::Inventory& body, const accounting::Inventory& reserve, std::uint32_t temperature_millikelvin, std::uint32_t share_per_thousand, std::uint32_t min_growth, const BodyTuning& tuning = default_body_tuning); +// Rules 13: the largest growth whose body `genome` builds within `matter` on every channel and +// that body; nothing when even the smallest does not fit. +[[nodiscard]] std::expected>, + BuddingError> +largest_growth_within(const Genome& genome, const accounting::Inventory& matter, + std::uint32_t temperature_millikelvin, + const BodyTuning& tuning = default_body_tuning); // What one bud takes from a fully grown, undamaged parent of this genome at this temperature // (ADR-0129 amendment): investment matter per channel, and construction energy plus the // bud's provision; exactly what `fund_bud` charges such a parent. Nullopt when the genome diff --git a/include/evo/biology/cellular_region_step.hpp b/include/evo/biology/cellular_region_step.hpp index 310b512..a7fe6b1 100644 --- a/include/evo/biology/cellular_region_step.hpp +++ b/include/evo/biology/cellular_region_step.hpp @@ -97,7 +97,15 @@ struct CellularPatchStockUpdate { auto operator<=>(const CellularPatchStockUpdate&) const = default; }; // Unrecorded: a corpse from a checkpoint format that kept no cause (before format 4). -enum class CellularDeathCause : std::uint8_t { unrecorded = 0, starved = 1, engulfed = 2 }; +// Rules 13 (ADR-0179): merged, a single cell that became a multicellular organism (its body and +// reserve moved into the organism); emerged, an organism that left the region for the world. +enum class CellularDeathCause : std::uint8_t { + unrecorded = 0, + starved = 1, + engulfed = 2, + merged = 3, + emerged = 4 +}; struct CellularCorpseCandidate { std::uint64_t life_id{}; CellularPosition position; diff --git a/include/evo/biology/cellular_revamp_tuning.hpp b/include/evo/biology/cellular_revamp_tuning.hpp index fd12914..dd0e998 100644 --- a/include/evo/biology/cellular_revamp_tuning.hpp +++ b/include/evo/biology/cellular_revamp_tuning.hpp @@ -50,6 +50,9 @@ struct CellularRevampTuning { std::int64_t reproduction_bud_fee_e_pj{}, reproduction_bud_fee_c_fg{}, reproduction_bud_fee_n_fg{}, reproduction_bud_fee_p_fg{}, reproduction_bud_fee_o_fg{}; std::int64_t reproduction_bud_fee_scale_percent{}, reproduction_organism_cap{}; + // Multicellular organisms. + std::int64_t organism_load_per_mille{}, organism_emerge_members{}, organism_emerge_mass_fg{}, + organism_emerge_reserve_pj{}; // Each catalog mutation's tunables, in catalog order. Optional keys // `mutation..` override the defaults from its spec. std::array mutations{}; diff --git a/include/evo/biology/cellular_step.hpp b/include/evo/biology/cellular_step.hpp index fa92964..e021c68 100644 --- a/include/evo/biology/cellular_step.hpp +++ b/include/evo/biology/cellular_step.hpp @@ -27,6 +27,8 @@ struct CellularStepIntent { std::uint8_t exclude{}; // Rules 13: with `bud`, the player continues as the (first) bud; the parent becomes wildlife. bool become{}; + // Rules 13: an organism at the emergence threshold leaves the region for the world. + bool emerge{}; auto operator<=>(const CellularStepIntent&) const = default; }; diff --git a/include/evo/server/lifecycle/cellular_lives.hpp b/include/evo/server/lifecycle/cellular_lives.hpp index 7deec4f..d089946 100644 --- a/include/evo/server/lifecycle/cellular_lives.hpp +++ b/include/evo/server/lifecycle/cellular_lives.hpp @@ -168,6 +168,10 @@ struct CellularOffspringRevision { [[nodiscard]] constexpr std::uint64_t cellular_offspring_genome(const CellularOwnedLife& life) { return life.offspring_genome == 0 ? life.identity.genome : life.offspring_genome; } +// Rules 13 (reproduction plan section 7): an owned organism with enough members, body and reserve +// mass, and reserve energy may emerge. +[[nodiscard]] bool cellular_can_emerge(const CellularOwnedLife& life, + const CellularRevampRules& rules) noexcept; class CellularMigration; class CellularEnvironment; struct CellularLifeIntent { diff --git a/include/evo/server/lifecycle/cellular_play_summary.hpp b/include/evo/server/lifecycle/cellular_play_summary.hpp index 9905c75..4840bcc 100644 --- a/include/evo/server/lifecycle/cellular_play_summary.hpp +++ b/include/evo/server/lifecycle/cellular_play_summary.hpp @@ -15,6 +15,8 @@ struct CellularPlaySummary { std::uint64_t owned{}, wildlife{}, lingering{}, suspended{}; // Every death so far, by recorded cause (unrecorded below rules 3) and by kind. std::uint64_t deaths{}, starved{}, engulfed{}, unrecorded{}; + // Rules 13: single cells that became organisms, and organisms that emerged. + std::uint64_t merged{}, emerged{}; std::uint64_t owned_deaths{}, wildlife_deaths{}; // Lifespans in ticks of the dead (born to death), from the archive. std::uint64_t lifespan_min{}, lifespan_median{}, lifespan_max{}; diff --git a/include/evo/server/lifecycle/cellular_revamp.hpp b/include/evo/server/lifecycle/cellular_revamp.hpp index be7715e..4d9e9e7 100644 --- a/include/evo/server/lifecycle/cellular_revamp.hpp +++ b/include/evo/server/lifecycle/cellular_revamp.hpp @@ -45,6 +45,11 @@ struct CellularRevampRules { accounting::Inventory bud_fee{}; std::uint32_t bud_fee_scale_percent{}; std::uint32_t organism_cap{256}; + // Multicellular organisms (reproduction plan section 6): the share of the extra members' + // mass carried as load on one cell's thrust, and the emergence threshold. + std::uint32_t organism_load_per_thousand{500}; + std::uint32_t emerge_members{8}; + std::uint64_t emerge_mass_fg{}, emerge_reserve_pj{}; auto operator<=>(const CellularRevampRules&) const = default; }; @@ -64,6 +69,7 @@ struct CellularRevampLife { biology::CellularLineageProgress progress{}; std::uint32_t active_ticks{}; std::uint8_t last_brake{}; + std::uint16_t members{1}; // Cells in the organism: 1 for a single cell. std::uint32_t growth_carry{}; std::uint64_t events{}; // Offers made so far; the next offer's event index is events + 1. CellularRevampOffer offer{}; @@ -116,7 +122,8 @@ cellular_mutation_cost(const biology::CellularMutationTuning& tuning) noexcept; // 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; + std::uint64_t carried, const CellularRevampRules& rules, + std::uint64_t extra_load = 0) noexcept; // Rules from the revamp tuning file. [[nodiscard]] CellularRevampRules cellular_revamp_rules(const biology::CellularRevampTuning& tuning); diff --git a/src/biology/budding.cpp b/src/biology/budding.cpp index 42121e2..7c5a8ff 100644 --- a/src/biology/budding.cpp +++ b/src/biology/budding.cpp @@ -138,6 +138,12 @@ largest_fit(const Genome& genome, const accounting::Inventory& matter, std::uint } } // namespace +std::expected>, BuddingError> +largest_growth_within(const Genome& genome, const accounting::Inventory& matter, + std::uint32_t temperature_millikelvin, const BodyTuning& tuning) { + return largest_fit(genome, matter, temperature_millikelvin, tuning); +} + std::expected split_cell(const Genome& parent, const Genome& child, GrowthState growth, const accounting::Inventory& body, const accounting::Inventory& reserve, diff --git a/src/biology/cellular_revamp_tuning.cpp b/src/biology/cellular_revamp_tuning.cpp index 993b04f..c4895c0 100644 --- a/src/biology/cellular_revamp_tuning.cpp +++ b/src/biology/cellular_revamp_tuning.cpp @@ -79,6 +79,12 @@ constexpr std::array fields{ Field{"reproduction.bud_fee_scale_percent", &CellularRevampTuning::reproduction_bud_fee_scale_percent, 0, 100}, Field{"reproduction.organism_cap", &CellularRevampTuning::reproduction_organism_cap, 1, 256}, + Field{"organism.load_per_mille", &CellularRevampTuning::organism_load_per_mille, 0, 10'000}, + Field{"organism.emerge_members", &CellularRevampTuning::organism_emerge_members, 2, 10'000}, + Field{"organism.emerge_mass_fg", &CellularRevampTuning::organism_emerge_mass_fg, 0, + amount_limit}, + Field{"organism.emerge_reserve_pj", &CellularRevampTuning::organism_emerge_reserve_pj, 0, + amount_limit}, }; // A per-mutation field's bounds, in cellular_mutation_tuning_fields order. diff --git a/src/server/lifecycle/cellular_batch.cpp b/src/server/lifecycle/cellular_batch.cpp index af6d5e2..063a4f8 100644 --- a/src/server/lifecycle/cellular_batch.cpp +++ b/src/server/lifecycle/cellular_batch.cpp @@ -58,7 +58,8 @@ bool valid_intent(const CellularLifeIntent& life) { !(step.bud && (step.intake_target || step.engulf)) && !(step.frozen && (step.movement != biology::CellularIntent{} || step.intake_target || step.engulf || step.bud || step.brake || step.exclude != 0)) && - step.exclude <= 0x0F && !(step.become && !step.bud); + step.exclude <= 0x0F && !(step.become && !step.bud) && + !(step.emerge && (step.frozen || step.bud || step.engulf || step.intake_target)); } bool valid_ticks(std::span ticks) { std::set identities; @@ -167,9 +168,9 @@ void put_intent(std::vector& out, const CellularLifeIntent& life) // Flags: bit 0 frozen (ADR-0128), bit 1 brake (rules 12). SQL never parses this byte, and // player action records keep it zero: the trace alone carries a brake. // Bit 2 (rules 13): continue as the bud. - out.push_back(static_cast((life.intent.frozen ? 1U : 0U) | - (life.intent.brake ? 2U : 0U) | - (life.intent.become ? 4U : 0U))); + out.push_back( + static_cast((life.intent.frozen ? 1U : 0U) | (life.intent.brake ? 2U : 0U) | + (life.intent.become ? 4U : 0U) | (life.intent.emerge ? 8U : 0U))); // Byte 14 (rules 13): kept matter channels, bits 0-3; byte 15 stays zero. out.push_back(life.intent.exclude); out.push_back(0); @@ -311,7 +312,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] > 7 || record[14] > 0x0F || record[15] != 0) + if (record[12] > 3 || record[13] > 15 || record[14] > 0x0F || record[15] != 0) return std::unexpected{CellularBatchError::format}; CellularLifeIntent life; life.life_id = get(record, 0, 8); @@ -332,6 +333,7 @@ decode_cellular_batch(std::span bytes) { life.intent.brake = (record[13] & 2U) != 0; // Rules 12; owners below refuse it. life.intent.exclude = record[14]; // Rules 13; owners below refuse it. life.intent.become = (record[13] & 4U) != 0; // Rules 13; owners below refuse it. + life.intent.emerge = (record[13] & 8U) != 0; // 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 8d0ff9d..f8778f3 100644 --- a/src/server/lifecycle/cellular_lives.cpp +++ b/src/server/lifecycle/cellular_lives.cpp @@ -66,7 +66,7 @@ constexpr std::size_t cellular_revamp_mutation_bytes = 80; // the bud fee (40). constexpr std::size_t cellular_lives_v11_header_bytes = cellular_lives_v10_header_bytes + 120 + 8 + 32 + 32 + 8 + - biology::cellular_catalog_size * cellular_revamp_mutation_bytes + 56; + biology::cellular_catalog_size * cellular_revamp_mutation_bytes + 56 + 24; // Each format-11 life adds its mutation state: 49 scores and a reserved zero (100), 98 trigger // states of 24 bytes (2,352), lineage progress and the cadence counter (16), the last brake, // three zeros and the growth carry (8), the offers made (8), and the pending offer (88). @@ -249,6 +249,10 @@ void write_revamp_offers(Writer& out, const CellularRevampRules& r) { {r.split_share_per_thousand, r.split_min_growth, r.organism_cap, r.bud_fee_scale_percent}) out.put(value, 4); out.inventory(r.bud_fee); + out.put(r.organism_load_per_thousand, 4); + out.put(r.emerge_members, 4); + out.put(r.emerge_mass_fg); + out.put(r.emerge_reserve_pj); } bool read_revamp_offers(Reader& in, CellularRevampRules& r) { const auto u32 = [&in] { return static_cast(in.get(4)); }; @@ -297,6 +301,10 @@ bool read_revamp_offers(Reader& in, CellularRevampRules& r) { r.organism_cap = u32(); r.bud_fee_scale_percent = u32(); r.bud_fee = in.inventory(); + r.organism_load_per_thousand = u32(); + r.emerge_members = u32(); + r.emerge_mass_fg = in.get(); + r.emerge_reserve_pj = in.get(); return zero; } void write_revamp_life(Writer& out, const CellularRevampLife& life) { @@ -311,7 +319,8 @@ void write_revamp_life(Writer& out, const CellularRevampLife& life) { out.put(life.progress.buds, 4); out.put(life.active_ticks, 4); out.put(life.last_brake, 1); - out.zeros(3); + out.zeros(1); + out.put(life.members, 2); out.put(life.growth_carry, 4); out.put(life.events); const auto& offer = life.offer; @@ -346,8 +355,10 @@ std::optional read_revamp_life(Reader& in) { life.progress.buds = static_cast(in.get(4)); life.active_ticks = static_cast(in.get(4)); const auto brake = in.get(1); - zero = zero && brake <= 1 && in.get(3) == 0; + zero = zero && brake <= 1 && in.get(1) == 0; life.last_brake = static_cast(brake); + life.members = static_cast(in.get(2)); + zero = zero && life.members >= 1; life.growth_carry = static_cast(in.get(4)); life.events = in.get(); auto& offer = life.offer; @@ -381,13 +392,75 @@ std::optional read_revamp_life(Reader& in) { return life; } +// Rules 13 (reproduction plan section 6): a multicellular organism develops as its genome with +// the target size times its members, so mass, footprint, upkeep and growth follow from it. +std::expected organism_genome(const biology::Genome& genome, + std::uint32_t members) { + if (members <= 1) + return genome; + biology::GenomeDraft draft; + draft.schema_version = genome.schema_version(); + draft.id = genome.id(); + draft.origin_event = genome.origin_event(); + draft.development_version = genome.development_version(); + draft.parents.assign(genome.parents().begin(), genome.parents().end()); + draft.capabilities.assign(genome.capabilities().begin(), genome.capabilities().end()); + draft.movement_arrangement = genome.movement_arrangement(); + draft.cellular_traits = genome.cellular_traits(); + for (auto& record : draft.capabilities) + if (record.kind == biology::Capability::target_size) { + if (record.parameter > std::numeric_limits::max() / members) + return std::unexpected{CellularLivesError::biology}; + record.parameter *= members; + } + const auto made = biology::Genome::create(draft); + if (!made) + return std::unexpected{CellularLivesError::biology}; + return *made; +} +std::expected +life_genome(const biology::LineageArchive& archive, const CellularOwnedLife& life) { + const auto genome = archive.find(life.identity.genome); + if (!genome) + return std::unexpected{CellularLivesError::archive}; + return organism_genome(*genome, life.revamp.members); +} +// Moves `body` to `target`: added matter from `reserve` per channel with construction energy +// (to `heat`) at `price` pJ per 1,000 fg added, freed matter back to the reserve. Changes nothing +// and returns false when the reserve cannot pay. +bool rebody(accounting::Inventory& body, accounting::Inventory& reserve, + accounting::Inventory& heat, const accounting::Inventory& target, std::uint64_t price) { + auto next_reserve = reserve; + std::uint64_t added{}; + for (std::size_t c = 0; c < body.matter.size(); ++c) { + const auto have = body.matter[c].value, want = target.matter[c].value; + if (want > have) { + if (next_reserve.matter[c].value < want - have) + return false; + next_reserve.matter[c].value -= want - have; + added += want - have; + } else { + next_reserve.matter[c].value += have - want; + } + } + const auto energy = added / 1'000 * price + added % 1'000 * price / 1'000; + if (next_reserve.energy.value < energy) + return false; + next_reserve.energy.value -= energy; + reserve = next_reserve; + heat.energy.value += energy; + body = target; + body.energy = {}; + return true; +} + std::expected budget_for(const biology::LineageArchive& archive, const CellularOwnedLife& life, std::uint32_t temperature, const biology::BodyTuning& body = biology::default_body_tuning) { - const auto genome = archive.find(life.identity.genome); + const auto genome = life_genome(archive, life); if (!genome) - return std::unexpected{CellularLivesError::archive}; + return std::unexpected{genome.error()}; const auto budget = biology::metabolic_budget(*genome, life.growth, {temperature, {}}, 1000, body); if (!budget) @@ -950,6 +1023,14 @@ CellularLives::create(const PrimitiveLives& opening, return std::unique_ptr{new CellularLives{std::move(state)}}; } +bool cellular_can_emerge(const CellularOwnedLife& life, const CellularRevampRules& rules) noexcept { + std::uint64_t mass{}; + for (std::size_t c = 0; c < life.body.matter.size(); ++c) + mass += life.body.matter[c].value + life.reserve.matter[c].value; + return life.account != LifeAccount{} && life.revamp.members >= rules.emerge_members && + mass >= rules.emerge_mass_fg && life.reserve.energy.value >= rules.emerge_reserve_pj; +} + bool cellular_twin_bud(std::uint64_t world, std::uint64_t region, std::uint64_t parent_life, std::uint64_t tick, std::uint32_t reproduction) noexcept { // Its own stream: the parent and tick hashed with a twin-only salt ("twin"). @@ -2065,8 +2146,12 @@ CellularLives::restore(std::span bytes, std::uint64_t world, corpse.predator_life = in.get(); corpse.cause = static_cast(cause); const bool engulfed = corpse.cause == biology::CellularDeathCause::engulfed; + const bool revamp_cause = + revamp_version && (corpse.cause == biology::CellularDeathCause::merged || + corpse.cause == biology::CellularDeathCause::emerged); if (padding != 0 || - (corpse.cause != biology::CellularDeathCause::starved && !engulfed) || + (corpse.cause != biology::CellularDeathCause::starved && !engulfed && + !revamp_cause) || engulfed != (corpse.predator_life != 0) || corpse.predator_life == corpse.life_id || corpse.inventory != accounting::Inventory{}) return std::unexpected{CellularLivesError::noncanonical}; @@ -2215,7 +2300,11 @@ CellularLives::advance_tick_with_mutations(std::span i if (intent.brake && !liquid_rules) return std::unexpected{CellularLivesError::invalid_intents}; if (intent.become && - (!revamp_rules || !intent.bud || state_->lives[i].account == LifeAccount{})) + (!revamp_rules || !intent.bud || state_->lives[i].account == LifeAccount{} || + state_->lives[i].revamp.members > 1)) + return std::unexpected{CellularLivesError::invalid_intents}; + if (intent.emerge && (!revamp_rules || state_->lives[i].account == LifeAccount{} || + intent.frozen || intent.bud || intent.engulf || intent.intake_target)) 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 || @@ -2310,8 +2399,11 @@ CellularLives::advance_tick_with_mutations(std::span i std::uint64_t carried{}; for (const auto& channel : life.reserve.matter) carried += channel.value; + const auto members = std::uint64_t{life.revamp.members}; + const auto extra = budget->phenotype.total_mass / members * (members - 1) / 1'000 * + state_->revamp.organism_load_per_thousand; *handling = cellular_loaded_handling(*handling, budget->phenotype.total_mass, - carried, state_->revamp); + carried, state_->revamp, extra); } inputs.back().liquid = biology::CellularLiquidInput{ life.motion, *handling, @@ -2505,8 +2597,10 @@ CellularLives::advance_tick_with_mutations(std::span i if (found == next_lives.end() || found->identity.life != dead.life_id || !next_archive.record_death(found->identity.organism, {proposal->end_tick})) return std::unexpected{CellularLivesError::archive}; + auto single = *found; + single.revamp.members = 1; // A corpse records the single-cell extent. const auto corpse_budget = - budget_for(next_archive, *found, state_->config.ambient_temperature_millikelvin, + budget_for(next_archive, single, state_->config.ambient_temperature_millikelvin, state_->revamp.body); if (!corpse_budget) return std::unexpected{corpse_budget.error()}; @@ -2585,6 +2679,129 @@ CellularLives::advance_tick_with_mutations(std::span i const auto successor = biology::Genome::create(*draft); if (!successor) return std::unexpected{CellularLivesError::mutation}; + const auto price = [&]() -> std::uint64_t { + const auto rules = biology::rules_for(successor->development_version()); + return rules ? rules->construction_per_kilogram : 0; + }(); + if (found->revamp.members > 1) { + // A multicellular organism expresses the mutation as a whole (ADR-0179), its + // changed tissue funded from the shared reserve; "not now" when it cannot be. + const auto scaled = organism_genome(*successor, found->revamp.members); + const auto target = scaled + ? biology::metabolic_budget( + *scaled, found->growth, + {state_->config.ambient_temperature_millikelvin, {}}, + 1000, state_->revamp.body) + : std::unexpected{biology::DevelopmentError::overflow}; + auto body = found->body; + auto heat = accounting::Inventory{}; + if (!target) + return std::unexpected{CellularLivesError::biology}; + if (!rebody(body, reserve, heat, target->body, price)) { + // The offer stays, as for any unaffordable cost. + mutation_results.push_back({selection.life_id, selection.successor_id, + CellularMutationResult::insufficient_funding}); + continue; + } + if (!next_archive.record_mutation(found->identity.organism, *successor, + {proposal->end_tick}) || + !add_inventory(next_heat, heat) || !add_inventory(next_spent, payment->spent)) + return std::unexpected{CellularLivesError::archive}; + auto returned = cost; + returned.energy.value = payment->energy; + reclaims.emplace_back(returned, found->position); + found->identity.genome = successor->id(); + found->offspring_genome = successor->id(); + found->body = body; + found->reserve = reserve; + pending = {}; + mutation_results.push_back( + {selection.life_id, selection.successor_id, CellularMutationResult::applied}); + continue; + } + if (spec->effect == biology::CellularEffect::acquire_adhesion) { + // Adhesion: the split's offspring attaches at once, so the cell becomes a + // two-member organism holding its whole body and reserve under the new plan. The + // single cell's life ends as merged; the player continues as the organism. + const auto temperature = state_->config.ambient_temperature_millikelvin; + const auto organism = organism_genome(*successor, 2); + if (!organism) + return std::unexpected{organism.error()}; + const auto fit = biology::largest_growth_within(*organism, found->body, temperature, + state_->revamp.body); + if (!fit) + return std::unexpected{CellularLivesError::biology}; + const auto identity = cellular_bud_identity(state_->region, next_bud_sequence); + const auto& formed = *fit; + if (!formed || identity == 0 || next_archive.organism(identity)) { + mutation_results.push_back({selection.life_id, selection.successor_id, + CellularMutationResult::split_refused}); + continue; + } + const auto grown = biology::metabolic_budget( + *organism, formed->first, {temperature, {}}, 1000, state_->revamp.body); + if (!grown) + return std::unexpected{CellularLivesError::biology}; + const auto single_budget = + budget_for(next_archive, *found, temperature, state_->revamp.body); + if (!single_budget) + return std::unexpected{single_budget.error()}; + if (!next_archive.admit(*successor) || + !next_archive.record_birth(identity, successor->id(), {proposal->end_tick}) || + !next_archive.record_death(found->identity.organism, {proposal->end_tick})) + return std::unexpected{CellularLivesError::archive}; + if (!add_inventory(next_spent, payment->spent)) + return std::unexpected{CellularLivesError::overflow}; + auto returned = cost; + returned.energy.value = payment->energy; + reclaims.emplace_back(returned, found->position); + CellularOwnedLife whole{}; + whole.account = found->account; + whole.identity = { + identity, identity, successor->id(), identity, {proposal->end_tick}}; + whole.source = found->source; + whole.growth = formed->first; + whole.body = formed->second; + whole.reserve = reserve; + for (std::size_t c = 0; c < whole.body.matter.size(); ++c) + whole.reserve.matter[c].value += + found->body.matter[c].value - formed->second.matter[c].value; + // Keep the larger body inside the region. + const auto extent = grown->phenotype.extent; + whole.position = found->position; + whole.position.x_um = std::min( + whole.position.x_um, state_->config.area.width_um - extent); + whole.position.y_um = std::min( + whole.position.y_um, state_->config.area.height_um - extent); + whole.motion = found->motion; + whole.parent_life = found->identity.life; + whole.offspring_genome = successor->id(); + whole.revamp.affinity.score = found->revamp.affinity.score; + whole.revamp.progress = found->revamp.progress; + whole.revamp.members = 2; + next_corpses.push_back({found->identity.life, + found->identity.organism, + found->source, + proposal->end_tick, + found->position, + found->growth, + single_budget->phenotype.extent, + {}, + biology::CellularDeathCause::merged, + 0, + found->parent_life, + found->offspring_genome}); + next_lives.erase(found); + ++next_bud_sequence; + next_lives.insert(std::ranges::lower_bound(next_lives, identity, {}, + [](const CellularOwnedLife& life) { + return life.identity.life; + }), + whole); + mutation_results.push_back({selection.life_id, selection.successor_id, + CellularMutationResult::split_applied}); + continue; + } // The split (Cellular_reproduction_plan.md section 4): body and reserve divide, the // offspring expresses the mutation, both plans carry it. Refused, spending nothing, // when the cell is too small, has no room beside it, or the region is full. @@ -2736,6 +2953,68 @@ CellularLives::advance_tick_with_mutations(std::span i bud_results.push_back({request.life_id, 0, CellularBudResult::not_able}); continue; // Out of the world (ADR-0128). } + if (revamp_rules && parent->revamp.members > 1) { + // An organism's bud is an internal cell (reproduction plan section 6): litter adds + // members, funded from the shared reserve. Wildlife organisms stop one short of + // the emergence threshold. + const auto expressed_genome = next_archive.find(parent->identity.genome); + if (!expressed_genome) + return std::unexpected{CellularLivesError::archive}; + const auto& traits = expressed_genome->cellular_traits(); + Random roll{state_->world * 0x9e3779b97f4a7c15ULL ^ request.life_id ^ + proposal->end_tick * 0xbf58476d1ce4e5b9ULL}; + const auto added = cellular_litter_count(traits ? traits->litter : 0U, roll.next(), + state_->revamp.bounds.max_litter); + auto members = std::uint32_t{parent->revamp.members} + added; + if (parent->account == LifeAccount{}) + members = std::min(members, state_->revamp.emerge_members - 1); + const auto grown = members > parent->revamp.members + ? organism_genome(*expressed_genome, members) + : std::unexpected{CellularLivesError::biology}; + const auto target = grown ? biology::metabolic_budget( + *grown, parent->growth, + {state_->config.ambient_temperature_millikelvin, {}}, + 1000, state_->revamp.body) + : std::unexpected{biology::DevelopmentError::overflow}; + const auto rules = biology::rules_for(expressed_genome->development_version()); + // The same fee per bud action as a single cell's, then the new tissue. + const auto fee = cellular_mutation_cost( + {.cost = state_->revamp.bud_fee, + .cost_scale_percent = state_->revamp.bud_fee_scale_percent}); + auto body = parent->body; + auto reserve = parent->reserve; + bool funded = reserve.energy.value >= fee.energy.value; + for (std::size_t c = 0; c < fee.matter.size(); ++c) + funded = funded && reserve.matter[c].value >= fee.matter[c].value; + if (funded) { + reserve.energy.value -= fee.energy.value; + for (std::size_t c = 0; c < fee.matter.size(); ++c) + reserve.matter[c].value -= fee.matter[c].value; + } + auto heat = accounting::Inventory{}; + if (!target || !rules || !funded || + !rebody(body, reserve, heat, target->body, rules->construction_per_kilogram)) { + bud_results.push_back({request.life_id, 0, + target ? CellularBudResult::insufficient_funding + : CellularBudResult::not_able}); + if (target && parent->account != LifeAccount{}) + activity_of(request.life_id)[biology::CellularSignal::bud_refused] += 1; + continue; + } + if (!add_inventory(next_heat, heat)) + return std::unexpected{CellularLivesError::overflow}; + reclaims.emplace_back(fee, parent->position); + parent->body = body; + parent->reserve = reserve; + parent->revamp.members = static_cast(members); + if (parent->account != LifeAccount{}) { + activity_of(request.life_id)[biology::CellularSignal::bud_done] += 1; + parent->revamp.progress.buds += 1; + } + // The bud is internal: the organism reports itself as the bud. + bud_results.push_back({request.life_id, request.life_id, CellularBudResult::budded}); + continue; + } // ADR-0137 (rules 7): on a twin roll the bud investment is split between two buds // (each a quarter of the parent's body). The parent's reported result is the // first bud's; a twin that finds no room is simply not made. @@ -2900,6 +3179,44 @@ CellularLives::advance_tick_with_mutations(std::span i } std::ranges::sort(next_lives, {}, [](const CellularOwnedLife& life) { return life.identity.life; }); + // Rules 13 (reproduction plan section 7): an owned organism at the emergence threshold that + // asks leaves for the world. Its matter is a recorded export; its life ends as emerged. + auto next_boundary = state_->boundary; + if (revamp_rules) { + for (const auto& request : ordered) { + if (!request.intent.emerge) + continue; + const auto life = std::ranges::lower_bound( + next_lives, request.life_id, {}, + [](const CellularOwnedLife& value) { return value.identity.life; }); + if (life == next_lives.end() || life->identity.life != request.life_id || + !cellular_can_emerge(*life, state_->revamp)) + continue; + auto single = *life; + single.revamp.members = 1; + const auto budget = + budget_for(next_archive, single, state_->config.ambient_temperature_millikelvin, + state_->revamp.body); + if (!budget || + !next_archive.record_death(life->identity.organism, {proposal->end_tick}) || + !add_inventory(next_boundary.outgoing, life->body) || + !add_inventory(next_boundary.outgoing, life->reserve)) + return std::unexpected{CellularLivesError::archive}; + next_corpses.push_back({life->identity.life, + life->identity.organism, + life->source, + proposal->end_tick, + life->position, + life->growth, + budget->phenotype.extent, + {}, + biology::CellularDeathCause::emerged, + 0, + life->parent_life, + life->offspring_genome}); + next_lives.erase(life); + } + } // Rules 5 presence (ADR-0128), after deaths, mutations and buds: a death in this tick // is final before any presence change. std::vector resume_blocked; @@ -2956,9 +3273,9 @@ CellularLives::advance_tick_with_mutations(std::span i previous->presence == CellularPresence::suspended || life.growth.realized_per_thousand == 1000) continue; - const auto genome = next_archive.find(life.identity.genome); + const auto genome = life_genome(next_archive, life); if (!genome) - return std::unexpected(CellularLivesError::archive); + return std::unexpected(genome.error()); // Rules 13: growth speed scales the per-tick step; the fraction carries over. auto step = cellular_growth_per_tick; const auto& traits = genome->cellular_traits(); @@ -3153,7 +3470,7 @@ CellularLives::advance_tick_with_mutations(std::span i state_->nursery_config, **next_habitat, next_lives, next_corpses, next_archive, 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, + state_->format_version >= cellular_lives_migration_format ? &next_boundary : nullptr, inheritance_rules ? &next_offspring_revisions : nullptr, next_spent, revamp_rules); if (!total) return std::unexpected{total.error()}; @@ -3164,7 +3481,7 @@ CellularLives::advance_tick_with_mutations(std::span i state_->config.ambient_temperature_millikelvin}, state_->nursery_config, std::move(*next_habitat), std::move(next_lives), std::move(next_corpses), next_archive, state_->nursery, next_heat, state_->opening_total, - *total, state_->format_version, state_->rules_version, state_->boundary); + *total, state_->format_version, state_->rules_version, next_boundary); next->next_bud_sequence = next_bud_sequence; next->offspring_revisions = std::move(next_offspring_revisions); next->light = state_->light; diff --git a/src/server/lifecycle/cellular_play_summary.cpp b/src/server/lifecycle/cellular_play_summary.cpp index 9229aa6..e1f63ad 100644 --- a/src/server/lifecycle/cellular_play_summary.cpp +++ b/src/server/lifecycle/cellular_play_summary.cpp @@ -41,6 +41,12 @@ summarize_cellular_play(const CellularLives& state) { case biology::CellularDeathCause::unrecorded: ++summary.unrecorded; break; + case biology::CellularDeathCause::merged: + ++summary.merged; + break; + case biology::CellularDeathCause::emerged: + ++summary.emerged; + break; } (corpse.parent_life == 0 ? summary.owned_deaths : summary.wildlife_deaths) += 1; const auto record = archive.organism(corpse.organism); diff --git a/src/server/lifecycle/cellular_revamp.cpp b/src/server/lifecycle/cellular_revamp.cpp index dac1153..6e134df 100644 --- a/src/server/lifecycle/cellular_revamp.cpp +++ b/src/server/lifecycle/cellular_revamp.cpp @@ -55,15 +55,18 @@ bool cellular_revamp_valid(const CellularRevampRules& rules) noexcept { rules.bud_fee.matter, [](const accounting::Femtograms& f) { return f.value <= most; }) && rules.organism_cap != 0 && rules.organism_cap <= biology::max_cellular_tick_lives && - cellular_revamp_offer_rules_valid(rules); + rules.organism_load_per_thousand <= 10'000 && rules.emerge_members >= 2 && + rules.emerge_members <= 10'000 && rules.emerge_mass_fg <= most && + rules.emerge_reserve_pj <= most && cellular_revamp_offer_rules_valid(rules); } biology::CellularHandling cellular_loaded_handling(const biology::CellularHandling& handling, std::uint64_t body_mass, std::uint64_t carried, - const CellularRevampRules& rules) noexcept { + const CellularRevampRules& rules, + std::uint64_t extra_load) 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; + carried % 1'000 * rules.reserve_load_per_thousand / 1'000 + extra_load; if (load == 0 || body_mass == 0 || body_mass > (1ULL << 40U) || load > (1ULL << 40U)) return handling; const auto total = body_mass + load; @@ -275,6 +278,10 @@ CellularRevampRules cellular_revamp_rules(const biology::CellularRevampTuning& t accounting::Femtograms{u64(t.reproduction_bud_fee_p_fg)}, accounting::Femtograms{u64(t.reproduction_bud_fee_o_fg)}}}, .bud_fee_scale_percent = u32(t.reproduction_bud_fee_scale_percent), - .organism_cap = u32(t.reproduction_organism_cap)}; + .organism_cap = u32(t.reproduction_organism_cap), + .organism_load_per_thousand = u32(t.organism_load_per_mille), + .emerge_members = u32(t.organism_emerge_members), + .emerge_mass_fg = u64(t.organism_emerge_mass_fg), + .emerge_reserve_pj = u64(t.organism_emerge_reserve_pj)}; } } // namespace evo::server diff --git a/tests/cellular_revamp_owner_tests.cpp b/tests/cellular_revamp_owner_tests.cpp index 017fbea..8c3c123 100644 --- a/tests/cellular_revamp_owner_tests.cpp +++ b/tests/cellular_revamp_owner_tests.cpp @@ -1,6 +1,8 @@ #include "evo/server/lifecycle/cellular_batch.hpp" #include "fixtures/cellular_ecology.hpp" +#include +#include #include #include @@ -11,8 +13,8 @@ using namespace evo; using namespace evo::server; using namespace evo::fixture; -CellularLiquidRules liquid() { - return {.currents = {5, 48'000, 48'000, 250, 2, 4, 3'000, 6'000, 60, 300}, +CellularLiquidRules liquid(std::uint32_t side = 48'000) { + return {.currents = {5, side, side, 250, 2, 4, side / 16, side / 8, 60, 300}, .founder = {.thrust_q10 = 20'480, .reverse_thrust_q10 = 20'480, .forward_drag_ppm = 95'163, @@ -432,6 +434,205 @@ void thrust_moves_affinity() { "ten seconds of thrust did not move propulsion affinity"); } +// Rules 13 (reproduction plan sections 6-7): Adhesion turns the cell into a two-member organism +// that holds its whole body and reserve; the organism expresses later mutations as a whole, +// buds add internal members, and at the threshold it emerges as a recorded export. +Owner adhesion_region() { + auto rules = revamp(); + rules.offer_interval_ticks = 40; + rules.bounds.buds_for_adhesion = 0; + rules.emerge_members = 3; + rules.emerge_mass_fg = 0; + rules.growth_per_tick_centi_mille = 0; // Collected matter stays in the reserve for buds. + for (auto& m : rules.mutations) + m.enabled = false; + // Adhesion and five movement mutations: three options capped at 70% each need five. + rules.mutations.at(48).enabled = true; + rules.mutations.at(48).base_weight = 10'000; + for (std::size_t i = 0; i < 5; ++i) + rules.mutations.at(i).enabled = true; + auto fresh = opening(7, true, 4, false); // A 6 mm region, rich motes at four sites. + checked(fresh->advance_tick({}), "genesis tick"); + fresh = checked(fresh->migration_upgrade_candidate(), "boundary upgrade"); + fresh = checked(fresh->maturation_upgrade_candidate(), "maturation upgrade"); + fresh = checked(fresh->inheritance_upgrade_candidate(), "inheritance upgrade"); + fresh = checked(fresh->photosynthesis_upgrade_candidate({0, 1, {0}}), "light upgrade"); + fresh = checked(fresh->liquid_upgrade_candidate(liquid(6'000)), "liquid upgrade"); + fresh = checked(fresh->revamp_upgrade_candidate(rules), "revamp upgrade"); + fresh = checked(fresh->birth_candidate({account(2), 1}, {101, 101, 101, 101, {fresh->tick()}}), + "founder 6 birth"); + return fresh; +} +// One tick's intents steering `life_id` toward the richest bubble (the fixture's rich founding +// motes), with matter excluded from burning so the reserve keeps it for growth and buds. +std::vector forage(const CellularLives& state, std::uint64_t life_id) { + const auto& life = life_of(state, life_id); + const biology::CellularPatch* best = nullptr; + double nearest{}; + for (const auto& patch : state.habitat().patches()) { + auto richest = patch.stock.energy.value; + for (const auto& channel : patch.stock.matter) + richest = std::max(richest, channel.value); + const auto distance = std::hypot( + static_cast(patch.address.x_um) - static_cast(life.position.x_um), + static_cast(patch.address.y_um) - static_cast(life.position.y_um)); + if (richest >= 1'000'000'000 && (best == nullptr || distance < nearest)) { + nearest = distance; + best = &patch; + } + } + require(best != nullptr, "nothing left in the region"); + auto input = swim(state, {}, 0x0F); + const auto dx = + static_cast(best->address.x_um) - static_cast(life.position.x_um); + const auto dy = + static_cast(best->address.y_um) - static_cast(life.position.y_um); + // Inside the unit circle: scale by the Euclidean length, rounded toward zero. + const auto span = std::max(1.0, std::hypot(dx, dy)); + for (auto& entry : input) + if (entry.life_id == life_id) + entry.intent.movement = {static_cast(dx * 999.0 / span), + static_cast(dy * 999.0 / span)}; + return input; +} +// Forages in offer intervals, declining offers, until one names `id`. +std::uint16_t await_offer(Owner& state, std::uint64_t life_id, std::uint16_t id) { + for (std::uint64_t round = 0; round < 40; ++round) { + for (int tick = 0; tick < 40; ++tick) + checked(state->advance_tick(forage(*state, life_id)), "forage tick"); + const auto& offer = life_of(*state, life_id).revamp.offer; + const auto end = offer.ids.begin() + offer.count; + if (std::ranges::find(offer.ids.begin(), end, id) != end) + return id; + if (offer.count != 0) + checked(state->advance_tick_with_mutations(swim(*state, {}), + choose(*state, life_id, 0, 8'000 + round)), + "decline tick"); + } + require(false, "the expected mutation was never offered"); + return 0; +} +// Forages, asking to bud every 50 ticks, until a bud is funded or `ticks` pass; returns the last +// bud result (a single request when `ticks` is 0). +CellularBudExecution bud_until_funded(Owner& state, std::uint64_t life_id, int ticks) { + CellularBudExecution last{}; + for (int tick = 0; tick <= ticks; ++tick) { + auto input = forage(*state, life_id); + const bool ask = tick % 50 == 0; + if (ask) { + for (auto& entry : input) + if (entry.life_id == life_id) { + entry.intent = {}; + entry.intent.bud = true; + } + } + const auto executed = checked(state->advance_tick_with_mutations(input, {}), "bud tick"); + if (ask) { + require(executed.buds.size() == 1, "a bud request went unanswered"); + last = executed.buds.front(); + if (last.result == CellularBudResult::budded) + break; + } + } + return last; +} +void an_organism_forms_grows_and_emerges() { + auto state = adhesion_region(); + const auto adhesion = await_offer(state, 101, 49); + const auto single = life_of(*state, 101); + auto choice = choose(*state, 101, adhesion, 9'000); + const auto formed = + checked(state->advance_tick_with_mutations(swim(*state, {}), choice), "adhesion tick"); + require(formed.mutations.front().result == CellularMutationResult::split_applied, + "Adhesion did not form an organism"); + const auto identity = cellular_bud_identity(state->region(), 1); + require(state->lives().size() == 1, "Adhesion left the single cell alive"); + const auto organism = life_of(*state, identity); + require(organism.revamp.members == 2 && organism.account == account(2) && + organism.identity.genome == 9'000 && organism.offspring_genome == 9'000 && + organism.parent_life == 101 && + organism.revamp.affinity.score == single.revamp.affinity.score, + "the organism did not take the cell's place, plan and account"); + const auto merged = std::ranges::find(state->corpses(), std::uint64_t{101}, + [](const CellularOwnedCorpse& c) { return c.life_id; }); + require(merged != state->corpses().end() && + merged->cause == biology::CellularDeathCause::merged && + merged->inventory == accounting::Inventory{}, + "the single cell did not end as an empty merged corpse"); + closed(*state); + require(restore(*state)->snapshot() == state->snapshot(), "an organism did not restore"); + + // An organism cannot become its bud; its next mutation is expressed as a whole. + auto become = swim(*state, {}); + become.front().intent.bud = true; + become.front().intent.become = true; + require(!state->advance_tick(become), "an organism was allowed to become a bud"); + const auto strong = await_offer(state, identity, 1); + const auto whole = checked(state->advance_tick_with_mutations( + swim(*state, {}), choose(*state, identity, strong, 9'001)), + "organism mutation tick"); + require(whole.mutations.front().result == CellularMutationResult::applied && + life_of(*state, identity).identity.genome == 9'001 && + life_of(*state, identity).offspring_genome == 9'001 && state->lives().size() == 1, + "the organism did not express its mutation as a whole"); + closed(*state); + + // A bud adds an internal member, not a new life, once the organism has fed enough. + const auto refused = bud_until_funded(state, identity, 0); + require(refused.result == CellularBudResult::insufficient_funding && + life_of(*state, identity).revamp.members == 2, + "an unfed organism's bud was not refused"); + const auto budded = bud_until_funded(state, identity, 10'000); + require(budded.result == CellularBudResult::budded && budded.bud_life == identity && + life_of(*state, identity).revamp.members == 3 && state->lives().size() == 1, + "an organism's bud did not add an internal member"); + closed(*state); + require(cellular_can_emerge(life_of(*state, identity), state->revamp_rules()), + "a three-member organism could not emerge"); + + // Emerge: the whole organism leaves as an export and the life ends as emerged. + const auto outgoing = state->boundary_ledger().outgoing; + const auto leaving = life_of(*state, identity); + auto emerge = swim(*state, {}); + emerge.front().intent = {}; + emerge.front().intent.emerge = true; + checked(state->advance_tick(emerge), "emerge tick"); + require(state->lives().empty(), "the organism did not leave"); + const auto emerged = std::ranges::find(state->corpses(), identity, + [](const CellularOwnedCorpse& c) { return c.life_id; }); + require(emerged != state->corpses().end() && + emerged->cause == biology::CellularDeathCause::emerged, + "the organism did not end as emerged"); + // The tick's step still moved the reserve first; the body (no growth here) leaves whole, + // and closure accounts for every femtogram exactly. + const auto& exported = state->boundary_ledger().outgoing; + for (std::size_t c = 0; c < exported.matter.size(); ++c) + require(exported.matter[c].value - outgoing.matter[c].value >= leaving.body.matter[c].value, + "the emerged body was not recorded as an export"); + require(exported.energy.value > outgoing.energy.value, "the emerged reserve stayed behind"); + closed(*state); + require(restore(*state)->snapshot() == state->snapshot(), "an emerged region did not restore"); +} + +// Emerge needs an owned life at the threshold; a single cell asking is ignored, wildlife refused. +void emerge_needs_the_threshold() { + auto state = adhesion_region(); + auto ask = swim(*state, {}); + ask.front().intent = {}; + ask.front().intent.emerge = true; + checked(state->advance_tick(ask), "single-cell emerge tick"); + require(state->lives().size() == 1, "a single cell emerged"); + auto mixed = swim(*state, {}); + mixed.front().intent.emerge = true; + mixed.front().intent.bud = true; + require(!state->advance_tick(mixed), "emerge with a bud was accepted"); + CellularOwnedLife wild = life_of(*state, 101); + wild.revamp.members = 8; + require(cellular_can_emerge(wild, state->revamp_rules()), "an owned organism at the threshold"); + wild.account = {}; + require(!cellular_can_emerge(wild, state->revamp_rules()), "wildlife could emerge"); +} + // A recorded trace replays to the exact live result under rules 13. void trace_replays() { auto live = revamp_region(); @@ -442,8 +643,10 @@ 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}, - static_cast(tick % 16)); + auto intents = swim(*live, {static_cast(tick < 12 ? 1'000 : -400), 0}, + static_cast(tick % 16)); + // A single cell asking to emerge is below the threshold and stays. + intents.front().intent.emerge = tick == 5; checked(live->advance_tick(intents), "recorded tick"); batch.ticks.push_back({intents, {}, {}}); } @@ -454,6 +657,9 @@ void 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"); + require(decoded.ticks.at(5).lives.front().intent.emerge && + !decoded.ticks.at(6).lives.front().intent.emerge, + "Emerge did not survive the trace"); } } // namespace @@ -471,6 +677,8 @@ int main() try { become_and_litter(); unaffordable_choices_wait_and_declines_clear(); thrust_moves_affinity(); + an_organism_forms_grows_and_emerges(); + emerge_needs_the_threshold(); trace_replays(); std::puts("PASS rules 13 owner: upgrade, founder 6, restore and replay"); return 0; diff --git a/tests/cellular_revamp_tuning_tests.cpp b/tests/cellular_revamp_tuning_tests.cpp index 6be1531..55fe28a 100644 --- a/tests/cellular_revamp_tuning_tests.cpp +++ b/tests/cellular_revamp_tuning_tests.cpp @@ -55,7 +55,11 @@ CellularRevampTuning trial() { .reproduction_bud_fee_p_fg = 0, .reproduction_bud_fee_o_fg = 0, .reproduction_bud_fee_scale_percent = 0, - .reproduction_organism_cap = 256}; + .reproduction_organism_cap = 256, + .organism_load_per_mille = 500, + .organism_emerge_members = 8, + .organism_emerge_mass_fg = 100'000'000, + .organism_emerge_reserve_pj = 0}; const auto catalog = cellular_catalog(); for (std::size_t i = 0; i < catalog.size(); ++i) t.mutations.at(i) = cellular_default_tuning(catalog[i]);