Foundation / checks (checks) (push) Successful in 42m33s
Foundation / checks (deploy) (push) Successful in 4m11s
Foundation / checks (ecs) (push) Successful in 2m27s
Foundation / checks (network) (push) Successful in 19m23s
Foundation / checks (postgres) (push) Successful in 44m44s
Foundation / checks (tsan) (push) Successful in 9m53s
Foundation / checks (client) (push) Successful in 16m19s
Foundation / postgres-tools (push) Successful in 30s
Foundation / server-image (push) Successful in 3m14s
Foundation / image (push) Successful in 3m16s
The playtest found mutation offers the arena could never pay for. A mutation's matter cost is the real body difference (ADR-0118), so it cannot be discounted. Rules 6 cut it honestly: - genome schema 3 steps a third as far (1/300 of the range); - development version 3 charges a third of the construction energy (13 instead of 40 pJ per 1000 fg). Founder 2 uses both. The cellular-v5 opening creates rules-6 regions on bundle v7, which schema v41 admits. Existing lineages, regions and committed history are unchanged. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1646 lines
88 KiB
C++
1646 lines
88 KiB
C++
#include "evo/server/lifecycle/cellular_lives.hpp"
|
|
#include "evo/biology/budding.hpp"
|
|
#include "evo/biology/founder.hpp"
|
|
|
|
#include <algorithm>
|
|
#include <array>
|
|
#include <bit>
|
|
#include <limits>
|
|
#include <ranges>
|
|
#include <stdexcept>
|
|
#include <utility>
|
|
|
|
namespace evo::server {
|
|
namespace {
|
|
constexpr std::uint64_t cellular_lives_v1_magic = 0x3130564C43564541ULL; // AEVCLV01
|
|
constexpr std::uint64_t cellular_lives_v2_magic = 0x3230564C43564541ULL; // AEVCLV02
|
|
constexpr std::uint64_t cellular_lives_v3_magic = 0x3330564C43564541ULL; // AEVCLV03
|
|
constexpr std::uint64_t cellular_lives_v4_magic = 0x3430564C43564541ULL; // AEVCLV04
|
|
constexpr std::uint64_t cellular_lives_v5_magic = 0x3530564C43564541ULL; // AEVCLV05
|
|
constexpr std::uint64_t cellular_lives_v6_magic = 0x3630564C43564541ULL; // AEVCLV06
|
|
constexpr std::size_t cellular_lives_header_bytes = 212;
|
|
constexpr std::size_t cellular_site_bytes = 8;
|
|
constexpr std::size_t cellular_life_v1_bytes = 168;
|
|
constexpr std::size_t cellular_life_v2_bytes = 480;
|
|
constexpr std::size_t cellular_corpse_bytes = 100;
|
|
// Format 4: cause (1), 7 zero bytes and the predator's life id (8).
|
|
constexpr std::size_t cellular_corpse_v4_bytes = cellular_corpse_bytes + 16;
|
|
// Format 5 (ADR-0125): the header adds the next bud sequence, each life and each corpse
|
|
// its parent life (8 bytes each).
|
|
constexpr std::size_t cellular_lives_v5_header_bytes = cellular_lives_header_bytes + 8;
|
|
constexpr std::size_t cellular_life_v5_bytes = cellular_life_v2_bytes + 8;
|
|
constexpr std::size_t cellular_corpse_v5_bytes = cellular_corpse_v4_bytes + 8;
|
|
// Format 6 (ADR-0128): each life adds presence (1), 7 zero bytes and its freeze tick (8).
|
|
constexpr std::size_t cellular_life_v6_bytes = cellular_life_v5_bytes + 16;
|
|
|
|
std::uint64_t checksum(std::span<const std::uint8_t> bytes) noexcept {
|
|
std::uint64_t value = 14695981039346656037ULL;
|
|
for (const auto byte : bytes)
|
|
value = (value ^ byte) * 1099511628211ULL;
|
|
return value;
|
|
}
|
|
|
|
std::uint64_t mutation_seed(std::uint64_t world, std::uint64_t region, std::uint64_t life,
|
|
std::uint64_t event) noexcept {
|
|
auto value = 14695981039346656037ULL;
|
|
for (const auto part : {world, region, life, event}) {
|
|
for (unsigned index = 0; index < 8; ++index) {
|
|
value = (value ^ static_cast<std::uint8_t>(part >> (index * 8U))) * 1099511628211ULL;
|
|
}
|
|
}
|
|
return value == 0 ? 1 : value;
|
|
}
|
|
|
|
class Writer {
|
|
public:
|
|
explicit Writer(std::vector<std::uint8_t>& bytes) : bytes_{bytes} {}
|
|
void put(std::uint64_t value, unsigned width = 8) {
|
|
for (unsigned i = 0; i < width; ++i, value >>= 8U)
|
|
bytes_.push_back(static_cast<std::uint8_t>(value & 255U));
|
|
}
|
|
void inventory(const accounting::Inventory& value) {
|
|
put(value.energy.value);
|
|
for (const auto mass : value.matter)
|
|
put(mass.value);
|
|
}
|
|
void site(SpawnSite value) {
|
|
put(std::bit_cast<std::uint32_t>(value.x_um), 4);
|
|
put(std::bit_cast<std::uint32_t>(value.y_um), 4);
|
|
}
|
|
template <std::size_t N> void bytes(const std::array<std::uint8_t, N>& value) {
|
|
bytes_.insert(bytes_.end(), value.begin(), value.end());
|
|
}
|
|
void raw(std::span<const std::uint8_t> value) {
|
|
bytes_.insert(bytes_.end(), value.begin(), value.end());
|
|
}
|
|
void zeros(std::size_t count) {
|
|
bytes_.insert(bytes_.end(), count, 0);
|
|
}
|
|
|
|
private:
|
|
std::vector<std::uint8_t>& bytes_;
|
|
};
|
|
|
|
class Reader {
|
|
public:
|
|
explicit Reader(std::span<const std::uint8_t> bytes) : bytes_{bytes} {}
|
|
std::uint64_t get(unsigned width = 8) {
|
|
std::uint64_t value{};
|
|
for (unsigned i = 0; i < width; ++i)
|
|
value |= std::uint64_t{bytes_[at_++]} << (8U * i);
|
|
return value;
|
|
}
|
|
accounting::Inventory inventory() {
|
|
accounting::Inventory value{};
|
|
value.energy.value = get();
|
|
for (auto& mass : value.matter)
|
|
mass.value = get();
|
|
return value;
|
|
}
|
|
SpawnSite site() {
|
|
return {std::bit_cast<std::int32_t>(static_cast<std::uint32_t>(get(4))),
|
|
std::bit_cast<std::int32_t>(static_cast<std::uint32_t>(get(4)))};
|
|
}
|
|
template <std::size_t N> std::array<std::uint8_t, N> bytes() {
|
|
std::array<std::uint8_t, N> result{};
|
|
std::ranges::copy(bytes_.subspan(at_, N), result.begin());
|
|
at_ += N;
|
|
return result;
|
|
}
|
|
std::span<const std::uint8_t> raw(std::size_t size) {
|
|
const auto result = bytes_.subspan(at_, size);
|
|
at_ += size;
|
|
return result;
|
|
}
|
|
|
|
private:
|
|
std::span<const std::uint8_t> bytes_;
|
|
std::size_t at_{};
|
|
};
|
|
|
|
bool add_inventory(accounting::Inventory& total, const accounting::Inventory& value) noexcept {
|
|
constexpr auto maximum = std::numeric_limits<std::uint64_t>::max();
|
|
if (value.energy.value > maximum - total.energy.value)
|
|
return false;
|
|
for (std::size_t channel = 0; channel < total.matter.size(); ++channel)
|
|
if (value.matter[channel].value > maximum - total.matter[channel].value)
|
|
return false;
|
|
total.energy.value += value.energy.value;
|
|
for (std::size_t channel = 0; channel < total.matter.size(); ++channel)
|
|
total.matter[channel].value += value.matter[channel].value;
|
|
return true;
|
|
}
|
|
|
|
bool subtract_inventory(accounting::Inventory& total, const accounting::Inventory& value) noexcept {
|
|
if (value.energy.value > total.energy.value)
|
|
return false;
|
|
for (std::size_t channel = 0; channel < total.matter.size(); ++channel)
|
|
if (value.matter[channel].value > total.matter[channel].value)
|
|
return false;
|
|
total.energy.value -= value.energy.value;
|
|
for (std::size_t channel = 0; channel < total.matter.size(); ++channel)
|
|
total.matter[channel].value -= value.matter[channel].value;
|
|
return true;
|
|
}
|
|
|
|
std::expected<biology::MetabolicBudget, CellularLivesError>
|
|
budget_for(const biology::LineageArchive& archive, const CellularOwnedLife& life,
|
|
std::uint32_t temperature) {
|
|
const auto genome = archive.find(life.identity.genome);
|
|
if (!genome)
|
|
return std::unexpected{CellularLivesError::archive};
|
|
const auto budget = biology::metabolic_budget(*genome, life.growth, {temperature, {}});
|
|
if (!budget)
|
|
return std::unexpected{CellularLivesError::biology};
|
|
return *budget;
|
|
}
|
|
|
|
bool separated(std::uint64_t left, std::uint64_t right, std::uint32_t left_extent,
|
|
std::uint32_t right_extent) noexcept {
|
|
return left < right ? right - left >= left_extent : left - right >= right_extent;
|
|
}
|
|
|
|
// ADR-0125 placement: touching the parent, centres (parent + bud extent) / 2 + 1 apart on
|
|
// each moved axis, trying east and then counter-clockwise in 45-degree steps. The first
|
|
// spot inside the area and clear of every living cell wins; none is a refusal.
|
|
std::expected<std::optional<biology::CellularPosition>, CellularLivesError>
|
|
bud_position(const CellularOwnedLife& parent, std::uint32_t parent_extent, std::uint32_t bud_extent,
|
|
std::span<const CellularOwnedLife> lives, const biology::LineageArchive& archive,
|
|
const CellularLivesConfig& config) {
|
|
constexpr std::array<std::array<std::int64_t, 2>, 8> directions{
|
|
{{1, 0}, {1, 1}, {0, 1}, {-1, 1}, {-1, 0}, {-1, -1}, {0, -1}, {1, -1}}};
|
|
if (bud_extent == 0 || bud_extent > config.area.width_um || bud_extent > config.area.height_um)
|
|
return std::optional<biology::CellularPosition>{};
|
|
std::vector<std::uint32_t> extents;
|
|
extents.reserve(lives.size());
|
|
for (const auto& living : lives) {
|
|
const auto budget = budget_for(archive, living, config.ambient_temperature_millikelvin);
|
|
if (!budget)
|
|
return std::unexpected{budget.error()};
|
|
extents.push_back(budget->phenotype.extent);
|
|
}
|
|
// Doubled centre coordinates keep half extents exact.
|
|
const auto step = std::int64_t{parent_extent} + bud_extent + 2;
|
|
// Twice the bud's corner coordinate on one axis; negative is outside the area.
|
|
const auto doubled_corner = [&](std::uint64_t parent_corner, std::int64_t direction) {
|
|
return 2 * static_cast<std::int64_t>(parent_corner) + parent_extent + direction * step -
|
|
std::int64_t{bud_extent};
|
|
};
|
|
for (const auto& [dx, dy] : directions) {
|
|
const auto twice_x = doubled_corner(parent.position.x_um, dx);
|
|
const auto twice_y = doubled_corner(parent.position.y_um, dy);
|
|
const auto x = twice_x / 2;
|
|
const auto y = twice_y / 2;
|
|
if (twice_x < 0 || twice_y < 0 ||
|
|
static_cast<std::uint64_t>(x) > config.area.width_um - bud_extent ||
|
|
static_cast<std::uint64_t>(y) > config.area.height_um - bud_extent)
|
|
continue;
|
|
const biology::CellularPosition candidate{static_cast<std::uint64_t>(x),
|
|
static_cast<std::uint64_t>(y)};
|
|
bool clear = true;
|
|
for (std::size_t i = 0; i < lives.size() && clear; ++i)
|
|
clear = lives[i].presence == CellularPresence::suspended ||
|
|
separated(candidate.x_um, lives[i].position.x_um, bud_extent, extents[i]) ||
|
|
separated(candidate.y_um, lives[i].position.y_um, bud_extent, extents[i]);
|
|
if (clear)
|
|
return std::optional{candidate};
|
|
}
|
|
return std::optional<biology::CellularPosition>{};
|
|
}
|
|
|
|
// ADR-0128 resume: its own position if clear of every cell in the world, else the first
|
|
// clear spot at one, two or three of its extents in the eight fixed directions.
|
|
std::expected<std::optional<biology::CellularPosition>, CellularLivesError>
|
|
resume_position(const CellularOwnedLife& life, std::uint32_t extent,
|
|
std::span<const CellularOwnedLife> lives, const biology::LineageArchive& archive,
|
|
const CellularLivesConfig& config) {
|
|
constexpr std::array<std::array<std::int64_t, 2>, 8> directions{
|
|
{{1, 0}, {1, 1}, {0, 1}, {-1, 1}, {-1, 0}, {-1, -1}, {0, -1}, {1, -1}}};
|
|
if (extent == 0 || extent > config.area.width_um || extent > config.area.height_um)
|
|
return std::optional<biology::CellularPosition>{};
|
|
std::vector<std::pair<const CellularOwnedLife*, std::uint32_t>> present;
|
|
for (const auto& other : lives) {
|
|
if (other.presence == CellularPresence::suspended ||
|
|
other.identity.life == life.identity.life)
|
|
continue;
|
|
const auto budget = budget_for(archive, other, config.ambient_temperature_millikelvin);
|
|
if (!budget)
|
|
return std::unexpected{budget.error()};
|
|
present.emplace_back(&other, budget->phenotype.extent);
|
|
}
|
|
const auto clear = [&](std::int64_t x, std::int64_t y) {
|
|
if (x < 0 || y < 0 || static_cast<std::uint64_t>(x) > config.area.width_um - extent ||
|
|
static_cast<std::uint64_t>(y) > config.area.height_um - extent)
|
|
return false;
|
|
return std::ranges::all_of(present, [&](const auto& entry) {
|
|
const auto& [other, other_extent] = entry;
|
|
return separated(static_cast<std::uint64_t>(x), other->position.x_um, extent,
|
|
other_extent) ||
|
|
separated(static_cast<std::uint64_t>(y), other->position.y_um, extent,
|
|
other_extent);
|
|
});
|
|
};
|
|
const auto x0 = static_cast<std::int64_t>(life.position.x_um);
|
|
const auto y0 = static_cast<std::int64_t>(life.position.y_um);
|
|
if (clear(x0, y0))
|
|
return std::optional{life.position};
|
|
for (std::uint32_t ring = 1; ring <= cellular_resume_extents; ++ring)
|
|
for (const auto& [dx, dy] : directions) {
|
|
const auto step = static_cast<std::int64_t>(ring) * extent;
|
|
if (clear(x0 + dx * step, y0 + dy * step))
|
|
return std::optional{
|
|
biology::CellularPosition{static_cast<std::uint64_t>(x0 + dx * step),
|
|
static_cast<std::uint64_t>(y0 + dy * step)}};
|
|
}
|
|
return std::optional<biology::CellularPosition>{};
|
|
}
|
|
|
|
std::expected<accounting::Inventory, CellularLivesError>
|
|
sum_state(accounting::Inventory nursery, accounting::Inventory heat,
|
|
const biology::CellularHabitat& habitat, std::span<const CellularOwnedLife> lives,
|
|
std::span<const CellularOwnedCorpse> corpses) noexcept {
|
|
auto total = nursery;
|
|
if (!add_inventory(total, heat))
|
|
return std::unexpected{CellularLivesError::overflow};
|
|
if (!add_inventory(total, habitat.totals()))
|
|
return std::unexpected{CellularLivesError::overflow};
|
|
for (const auto& life : lives)
|
|
if (!add_inventory(total, life.body) || !add_inventory(total, life.reserve))
|
|
return std::unexpected{CellularLivesError::overflow};
|
|
for (const auto& corpse : corpses)
|
|
if (!add_inventory(total, corpse.inventory))
|
|
return std::unexpected{CellularLivesError::overflow};
|
|
return total;
|
|
}
|
|
|
|
std::expected<accounting::Inventory, CellularLivesError>
|
|
validate_state(std::uint64_t world, std::uint64_t region, std::uint64_t frame,
|
|
const CellularLivesConfig& config, const NurseryConfig& nursery_config,
|
|
const biology::CellularHabitat& habitat, std::span<const CellularOwnedLife> lives,
|
|
std::span<const CellularOwnedCorpse> corpses, const biology::LineageArchive& archive,
|
|
accounting::Inventory nursery, accounting::Inventory heat,
|
|
accounting::Inventory opening_total, bool detritus_rules = false,
|
|
bool bud_rules = false, std::uint64_t next_bud_sequence = 1,
|
|
bool presence_rules = false) {
|
|
// 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 {
|
|
const auto first = cellular_bud_identity(region, 1);
|
|
return bud_rules && first != 0 && next_bud_sequence > 1 && identity >= first &&
|
|
identity - first < next_bud_sequence - 1;
|
|
};
|
|
const auto lineage_valid = [&](std::uint64_t life_id, std::uint64_t parent) noexcept {
|
|
if (parent == 0) // Rules 4 keep allocated identities below the bud namespace.
|
|
return !bud_rules || life_id < cellular_bud_namespace;
|
|
return bud_identity(life_id) && parent != life_id;
|
|
};
|
|
const auto& map = habitat.config();
|
|
if (world == 0 || region == 0 || frame == 0 || nursery_config.world != world ||
|
|
nursery_config.region != region || nursery_config.frame != frame ||
|
|
nursery_config.source == 0 || nursery_config.funding != nursery || map.world != world ||
|
|
map.region != region || map.frame != frame || config.area.width_um == 0 ||
|
|
config.area.height_um == 0 || map.width_um != config.area.width_um ||
|
|
map.height_um != config.area.height_um || config.ambient_temperature_millikelvin == 0 ||
|
|
nursery_config.sites.empty() || nursery_config.sites.size() > max_primitive_lives ||
|
|
!std::ranges::is_sorted(nursery_config.sites) ||
|
|
lives.size() > biology::max_cellular_tick_lives ||
|
|
corpses.size() > biology::max_archived_organisms ||
|
|
archive.recorded() != lives.size() + corpses.size())
|
|
return std::unexpected{CellularLivesError::invalid_config};
|
|
if (std::ranges::any_of(heat.matter, [](const auto& value) { return value.value != 0; }))
|
|
return std::unexpected{CellularLivesError::conservation};
|
|
|
|
const auto founder = biology::primitive_founder(1, 1);
|
|
if (!founder)
|
|
return std::unexpected{CellularLivesError::biology};
|
|
const auto founder_budget = biology::metabolic_budget(
|
|
*founder, {1000, 0}, {config.ambient_temperature_millikelvin, {}});
|
|
if (!founder_budget)
|
|
return std::unexpected{CellularLivesError::biology};
|
|
const auto spawn_extent = founder_budget->phenotype.extent;
|
|
for (std::size_t i = 0; i < nursery_config.sites.size(); ++i) {
|
|
const auto site = nursery_config.sites[i];
|
|
if (site.x_um < 0 || site.y_um < 0 || spawn_extent > config.area.width_um ||
|
|
spawn_extent > config.area.height_um ||
|
|
static_cast<std::uint64_t>(site.x_um) > config.area.width_um - spawn_extent ||
|
|
static_cast<std::uint64_t>(site.y_um) > config.area.height_um - spawn_extent)
|
|
return std::unexpected{CellularLivesError::invalid_config};
|
|
for (std::size_t j = 0; j < i; ++j) {
|
|
const auto delta_x = std::int64_t{site.x_um} - nursery_config.sites[j].x_um;
|
|
const auto delta_y = std::int64_t{site.y_um} - nursery_config.sites[j].y_um;
|
|
const auto dx = static_cast<std::uint64_t>(delta_x < 0 ? -delta_x : delta_x);
|
|
const auto dy = static_cast<std::uint64_t>(delta_y < 0 ? -delta_y : delta_y);
|
|
if (dx < spawn_extent && dy < spawn_extent)
|
|
return std::unexpected{CellularLivesError::invalid_config};
|
|
}
|
|
}
|
|
|
|
std::vector<std::uint64_t> live_organisms;
|
|
std::vector<std::uint64_t> life_ids;
|
|
live_organisms.reserve(lives.size());
|
|
life_ids.reserve(lives.size() + corpses.size());
|
|
for (std::size_t i = 0; i < lives.size(); ++i) {
|
|
const auto& life = lives[i];
|
|
// Founders are owned; buds are unowned wildlife (rules 4) and never earn offers.
|
|
const bool wildlife = life.parent_life != 0;
|
|
// ADR-0128: only owned lives leave; a lingering life is within its linger time.
|
|
const bool presence_valid =
|
|
life.presence == CellularPresence::active
|
|
? life.frozen_since == 0
|
|
: presence_rules && !wildlife && life.frozen_since != 0 &&
|
|
life.frozen_since <= config.tick &&
|
|
(life.presence == CellularPresence::suspended ||
|
|
(life.presence == CellularPresence::lingering &&
|
|
config.tick - life.frozen_since < cellular_linger_ticks));
|
|
if (!presence_valid)
|
|
return std::unexpected{CellularLivesError::invalid_life};
|
|
if ((life.account == LifeAccount{}) != wildlife || life.identity.life == 0 ||
|
|
life.identity.organism == 0 || life.identity.genome == 0 || life.identity.event == 0 ||
|
|
life.identity.born.value == 0 || life.identity.born.value > config.tick ||
|
|
life.source == 0 || (i != 0 && lives[i - 1].identity.life >= life.identity.life) ||
|
|
!lineage_valid(life.identity.life, life.parent_life) ||
|
|
(wildlife && (life.identity.organism != life.identity.life ||
|
|
life.identity.event != life.identity.life ||
|
|
life.mutation != CellularMutationProgress{})))
|
|
return std::unexpected{CellularLivesError::invalid_life};
|
|
for (std::size_t j = 0; j < i; ++j)
|
|
if ((!wildlife && lives[j].account == life.account) ||
|
|
lives[j].identity.organism == life.identity.organism)
|
|
return std::unexpected{CellularLivesError::duplicate_life};
|
|
const auto record = archive.organism(life.identity.organism);
|
|
const auto current_genome = archive.current_genome(life.identity.organism);
|
|
if (!record || !record->alive || !current_genome ||
|
|
*current_genome != life.identity.genome || record->born != life.identity.born)
|
|
return std::unexpected{CellularLivesError::archive};
|
|
const auto budget = budget_for(archive, life, config.ambient_temperature_millikelvin);
|
|
if (!budget || budget->body != life.body || life.body.energy.value != 0 ||
|
|
budget->phenotype.extent == 0 || budget->phenotype.extent > config.area.width_um ||
|
|
budget->phenotype.extent > config.area.height_um ||
|
|
life.position.x_um > config.area.width_um - budget->phenotype.extent ||
|
|
life.position.y_um > config.area.height_um - budget->phenotype.extent)
|
|
return std::unexpected{CellularLivesError::invalid_life};
|
|
live_organisms.push_back(life.identity.organism);
|
|
life_ids.push_back(life.identity.life);
|
|
}
|
|
std::ranges::sort(live_organisms);
|
|
if (archive.living_organisms() != live_organisms)
|
|
return std::unexpected{CellularLivesError::archive};
|
|
|
|
for (std::size_t i = 0; i < corpses.size(); ++i) {
|
|
const auto& corpse = corpses[i];
|
|
if (corpse.life_id == 0 || corpse.organism == 0 || corpse.source == 0 ||
|
|
corpse.died_tick == 0 || corpse.died_tick > config.tick || corpse.extent_um == 0 ||
|
|
(i != 0 && corpses[i - 1].organism >= corpse.organism) ||
|
|
!lineage_valid(corpse.life_id, corpse.parent_life))
|
|
return std::unexpected{CellularLivesError::invalid_life};
|
|
const auto record = archive.organism(corpse.organism);
|
|
if (!record || record->alive || record->died.value != corpse.died_tick)
|
|
return std::unexpected{CellularLivesError::archive};
|
|
const auto current_genome = archive.current_genome(corpse.organism);
|
|
if (!current_genome)
|
|
return std::unexpected{CellularLivesError::archive};
|
|
const auto genome = archive.find(*current_genome);
|
|
if (!genome)
|
|
return std::unexpected{CellularLivesError::archive};
|
|
const auto budget = biology::metabolic_budget(*genome, corpse.growth,
|
|
{config.ambient_temperature_millikelvin, {}});
|
|
if (!budget || budget->phenotype.extent != corpse.extent_um ||
|
|
corpse.extent_um > config.area.width_um || corpse.extent_um > config.area.height_um ||
|
|
corpse.position.x_um > config.area.width_um - corpse.extent_um ||
|
|
corpse.position.y_um > config.area.height_um - corpse.extent_um)
|
|
return std::unexpected{CellularLivesError::invalid_life};
|
|
if (detritus_rules) {
|
|
// Rules 3 (ADR-0124): the inventory became detritus or the predator's.
|
|
if (corpse.inventory != accounting::Inventory{})
|
|
return std::unexpected{CellularLivesError::conservation};
|
|
} else {
|
|
for (std::size_t channel = 0; channel < corpse.inventory.matter.size(); ++channel)
|
|
if (corpse.inventory.matter[channel].value < budget->body.matter[channel].value)
|
|
return std::unexpected{CellularLivesError::conservation};
|
|
}
|
|
life_ids.push_back(corpse.life_id);
|
|
}
|
|
std::ranges::sort(life_ids);
|
|
if (std::ranges::adjacent_find(life_ids) != life_ids.end())
|
|
return std::unexpected{CellularLivesError::duplicate_life};
|
|
|
|
const auto current = sum_state(nursery, heat, habitat, lives, corpses);
|
|
if (!current)
|
|
return std::unexpected{current.error()};
|
|
if (*current != opening_total)
|
|
return std::unexpected{CellularLivesError::conservation};
|
|
return *current;
|
|
}
|
|
} // namespace
|
|
|
|
struct CellularLives::State {
|
|
std::uint64_t world{}, region{}, frame{};
|
|
std::uint32_t format_version{cellular_lives_format}, rules_version{cellular_lives_rules};
|
|
CellularLivesConfig config{};
|
|
NurseryConfig nursery_config{};
|
|
std::unique_ptr<biology::CellularHabitat> habitat;
|
|
std::vector<CellularOwnedLife> lives;
|
|
std::vector<CellularOwnedCorpse> corpses;
|
|
biology::LineageArchive archive;
|
|
accounting::Inventory nursery{};
|
|
accounting::Inventory heat{};
|
|
accounting::Inventory opening_total{};
|
|
accounting::Inventory current_total{};
|
|
std::uint64_t next_bud_sequence{1}; // Format 5: the next bud identity's sequence.
|
|
|
|
State(std::uint64_t world_id, std::uint64_t region_id, std::uint64_t frame_id,
|
|
CellularLivesConfig cfg, NurseryConfig nursery_definition,
|
|
std::unique_ptr<biology::CellularHabitat> map, std::vector<CellularOwnedLife> living,
|
|
std::vector<CellularOwnedCorpse> dead, const biology::LineageArchive& history,
|
|
accounting::Inventory source, accounting::Inventory accumulated_heat,
|
|
accounting::Inventory initial, accounting::Inventory current,
|
|
std::uint32_t format = cellular_lives_format, std::uint32_t rules = cellular_lives_rules)
|
|
: world{world_id}, region{region_id}, frame{frame_id}, format_version{format},
|
|
rules_version{rules}, config{cfg}, nursery_config{std::move(nursery_definition)},
|
|
habitat{std::move(map)}, lives{std::move(living)}, corpses{std::move(dead)},
|
|
archive{history}, nursery{source}, heat{accumulated_heat}, opening_total{initial},
|
|
current_total{current} {}
|
|
};
|
|
|
|
CellularLives::CellularLives(std::unique_ptr<State> state) : state_{std::move(state)} {}
|
|
CellularLives::~CellularLives() = default;
|
|
|
|
std::expected<std::unique_ptr<CellularLives>, CellularLivesError>
|
|
CellularLives::create(const PrimitiveLives& opening,
|
|
std::unique_ptr<biology::CellularHabitat> habitat, CellularLivesConfig config,
|
|
CellularLivesProfile profile) {
|
|
if (!habitat)
|
|
return std::unexpected{CellularLivesError::invalid_config};
|
|
auto nursery_config = opening.config();
|
|
const auto& map = habitat->config();
|
|
if (nursery_config.world == 0 || nursery_config.region == 0 || nursery_config.frame == 0 ||
|
|
map.world != nursery_config.world || map.region != nursery_config.region ||
|
|
map.frame != nursery_config.frame || config.area.width_um == 0 ||
|
|
config.area.height_um == 0 || config.area.width_um != map.width_um ||
|
|
config.area.height_um != map.height_um || config.ambient_temperature_millikelvin == 0 ||
|
|
opening.lives().size() > biology::max_cellular_tick_lives ||
|
|
opening.balances().size() != 2 + 2 * nursery_config.sites.size())
|
|
return std::unexpected{CellularLivesError::invalid_config};
|
|
|
|
std::vector<CellularOwnedLife> lives;
|
|
lives.reserve(opening.lives().size());
|
|
for (const auto& primitive : opening.lives()) {
|
|
if (primitive.identity.born.value == 0 || primitive.identity.born.value > config.tick ||
|
|
primitive.identity.life == 0 || primitive.identity.organism == 0 ||
|
|
primitive.identity.genome == 0 || primitive.source == 0 || primitive.site.x_um < 0 ||
|
|
primitive.site.y_um < 0)
|
|
return std::unexpected{CellularLivesError::invalid_life};
|
|
if (primitive.body.value == 0 || primitive.reserve.value == 0)
|
|
return std::unexpected{CellularLivesError::invalid_life};
|
|
const auto body_index = static_cast<std::size_t>(primitive.body.value - 1);
|
|
const auto reserve_index = static_cast<std::size_t>(primitive.reserve.value - 1);
|
|
if (body_index >= opening.balances().size() || reserve_index >= opening.balances().size())
|
|
return std::unexpected{CellularLivesError::invalid_life};
|
|
lives.push_back({primitive.request.account,
|
|
primitive.identity,
|
|
primitive.source,
|
|
primitive.growth,
|
|
{static_cast<std::uint64_t>(primitive.site.x_um),
|
|
static_cast<std::uint64_t>(primitive.site.y_um)},
|
|
opening.balances()[body_index],
|
|
opening.balances()[reserve_index]});
|
|
}
|
|
auto archive = opening.archive();
|
|
std::ranges::sort(lives, {}, [](const auto& life) { return life.identity.life; });
|
|
for (std::size_t i = 0; i < lives.size(); ++i) {
|
|
const auto& life = lives[i];
|
|
if (i != 0 && lives[i - 1].identity.life == life.identity.life)
|
|
return std::unexpected{CellularLivesError::duplicate_life};
|
|
const auto budget = budget_for(archive, life, config.ambient_temperature_millikelvin);
|
|
if (!budget || budget->phenotype.extent == 0 ||
|
|
budget->phenotype.extent > config.area.width_um ||
|
|
budget->phenotype.extent > config.area.height_um || life.body.energy.value != 0 ||
|
|
budget->body != life.body ||
|
|
life.position.x_um > config.area.width_um - budget->phenotype.extent ||
|
|
life.position.y_um > config.area.height_um - budget->phenotype.extent)
|
|
return std::unexpected{CellularLivesError::invalid_life};
|
|
}
|
|
auto opening_total = opening.totals();
|
|
if (!add_inventory(opening_total, habitat->totals()))
|
|
return std::unexpected{CellularLivesError::overflow};
|
|
const auto nursery = opening.balances()[0];
|
|
nursery_config.funding = nursery;
|
|
const auto heat = opening.balances()[1];
|
|
const auto current =
|
|
validate_state(nursery_config.world, nursery_config.region, nursery_config.frame, config,
|
|
nursery_config, *habitat, lives, {}, archive, nursery, heat, opening_total);
|
|
if (!current)
|
|
return std::unexpected{current.error()};
|
|
|
|
const auto world = nursery_config.world;
|
|
const auto region = nursery_config.region;
|
|
const auto frame = nursery_config.frame;
|
|
const bool balance = profile == CellularLivesProfile::balance; // Rules 6: presence plus.
|
|
const bool presence = profile == CellularLivesProfile::presence || balance;
|
|
const bool budding = profile == CellularLivesProfile::budding || presence;
|
|
const bool engulf = profile == CellularLivesProfile::engulf || budding;
|
|
if (engulf)
|
|
archive.upgrade_to_revision_format(); // Rules 3+ regions carry genome revisions.
|
|
auto state = std::make_unique<State>(world, region, frame, config, std::move(nursery_config),
|
|
std::move(habitat), std::move(lives),
|
|
std::vector<CellularOwnedCorpse>{}, archive, nursery, heat,
|
|
opening_total, *current,
|
|
presence ? cellular_lives_presence_format
|
|
: budding ? cellular_lives_bud_format
|
|
: engulf ? cellular_lives_engulf_format
|
|
: cellular_lives_format,
|
|
balance ? cellular_lives_balance_rules
|
|
: presence ? cellular_lives_presence_rules
|
|
: budding ? cellular_lives_bud_rules
|
|
: engulf ? cellular_lives_engulf_rules
|
|
: cellular_lives_rules);
|
|
return std::unique_ptr<CellularLives>{new CellularLives{std::move(state)}};
|
|
}
|
|
|
|
std::uint64_t CellularLives::world() const noexcept {
|
|
return state_->world;
|
|
}
|
|
std::uint64_t CellularLives::region() const noexcept {
|
|
return state_->region;
|
|
}
|
|
std::uint64_t CellularLives::frame() const noexcept {
|
|
return state_->frame;
|
|
}
|
|
std::uint64_t CellularLives::tick() const noexcept {
|
|
return state_->config.tick;
|
|
}
|
|
std::uint32_t CellularLives::format_version() const noexcept {
|
|
return state_->format_version;
|
|
}
|
|
std::uint32_t CellularLives::rules_version() const noexcept {
|
|
return state_->rules_version;
|
|
}
|
|
std::uint64_t CellularLives::next_bud_sequence() const noexcept {
|
|
return state_->next_bud_sequence;
|
|
}
|
|
std::uint32_t CellularLives::ambient_temperature_millikelvin() const noexcept {
|
|
return state_->config.ambient_temperature_millikelvin;
|
|
}
|
|
biology::CellularArea CellularLives::area() const noexcept {
|
|
return state_->config.area;
|
|
}
|
|
std::span<const CellularOwnedLife> CellularLives::lives() const noexcept {
|
|
return state_->lives;
|
|
}
|
|
std::span<const CellularOwnedCorpse> CellularLives::corpses() const noexcept {
|
|
return state_->corpses;
|
|
}
|
|
const biology::CellularHabitat& CellularLives::habitat() const noexcept {
|
|
return *state_->habitat;
|
|
}
|
|
const biology::LineageArchive& CellularLives::archive() const noexcept {
|
|
return state_->archive;
|
|
}
|
|
accounting::Inventory CellularLives::nursery() const noexcept {
|
|
return state_->nursery;
|
|
}
|
|
accounting::Inventory CellularLives::heat() const noexcept {
|
|
return state_->heat;
|
|
}
|
|
accounting::Inventory CellularLives::opening_total() const noexcept {
|
|
return state_->opening_total;
|
|
}
|
|
accounting::Inventory CellularLives::current_total() const noexcept {
|
|
return state_->current_total;
|
|
}
|
|
std::span<const CellularLifeTickFeedback> CellularLives::last_tick_feedback() const noexcept {
|
|
return last_tick_feedback_;
|
|
}
|
|
|
|
std::vector<std::uint8_t> CellularLives::snapshot() const {
|
|
const auto habitat = state_->habitat->snapshot();
|
|
const auto archive = state_->archive.encode();
|
|
const auto site_count = state_->nursery_config.sites.size();
|
|
const auto life_count = state_->lives.size();
|
|
const auto corpse_count = state_->corpses.size();
|
|
const bool parents = state_->format_version >= cellular_lives_bud_format;
|
|
const bool presence = state_->format_version >= cellular_lives_presence_format;
|
|
const auto life_bytes = state_->format_version == cellular_lives_legacy_format
|
|
? cellular_life_v1_bytes
|
|
: presence ? cellular_life_v6_bytes
|
|
: parents ? cellular_life_v5_bytes
|
|
: cellular_life_v2_bytes;
|
|
const bool causes = state_->format_version >= cellular_lives_engulf_format;
|
|
const auto corpse_bytes = parents ? cellular_corpse_v5_bytes
|
|
: causes ? cellular_corpse_v4_bytes
|
|
: cellular_corpse_bytes;
|
|
const auto header_bytes =
|
|
parents ? cellular_lives_v5_header_bytes : cellular_lives_header_bytes;
|
|
const auto total_bytes = header_bytes + cellular_site_bytes * site_count +
|
|
life_bytes * life_count + corpse_bytes * corpse_count +
|
|
habitat.size() + archive.size() + 8;
|
|
if (total_bytes > max_cellular_lives_bytes ||
|
|
habitat.size() > biology::max_cellular_habitat_bytes ||
|
|
archive.size() > biology::max_archive_bytes || site_count > max_primitive_lives ||
|
|
life_count > biology::max_cellular_tick_lives ||
|
|
corpse_count > biology::max_archived_organisms)
|
|
throw std::length_error{"cellular lives checkpoint exceeds its format bounds"};
|
|
|
|
std::vector<std::uint8_t> bytes;
|
|
bytes.reserve(total_bytes);
|
|
Writer out{bytes};
|
|
const auto magic =
|
|
state_->format_version == cellular_lives_legacy_format ? cellular_lives_v1_magic
|
|
: state_->format_version == cellular_lives_revision_format ? cellular_lives_v3_magic
|
|
: state_->format_version == cellular_lives_engulf_format ? cellular_lives_v4_magic
|
|
: state_->format_version == cellular_lives_bud_format ? cellular_lives_v5_magic
|
|
: state_->format_version == cellular_lives_presence_format ? cellular_lives_v6_magic
|
|
: cellular_lives_v2_magic;
|
|
out.put(magic);
|
|
out.put(state_->format_version, 4);
|
|
out.put(state_->rules_version, 4);
|
|
out.put(state_->world);
|
|
out.put(state_->region);
|
|
out.put(state_->frame);
|
|
out.put(state_->config.tick);
|
|
out.put(state_->config.area.width_um, 4);
|
|
out.put(state_->config.area.height_um, 4);
|
|
out.put(state_->config.ambient_temperature_millikelvin, 4);
|
|
out.put(site_count, 4);
|
|
out.put(life_count, 4);
|
|
out.put(corpse_count, 4);
|
|
out.put(habitat.size(), 4);
|
|
out.put(archive.size(), 4);
|
|
out.put(0, 4);
|
|
out.put(state_->nursery_config.source);
|
|
out.inventory(state_->opening_total);
|
|
out.inventory(state_->nursery);
|
|
out.inventory(state_->heat);
|
|
if (parents)
|
|
out.put(state_->next_bud_sequence);
|
|
for (const auto site : state_->nursery_config.sites)
|
|
out.site(site);
|
|
for (const auto& life : state_->lives) {
|
|
out.bytes(life.account);
|
|
out.put(life.identity.life);
|
|
out.put(life.identity.organism);
|
|
out.put(life.identity.genome);
|
|
out.put(life.identity.event);
|
|
out.put(life.identity.born.value);
|
|
out.put(life.source);
|
|
out.put(life.growth.realized_per_thousand, 4);
|
|
out.put(life.growth.damage_per_thousand, 4);
|
|
out.put(life.position.x_um);
|
|
out.put(life.position.y_um);
|
|
out.inventory(life.body);
|
|
out.inventory(life.reserve);
|
|
if (state_->format_version >= cellular_lives_format) {
|
|
const auto& mutation = life.mutation;
|
|
out.put(mutation.fed_energy_credit_pj);
|
|
out.put(mutation.event_index);
|
|
out.put(mutation.offer_tick);
|
|
out.put(mutation.offer ? mutation.offer->parent : 0);
|
|
out.put(mutation.offer ? mutation.offer->parent_digest : 0);
|
|
out.put(mutation.offer ? mutation.offer->context.seed : 0);
|
|
out.put(mutation.offer ? mutation.offer->context.stream : 0, 4);
|
|
out.put(mutation.offer ? mutation.offer->context.event_index : 0);
|
|
out.put(mutation.offer ? mutation.offer->context.candidate_count : 0, 2);
|
|
out.put(0, 2);
|
|
out.put(mutation.offer ? mutation.offer->context.growth.realized_per_thousand : 0, 4);
|
|
out.put(mutation.offer ? mutation.offer->context.growth.damage_per_thousand : 0, 4);
|
|
out.put(mutation.offer ? mutation.offer->context.environment.temperature_millikelvin
|
|
: 0,
|
|
4);
|
|
out.put(0, 4);
|
|
out.inventory(mutation.offer ? mutation.offer->context.environment.available
|
|
: accounting::Inventory{});
|
|
for (std::size_t index = 0; index < biology::max_candidates; ++index) {
|
|
if (mutation.offer && index < mutation.offer->candidates.size()) {
|
|
const auto& candidates = mutation.offer.value().candidates;
|
|
const auto& candidate = candidates[index];
|
|
out.put(candidate.operator_id, 2);
|
|
out.put(static_cast<std::uint8_t>(candidate.target), 1);
|
|
out.put(static_cast<std::uint8_t>(candidate.effect), 1);
|
|
out.put(candidate.parameter, 4);
|
|
out.put(candidate.maintenance);
|
|
out.put(candidate.total_mass);
|
|
} else {
|
|
out.zeros(24);
|
|
}
|
|
}
|
|
}
|
|
if (parents)
|
|
out.put(life.parent_life);
|
|
if (presence) {
|
|
out.put(static_cast<std::uint8_t>(life.presence), 1);
|
|
out.zeros(7);
|
|
out.put(life.frozen_since);
|
|
}
|
|
}
|
|
for (const auto& corpse : state_->corpses) {
|
|
out.put(corpse.life_id);
|
|
out.put(corpse.organism);
|
|
out.put(corpse.source);
|
|
out.put(corpse.died_tick);
|
|
out.put(corpse.position.x_um);
|
|
out.put(corpse.position.y_um);
|
|
out.put(corpse.growth.realized_per_thousand, 4);
|
|
out.put(corpse.growth.damage_per_thousand, 4);
|
|
out.put(corpse.extent_um, 4);
|
|
out.inventory(corpse.inventory);
|
|
if (causes) {
|
|
out.put(static_cast<std::uint8_t>(corpse.cause), 1);
|
|
out.zeros(7);
|
|
out.put(corpse.predator_life);
|
|
}
|
|
if (parents)
|
|
out.put(corpse.parent_life);
|
|
}
|
|
out.raw(habitat);
|
|
out.raw(archive);
|
|
if (bytes.size() + 8 != total_bytes)
|
|
throw std::logic_error{"cellular lives checkpoint size calculation mismatch"};
|
|
out.put(checksum(bytes));
|
|
return bytes;
|
|
}
|
|
|
|
std::expected<std::vector<biology::CellularPatchPerception>, CellularLivesError>
|
|
CellularLives::perceive(std::uint64_t life_id) const {
|
|
const auto life = std::ranges::find(state_->lives, life_id,
|
|
[](const auto& owned) { return owned.identity.life; });
|
|
if (life == state_->lives.end())
|
|
return std::unexpected{CellularLivesError::invalid_life};
|
|
const auto budget =
|
|
budget_for(state_->archive, *life, state_->config.ambient_temperature_millikelvin);
|
|
if (!budget)
|
|
return std::unexpected{budget.error()};
|
|
auto view = state_->habitat->perceive(life->position, budget->phenotype.extent);
|
|
if (!view)
|
|
return std::unexpected{CellularLivesError::habitat};
|
|
return std::move(*view);
|
|
}
|
|
|
|
std::expected<std::optional<biology::MutationOffer>, CellularLivesError>
|
|
CellularLives::mutation_offer(std::uint64_t life_id) const {
|
|
const auto life = std::ranges::find(state_->lives, life_id,
|
|
[](const auto& owned) { return owned.identity.life; });
|
|
if (life == state_->lives.end())
|
|
return std::unexpected{CellularLivesError::invalid_life};
|
|
return life->mutation.offer;
|
|
}
|
|
|
|
std::expected<std::unique_ptr<CellularLives>, CellularLivesError>
|
|
CellularLives::migrate_to_v2() const {
|
|
if (state_->format_version != cellular_lives_legacy_format || state_->rules_version != 1)
|
|
return std::unexpected{CellularLivesError::version};
|
|
auto lives = state_->lives;
|
|
for (auto& life : lives)
|
|
life.mutation = {};
|
|
auto habitat = biology::CellularHabitat::restore(state_->habitat->snapshot(), state_->world,
|
|
state_->region, state_->frame);
|
|
if (!habitat)
|
|
return std::unexpected{CellularLivesError::habitat};
|
|
auto candidate = std::unique_ptr<CellularLives>{new CellularLives{std::make_unique<State>(
|
|
state_->world, state_->region, state_->frame, state_->config, state_->nursery_config,
|
|
std::move(*habitat), std::move(lives), state_->corpses, state_->archive, state_->nursery,
|
|
state_->heat, state_->opening_total, state_->current_total, cellular_lives_format,
|
|
cellular_lives_rules)}};
|
|
return candidate;
|
|
}
|
|
|
|
std::expected<std::unique_ptr<CellularLives>, CellularLivesError>
|
|
CellularLives::migrate_to_v3() const {
|
|
if (state_->format_version != cellular_lives_format ||
|
|
state_->rules_version != cellular_lives_rules ||
|
|
state_->archive.format_version() != biology::lineage_archive_format)
|
|
return std::unexpected{CellularLivesError::version};
|
|
auto archive = state_->archive;
|
|
archive.upgrade_to_revision_format();
|
|
auto habitat = biology::CellularHabitat::restore(state_->habitat->snapshot(), state_->world,
|
|
state_->region, state_->frame);
|
|
if (!habitat)
|
|
return std::unexpected{CellularLivesError::habitat};
|
|
const auto current =
|
|
validate_state(state_->world, state_->region, state_->frame, state_->config,
|
|
state_->nursery_config, **habitat, state_->lives, state_->corpses, archive,
|
|
state_->nursery, state_->heat, state_->opening_total);
|
|
if (!current || *current != state_->current_total)
|
|
return std::unexpected{current ? CellularLivesError::conservation : current.error()};
|
|
auto candidate = std::unique_ptr<CellularLives>{new CellularLives{std::make_unique<State>(
|
|
state_->world, state_->region, state_->frame, state_->config, state_->nursery_config,
|
|
std::move(*habitat), state_->lives, state_->corpses, archive, state_->nursery, state_->heat,
|
|
state_->opening_total, state_->current_total, cellular_lives_revision_format,
|
|
cellular_lives_rules)}};
|
|
return candidate;
|
|
}
|
|
|
|
std::expected<std::unique_ptr<CellularLives>, CellularLivesError>
|
|
CellularLives::birth_candidate(LifeRequest request, LifeAllocation allocation) const {
|
|
if (request.action == 0 ||
|
|
std::ranges::all_of(request.account, [](std::uint8_t value) { return value == 0; }))
|
|
return std::unexpected{CellularLivesError::invalid_life};
|
|
if (allocation.life == 0 || allocation.life != allocation.organism ||
|
|
allocation.life != allocation.genome || allocation.life != allocation.event)
|
|
return std::unexpected{CellularLivesError::identity};
|
|
if (allocation.born.value == 0 || allocation.born.value != state_->config.tick)
|
|
return std::unexpected{CellularLivesError::invalid_tick};
|
|
if (state_->lives.size() >= biology::max_cellular_tick_lives)
|
|
return std::unexpected{CellularLivesError::no_placement};
|
|
if (std::ranges::any_of(state_->lives, [&](const CellularOwnedLife& life) {
|
|
return life.account == request.account;
|
|
}))
|
|
return std::unexpected{CellularLivesError::life_exists};
|
|
if (std::ranges::any_of(state_->lives,
|
|
[&](const CellularOwnedLife& life) {
|
|
return life.identity.life == allocation.life ||
|
|
life.identity.organism == allocation.organism ||
|
|
life.identity.genome == allocation.genome ||
|
|
life.identity.event == allocation.event;
|
|
}) ||
|
|
std::ranges::any_of(state_->corpses,
|
|
[&](const CellularOwnedCorpse& corpse) {
|
|
return corpse.life_id == allocation.life ||
|
|
corpse.organism == allocation.organism;
|
|
}) ||
|
|
state_->archive.find(allocation.genome) || state_->archive.organism(allocation.organism))
|
|
return std::unexpected{CellularLivesError::duplicate_life};
|
|
|
|
// Rules 6 found version-2 founders: lower construction energy, finer mutations.
|
|
const auto founder_version = cellular_founder_version(state_->rules_version);
|
|
const auto endowed = biology::primitive_endowment(founder_version);
|
|
const auto genome =
|
|
biology::primitive_founder(allocation.genome, allocation.event, founder_version);
|
|
if (!endowed || !genome)
|
|
return std::unexpected{CellularLivesError::biology};
|
|
const auto budget = biology::metabolic_budget(
|
|
*genome, endowed->growth, {state_->config.ambient_temperature_millikelvin, {}});
|
|
if (!budget || budget->body != endowed->body)
|
|
return std::unexpected{CellularLivesError::biology};
|
|
|
|
std::optional<biology::CellularPosition> position;
|
|
for (const auto site : state_->nursery_config.sites) {
|
|
if (site.x_um < 0 || site.y_um < 0)
|
|
return std::unexpected{CellularLivesError::invalid_config};
|
|
const biology::CellularPosition candidate{static_cast<std::uint64_t>(site.x_um),
|
|
static_cast<std::uint64_t>(site.y_um)};
|
|
bool occupied = false;
|
|
for (const auto& living : state_->lives) {
|
|
if (living.presence == CellularPresence::suspended)
|
|
continue; // Out of the world (ADR-0128).
|
|
const auto living_budget =
|
|
budget_for(state_->archive, living, state_->config.ambient_temperature_millikelvin);
|
|
if (!living_budget)
|
|
return std::unexpected{living_budget.error()};
|
|
const auto separated = [](std::uint64_t left, std::uint64_t right,
|
|
std::uint32_t left_extent,
|
|
std::uint32_t right_extent) noexcept {
|
|
return left < right ? right - left >= left_extent : left - right >= right_extent;
|
|
};
|
|
if (!separated(candidate.x_um, living.position.x_um, budget->phenotype.extent,
|
|
living_budget->phenotype.extent) &&
|
|
!separated(candidate.y_um, living.position.y_um, budget->phenotype.extent,
|
|
living_budget->phenotype.extent)) {
|
|
occupied = true;
|
|
break;
|
|
}
|
|
}
|
|
if (!occupied) {
|
|
position = candidate;
|
|
break;
|
|
}
|
|
}
|
|
if (!position)
|
|
return std::unexpected{CellularLivesError::no_placement};
|
|
|
|
auto nursery = state_->nursery;
|
|
if (!subtract_inventory(nursery, endowed->body) ||
|
|
!subtract_inventory(nursery, endowed->reserve) ||
|
|
endowed->construction.value > nursery.energy.value)
|
|
return std::unexpected{CellularLivesError::insufficient_funding};
|
|
nursery.energy.value -= endowed->construction.value;
|
|
auto heat = state_->heat;
|
|
if (endowed->construction.value > std::numeric_limits<std::uint64_t>::max() - heat.energy.value)
|
|
return std::unexpected{CellularLivesError::overflow};
|
|
heat.energy.value += endowed->construction.value;
|
|
|
|
auto archive = state_->archive;
|
|
if (!archive.admit(*genome) ||
|
|
!archive.record_birth(allocation.organism, allocation.genome, allocation.born))
|
|
return std::unexpected{CellularLivesError::archive};
|
|
auto lives = state_->lives;
|
|
lives.push_back({request.account, allocation, state_->nursery_config.source, endowed->growth,
|
|
*position, endowed->body, endowed->reserve});
|
|
std::ranges::sort(lives, {}, [](const CellularOwnedLife& life) { return life.identity.life; });
|
|
|
|
auto nursery_config = state_->nursery_config;
|
|
nursery_config.funding = nursery;
|
|
auto habitat = biology::CellularHabitat::restore(state_->habitat->snapshot(), state_->world,
|
|
state_->region, state_->frame);
|
|
if (!habitat)
|
|
return std::unexpected{CellularLivesError::habitat};
|
|
const auto current =
|
|
validate_state(state_->world, state_->region, state_->frame, state_->config, nursery_config,
|
|
**habitat, lives, state_->corpses, archive, nursery, heat,
|
|
state_->opening_total, state_->rules_version >= cellular_lives_engulf_rules,
|
|
state_->rules_version >= cellular_lives_bud_rules, state_->next_bud_sequence,
|
|
state_->rules_version >= cellular_lives_presence_rules);
|
|
if (!current)
|
|
return std::unexpected{current.error()};
|
|
|
|
auto candidate = std::unique_ptr<CellularLives>{new CellularLives{std::make_unique<State>(
|
|
state_->world, state_->region, state_->frame, state_->config, std::move(nursery_config),
|
|
std::move(*habitat), std::move(lives), state_->corpses, archive, nursery, heat,
|
|
state_->opening_total, *current, state_->format_version, state_->rules_version)}};
|
|
candidate->last_tick_feedback_ = last_tick_feedback_;
|
|
candidate->state_->next_bud_sequence = state_->next_bud_sequence;
|
|
return candidate;
|
|
}
|
|
|
|
std::expected<std::unique_ptr<CellularLives>, CellularLivesError>
|
|
CellularLives::restore(std::span<const std::uint8_t> bytes, std::uint64_t world,
|
|
std::uint64_t region, std::uint64_t frame, std::uint64_t tick) {
|
|
if (bytes.size() < cellular_lives_header_bytes + 8 || bytes.size() > max_cellular_lives_bytes)
|
|
return std::unexpected{CellularLivesError::format};
|
|
Reader tail{bytes.last(8)};
|
|
if (checksum(bytes.first(bytes.size() - 8)) != tail.get())
|
|
return std::unexpected{CellularLivesError::checksum};
|
|
|
|
Reader in{bytes};
|
|
const auto magic = in.get();
|
|
const auto format_version = static_cast<std::uint32_t>(in.get(4));
|
|
const auto rules_version = static_cast<std::uint32_t>(in.get(4));
|
|
const bool legacy = magic == cellular_lives_v1_magic &&
|
|
format_version == cellular_lives_legacy_format && rules_version == 1;
|
|
const bool offer_version = magic == cellular_lives_v2_magic &&
|
|
format_version == cellular_lives_format &&
|
|
rules_version == cellular_lives_rules;
|
|
// Format 6 carries rules 5 or rules 6 (founder 2, no new state).
|
|
const bool presence_version = magic == cellular_lives_v6_magic &&
|
|
format_version == cellular_lives_presence_format &&
|
|
(rules_version == cellular_lives_presence_rules ||
|
|
rules_version == cellular_lives_balance_rules);
|
|
// Formats 5 and 6 carry the bud sequence and parent lives (rules 4 and 5).
|
|
const bool bud_version = presence_version || (magic == cellular_lives_v5_magic &&
|
|
format_version == cellular_lives_bud_format &&
|
|
rules_version == cellular_lives_bud_rules);
|
|
// Formats 4 and 5 record death causes and leave detritus (rules 3 and 4).
|
|
const bool engulf_version = bud_version || (magic == cellular_lives_v4_magic &&
|
|
format_version == cellular_lives_engulf_format &&
|
|
rules_version == cellular_lives_engulf_rules);
|
|
const bool revision_version =
|
|
engulf_version ||
|
|
(magic == cellular_lives_v3_magic && format_version == cellular_lives_revision_format &&
|
|
rules_version == cellular_lives_rules);
|
|
const bool mutation_version = offer_version || revision_version;
|
|
if (!legacy && !mutation_version)
|
|
return std::unexpected{CellularLivesError::version};
|
|
const auto saved_world = in.get();
|
|
const auto saved_region = in.get();
|
|
const auto saved_frame = in.get();
|
|
const auto saved_tick = in.get();
|
|
if (saved_world != world || saved_region != region || saved_frame != frame)
|
|
return std::unexpected{CellularLivesError::identity};
|
|
if (saved_tick != tick)
|
|
return std::unexpected{CellularLivesError::invalid_tick};
|
|
|
|
CellularLivesConfig config;
|
|
config.area.width_um = static_cast<std::uint32_t>(in.get(4));
|
|
config.area.height_um = static_cast<std::uint32_t>(in.get(4));
|
|
config.tick = saved_tick;
|
|
config.ambient_temperature_millikelvin = static_cast<std::uint32_t>(in.get(4));
|
|
const auto site_count = in.get(4);
|
|
const auto life_count = in.get(4);
|
|
const auto corpse_count = in.get(4);
|
|
const auto habitat_size = in.get(4);
|
|
const auto archive_size = in.get(4);
|
|
if (in.get(4) != 0 || site_count == 0 || site_count > max_primitive_lives ||
|
|
life_count > biology::max_cellular_tick_lives ||
|
|
corpse_count > biology::max_archived_organisms ||
|
|
habitat_size > biology::max_cellular_habitat_bytes ||
|
|
archive_size > biology::max_archive_bytes)
|
|
return std::unexpected{CellularLivesError::format};
|
|
const auto source = in.get();
|
|
const auto opening_total = in.inventory();
|
|
const auto nursery = in.inventory();
|
|
const auto heat = in.inventory();
|
|
const auto next_bud_sequence = bud_version ? in.get() : std::uint64_t{1};
|
|
const auto life_bytes = legacy ? cellular_life_v1_bytes
|
|
: presence_version ? cellular_life_v6_bytes
|
|
: bud_version ? cellular_life_v5_bytes
|
|
: cellular_life_v2_bytes;
|
|
const auto corpse_bytes = bud_version ? cellular_corpse_v5_bytes
|
|
: engulf_version ? cellular_corpse_v4_bytes
|
|
: cellular_corpse_bytes;
|
|
const auto expected_size =
|
|
(bud_version ? cellular_lives_v5_header_bytes : cellular_lives_header_bytes) +
|
|
cellular_site_bytes * site_count + life_bytes * life_count + corpse_bytes * corpse_count +
|
|
habitat_size + archive_size + 8;
|
|
if (source == 0 || next_bud_sequence == 0 || expected_size != bytes.size())
|
|
return std::unexpected{CellularLivesError::format};
|
|
|
|
NurseryConfig nursery_config{saved_world, saved_region, saved_frame, source, nursery, {}};
|
|
nursery_config.sites.reserve(static_cast<std::size_t>(site_count));
|
|
for (std::uint64_t i = 0; i < site_count; ++i)
|
|
nursery_config.sites.push_back(in.site());
|
|
|
|
std::vector<CellularOwnedLife> lives;
|
|
lives.reserve(static_cast<std::size_t>(life_count));
|
|
for (std::uint64_t i = 0; i < life_count; ++i) {
|
|
CellularOwnedLife life{};
|
|
life.account = in.bytes<16>();
|
|
life.identity.life = in.get();
|
|
life.identity.organism = in.get();
|
|
life.identity.genome = in.get();
|
|
life.identity.event = in.get();
|
|
life.identity.born.value = in.get();
|
|
life.source = in.get();
|
|
life.growth.realized_per_thousand = static_cast<std::uint32_t>(in.get(4));
|
|
life.growth.damage_per_thousand = static_cast<std::uint32_t>(in.get(4));
|
|
life.position = {in.get(), in.get()};
|
|
life.body = in.inventory();
|
|
life.reserve = in.inventory();
|
|
if (mutation_version) {
|
|
auto& mutation = life.mutation;
|
|
mutation.fed_energy_credit_pj = in.get();
|
|
mutation.event_index = in.get();
|
|
mutation.offer_tick = in.get();
|
|
biology::MutationOffer offer{};
|
|
offer.parent = in.get();
|
|
offer.parent_digest = in.get();
|
|
offer.context.seed = in.get();
|
|
offer.context.stream = static_cast<std::uint32_t>(in.get(4));
|
|
offer.context.event_index = in.get();
|
|
const auto offered_count = static_cast<std::uint16_t>(in.get(2));
|
|
if (offered_count != 0)
|
|
offer.context.candidate_count = cellular_mutation_candidate_count;
|
|
const auto reserved16 = in.get(2);
|
|
offer.context.growth.realized_per_thousand = static_cast<std::uint32_t>(in.get(4));
|
|
offer.context.growth.damage_per_thousand = static_cast<std::uint32_t>(in.get(4));
|
|
offer.context.environment.temperature_millikelvin =
|
|
static_cast<std::uint32_t>(in.get(4));
|
|
const auto reserved32 = in.get(4);
|
|
offer.context.environment.available = in.inventory();
|
|
for (std::size_t slot = 0; slot < biology::max_candidates; ++slot) {
|
|
biology::MutationCandidate candidate{};
|
|
candidate.operator_id = static_cast<std::uint16_t>(in.get(2));
|
|
candidate.target = static_cast<biology::Capability>(in.get(1));
|
|
candidate.effect = static_cast<biology::MutationEffect>(in.get(1));
|
|
candidate.parameter = static_cast<std::uint32_t>(in.get(4));
|
|
candidate.maintenance = in.get();
|
|
candidate.total_mass = in.get();
|
|
if (slot < offered_count)
|
|
offer.candidates.push_back(candidate);
|
|
else if (candidate != biology::MutationCandidate{})
|
|
return std::unexpected{CellularLivesError::noncanonical};
|
|
}
|
|
const bool has_offer = mutation.offer_tick != 0;
|
|
if (reserved16 != 0 || reserved32 != 0 ||
|
|
(has_offer &&
|
|
(offer.parent == 0 || offer.parent_digest == 0 || offer.context.seed == 0 ||
|
|
offer.context.stream == 0 || offer.context.event_index != mutation.event_index ||
|
|
offered_count == 0 || offered_count > cellular_mutation_candidate_count ||
|
|
offer.candidates.size() != offered_count)) ||
|
|
(!has_offer && (offer.parent != 0 || offer.parent_digest != 0 ||
|
|
offer.context != biology::MutationContext{})))
|
|
return std::unexpected{CellularLivesError::noncanonical};
|
|
if (has_offer) {
|
|
mutation.offer = std::move(offer);
|
|
}
|
|
}
|
|
if (bud_version)
|
|
life.parent_life = in.get();
|
|
if (presence_version) {
|
|
const auto presence = in.get(1);
|
|
const auto padding = in.get(7);
|
|
life.frozen_since = in.get();
|
|
if (presence > static_cast<std::uint8_t>(CellularPresence::suspended) || padding != 0)
|
|
return std::unexpected{CellularLivesError::noncanonical};
|
|
life.presence = static_cast<CellularPresence>(presence);
|
|
}
|
|
lives.push_back(life);
|
|
}
|
|
|
|
std::vector<CellularOwnedCorpse> corpses;
|
|
corpses.reserve(static_cast<std::size_t>(corpse_count));
|
|
for (std::uint64_t i = 0; i < corpse_count; ++i) {
|
|
CellularOwnedCorpse corpse{};
|
|
corpse.life_id = in.get();
|
|
corpse.organism = in.get();
|
|
corpse.source = in.get();
|
|
corpse.died_tick = in.get();
|
|
corpse.position = {in.get(), in.get()};
|
|
corpse.growth.realized_per_thousand = static_cast<std::uint32_t>(in.get(4));
|
|
corpse.growth.damage_per_thousand = static_cast<std::uint32_t>(in.get(4));
|
|
corpse.extent_um = static_cast<std::uint32_t>(in.get(4));
|
|
corpse.inventory = in.inventory();
|
|
if (engulf_version) {
|
|
// Rules 3: a known cause, a predator exactly when engulfed, and no inventory
|
|
// (it became detritus or the predator's).
|
|
const auto cause = in.get(1);
|
|
const auto padding = in.get(7);
|
|
corpse.predator_life = in.get();
|
|
corpse.cause = static_cast<biology::CellularDeathCause>(cause);
|
|
const bool engulfed = corpse.cause == biology::CellularDeathCause::engulfed;
|
|
if (padding != 0 ||
|
|
(corpse.cause != biology::CellularDeathCause::starved && !engulfed) ||
|
|
engulfed != (corpse.predator_life != 0) || corpse.predator_life == corpse.life_id ||
|
|
corpse.inventory != accounting::Inventory{})
|
|
return std::unexpected{CellularLivesError::noncanonical};
|
|
}
|
|
if (bud_version)
|
|
corpse.parent_life = in.get();
|
|
corpses.push_back(corpse);
|
|
}
|
|
const auto habitat_payload = in.raw(static_cast<std::size_t>(habitat_size));
|
|
const auto archive_payload = in.raw(static_cast<std::size_t>(archive_size));
|
|
|
|
auto habitat =
|
|
biology::CellularHabitat::restore(habitat_payload, saved_world, saved_region, saved_frame);
|
|
if (!habitat) {
|
|
if (habitat.error() == biology::CellularHabitatError::version)
|
|
return std::unexpected{CellularLivesError::version};
|
|
if (habitat.error() == biology::CellularHabitatError::checksum)
|
|
return std::unexpected{CellularLivesError::checksum};
|
|
return std::unexpected{CellularLivesError::habitat};
|
|
}
|
|
auto archive = biology::LineageArchive::decode(archive_payload);
|
|
if (!archive) {
|
|
if (archive.error() == biology::ArchiveCodecError::version)
|
|
return std::unexpected{CellularLivesError::version};
|
|
if (archive.error() == biology::ArchiveCodecError::checksum)
|
|
return std::unexpected{CellularLivesError::checksum};
|
|
if (archive.error() == biology::ArchiveCodecError::noncanonical)
|
|
return std::unexpected{CellularLivesError::noncanonical};
|
|
return std::unexpected{CellularLivesError::archive};
|
|
}
|
|
if (archive->format_version() != (revision_version ? biology::lineage_archive_revision_format
|
|
: biology::lineage_archive_format))
|
|
return std::unexpected{CellularLivesError::version};
|
|
if (mutation_version) {
|
|
for (const auto& life : lives) {
|
|
if (!life.mutation.offer)
|
|
continue;
|
|
const auto genome = archive->find(life.identity.genome);
|
|
if (!genome)
|
|
return std::unexpected{CellularLivesError::archive};
|
|
const auto& offer = *life.mutation.offer;
|
|
if (life.mutation.event_index == 0 || life.mutation.offer_tick == 0 ||
|
|
life.mutation.offer_tick > saved_tick || offer.parent != life.identity.genome ||
|
|
offer.context.seed != mutation_seed(saved_world, saved_region, life.identity.life,
|
|
life.mutation.event_index) ||
|
|
offer.context.stream != cellular_mutation_stream ||
|
|
offer.context.event_index != life.mutation.event_index ||
|
|
offer.context.environment.temperature_millikelvin !=
|
|
config.ambient_temperature_millikelvin)
|
|
return std::unexpected{CellularLivesError::noncanonical};
|
|
const auto generated = biology::mutation_candidates(*genome, offer.context);
|
|
if (!generated || *generated != offer)
|
|
return std::unexpected{CellularLivesError::noncanonical};
|
|
}
|
|
}
|
|
const auto current =
|
|
validate_state(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);
|
|
if (!current)
|
|
return std::unexpected{current.error()};
|
|
|
|
auto restored = std::unique_ptr<CellularLives>{new CellularLives{std::make_unique<State>(
|
|
saved_world, saved_region, saved_frame, config, std::move(nursery_config),
|
|
std::move(*habitat), std::move(lives), std::move(corpses), *archive, nursery, heat,
|
|
opening_total, *current, format_version, rules_version)}};
|
|
restored->state_->next_bud_sequence = next_bud_sequence;
|
|
if (!std::ranges::equal(bytes, restored->snapshot()))
|
|
return std::unexpected{CellularLivesError::noncanonical};
|
|
return restored;
|
|
}
|
|
|
|
std::expected<biology::CellularRegionStepCandidate, CellularLivesError>
|
|
CellularLives::advance_tick(std::span<const CellularLifeIntent> intents) {
|
|
auto execution =
|
|
advance_tick_with_mutations(intents, std::span<const CellularMutationSelection>{});
|
|
if (!execution)
|
|
return std::unexpected{execution.error()};
|
|
return std::move(execution->step);
|
|
}
|
|
|
|
std::expected<CellularTickExecution, CellularLivesError>
|
|
CellularLives::advance_tick_with_mutations(std::span<const CellularLifeIntent> intents,
|
|
std::span<const CellularMutationSelection> selections) {
|
|
if (state_->config.tick == std::numeric_limits<std::uint64_t>::max())
|
|
return std::unexpected{CellularLivesError::invalid_tick};
|
|
if (intents.size() != state_->lives.size())
|
|
return std::unexpected{CellularLivesError::invalid_intents};
|
|
std::vector<CellularLifeIntent> ordered{intents.begin(), intents.end()};
|
|
std::ranges::sort(ordered, {}, &CellularLifeIntent::life_id);
|
|
for (std::size_t i = 0; i < ordered.size(); ++i)
|
|
if ((i != 0 && ordered[i - 1].life_id == ordered[i].life_id) ||
|
|
ordered[i].life_id != state_->lives[i].identity.life)
|
|
return std::unexpected{CellularLivesError::invalid_intents};
|
|
|
|
if (!selections.empty() && state_->format_version < cellular_lives_revision_format)
|
|
return std::unexpected{CellularLivesError::version};
|
|
// Rules 4 keep rules 3 (engulfment, detritus) and add budding (ADR-0125).
|
|
const bool engulf_rules = state_->rules_version >= cellular_lives_engulf_rules;
|
|
const bool bud_rules = state_->rules_version >= cellular_lives_bud_rules;
|
|
const bool presence_rules = state_->rules_version >= cellular_lives_presence_rules;
|
|
for (std::size_t i = 0; i < ordered.size(); ++i) {
|
|
const auto& intent = ordered[i].intent;
|
|
// Below rules 4 a bud is ignored, as engulfment is below rules 3 (ADR-0124/0125).
|
|
if (intent.bud && (intent.intake_target || intent.engulf))
|
|
return std::unexpected{CellularLivesError::invalid_intents};
|
|
// ADR-0128: only an owned life of a rules-5 region freezes, and a frozen intent
|
|
// carries nothing else.
|
|
if (intent.frozen && (!presence_rules || state_->lives[i].account == LifeAccount{} ||
|
|
intent.movement != biology::CellularIntent{} ||
|
|
intent.intake_target || intent.engulf || intent.bud))
|
|
return std::unexpected{CellularLivesError::invalid_intents};
|
|
}
|
|
for (std::size_t i = 0; i < selections.size(); ++i) {
|
|
const auto& selection = selections[i];
|
|
if (selection.life_id == 0 || selection.event_index == 0 || selection.offer_tick == 0 ||
|
|
selection.successor_id == 0 || // Operator 0 declines (ADR-0120 amendment).
|
|
(i != 0 && selections[i - 1].life_id >= selection.life_id))
|
|
return std::unexpected{CellularLivesError::invalid_intents};
|
|
const auto life = std::ranges::lower_bound(
|
|
state_->lives, selection.life_id, {},
|
|
[](const CellularOwnedLife& value) { return value.identity.life; });
|
|
if (life == state_->lives.end() || life->identity.life != selection.life_id ||
|
|
life->mutation.event_index != selection.event_index ||
|
|
life->mutation.offer_tick != selection.offer_tick)
|
|
return std::unexpected{CellularLivesError::mutation};
|
|
if (!life->mutation.offer.has_value())
|
|
return std::unexpected{CellularLivesError::mutation};
|
|
const auto offer = life->mutation.offer.value_or(biology::MutationOffer{});
|
|
if (offer.parent != life->identity.genome ||
|
|
offer.context.event_index != selection.event_index ||
|
|
(selection.operator_id != 0 && !std::ranges::any_of(offer.candidates,
|
|
[&](const auto& candidate) {
|
|
return candidate.operator_id ==
|
|
selection.operator_id;
|
|
})) ||
|
|
state_->archive.find(selection.successor_id))
|
|
return std::unexpected{CellularLivesError::mutation};
|
|
for (std::size_t j = 0; j < i; ++j)
|
|
if (selections[j].successor_id == selection.successor_id)
|
|
return std::unexpected{CellularLivesError::identity};
|
|
}
|
|
|
|
std::vector<biology::CellularLifeStepInput> inputs;
|
|
inputs.reserve(state_->lives.size());
|
|
for (std::size_t i = 0; i < state_->lives.size(); ++i) {
|
|
const auto& life = state_->lives[i];
|
|
if (life.presence == CellularPresence::suspended)
|
|
continue; // Out of the world: no step, no contact (ADR-0128).
|
|
const auto budget =
|
|
budget_for(state_->archive, life, state_->config.ambient_temperature_millikelvin);
|
|
if (!budget)
|
|
return std::unexpected{budget.error()};
|
|
const auto genome = state_->archive.find(life.identity.genome);
|
|
if (!genome)
|
|
return std::unexpected{CellularLivesError::archive};
|
|
const auto membrane = genome->parameter(biology::Capability::membrane);
|
|
if (!membrane)
|
|
return std::unexpected{CellularLivesError::biology};
|
|
inputs.push_back({life.identity.life,
|
|
life.position,
|
|
budget->phenotype.extent,
|
|
ordered[i].intent,
|
|
life.body,
|
|
life.reserve,
|
|
{},
|
|
*budget,
|
|
*membrane,
|
|
life.source});
|
|
}
|
|
auto proposal = biology::propose_cellular_region_step(state_->config.tick, state_->config.area,
|
|
inputs, *state_->habitat, {engulf_rules});
|
|
if (!proposal)
|
|
return std::unexpected{CellularLivesError::region_step};
|
|
|
|
auto next_lives = state_->lives;
|
|
auto next_corpses = state_->corpses;
|
|
auto next_archive = state_->archive;
|
|
auto next_heat = state_->heat;
|
|
auto habitat_config = state_->habitat->config();
|
|
for (const auto& result : proposal->lives) {
|
|
const auto found = std::ranges::lower_bound(
|
|
next_lives, result.life_id, {}, [](const auto& life) { return life.identity.life; });
|
|
if (found == next_lives.end() || found->identity.life != result.life_id)
|
|
return std::unexpected{CellularLivesError::invalid_life};
|
|
found->position = result.candidate.position;
|
|
found->reserve = result.candidate.reserve_after;
|
|
if (!add_inventory(next_heat, result.candidate.heat_after))
|
|
return std::unexpected{CellularLivesError::overflow};
|
|
// Only owned lives earn mutation offers; wildlife never mutates in M11 (ADR-0098).
|
|
if (state_->format_version >= cellular_lives_format && result.candidate.intake &&
|
|
found->account != LifeAccount{}) {
|
|
const auto acquired = result.candidate.intake->transfer.acquired.energy.value;
|
|
if (acquired >
|
|
std::numeric_limits<std::uint64_t>::max() - found->mutation.fed_energy_credit_pj)
|
|
return std::unexpected{CellularLivesError::overflow};
|
|
found->mutation.fed_energy_credit_pj += acquired;
|
|
if (!found->mutation.offer) {
|
|
const auto budget = budget_for(next_archive, *found,
|
|
state_->config.ambient_temperature_millikelvin);
|
|
if (!budget ||
|
|
budget->maintenance.value > std::numeric_limits<std::uint64_t>::max() /
|
|
cellular_mutation_surplus_seconds)
|
|
return std::unexpected{CellularLivesError::mutation};
|
|
const auto threshold =
|
|
budget->maintenance.value * cellular_mutation_surplus_seconds;
|
|
if (threshold == 0)
|
|
return std::unexpected{CellularLivesError::mutation};
|
|
if (found->mutation.fed_energy_credit_pj >= threshold) {
|
|
if (found->mutation.event_index == std::numeric_limits<std::uint64_t>::max())
|
|
return std::unexpected{CellularLivesError::overflow};
|
|
const auto genome = next_archive.find(found->identity.genome);
|
|
if (!genome)
|
|
return std::unexpected{CellularLivesError::archive};
|
|
const auto next_event = found->mutation.event_index + 1;
|
|
biology::MutationContext context{
|
|
mutation_seed(state_->world, state_->region, result.life_id, next_event),
|
|
cellular_mutation_stream,
|
|
next_event,
|
|
cellular_mutation_candidate_count,
|
|
found->growth,
|
|
{state_->config.ambient_temperature_millikelvin,
|
|
result.candidate.intake->transfer.patch_after}};
|
|
const auto offer = biology::mutation_candidates(*genome, context);
|
|
if (offer) {
|
|
found->mutation.fed_energy_credit_pj -= threshold;
|
|
found->mutation.event_index = next_event;
|
|
found->mutation.offer_tick = proposal->end_tick;
|
|
found->mutation.offer = *offer;
|
|
} else if (offer.error() != biology::MutationError::no_candidates) {
|
|
return std::unexpected{CellularLivesError::mutation};
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
for (const auto& dead : proposal->starved) {
|
|
const auto found = std::ranges::lower_bound(
|
|
next_lives, dead.life_id, {}, [](const auto& life) { return life.identity.life; });
|
|
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};
|
|
const auto corpse_budget =
|
|
budget_for(next_archive, *found, state_->config.ambient_temperature_millikelvin);
|
|
if (!corpse_budget)
|
|
return std::unexpected{corpse_budget.error()};
|
|
next_corpses.push_back({found->identity.life, found->identity.organism, found->source,
|
|
proposal->end_tick, dead.position, found->growth,
|
|
corpse_budget->phenotype.extent, dead.inventory,
|
|
engulf_rules ? dead.cause : biology::CellularDeathCause::unrecorded,
|
|
engulf_rules ? dead.predator_id : 0, found->parent_life});
|
|
next_lives.erase(found);
|
|
}
|
|
std::vector<CellularMutationExecution> mutation_results;
|
|
mutation_results.reserve(selections.size());
|
|
for (const auto& selection : selections) {
|
|
const auto found = std::ranges::lower_bound(
|
|
next_lives, selection.life_id, {},
|
|
[](const CellularOwnedLife& value) { return value.identity.life; });
|
|
if (found == next_lives.end() || found->identity.life != selection.life_id) {
|
|
mutation_results.push_back(
|
|
{selection.life_id, selection.successor_id, CellularMutationResult::life_died});
|
|
continue;
|
|
}
|
|
const auto parent = next_archive.find(found->identity.genome);
|
|
if (!parent || !found->mutation.offer.has_value())
|
|
return std::unexpected{CellularLivesError::mutation};
|
|
if (selection.operator_id == 0) {
|
|
// ADR-0120 amendment: a decline consumes the offer and changes nothing else; its
|
|
// reserved successor identity stays unused. Banked credit may earn the next offer.
|
|
found->mutation.offer.reset();
|
|
found->mutation.offer_tick = 0;
|
|
mutation_results.push_back(
|
|
{selection.life_id, selection.successor_id, CellularMutationResult::declined});
|
|
continue;
|
|
}
|
|
const auto offer = found->mutation.offer.value_or(biology::MutationOffer{});
|
|
auto transition =
|
|
biology::fund_mutation(*parent, offer.context, offer, selection.operator_id,
|
|
selection.successor_id, selection.successor_id, found->reserve);
|
|
if (!transition) {
|
|
if (transition.error() == biology::MutationError::insufficient_funding) {
|
|
mutation_results.push_back({selection.life_id, selection.successor_id,
|
|
CellularMutationResult::insufficient_funding});
|
|
continue;
|
|
}
|
|
return std::unexpected{CellularLivesError::mutation};
|
|
}
|
|
if (!next_archive.record_mutation(found->identity.organism, transition->successor,
|
|
{proposal->end_tick}))
|
|
return std::unexpected{CellularLivesError::archive};
|
|
if (transition->intake.energy.value >
|
|
std::numeric_limits<std::uint64_t>::max() - next_heat.energy.value)
|
|
return std::unexpected{CellularLivesError::overflow};
|
|
next_heat.energy.value += transition->intake.energy.value;
|
|
found->identity.genome = selection.successor_id;
|
|
found->body = transition->body;
|
|
found->reserve = transition->reserve;
|
|
found->mutation.offer.reset();
|
|
found->mutation.offer_tick = 0;
|
|
mutation_results.push_back(
|
|
{selection.life_id, selection.successor_id, CellularMutationResult::applied});
|
|
}
|
|
// Rules 4 budding (ADR-0125), after mutations and in parent life order: a parent that
|
|
// died this tick cannot bud, and a bud born this tick asked for nothing.
|
|
std::vector<CellularBudExecution> bud_results;
|
|
auto next_bud_sequence = state_->next_bud_sequence;
|
|
for (const auto& request : ordered) {
|
|
if (!bud_rules || !request.intent.bud)
|
|
continue;
|
|
const auto parent = std::ranges::lower_bound(
|
|
next_lives, request.life_id, {},
|
|
[](const CellularOwnedLife& value) { return value.identity.life; });
|
|
if (parent == next_lives.end() || parent->identity.life != request.life_id) {
|
|
bud_results.push_back({request.life_id, 0, CellularBudResult::life_died});
|
|
continue;
|
|
}
|
|
if (parent->presence == CellularPresence::suspended) {
|
|
bud_results.push_back({request.life_id, 0, CellularBudResult::not_able});
|
|
continue; // Out of the world (ADR-0128).
|
|
}
|
|
const auto temperature = state_->config.ambient_temperature_millikelvin;
|
|
const auto genome = next_archive.find(parent->identity.genome);
|
|
const auto parent_budget = budget_for(next_archive, *parent, temperature);
|
|
if (!genome || !parent_budget)
|
|
return std::unexpected{CellularLivesError::archive};
|
|
const auto transition =
|
|
biology::fund_bud(*genome, parent->growth, parent->reserve, temperature);
|
|
if (!transition) {
|
|
if (transition.error() == biology::BuddingError::development)
|
|
return std::unexpected{CellularLivesError::biology};
|
|
bud_results.push_back({request.life_id, 0,
|
|
transition.error() == biology::BuddingError::insufficient_funding
|
|
? CellularBudResult::insufficient_funding
|
|
: CellularBudResult::not_able});
|
|
continue;
|
|
}
|
|
const auto bud_budget =
|
|
biology::metabolic_budget(*genome, transition->growth, {temperature, {}});
|
|
if (!bud_budget || bud_budget->body.matter != transition->body.matter)
|
|
return std::unexpected{CellularLivesError::biology};
|
|
const auto identity = cellular_bud_identity(state_->region, next_bud_sequence);
|
|
const auto position =
|
|
bud_position(*parent, parent_budget->phenotype.extent, bud_budget->phenotype.extent,
|
|
next_lives, next_archive, state_->config);
|
|
if (!position)
|
|
return std::unexpected{position.error()};
|
|
if (identity == 0 || !*position || next_lives.size() >= biology::max_cellular_tick_lives ||
|
|
next_archive.organism(identity)) {
|
|
bud_results.push_back({request.life_id, 0, CellularBudResult::no_placement});
|
|
continue;
|
|
}
|
|
if (!add_inventory(next_heat, accounting::Inventory{transition->heat, {}}) ||
|
|
!next_archive.record_birth(identity, parent->identity.genome, {proposal->end_tick}))
|
|
return std::unexpected{CellularLivesError::archive};
|
|
parent->reserve = transition->parent_reserve;
|
|
CellularOwnedLife bud{};
|
|
bud.identity = {
|
|
identity, identity, parent->identity.genome, identity, {proposal->end_tick}};
|
|
bud.source = parent->source;
|
|
bud.growth = transition->growth;
|
|
bud.position = **position;
|
|
bud.body = transition->body;
|
|
bud.reserve = transition->reserve;
|
|
bud.parent_life = parent->identity.life;
|
|
// Bud identities increase within the region and exceed every allocated identity,
|
|
// so the new life sorts after all existing ones and `parent` stays valid.
|
|
next_lives.push_back(bud);
|
|
++next_bud_sequence;
|
|
bud_results.push_back({request.life_id, identity, CellularBudResult::budded});
|
|
}
|
|
std::ranges::sort(next_lives, {},
|
|
[](const CellularOwnedLife& life) { return life.identity.life; });
|
|
// Rules 5 presence (ADR-0128), after deaths, mutations and buds: a death in this tick
|
|
// is final before any presence change.
|
|
std::vector<std::uint64_t> resume_blocked;
|
|
if (presence_rules) {
|
|
for (auto& life : next_lives) {
|
|
const auto request = std::ranges::lower_bound(ordered, life.identity.life, {},
|
|
&CellularLifeIntent::life_id);
|
|
if (request == ordered.end() || request->life_id != life.identity.life)
|
|
continue; // Born this tick: active.
|
|
const bool frozen = request->intent.frozen;
|
|
if (life.presence == CellularPresence::active && frozen) {
|
|
life.presence = CellularPresence::lingering;
|
|
life.frozen_since = proposal->end_tick;
|
|
} else if (life.presence == CellularPresence::lingering && !frozen) {
|
|
life.presence = CellularPresence::active;
|
|
life.frozen_since = 0;
|
|
} else if (life.presence == CellularPresence::lingering &&
|
|
proposal->end_tick - life.frozen_since >= cellular_linger_ticks) {
|
|
life.presence = CellularPresence::suspended;
|
|
} else if (life.presence == CellularPresence::suspended && !frozen) {
|
|
const auto budget =
|
|
budget_for(next_archive, life, state_->config.ambient_temperature_millikelvin);
|
|
if (!budget)
|
|
return std::unexpected{budget.error()};
|
|
const auto spot = resume_position(life, budget->phenotype.extent, next_lives,
|
|
next_archive, state_->config);
|
|
if (!spot)
|
|
return std::unexpected{spot.error()};
|
|
if (*spot) {
|
|
life.position = **spot;
|
|
life.presence = CellularPresence::active;
|
|
life.frozen_since = 0;
|
|
} else {
|
|
resume_blocked.push_back(life.identity.life);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
std::ranges::sort(next_corpses, {}, &CellularOwnedCorpse::organism);
|
|
if (proposal->heat_released.value >
|
|
std::numeric_limits<std::uint64_t>::max() - next_heat.energy.value)
|
|
return std::unexpected{CellularLivesError::overflow};
|
|
next_heat.energy.value += proposal->heat_released.value;
|
|
for (const auto& update : proposal->patches) {
|
|
const auto found =
|
|
std::ranges::lower_bound(habitat_config.patches, update.address, {},
|
|
[](const auto& patch) { return patch.address; });
|
|
if (found == habitat_config.patches.end() || found->address != update.address)
|
|
return std::unexpected{CellularLivesError::habitat};
|
|
found->stock = update.stock;
|
|
}
|
|
// Rules 3 detritus at empty cells becomes new patches; create() revalidates the map.
|
|
for (const auto& made : proposal->new_patches) {
|
|
const auto at = std::ranges::lower_bound(habitat_config.patches, made.address, {},
|
|
[](const auto& patch) { return patch.address; });
|
|
if (at != habitat_config.patches.end() && at->address == made.address)
|
|
return std::unexpected{CellularLivesError::habitat};
|
|
habitat_config.patches.insert(at, made);
|
|
}
|
|
auto next_habitat = biology::CellularHabitat::create(std::move(habitat_config));
|
|
if (!next_habitat)
|
|
return std::unexpected{CellularLivesError::habitat};
|
|
const auto total =
|
|
validate_state(state_->world, state_->region, state_->frame,
|
|
CellularLivesConfig{state_->config.area, proposal->end_tick,
|
|
state_->config.ambient_temperature_millikelvin},
|
|
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);
|
|
if (!total)
|
|
return std::unexpected{total.error()};
|
|
|
|
auto next = std::make_unique<State>(
|
|
state_->world, state_->region, state_->frame,
|
|
CellularLivesConfig{state_->config.area, proposal->end_tick,
|
|
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);
|
|
next->next_bud_sequence = next_bud_sequence;
|
|
std::vector<CellularLifeTickFeedback> feedback;
|
|
feedback.reserve(proposal->lives.size());
|
|
for (const auto& result : proposal->lives) {
|
|
const auto input =
|
|
std::ranges::lower_bound(ordered, result.life_id, {},
|
|
[](const CellularLifeIntent& value) { return value.life_id; });
|
|
feedback.push_back({result.life_id, proposal->end_tick, result.candidate.reserve_after,
|
|
result.candidate.maintenance_cost, result.candidate.movement_cost,
|
|
result.candidate.movement_status, result.candidate.intake_status,
|
|
result.engulf, result.prey_id, std::nullopt, 0,
|
|
CellularPresence::active, false});
|
|
if (const auto bud =
|
|
std::ranges::find(bud_results, result.life_id, &CellularBudExecution::parent_life);
|
|
bud != bud_results.end()) {
|
|
feedback.back().bud = bud->result;
|
|
feedback.back().bud_life = bud->bud_life;
|
|
}
|
|
if (input == ordered.end() || input->life_id != result.life_id)
|
|
return std::unexpected{CellularLivesError::invalid_intents};
|
|
}
|
|
// ADR-0128: each surviving life reports its presence after the tick; a suspended life,
|
|
// which took no step, reports its unchanged reserve and any blocked resume.
|
|
for (const auto& life : next->lives) {
|
|
auto entry =
|
|
std::ranges::find(feedback, life.identity.life, &CellularLifeTickFeedback::life_id);
|
|
if (entry == feedback.end()) {
|
|
feedback.push_back({life.identity.life,
|
|
proposal->end_tick,
|
|
life.reserve,
|
|
{},
|
|
{},
|
|
biology::CellularMovementStatus::not_requested,
|
|
biology::CellularIntakeStatus::not_requested,
|
|
biology::CellularEngulfStatus::not_requested,
|
|
0,
|
|
std::nullopt,
|
|
0,
|
|
life.presence,
|
|
false});
|
|
entry = std::prev(feedback.end());
|
|
}
|
|
entry->presence = life.presence;
|
|
entry->resume_blocked =
|
|
std::ranges::find(resume_blocked, life.identity.life) != resume_blocked.end();
|
|
}
|
|
std::ranges::sort(feedback, {}, &CellularLifeTickFeedback::life_id);
|
|
state_.swap(next);
|
|
last_tick_feedback_ = std::move(feedback);
|
|
return CellularTickExecution{std::move(*proposal), std::move(mutation_results),
|
|
std::move(bud_results)};
|
|
}
|
|
} // namespace evo::server
|