diff --git a/apps/evo-admin-api/portal/app.js b/apps/evo-admin-api/portal/app.js index ea35a1e..c087223 100644 --- a/apps/evo-admin-api/portal/app.js +++ b/apps/evo-admin-api/portal/app.js @@ -630,23 +630,26 @@ function windowBadge(r) { // listed cells and deposits. function regionLedger(view) { const zero = () => [0, 0, 0, 0, 0]; + // Heat: energy the cells used that has not (yet) returned to the spent pool. + const heat = view.heat === undefined ? null : [Number(view.heat), 0, 0, 0, 0]; if (view.totals) { const t = view.totals; - return { complete: true, reserve: t.reserve, body: t.body, bubbles: t.bubbles, pools: t.pools, patches: t.patches, spent: view.spent }; + return { complete: true, reserve: t.reserve, body: t.body, bubbles: t.bubbles, pools: t.pools, patches: t.patches, spent: view.spent, heat }; } const reserve = zero(), bubbles = zero(), pools = zero(), patches = zero(); for (const c of view.cells) addTo(reserve, c.reserve); for (const d of view.deps) addTo(d.kind === 2 ? bubbles : d.kind === 1 ? pools : patches, d.stock); - return { complete: false, reserve, body: null, bubbles, pools, patches, spent: view.spent }; + return { complete: false, reserve, body: null, bubbles, pools, patches, spent: view.spent, heat }; } -// The rules-13 drip: every `interval` ticks, one bubble per non-empty channel of at most the cap. +// The rules-13 drip: every `interval` ticks, one bubble per non-empty channel of at most the cap; +// the energy cycle (ADR-0182 section 14): heat recycled per mille each tick, absorbing drip. function dripPlan(view) { if (!view.drip) return null; - const [interval, capE, capM] = view.drip.map(Number); + const [interval, capE, capM, recycle = 0, absorb = 0] = view.drip.map(Number); const caps = [capE, capM, capM, capM, capM]; const spent = view.spent.map(Number); return { - interval, caps, + interval, caps, recycle, absorb: absorb === 1, next: spent.map((v, i) => Math.min(v, caps[i])), drips: spent.map((v, i) => (caps[i] ? Math.ceil(v / caps[i]) : 0)), }; @@ -1116,13 +1119,15 @@ async function regionPage(region, params) { const rows = [ ['Cell reserves', L.reserve], ['Cell bodies', L.body], ['Bubbles', L.bubbles], ['Liquid pools', L.pools], ...(sum(L.patches) ? [['Patches', L.patches]] : []), ['Spent pool', L.spent], + ...(L.heat ? [['Heat (used energy)', L.heat]] : []), ]; const total = rows.reduce((t, [, v]) => (v ? addTo(t, v) : t), [0, 0, 0, 0, 0]); const held = [0, 0, 0, 0, 0], free = [0, 0, 0, 0, 0]; if (L.reserve) addTo(held, L.reserve); if (L.body) addTo(held, L.body); for (const v of [L.bubbles, L.pools, L.patches]) addTo(free, v); - const parts = [['In cells', held, 'var(--wildlife)'], ['Bubbles and pools', free, 'var(--accent)'], ['Spent pool', L.spent.map(Number), 'var(--warn)']]; + const parts = [['In cells', held, 'var(--wildlife)'], ['Bubbles and pools', free, 'var(--accent)'], ['Spent pool', L.spent.map(Number), 'var(--warn)'], + ...(L.heat ? [['Heat', L.heat, 'var(--bad)']] : [])]; fill(ledgerBox, h('table', { class: 'ledger' }, h('thead', {}, h('tr', {}, h('th', {}, ''), channels.map((c) => h('th', { class: 'num' }, swatch(c.key), c.short)))), @@ -1139,7 +1144,12 @@ async function regionPage(region, params) { const plan = dripPlan(view); const notes = []; const deposits = Number(view.deposits_total); - if (deposits >= depositLimit) notes.push(`The region holds ${fmtInt(deposits)} deposits, its limit: the drip waits and new bubbles are refused until cells eat some.`); + const absorbing = plan && plan.absorb; + if (deposits >= depositLimit) { + notes.push(absorbing + ? `The region holds ${fmtInt(deposits)} deposits, its limit: drips join existing bubbles, and Add bubbles is refused until cells eat some.` + : `The region holds ${fmtInt(deposits)} deposits, its limit: the drip waits and new bubbles are refused until cells eat some.`); + } else if (deposits >= depositLimit * 0.95) notes.push(`${fmtInt(depositLimit - deposits)} deposit places left before the limit of ${fmtInt(depositLimit)}.`); if (pace.stalled) notes.push('The tick is not advancing, so nothing drips until the region ticks again.'); if (!plan) { @@ -1149,6 +1159,7 @@ async function regionPage(region, params) { } dripEvery.textContent = plan.interval ? `every ${(plan.interval * tickSeconds).toLocaleString()} s (${plan.interval} ticks)` : 'off'; if (!sum(plan.next)) notes.push('The spent pool is empty: drips release nothing.'); + if (!plan.recycle && L.heat && L.heat[0]) notes.push(`Energy cells use is lost as heat (${fmtEnergy(L.heat[0])} so far): set spent.heat_recycle_per_mille to return it through the drip.`); const dryIn = (i) => (!Number(view.spent[i]) ? h('span', { class: 'faint' }, 'empty') : plan.interval ? fmtDuration(plan.drips[i] * plan.interval * tickSeconds) : '—'); fill(dripBox, h('table', { class: 'ledger', style: { marginTop: '12px' } }, @@ -1158,7 +1169,10 @@ async function regionPage(region, params) { h('td', { class: 'num' }, c.fmt(view.spent[i])), h('td', { class: 'num' }, Number(plan.next[i]) ? c.fmt(plan.next[i]) : h('span', { class: 'faint' }, '—')), h('td', { class: 'num' }, dryIn(i)))))), - h('div', { class: 'muted small', style: { marginTop: '8px' } }, `Each drip makes one bubble per non-empty channel, at most ${fmtEnergy(plan.caps[0])} of energy or ${fmtMass(plan.caps[1])} of one matter, at random spots.`), + h('div', { class: 'muted small', style: { marginTop: '8px' } }, `Each drip makes one bubble per non-empty channel, at most ${fmtEnergy(plan.caps[0])} of energy or ${fmtMass(plan.caps[1])} of one matter, at random spots${plan.absorb ? '; at the deposit limit it joins an existing bubble instead' : ''}.`), + h('div', { class: 'muted small', style: { marginTop: '4px' } }, plan.recycle + ? `Energy cycle: ${(plan.recycle / 10).toLocaleString()}% of the region's heat returns to the spent pool every tick.` + : 'Energy cycle: off. Energy cells use stays as heat.'), notes.length ? h('div', { style: { marginTop: '12px' } }, notes.map((n) => h('div', { class: 'callout' }, n))) : null); } @@ -1255,7 +1269,7 @@ async function regionPage(region, params) { channels.forEach((c, i) => { chips[c.key].count.textContent = fmtInt(byChannel[i]); }); const L = regionLedger(view); - const totalOf = (i) => [L.reserve, L.body, L.bubbles, L.pools, L.patches, L.spent].reduce((s, v) => s + (v ? Number(v[i]) : 0), 0); + const totalOf = (i) => [L.reserve, L.body, L.bubbles, L.pools, L.patches, L.spent, L.heat].reduce((s, v) => s + (v ? Number(v[i]) : 0), 0); const freeOf = (i) => [L.bubbles, L.pools, L.patches].reduce((s, v) => s + Number(v[i]), 0); const energy = totalOf(0), matter = [1, 2, 3, 4].reduce((s, i) => s + totalOf(i), 0); const freeMatter = [1, 2, 3, 4].reduce((s, i) => s + freeOf(i), 0); diff --git a/deploy/kubernetes/region/dev/tuning/cellular-revamp.tuning b/deploy/kubernetes/region/dev/tuning/cellular-revamp.tuning index 7808221..2a0d98b 100644 --- a/deploy/kubernetes/region/dev/tuning/cellular-revamp.tuning +++ b/deploy/kubernetes/region/dev/tuning/cellular-revamp.tuning @@ -40,6 +40,11 @@ predation.kill_bubble_per_mille = 500 # a kill's remainder left as bubbles; th 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 +# Energy cycle (ADR-0182 section 14; optional, 0 when absent): the share of the region's heat +# (energy its cells used) returned to the spent pool every tick before the drip, and whether a +# drip at the deposit limit (8,192) joins an existing bubble instead of waiting. +spent.heat_recycle_per_mille = 1_000 # all of it: energy cycles back like matter +spent.drip_absorb = 1 # Mutation offers (mutation plan section 3). Chances in parts per million. mutation.options = 3 diff --git a/docs/STATUS.md b/docs/STATUS.md index d57a9e2..268a0c0 100644 --- a/docs/STATUS.md +++ b/docs/STATUS.md @@ -1,5 +1,13 @@ # Project status and next steps +## Energy cycle - 2026-10-28 + +Energy now cycles like matter: the heat cells produce (upkeep, motion, growth, feeding and +predation losses) returns to the spent pool every tick and drips back as bubbles, and a drip at +the deposit limit joins an existing bubble. Both are optional rules-13 tuning keys +(`spent.heat_recycle_per_mille`, `spent.drip_absorb`), adoptable live; the DEV revamp file +turns them on. See [ADR-0182](adr/0182-admin-portal-and-world-tuning.md) section 14. + ## Admin region page - 2026-10-28 The admin portal's region page is reorganized around the map: a KPI strip (tick pace, diff --git a/docs/adr/0182-admin-portal-and-world-tuning.md b/docs/adr/0182-admin-portal-and-world-tuning.md index 759de8a..cd99571 100644 --- a/docs/adr/0182-admin-portal-and-world-tuning.md +++ b/docs/adr/0182-admin-portal-and-world-tuning.md @@ -284,6 +284,34 @@ or worlds from the portal (a later gate: Git-generated manifests through the Git Argo sync for one more region in the world; several concurrent regions or worlds need per-region Deployments, volumes and routes). +### 14. Energy cycle (delivered 2026-10-28, live-tunable) + +Matter a cell burns returns to the spent pool and drips back; energy it uses (upkeep, motion, +growth, mutation rebuilds, the share of a bubble lost in feeding, predation losses) went to the +region's heat store and never came back. Light is the only new energy, so a region without +photosynthesizers drained into heat: region 16's wildlife ate the region's energy and starved, +its spent pool held only matter, and the matter-only bubbles it dripped filled the 8,192 +deposits. + +- **Heat recycling.** `spent.heat_recycle_per_mille` (rules field `heat_recycle_per_thousand`, + 0..1,000): at the end of every tick, before the drip, that share of the region's whole heat + store moves to the spent pool. 1,000 closes the loop, and adopting it also returns the heat + a region built up before. Energy is conserved as before (heat and spent are both region + stock). Below 1,000 the heat returns more slowly; nothing is lost. +- **Absorbing drip.** `spent.drip_absorb` (0/1): a drip at the deposit limit adds its amount + to an existing bubble, the first at or after its seeded spot in address order (wrapping), + instead of waiting. A habitat with no bubble at all still waits. +- **Encoding.** Both fields use the reserved word after the offer interval (the recycle share + in the low 16 bits, the absorbing drip in bit 16), so rules without them keep their exact + bytes, digests, checkpoints and replays. Both keys are optional in the tuning file and can be + adopted live as a tuning revision; the DEV file sets 1,000 and 1. +- **View and portal.** The region view reports `heat` and the drip's recycle share and absorb + flag; the region page counts heat in the region's energy and its ledger, and says when energy + is being lost as heat. + +Not changed: a region with no living cell does not tick, so it neither recycles nor drips; an +empty region needs a spawn or a player before the cycle restarts. + ## Delivery order 1. Read-only portal: login, accounts (from existing data), regions, region view (schema 61, diff --git a/include/evo/biology/cellular_revamp_tuning.hpp b/include/evo/biology/cellular_revamp_tuning.hpp index dc2076a..27ff7f4 100644 --- a/include/evo/biology/cellular_revamp_tuning.hpp +++ b/include/evo/biology/cellular_revamp_tuning.hpp @@ -41,6 +41,9 @@ struct CellularRevampTuning { 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{}; + // Optional energy cycle (ADR-0182 section 14): the share of the region's heat returned to + // the spent pool each tick, and whether a drip at the deposit limit joins an existing bubble. + std::int64_t spent_heat_recycle_per_mille{}, spent_drip_absorb{}; // Mutation offers (Cellular_mutation_plan.md section 3). std::int64_t mutation_options{}, mutation_floor_ppm{}, mutation_cap_ppm{}; std::int64_t mutation_score_min{}, mutation_score_max{}; diff --git a/include/evo/server/lifecycle/cellular_admin_view.hpp b/include/evo/server/lifecycle/cellular_admin_view.hpp index 71253ec..e494abe 100644 --- a/include/evo/server/lifecycle/cellular_admin_view.hpp +++ b/include/evo/server/lifecycle/cellular_admin_view.hpp @@ -12,7 +12,8 @@ // it is not a simulation output, a checkpoint or a client protocol. // // {"world":W,"region":R,"tick":T,"rules":N,["rules_sha256":"hex",]"area":[w,h], -// "spent":[e,c,n,p,o],["drip":[interval_ticks,bubble_pj,bubble_fg],] +// "spent":[e,c,n,p,o],"heat":pj, +// ["drip":[interval_ticks,bubble_pj,bubble_fg,heat_recycle_per_mille,absorb],] // "cells_total":N,"deposits_total":N, // "counts":[players,wildlife,patches,pools,bubbles], // "totals":{"reserve":[e,c,n,p,o],"body":[...],"patches":[...],"pools":[...],"bubbles":[...]}, @@ -28,7 +29,9 @@ // in pJ, matter in fg. Cells and deposits beyond the limits are left out (by ascending life id and // deposit id); the totals still count them. `rules_sha256` is given by the caller (the SHA-256 // of encode_cellular_revamp_rules, which tuning revisions are adopted by) and left out when empty. -// `drip` is the rules-13 spent-pool drip (cellular_drip_spent), left out before rules 13. +// `heat` is the energy the region's cells have used and not yet recycled (CellularLives::heat). +// `drip` is the rules-13 spent-pool drip (cellular_drip_spent) and its energy cycle (ADR-0182 +// section 14), left out before rules 13. // `counts` and `totals` cover every life and deposit, whatever the limits: the region's stock // is the totals plus `spent`. namespace evo::server { diff --git a/include/evo/server/lifecycle/cellular_revamp.hpp b/include/evo/server/lifecycle/cellular_revamp.hpp index c46bafe..11bc9d1 100644 --- a/include/evo/server/lifecycle/cellular_revamp.hpp +++ b/include/evo/server/lifecycle/cellular_revamp.hpp @@ -28,6 +28,12 @@ struct CellularRevampRules { // 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{}; + // ADR-0182 section 14 (0 and false keep the historical law): the share of the region's + // heat, per mille, moved to the spent pool at the end of every tick before the drip, so + // energy cycles back like matter; and a drip at the deposit limit joins an existing bubble + // (the first at or after its spot) instead of waiting. + std::uint32_t heat_recycle_per_thousand{}; + bool drip_absorb{}; // 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{}; @@ -114,8 +120,9 @@ cellular_mutation_cost(const biology::CellularMutationTuning& tuning) 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. +// A habitat at its deposit limit keeps the rest waiting, or with `drip_absorb` adds it to the +// first bubble at or after that spot in address order (wrapping). 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, diff --git a/src/biology/cellular_revamp_tuning.cpp b/src/biology/cellular_revamp_tuning.cpp index f8dadca..139af6a 100644 --- a/src/biology/cellular_revamp_tuning.cpp +++ b/src/biology/cellular_revamp_tuning.cpp @@ -48,6 +48,9 @@ constexpr std::array fields{ 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}, + Field{"spent.heat_recycle_per_mille", &CellularRevampTuning::spent_heat_recycle_per_mille, 0, + 1'000}, + Field{"spent.drip_absorb", &CellularRevampTuning::spent_drip_absorb, 0, 1}, Field{"mutation.options", &CellularRevampTuning::mutation_options, 1, 10}, Field{"mutation.floor_ppm", &CellularRevampTuning::mutation_floor_ppm, 0, 1'000'000}, Field{"mutation.cap_ppm", &CellularRevampTuning::mutation_cap_ppm, 1, 1'000'000}, @@ -257,6 +260,8 @@ parse_cellular_revamp_tuning(std::string_view text) { if (!seen.at(index) && fields.at(index).key != "playtest.starting_wildlife_cells" && fields.at(index).key != "feeding.collection_percent" && fields.at(index).key != "feeding.split_evenly" && + fields.at(index).key != "spent.heat_recycle_per_mille" && + fields.at(index).key != "spent.drip_absorb" && fields.at(index).key != "reproduction.safety_version" && fields.at(index).key != "body.growth_reserve_seconds" && fields.at(index).key != "reproduction.split_launch_um_per_s") diff --git a/src/server/lifecycle/cellular_admin_view.cpp b/src/server/lifecycle/cellular_admin_view.cpp index ed4df5f..2e40ad0 100644 --- a/src/server/lifecycle/cellular_admin_view.cpp +++ b/src/server/lifecycle/cellular_admin_view.cpp @@ -80,7 +80,8 @@ std::string render_cellular_admin_view(const CellularLives& state, append(out, state.area().height_um); out += "],\"spent\":["; append_inventory(out, state.spent()); - out.push_back(']'); + out += "],\"heat\":"; + append(out, state.heat().energy.value); if (state.rules_version() >= cellular_lives_revamp_rules) { const auto& rules = state.revamp_rules(); out += ",\"drip\":["; @@ -89,7 +90,9 @@ std::string render_cellular_admin_view(const CellularLives& state, append(out, rules.drip_bubble_pj); out.push_back(','); append(out, rules.drip_bubble_fg); - out.push_back(']'); + out.push_back(','); + append(out, rules.heat_recycle_per_thousand); + out += rules.drip_absorb ? ",1]" : ",0]"; } out += ",\"cells_total\":"; append(out, lives.size()); diff --git a/src/server/lifecycle/cellular_lives.cpp b/src/server/lifecycle/cellular_lives.cpp index eff8af4..2c05740 100644 --- a/src/server/lifecycle/cellular_lives.cpp +++ b/src/server/lifecycle/cellular_lives.cpp @@ -62,7 +62,9 @@ constexpr std::size_t cellular_life_motion_bytes = 20; // reserved zero, 32), the catalog bounds (five 4-byte fields, a reserved zero and the carbon // gate, 32), the offer interval and a reserved zero (8), and 49 mutation tunables of 80 bytes. // ADR-0181 uses the growth/offer/bounds reserved words for safety revision, -// growth fuel seconds and split launch speed; historical zeros retain their law. +// growth fuel seconds and split launch speed; ADR-0182 section 14 the offer interval's for the +// heat recycle share (low 16 bits) and the absorbing drip (bit 16). Historical zeros retain +// their law. constexpr std::size_t cellular_revamp_mutation_bytes = 80; // Then the reproduction tunables: split share, split growth, organism cap, fee scale (16) and // the bud fee (40). @@ -235,7 +237,8 @@ void write_revamp_offers(Writer& out, const CellularRevampRules& r) { out.put(r.split_launch_um_per_s, 4); out.put(b.carbon_for_light); out.put(r.offer_interval_ticks, 4); - out.put(0, 4); + // The offer interval's reserved word: the heat recycle share and the absorbing drip. + out.put(r.heat_recycle_per_thousand | (r.drip_absorb ? 0x10000U : 0U), 4); for (const auto& m : r.mutations) { out.put(m.enabled ? 1 : 0, 1); out.zeros(3); @@ -282,7 +285,10 @@ bool read_revamp_offers(Reader& in, CellularRevampRules& r) { r.split_launch_um_per_s = u32(); b.carbon_for_light = in.get(); r.offer_interval_ticks = u32(); - zero = zero && in.get(4) == 0; + const auto cycle = in.get(4); + r.heat_recycle_per_thousand = static_cast(cycle & 0xFFFFU); + r.drip_absorb = (cycle & 0x10000U) != 0; + zero = zero && (cycle & ~0x1FFFFULL) == 0; for (auto& m : r.mutations) { const auto enabled = in.get(1); zero = zero && enabled <= 1 && in.get(3) == 0; @@ -3988,6 +3994,17 @@ CellularLives::advance_tick_with_mutations(std::span i } habitat_config.patches.insert(at, made); } + // ADR-0182 section 14: a share of the region's heat returns to the spent pool before the + // drip, so the energy cells used cycles back like matter instead of draining away. + if (revamp_rules && state_->revamp.heat_recycle_per_thousand != 0) { + const auto heat = next_heat.energy.value; + const auto share = state_->revamp.heat_recycle_per_thousand; + const auto recycled = heat / 1'000 * share + heat % 1'000 * share / 1'000; + if (recycled > std::numeric_limits::max() - next_spent.energy.value) + return std::unexpected{CellularLivesError::overflow}; + next_heat.energy.value -= recycled; + next_spent.energy.value += recycled; + } // 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, diff --git a/src/server/lifecycle/cellular_revamp.cpp b/src/server/lifecycle/cellular_revamp.cpp index 8b74e3f..8988012 100644 --- a/src/server/lifecycle/cellular_revamp.cpp +++ b/src/server/lifecycle/cellular_revamp.cpp @@ -52,6 +52,7 @@ bool cellular_revamp_valid(const CellularRevampRules& rules) noexcept { 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.heat_recycle_per_thousand <= 1'000 && (rules.drip_interval_ticks == 0 || (rules.drip_bubble_pj != 0 && rules.drip_bubble_fg != 0)) && rules.reserve_load_per_thousand <= 1'000 && @@ -59,9 +60,8 @@ bool cellular_revamp_valid(const CellularRevampRules& rules) noexcept { rules.split_share_per_thousand < 1'000 && rules.split_min_growth != 0 && rules.split_min_growth <= 1'000 && rules.bud_fee_scale_percent <= 100 && rules.bud_fee.energy.value <= most && - std::ranges::all_of( - rules.bud_fee.matter, - [](const accounting::Femtograms& f) { return f.value <= most; }) && + std::ranges::all_of(rules.bud_fee.matter, + [](const accounting::Femtograms& f) { return f.value <= most; }) && rules.organism_cap != 0 && rules.organism_cap <= biology::max_cellular_tick_lives && rules.organism_load_per_thousand <= 10'000 && rules.emerge_members >= 2 && rules.emerge_members <= 10'000 && rules.emerge_mass_fg <= most && @@ -105,10 +105,34 @@ bool cellular_drip_spent(biology::CellularHabitatConfig& config, accounting::Inv // 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) + if (pool == 0) continue; biology::CellularPatchAddress address{static_cast(x % config.width_um), static_cast(y % config.height_um)}; + if (config.patches.size() >= biology::max_cellular_liquid_deposits) { + if (!rules.drip_absorb) + continue; + // At the limit an existing bubble takes the drip, as if absorbing it from the + // water: the first bubble at or after the spot in address order, wrapping. + const auto start = std::ranges::lower_bound(config.patches, address, {}, by_address); + const auto is_bubble = [](const biology::CellularPatch& patch) { + return patch.kind == biology::CellularDepositKind::mote; + }; + auto host = std::ranges::find_if(start, config.patches.end(), is_bubble); + if (host == config.patches.end()) { + host = std::ranges::find_if(config.patches.begin(), start, is_bubble); + if (host == start) + continue; // No bubble at all: the drip waits. + } + const auto amount = std::min(pool, cap); + auto& stock = + channel == 0 ? host->stock.energy.value : host->stock.matter[channel - 1].value; + if (amount > std::numeric_limits::max() - stock) + continue; + stock += amount; + pool -= amount; + continue; + } 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; @@ -301,6 +325,8 @@ CellularRevampRules cellular_revamp_rules(const biology::CellularRevampTuning& t .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), + .heat_recycle_per_thousand = u32(t.spent_heat_recycle_per_mille), + .drip_absorb = t.spent_drip_absorb != 0, .reserve_load_per_thousand = u32(t.body_reserve_load_per_mille), .growth_per_tick_centi_mille = u32(t.body_growth_per_tick_centi_mille), .offers = {.options = u32(t.mutation_options), diff --git a/tests/cellular_admin_view_tests.cpp b/tests/cellular_admin_view_tests.cpp index f11cede..1630501 100644 --- a/tests/cellular_admin_view_tests.cpp +++ b/tests/cellular_admin_view_tests.cpp @@ -95,6 +95,9 @@ void renders_cells_and_deposits() { require(text.find(",\"bubbles\":" + list(bubbles) + "}") != std::string::npos, "bubble totals"); require(text.find("\"drip\"") == std::string::npos, "a drip before rules 13"); + require(text.find("],\"heat\":" + std::to_string(state->heat().energy.value) + + ",\"cells_total\":") != std::string::npos, + "heat"); } } @@ -129,11 +132,14 @@ void renders_the_drip() { .kill_bubble_per_thousand = 500}, .drip_interval_ticks = 20, .drip_bubble_pj = 20'000'000, - .drip_bubble_fg = 1'000'000}; + .drip_bubble_fg = 1'000'000, + .heat_recycle_per_thousand = 1'000, + .drip_absorb = true}; state = checked(state->revamp_upgrade_candidate(rules), "revamp upgrade"); const auto view = render_cellular_admin_view(*state, {}); - require(view.find("],\"drip\":[20,20000000,1000000],\"cells_total\":") != std::string::npos, - "rules-13 drip"); + require(view.find(",\"drip\":[20,20000000,1000000,1000,1],\"cells_total\":") != + std::string::npos, + "rules-13 drip and energy cycle"); } } // namespace diff --git a/tests/cellular_revamp_owner_tests.cpp b/tests/cellular_revamp_owner_tests.cpp index 25cd3e2..45c89d6 100644 --- a/tests/cellular_revamp_owner_tests.cpp +++ b/tests/cellular_revamp_owner_tests.cpp @@ -1059,6 +1059,101 @@ void tuning_is_adopted_and_replayed() { require(!encode_cellular_batch(twice), "two adoptions shared a batch"); } +// ADR-0182 section 14: adopted energy cycling returns the region's heat (what its cells used, +// and what had built up before) to the spent pool before the drip. The fields sit in a reserved +// word, so historical rules keep their bytes; adopted rules restore and replay. +void heat_cycles_back() { + auto live = revamp_region(); + for (int tick = 0; tick < 30; ++tick) + checked(live->advance_tick(swim(*live, {1'000, 0})), "cells use energy"); + const auto heat = live->heat().energy.value; + require(heat > 0, "the cells used no energy"); + const auto before = live->revamp_rules(); + auto cycling = before; + cycling.heat_recycle_per_thousand = 1'000; + cycling.drip_absorb = true; + cycling.drip_interval_ticks = 0; // No drip: the whole recycled heat stays in the pool. + const auto old_bytes = encode_cellular_revamp_rules(before); + const auto new_bytes = encode_cellular_revamp_rules(cycling); + require(cellular_revamp_valid(cycling) && old_bytes.size() == new_bytes.size() && + old_bytes != new_bytes, + "the energy cycle is not a same-size distinct encoding"); + auto excessive = cycling; + excessive.heat_recycle_per_thousand = 1'001; + require(!cellular_revamp_valid(excessive), "more than all the heat was recycled"); + + std::array digest{}; + digest.fill(9); + const std::vector commands{cellular_adopt_tuning_command(1, 7, digest)}; + std::vector results; + auto after = + checked(live->admin_candidate(commands, &results, + [&](std::uint64_t, const std::array&) { + return std::optional{cycling}; + }), + "the energy cycle is adopted"); + require(results.size() == 1 && results.front().applied && after->revamp_rules() == cycling, + "the energy cycle was not adopted"); + require(restore(*after)->revamp_rules() == cycling && + restore(*after)->snapshot() == after->snapshot(), + "the energy cycle does not restore"); + + const auto spent = after->spent().energy.value; + const auto twin = restore(*after); + const auto intents = swim(*after, {1'000, 0}); + checked(after->advance_tick(intents), "a cycling tick"); + require(after->heat().energy.value == 0 && after->spent().energy.value > spent + heat, + "the heat, old and new, did not reach the spent pool"); + checked(twin->advance_tick(intents), "the cycling tick again"); + require(twin->snapshot() == after->snapshot(), "the cycling tick is not deterministic"); + // Without the cycle the heat keeps building. + checked(live->advance_tick(intents), "a historical tick"); + require(live->heat().energy.value > heat, "historical rules recycled heat"); +} + +// A drip at the deposit limit waits, or with the absorbing drip joins an existing bubble. +void full_drip_is_absorbed() { + biology::CellularHabitatConfig full{}; + full.world = full.region = full.frame = 1; + full.width_um = full.height_um = 1'000; + full.format = biology::cellular_habitat_liquid_format; + for (std::uint32_t i = 0; i < biology::max_cellular_liquid_deposits; ++i) { + biology::CellularPatch bubble{ + {i % 128 * 7, i / 128 * 11}, 1, {}, i + 1, biology::cellular_mote_radius_um, + biology::CellularDepositKind::mote}; + bubble.merged = 1; + bubble.stock.matter[0].value = 10; + full.patches.push_back(bubble); + } + std::ranges::sort(full.patches, {}, &biology::CellularPatch::address); + full.next_deposit = biology::max_cellular_liquid_deposits + 1; + auto rules = revamp(); + rules.drip_interval_ticks = 1; + accounting::Inventory pool{}; + pool.energy.value = 30'000'000; + pool.matter[0].value = 5; + const auto energy = [](const biology::CellularHabitatConfig& c) { + std::uint64_t total = 0; + for (const auto& patch : c.patches) + total += patch.stock.energy.value; + return total; + }; + + auto waiting = full; + auto kept = pool; + require(cellular_drip_spent(waiting, kept, rules, 1, 1, 1, 1) && kept == pool && + waiting == full, + "a full habitat took a drip without absorbing"); + rules.drip_absorb = true; + auto absorbing = full; + auto left = pool; + require(cellular_drip_spent(absorbing, left, rules, 1, 1, 1, 1), "the absorbing drip"); + require(absorbing.patches.size() == full.patches.size() && + left.energy.value == pool.energy.value - rules.drip_bubble_pj && + left.matter[0].value == 0 && energy(absorbing) == rules.drip_bubble_pj, + "the drip did not join existing bubbles"); +} + // The safety revision preserves all five channels, follows both control choices, // separates eligible predator/prey siblings and replays their actual motion exactly. void safety_split(bool become) { @@ -1219,6 +1314,8 @@ void safe_bud_provision(bool become) { int main() try { admin_commands_apply_and_replay(); tuning_is_adopted_and_replayed(); + heat_cycles_back(); + full_drip_is_absorbed(); safety_split(false); safety_split(true); safe_bud_provision(false); diff --git a/tests/cellular_revamp_tuning_tests.cpp b/tests/cellular_revamp_tuning_tests.cpp index 095d78f..0f7e1ee 100644 --- a/tests/cellular_revamp_tuning_tests.cpp +++ b/tests/cellular_revamp_tuning_tests.cpp @@ -74,6 +74,9 @@ CellularRevampTuning trial(bool safety = true) { t.reproduction_safety_version = 0; t.body_growth_reserve_seconds = 0; t.reproduction_split_launch_um_per_s = 0; + // The DEV revamp file cycles energy (ADR-0182 section 14). + t.spent_heat_recycle_per_mille = 1'000; + t.spent_drip_absorb = 1; } return t; } @@ -155,6 +158,20 @@ void refusals() { historical.erase(at, historical.find('\n', at) - at + 1); } CHECK(parse_cellular_revamp_tuning(historical)->reproduction_safety_version == 0); + // The energy cycle keys (ADR-0182 section 14) are optional and bounded. + auto uncycled = base; + for (const auto* key : {"spent.heat_recycle_per_mille", "spent.drip_absorb"}) { + const auto at = uncycled.find(key); + uncycled.erase(at, uncycled.find('\n', at) - at + 1); + } + CHECK(parse_cellular_revamp_tuning(uncycled) == trial()); + const auto cycled = parse_cellular_revamp_tuning( + with(with(base, "spent.heat_recycle_per_mille", "1_000"), "spent.drip_absorb", "1")); + CHECK(cycled && cycled->spent_heat_recycle_per_mille == 1'000 && + cycled->spent_drip_absorb == 1); + CHECK(error_of(with(base, "spent.heat_recycle_per_mille", "1001")) == + CellularTuningErrorKind::out_of_range); + CHECK(error_of(with(base, "spent.drip_absorb", "2")) == CellularTuningErrorKind::out_of_range); CHECK(error_of(with(base, "playtest.starting_wildlife_cells", "256")) == CellularTuningErrorKind::out_of_range); CHECK(error_of(with(base, "playtest.starting_wildlife_cells", "-1")) ==