Files
aevolution/tests/client_ui_model.cpp
T
dingoandClaude Opus 5.5 15b4342934
Foundation / checks (checks) (push) Successful in 5s
Foundation / checks (client) (push) Successful in 4s
Foundation / checks (ecs) (push) Successful in 4s
Foundation / checks (network) (push) Successful in 4s
Foundation / checks (postgres) (push) Successful in 5s
Foundation / checks (tsan) (push) Successful in 5s
Foundation / checks (deploy) (push) Successful in 4m23s
Foundation / postgres-tools (push) Successful in 21s
Foundation / server-image (push) Successful in 4m18s
Foundation / image (push) Successful in 4m56s
feat(cellular): show what holds growth back and each nutrient's flows
Playtest: phosphorus jumped between ~100 fg and a few pg because growth spends
it as it arrives and only pauses when another nutrient runs short. The owner
now records, per owned life and tick, which channel narrowed the growth step
(or no room) and what the tick collected, built into the body and burned;
session v14 carries them (flag bits 2-4 and a 120-byte flows block).

The client shows "Growing 62% - waiting for phosphorus" or "Fully grown",
outlines the limiting nutrient's bar in amber, and gives each bar (and the
energy figure) a tooltip with the last second's flows.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-26 09:48:37 -04:00

637 lines
29 KiB
C++

