Files
aevolution/tests/client_ui_model.cpp
T

484 lines
21 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 <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.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, {-10, 100}, {100, -10}, 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);
}
} // namespace
int main() try {
labels();
selection();
launcher();
outcome_log();
session_host();
cellular_play();
cellular_assistance();
std::puts("client UI model tests passed");
return 0;
} catch (const std::exception& e) {
std::fprintf(stderr, "%s\n", e.what());
return 1;
}