// M9.8c toolkit-independent UI model: labels keep data states distinct, selection
// follows presentations, the launcher bounds credentials and errors, and the outcome
// log stays bounded.
#include "cellular_controls.hpp"
#include "cellular_play.hpp"
#include "cellular_scene.hpp"
#include "evo/client/labels.hpp"
#include "evo/client/launcher.hpp"
#include "evo/client/outcome_log.hpp"
#include "evo/client/selection.hpp"
#include "evo/client/session_host.hpp"
#include <algorithm>
#include <chrono>
#include <cmath>
#include <cstdio>
#include <filesystem>
#include <fstream>
#include <source_location>
#include <stdexcept>
#include <string>
#include <utility>
#include <vector>
namespace {
using namespace evo;
using namespace evo::client;
void check(bool ok, std::source_location at = std::source_location::current()) {
if (!ok)
throw std::runtime_error("client UI model line " + std::to_string(at.line()));
}
#define CHECK(...) check(static_cast<bool>(__VA_ARGS__))
template <class T> const T& required(const std::optional<T>& value) {
if (!value)
throw std::runtime_error("missing client model test value");
return *value;
}
constexpr world::WorldIdentity identity{3, 9};
EnvironmentCell cell(std::int64_t x) {
EnvironmentCell c;
c.voxel = {x, 0, 0};
c.chunk_revision = 4;
c.habitat = {{0}, {0}, {0}, {1000}, {1000}, {10}};
c.volume = {10'000'000};
c.substrate = {1};
c.terrain_material = {1};
c.terrain_fill = world::fill_scale;
c.presence[0] = FieldPresence::present; // Water: value.
c.quantity[0] = 80'000'000;
c.presence[2] = FieldPresence::present; // Phosphorus: present zero.
c.presence[1] = FieldPresence::missing; // Nitrogen: missing.
c.moisture_status = world::MoistureStatus::available;
c.moisture = {1, 4};
return c;
}
EnvironmentPresentation environment(std::vector<EnvironmentCell> cells, std::uint64_t tick = 1) {
auto p = EnvironmentPresentation::create({identity, tick, 1}, 0b111, 0, cells);
CHECK(p);
return std::move(*p);
}
OrganismCell organism(std::uint64_t id, std::uint64_t x_um) {
OrganismCell o;
o.id = id;
o.voxel = {0, 0, 0};
o.x = {x_um};
o.y = {500000};
o.phenotype.extent = 20;
o.phenotype.structural_mass = 8'000'000;
o.phenotype.membrane_mass = 1'000'000;
o.phenotype.total_mass = 9'000'000;
o.phenotype.conversion_per_thousand = 400;
o.growth.realized_per_thousand = 1000;
return o;
}
OrganismPresentation organisms(std::vector<OrganismCell> cells, std::uint64_t tick = 1) {
auto p = OrganismPresentation::create({identity, tick, 0}, 0, cells);
CHECK(p);
return std::move(*p);
}
void cellular_assistance() {
using namespace client_app;
auto own = organism(42, 980);
own.y = {2000};
own.phenotype.movement_speed = 10000;
auto population = organisms({own});
network::CellularPerception view{2, 42, {{1000, 2000, 100, {}}}, {}};
CellularControls controls;
const Intention diagonal{1, 2, 707, -707};
auto steering = steer_cellular(controls, diagonal, &view, &population, {});
CHECK(steering.patch == std::pair<std::uint32_t, std::uint32_t>{1000, 2000});
CHECK(steering.intention.move_x == 35 && steering.intention.move_y == -35);
own.x = {979};
population = organisms({own});
CHECK(!steer_cellular(controls, diagonal, &view, &population, {}).patch);
controls.slow_near_food = false;
controls.precision = true;
controls.speed_percent = 50;
steering = steer_cellular(controls, diagonal, &view, &population, {});
CHECK(steering.intention.move_x == 70 && steering.intention.move_y == -70);
controls.auto_feed = false;
CHECK(steer_cellular(controls, {}, &view, &population, {{9000, 9000}}).patch ==
std::pair<std::uint32_t, std::uint32_t>{9000, 9000});
controls.auto_feed = true;
view.patches[0].energy_pj = 0;
own.x = {1000};
population = organisms({own});
CHECK(!steer_cellular(controls, {}, &view, &population, {}).patch);
view.patches[0].matter_fg[2] = 1;
CHECK(steer_cellular(controls, {}, &view, &population, {}).patch);
view.patches.push_back({0, 2000, 100, {}});
CHECK(steer_cellular(controls, {}, &view, &population, {}).patch ==
std::pair<std::uint32_t, std::uint32_t>{0, 2000});
view.patches.back().energy_pj = 0;
CHECK(steer_cellular(controls, {}, &view, &population, {}).patch ==
std::pair<std::uint32_t, std::uint32_t>{1000, 2000});
view.life_identity = 0;
CHECK(!steer_cellular(controls, {}, &view, &population, {}).patch);
network::CellularOfferedCandidate candidate;
candidate.cost_energy_pj = 10;
candidate.cost_matter_fg = {1, 2, 3, 4};
network::CellularLifeDiagnostics reserve;
reserve.reserve_energy_pj = 10;
reserve.reserve_matter_fg = {1, 2, 3, 4};
CHECK(can_fund(candidate, reserve));
reserve.reserve_matter_fg[3] = 3;
CHECK(!can_fund(candidate, reserve));
reserve.reserve_matter_fg[3] = 4;
reserve.reserve_energy_pj = 9;
CHECK(!can_fund(candidate, reserve));
std::vector<render::Rectangle> scene;
patch_box(scene, {0, 80}, {80, 0}, true, true, true, 80, 80);
CHECK(scene.size() == patch_rectangles);
for (const auto& r : scene)
CHECK(r.x >= 0 && r.y >= 0 && r.x + r.width <= 80 && r.y + r.height <= 80);
}
void labels() {
const auto c = cell(0);
const auto water = describe_field(c, world::Field::water);
const auto nitrogen = describe_field(c, world::Field::nitrogen);
const auto phosphorus = describe_field(c, world::Field::phosphorus);
const auto carbon = describe_field(c, world::Field::organic_carbon);
CHECK(water.kind == ValueKind::value &&
water.text.starts_with("80000000 fg (8 fg/um3, log2 3.0)"));
CHECK(nitrogen.kind == ValueKind::missing && nitrogen.text.starts_with("MISSING"));
CHECK(phosphorus.kind == ValueKind::zero && phosphorus.text == "0 fg (present zero)");
CHECK(carbon.kind == ValueKind::not_requested);
// Every state reads differently: missing is never shown as 0, zero never as missing.
const std::vector<std::string> texts{water.text, nitrogen.text, phosphorus.text, carbon.text};
for (std::size_t i = 0; i < texts.size(); ++i)
for (std::size_t j = i + 1; j < texts.size(); ++j)
CHECK(texts[i] != texts[j]);
CHECK(nitrogen.text.find('0') == std::string::npos);
CHECK(describe_moisture(c).text == "25.00 % saturated");
auto dry = c;
dry.moisture_status = world::MoistureStatus::zero_capacity;
CHECK(describe_moisture(dry).kind == ValueKind::undefined);
dry.moisture_status = world::MoistureStatus::missing_water;
CHECK(describe_moisture(dry).kind == ValueKind::missing);
dry.moisture_status = world::MoistureStatus::available;
dry.moisture = {0, 1};
CHECK(describe_moisture(dry).kind == ValueKind::zero);
CHECK(field_name(world::Field::heat) == "Heat" && field_unit(world::Field::heat) == "pJ" &&
field_unit(world::Field::organic_other) == "fg");
CHECK(freshness_name(Freshness::stale).starts_with("STALE") &&
freshness_name(Freshness::none) != freshness_name(Freshness::current));
CHECK(density_scale(world::Field::water).find("-30") != std::string::npos);
const auto rows = organism_rows(organism(77, 500000));
CHECK(rows.size() == 15 && rows[0].value == "alive");
const auto extent =
std::ranges::find_if(rows, [](const Row& r) { return r.label == "Extent (side)"; });
CHECK(extent != rows.end() && extent->value == "20" && extent->unit == "um");
const auto speed =
std::ranges::find_if(rows, [](const Row& r) { return r.label == "Movement speed"; });
CHECK(speed != rows.end() && speed->value == "none");
for (const auto& r : rows)
CHECK(r.value.find("77") == std::string::npos); // The opaque id is never displayed.
const auto cell_info = cell_rows(c);
CHECK(cell_info[1].value == "rock" && cell_info[2].value == "100.0");
}
void selection() {
const auto env = environment({cell(0), cell(1)});
const auto orgs = organisms({organism(5, 500000), organism(6, 500010)});
auto camera = Camera::create({800, 600, 800, 600}, {500, 500}, 1000);
CHECK(camera);
Selection s;
s.pick({400, 300}, &env, &orgs, *camera); // Both organisms overlap: topmost (6) wins.
CHECK(s.kind() == Selection::Kind::organism && s.organism(&orgs) && s.organism(&orgs)->id == 6);
// The organism disappears from the next presentation: selection clears.
const auto later = organisms({organism(5, 500000)}, 2);
CHECK(s.refresh(&env, &later) == Selection::Change::organism_gone);
CHECK(s.kind() == Selection::Kind::none);
// No organism under the point: the habitat cell beneath it is selected.
s.pick({700, 300}, &env, &later, *camera);
CHECK(s.kind() == Selection::Kind::cell && s.cell(&env) && s.cell(&env)->voxel.x == 0);
// Without a presentation the selection is kept (unknown is not gone).
CHECK(s.refresh(nullptr, nullptr) == Selection::Change::none &&
s.kind() == Selection::Kind::cell);
const auto shrunk = environment({cell(1)}, 3);
CHECK(s.refresh(&shrunk, &later) == Selection::Change::cell_gone);
// Outside any data: nothing.
auto far = Camera::create({800, 600, 800, 600}, {-50000, 500}, 1000);
CHECK(far);
s.pick({400, 300}, &env, &orgs, *far);
CHECK(s.kind() == Selection::Kind::none);
}
void launcher() {
CHECK(parse_endpoint("127.0.0.1:17400") && parse_endpoint("127.0.0.1:17400")->port == 17400);
CHECK(parse_endpoint("dev-region.evolution.test:443"));
CHECK(parse_endpoint("[::1]:9") && parse_endpoint("[::1]:9")->host == "::1");
for (const auto* bad :
{"", "host", ":1", "host:0", "host:65536", "host:x", "bad host:1", "a;b:1", "[zz]:1"})
CHECK(!parse_endpoint(bad));
CHECK(!parse_endpoint(std::string(2000, 'a') + ":1"));
const auto dir = std::filesystem::temp_directory_path() /
("evo-launcher-" +
std::to_string(std::chrono::steady_clock::now().time_since_epoch().count()));
std::filesystem::create_directories(dir);
const auto write = [&](const char* name, const std::string& bytes) {
std::ofstream out{dir / name, std::ios::binary};
out << bytes;
return (dir / name).string();
};
ConnectForm form;
form.authority_path =
write("ca.pem", "-----BEGIN CERTIFICATE-----\nMIIB\n-----END CERTIFICATE-----\n");
form.grants_path = write("grants.bin", std::string(grant_record_bytes * 3, '\x01'));
const auto loaded = load_connect(form);
// The default endpoint is the dev route (ADR-0087); records are M10 grants (160 bytes).
CHECK(loaded && loaded->grants.size() == 3 && loaded->endpoint.port == 7400 &&
loaded->endpoint.host == "void.aeternalisgames.com" && grant_record_bytes == 160 &&
loaded->server_name == "void.aeternalisgames.com" && // The dev certificate's name.
loaded->authority_path == form.authority_path);
const auto refused_with = [&](const ConnectForm& f, LaunchError e) {
const auto r = load_connect(f);
return !r && r.error() == e;
};
auto f = form;
f.endpoint = "nope";
CHECK(refused_with(f, LaunchError::endpoint));
f = form;
f.server_name = "bad name";
CHECK(refused_with(f, LaunchError::server_name));
f = form;
f.authority_path.clear();
CHECK(refused_with(f, LaunchError::authority_path));
f = form;
f.authority_path = (dir / "missing.pem").string();
CHECK(refused_with(f, LaunchError::authority_unreadable));
f = form;
f.authority_path = write("not-ca.pem", "hello");
CHECK(refused_with(f, LaunchError::authority_invalid));
f = form;
f.authority_path =
write("huge.pem", "-----BEGIN CERTIFICATE-----" + std::string(max_authority_bytes, 'A'));
CHECK(refused_with(f, LaunchError::authority_invalid));
f = form;
f.grants_path = write("partial.bin", std::string(grant_record_bytes + 1, '\x01'));
CHECK(refused_with(f, LaunchError::grants_invalid));
f = form;
f.grants_path =
write("many.bin", std::string(grant_record_bytes * (max_grant_records + 1), '\x01'));
CHECK(refused_with(f, LaunchError::grants_invalid));
f = form;
f.grants_path = (dir / "missing.bin").string();
CHECK(refused_with(f, LaunchError::grants_unreadable));
// Messages never echo file content.
for (auto e = 0; e <= static_cast<int>(LaunchError::no_session); ++e)
CHECK(launch_error_text(static_cast<LaunchError>(e)).find('\x01') ==
std::string_view::npos);
std::error_code ignored;
std::filesystem::remove_all(dir, ignored);
Launcher l;
CHECK(l.phase() == LaunchPhase::choosing && l.begin_connect());
CHECK(!l.begin_connect()); // Already connecting.
l.observe(ConnectSignal::not_ready);
l.observe(ConnectSignal::lost);
l.observe(ConnectSignal::lost);
CHECK(l.phase() == LaunchPhase::connecting);
l.observe(ConnectSignal::lost); // Third loss before any welcome: bounded failure.
CHECK(l.phase() == LaunchPhase::failed && l.error() == LaunchError::server_unreachable);
CHECK(l.begin_connect() && l.phase() == LaunchPhase::connecting); // Retry.
l.observe(ConnectSignal::refused);
CHECK(l.phase() == LaunchPhase::failed && l.error() == LaunchError::grant_refused);
l.cancel();
CHECK(l.phase() == LaunchPhase::choosing && l.begin_connect());
l.observe(ConnectSignal::welcome);
CHECK(l.phase() == LaunchPhase::connected && l.ever_connected());
for (int i = 0; i < 5; ++i)
l.observe(ConnectSignal::lost); // After a welcome: reconnecting, never failed.
CHECK(l.phase() == LaunchPhase::connecting);
l.observe(ConnectSignal::welcome);
l.observe(ConnectSignal::exhausted);
CHECK(l.phase() == LaunchPhase::failed && l.error() == LaunchError::grants_exhausted);
l.cancel();
l.start_fixture();
CHECK(l.phase() == LaunchPhase::fixture && !l.begin_connect());
l.observe(ConnectSignal::welcome); // Ignored outside a connect flow.
CHECK(l.phase() == LaunchPhase::fixture);
}
void outcome_log() {
OutcomeLog log;
log.record({1, OutcomeState::sent});
log.record({1, OutcomeState::admitted});
log.record({1, OutcomeState::durable, 0, 40, 3});
CHECK(log.entries().size() == 1 && log.entries()[0].state == OutcomeState::durable &&
log.entries()[0].commit_sequence == 3);
for (std::uint64_t s = 2; s < 2 + 200; ++s)
log.record({s, OutcomeState::unknown});
CHECK(log.entries().size() == OutcomeLog::capacity &&
log.evicted() == 201 - OutcomeLog::capacity);
CHECK(log.entries().back().sequence == 201);
}
// Host/session boundary: the visible mode and the session lifetime change together.
struct Server {
bool available{};
int steps{}, welcomes{}, intentions{}, alive{};
};
class FakeSession {
public:
explicit FakeSession(Server& server) : server_{&server} {
++server_->alive;
}
FakeSession(FakeSession&& other) noexcept : server_{std::exchange(other.server_, nullptr)} {}
FakeSession& operator=(FakeSession&&) = delete;
FakeSession(const FakeSession&) = delete;
FakeSession& operator=(const FakeSession&) = delete;
~FakeSession() {
if (server_ != nullptr)
--server_->alive;
}
void step(std::chrono::steady_clock::time_point, const Intention& intention, UiState&,
Launcher& launcher) {
++server_->steps;
if (!server_->available) {
launcher.observe(ConnectSignal::lost);
return;
}
if (!welcomed_) {
welcomed_ = true;
++server_->welcomes; // Spends a grant.
launcher.observe(ConnectSignal::welcome);
}
if (intention.move_x != 0 || intention.move_y != 0)
++server_->intentions;
}
private:
Server* server_;
bool welcomed_{};
};
void session_host() {
const auto now = std::chrono::steady_clock::now();
UiState ui;
const Intention move{1, 0, 1000, 0};
Server server;
SessionHost<FakeSession> host;
CHECK(!host.connect(std::nullopt) && host.session() == nullptr);
// Connecting -> Local fixture: the attempt ends; a later server sees nothing.
CHECK(host.connect(FakeSession{server}) && server.alive == 1);
host.step(now, move, ui);
CHECK(server.steps == 1 && host.launcher().phase() == LaunchPhase::connecting);
host.enter_fixture();
CHECK(server.alive == 0 && host.launcher().phase() == LaunchPhase::fixture);
server.available = true;
for (int i = 0; i < 10; ++i)
host.step(now, move, ui);
CHECK(server.steps == 1 && server.welcomes == 0 && server.intentions == 0);
// Failed -> Local fixture: the failure already dropped the session.
host.cancel();
server.available = false;
CHECK(host.connect(FakeSession{server}));
for (int i = 0; i < Launcher::max_attempts_without_welcome; ++i)
host.step(now, move, ui);
CHECK(host.launcher().phase() == LaunchPhase::failed && server.alive == 0);
host.enter_fixture();
server.available = true;
host.step(now, move, ui);
CHECK(server.welcomes == 0 && server.intentions == 0 && host.session() == nullptr);
// Ordinary live use still works, and Cancel ends it.
host.cancel();
CHECK(host.connect(FakeSession{server}));
host.step(now, move, ui);
CHECK(host.launcher().phase() == LaunchPhase::connected && server.welcomes == 1 &&
server.intentions == 1);
host.cancel();
host.step(now, move, ui);
CHECK(server.alive == 0 && server.intentions == 1 &&
host.launcher().phase() == LaunchPhase::choosing);
// Connect is refused outside choosing/failed and leaves no session behind.
host.enter_fixture();
// (Separate statements: the by-value argument may live until the full expression ends.)
CHECK(!host.connect(FakeSession{server}));
CHECK(server.alive == 0 && host.session() == nullptr);
}
void cellular_play() {
using namespace evo::client_app;
using namespace evo::network;
CellularPlay play;
play.initialize(100);
CHECK(play.birth_request() == 100 && play.birth_pending());
play.connected();
play.observe({101, 900, {}, CellularLifeDiagnostics{}});
CHECK(play.can_act() && !play.can_restart());
CellularLifeDiagnostics feedback;
feedback.has_tick_effects = true;
feedback.bud = CellularBudOutcome::insufficient_funding;
play.observe({101, 900, {}, feedback});
play.observe({102, 900, {}, CellularLifeDiagnostics{}});
CHECK(play.bud_feedback() ==
std::pair{std::uint64_t{101}, CellularBudOutcome::insufficient_funding});
const CellularMutationOffer offer{101, 900, 1, 100, {{3, 2, 0, 50, 20, 30}}};
play.observe_offer(offer);
CHECK(!play.queue(CellAction::mutation, 102, {900, 2, 100, 3}));
CHECK(!play.queue(CellAction::mutation, 100, {900, 1, 100, 3}));
CHECK(!play.queue(CellAction::mutation, 102, {900, 1, 100, 8}));
CHECK(play.queue(CellAction::mutation, 102, {900, 1, 100, 3}));
const auto id = required(play.pending()).id;
CHECK(!play.queue(CellAction::bud, 102)); // Double clicks cannot create another action.
play.sent();
play.receipt({id, AdmitStatus::not_ready, 101, 0});
CHECK(required(play.pending()).state == CellActionState::unresolved);
play.disconnected();
CHECK(!play.can_act() && !play.offer());
play.connected();
CHECK(!play.can_act());
play.observe({103, 900, {}, CellularLifeDiagnostics{}});
play.receipt({id, AdmitStatus::invalid_action, 103, 0});
CHECK(required(play.pending()).state ==
CellActionState::unresolved); // Refused retry != failed original.
play.outcome({id, ActionResult::committed, 102, 1});
CHECK(!play.pending() && play.history().back().state == CellActionState::committed);
CHECK(play.queue(CellAction::bud, 104));
const auto bud = required(play.pending()).id;
play.sent();
play.observe_end({104, 900, CellularDeathReason::starved});
play.observe({103, 900, {}, CellularLifeDiagnostics{}}); // Retained view is older than death.
CHECK(play.life() == 0 && play.can_restart() && !play.can_act());
CHECK(play.restart());
const auto request = play.birth_request();
CHECK(request != 100 && !play.restart());
play.birth({100, PrimitiveLifeResult::born, 900, 1}); // Old request cannot finish this birth.
CHECK(play.birth_pending());
play.birth({request, PrimitiveLifeResult::born, 901, 3});
CHECK(!play.can_restart()); // Birth reply may precede the first new-life view.
play.observe({105, 901, {}, CellularLifeDiagnostics{}});
play.observe_end({104, 900, CellularDeathReason::starved});
CHECK(play.life() == 901 && !play.ended() && !play.pending());
play.outcome({bud, ActionResult::not_committed, 0, 0});
CHECK(play.history().back().state == CellActionState::refused);
for (int i = 0; i < 20; ++i) {
CHECK(play.queue(CellAction::engulf, 106));
const auto action = required(play.pending()).id;
play.sent();
play.outcome({action, ActionResult::unknown, 0, 0});
play.keep_unknown();
}
CHECK(play.history().size() == CellularPlay::history_limit);
CHECK(play.history().back().state == CellActionState::unresolved);
play.disconnected();
CHECK(!play.queue(CellAction::engulf, 106) && !play.can_restart());
play.connected();
play.observe({106, 901, {}, CellularLifeDiagnostics{}});
CHECK(play.queue(CellAction::bud, 107));
play.disconnected();
CHECK(!play.pending() && play.history().back().state == CellActionState::refused);
CellularPlay exhausted;
exhausted.initialize(std::numeric_limits<std::uint64_t>::max());
CHECK(exhausted.allocate_id() == 0 && exhausted.allocate_id() == 0);
}
// Recent actions keep what the region did: the effect reported in the action's tick view
// is attached to that engulf, even after its committed outcome moved it to the history.
void cellular_action_effects() {
using namespace evo::client_app;
using namespace evo::network;
CellularPlay play;
play.initialize(50);
play.connected();
play.observe({200, 700, {}, CellularLifeDiagnostics{}});
CHECK(play.queue(CellAction::engulf, 203));
const auto id = required(play.pending()).id;
play.sent();
play.outcome({id, ActionResult::committed, 203, 1});
CHECK(!play.pending() && !play.history().back().engulf);
CellularLifeDiagnostics effect;
effect.has_tick_effects = true;
effect.engulf = CellularEngulfResult::membrane_too_thick;
play.observe({203, 700, {}, effect});
CHECK(play.history().back().engulf == CellularEngulfResult::membrane_too_thick);
// A later engulf result does not overwrite the reported one.
effect.engulf = CellularEngulfResult::engulfed;
play.observe({204, 700, {}, effect});
CHECK(play.history().back().engulf == CellularEngulfResult::membrane_too_thick);
}
// Rules 13 (v14): a bud may carry become, a choice its become, Emerge is a discrete action,
// and an emerged ending ends the life like any other.
void cellular_revamp_actions() {
using namespace evo::client_app;
using namespace evo::network;
CellularPlay play;
play.initialize(70);
play.connected();
CellularLifeDiagnostics body;
body.members = 1;
play.observe({300, 800, {}, body});
// Flows add up over the last second of views (20 ticks) and scale up over missed ones.
{
CellularPlay flows;
flows.initialize(5);
flows.connected();
CellularLifeDiagnostics flowing = body;
flowing.has_tick_effects = true;
flowing.movement = CellularMovementResult::no_movement;
flowing.intake = CellularIntakeResult::acquired;
flowing.collected = {0, 0, 0, 100, 0};
flowing.into_growth = {0, 0, 0, 90, 0};
for (std::uint64_t tick = 1; tick <= 30; ++tick)
flows.observe({tick, 800, {}, flowing});
const auto second = flows.flows_per_second();
CHECK(second.collected[3] == 2'000 && second.into_growth[3] == 1'800);
for (std::uint64_t tick = 31; tick <= 40; tick += 2) // Every other view missed.
flows.observe({tick, 800, {}, flowing});
CHECK(flows.flows_per_second().collected[3] == 2'000);
}
CHECK(play.queue(CellAction::bud, 301, {}, true) && required(play.pending()).become);
play.sent();
play.outcome({required(play.pending()).id, ActionResult::committed, 301, 1});
CHECK(play.history().back().become);
CHECK(play.queue(CellAction::engulf, 302, {}, true) && !required(play.pending()).become);
play.sent();
play.outcome({required(play.pending()).id, ActionResult::committed, 302, 1});
play.observe_offer(CellularMutationOffer{303, 800, 1, 300, {{12, 0, 0, 700'000, 0, 0}}});
CHECK(play.queue(CellAction::mutation, 304, {800, 1, 300, 12, true}) &&
required(play.pending()).choice.become);
play.sent();
play.outcome({required(play.pending()).id, ActionResult::committed, 304, 1});
CHECK(play.queue(CellAction::emerge, 305));
play.sent();
play.observe_end({305, 800, CellularDeathReason::emerged});
CHECK(play.life() == 0 && play.ended() && play.ended()->cause == CellularDeathReason::emerged &&
play.can_restart());
}
void cellular_energy_and_birth_wait() {
using namespace evo::client_app;
using namespace evo::network;
CellularPlay play;
play.initialize(1);
play.connected();
CHECK(!play.can_restart());
play.birth({1, PrimitiveLifeResult::pending, 7, 0});
CHECK(!play.can_restart());
play.birth({1, PrimitiveLifeResult::insufficient_funding, 7, 0});
CHECK(!play.fresh() && play.can_restart()); // Refusal arrives without any world view.
CHECK(play.restart() && play.birth_request() == 2 && !play.restart());
play.birth({1, PrimitiveLifeResult::no_placement, 7, 0});
CHECK(play.birth_pending()); // Delayed answer to an older request is ignored.
play.birth({2, PrimitiveLifeResult::existing_life, 9, 0});
CHECK(!play.can_restart()); // Wait for that existing life instead of offering another birth.
CellularLifeDiagnostics d;
d.reserve_energy_pj = 200;
play.observe({10, 9, {}, d});
CHECK(!play.energy_change());
play.observe({11, 0, {}, {}}); // The bridge may clear a view before sending its replacement.
d.reserve_energy_pj = 150;
play.observe({11, 9, {}, d});
CHECK(required(play.energy_change()).falling && required(play.energy_change()).amount == 50);
play.observe({11, 9, {}, d});
CHECK(required(play.energy_change()).amount == 50); // Duplicate views retain the change.
d.reserve_energy_pj = 175;
play.observe({15, 9, {}, d});
CHECK(!required(play.energy_change()).falling && required(play.energy_change()).amount == 25 &&
required(play.energy_change()).from_tick == 11);
play.disconnected();
CHECK(!play.energy_change());
play.connected();
play.observe({16, 9, {}, d});
CHECK(!play.energy_change());
play.observe({17, 10, {}, d});
CHECK(!play.energy_change()); // A different life starts a new baseline.
}
} // namespace
// A cell faces the way it moved (y up in the world is up on screen), eases into a turn,
// ignores sub-step jitter and camera panning, and is forgotten once it is not drawn.
void cell_headings() {
using namespace evo::client_app;
auto camera = Camera::create({800, 600, 800, 600}, {5, 5}, 100);
CHECK(camera);
CellHeadings headings;
CHECK(!headings.update(1, {5, 5}, *camera));
headings.end_frame();
CHECK(!headings.update(1, {5.001, 5}, *camera)); // Below the step: still unknown.
headings.end_frame();
const auto east = headings.update(1, {5.1, 5}, *camera);
CHECK(east && std::abs(*east) < 1e-4F);
headings.end_frame();
auto panned = Camera::create({800, 600, 800, 600}, {9, 2}, 100);
CHECK(panned);
const auto still = headings.update(1, {5.1, 5}, *panned);
CHECK(still && std::abs(*still) < 1e-4F);
headings.end_frame();
// Moving north is screen up (negative y): the heading eases toward -pi/2.
const auto turning = headings.update(1, {5.1, 5.2}, *camera);
CHECK(turning && *turning < 0 && *turning > -1.5707F);
headings.end_frame();
float heading = turning.value_or(0);
for (int i = 0; i < 60; ++i) {
heading = headings.update(1, {5.1, 5.2}, *camera).value_or(0);
headings.end_frame();
}
CHECK(std::abs(heading + 1.5708F) < 1e-3F);
headings.end_frame(); // Not drawn this frame: forgotten.
CHECK(!headings.update(1, {6, 6}, *camera));
}
int main() try {
labels();
selection();
launcher();
outcome_log();
session_host();
cellular_play();
cellular_action_effects();
cellular_revamp_actions();
cellular_energy_and_birth_wait();
cellular_assistance();
cell_headings();
std::puts("client UI model tests passed");
return 0;
} catch (const std::exception& e) {
std::fprintf(stderr, "%s\n", e.what());
return 1;
}