From 897055883a2e7fe1351b0a693afa7896d0a15b1f Mon Sep 17 00:00:00 2001 From: dingo Date: Fri, 2 Oct 2026 10:09:11 -0400 Subject: [PATCH] Add M9.8c launcher, legend, labelled inspector and click selection Toolkit-independent launcher, selection, label and outcome-log models with bounded inputs and fixed error text; Dear ImGui overlay in the native adapter with toolkit-first event routing and capture; engineering panels for fixture vs dev region, legend, inspector, session outcomes, notices and dialog. Additive SessionClient::unreachable_attempts() bounds unreachable connects. Docs, CI targets and validation evidence updated. Co-Authored-By: Claude Opus 5.5 --- CMakeLists.txt | 2 +- CMakePresets.json | 4 +- apps/evo-client/main.cpp | 306 +++++++++++++++---- apps/evo-client/panels.cpp | 358 +++++++++++++++++++++++ apps/evo-client/panels.hpp | 45 +++ apps/evo-client/remote_session.hpp | 175 ++++++----- cmake/ClientProbe.cmake | 18 +- cmake/EngineeringUi.cmake | 1 + deploy/docker/Dockerfile | 4 +- docs/ROADMAP.md | 4 +- docs/STATUS.md | 10 +- docs/adr/0081-organism-presentation.md | 4 +- docs/adr/0084-engineering-ui-toolkit.md | 15 + docs/architecture/CLIENT_ARCHITECTURE.md | 11 +- docs/engineering/CLIENT.md | 51 ++-- docs/engineering/CLIENT_UI_STATE.md | 36 ++- docs/engineering/M9_8_DELIVERY_PLAN.md | 5 +- docs/engineering/ORGANISM_RENDERING.md | 22 +- docs/engineering/VALIDATION.md | 45 +++ include/evo/client/application.hpp | 10 + include/evo/client/input.hpp | 6 + include/evo/client/labels.hpp | 32 ++ include/evo/client/launcher.hpp | 92 ++++++ include/evo/client/outcome_log.hpp | 40 +++ include/evo/client/selection.hpp | 39 +++ include/evo/network/session_client.hpp | 3 + src/client/input/input.cpp | 12 +- src/client/platform/application.cpp | 148 +++++++++- src/client/ui/labels.cpp | 151 ++++++++++ src/client/ui/launcher.cpp | 181 ++++++++++++ src/client/ui/outcome_log.cpp | 20 ++ src/client/ui/selection.cpp | 65 ++++ src/network/session/client.cpp | 8 +- tests/client_lifecycle.cpp | 104 +++++++ tests/client_ui_model.cpp | 259 ++++++++++++++++ tests/network_session.cpp | 20 ++ 36 files changed, 2106 insertions(+), 200 deletions(-) create mode 100644 apps/evo-client/panels.cpp create mode 100644 apps/evo-client/panels.hpp create mode 100644 include/evo/client/labels.hpp create mode 100644 include/evo/client/launcher.hpp create mode 100644 include/evo/client/outcome_log.hpp create mode 100644 include/evo/client/selection.hpp create mode 100644 src/client/ui/labels.cpp create mode 100644 src/client/ui/launcher.cpp create mode 100644 src/client/ui/outcome_log.cpp create mode 100644 src/client/ui/selection.cpp create mode 100644 tests/client_ui_model.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index d614be1..d908216 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -97,7 +97,7 @@ include(CTest) if(EVO_BUILD_CLIENT OR EVO_BUILD_NETWORK) # SDL-free client value contracts (M9.3-M9.5), shared by the client and the dev # session codec. They copy read-only world/biology views, never the reverse. - add_library(evo_client_controls STATIC src/client/camera/camera.cpp src/client/input/input.cpp src/client/ui/ui_state.cpp) + add_library(evo_client_controls STATIC src/client/camera/camera.cpp src/client/input/input.cpp src/client/ui/ui_state.cpp src/client/ui/outcome_log.cpp) target_include_directories(evo_client_controls PUBLIC "${CMAKE_CURRENT_SOURCE_DIR}/include") evo_owned_target(evo_client_controls) if(BUILD_TESTING) diff --git a/CMakePresets.json b/CMakePresets.json index a258bf4..7f42be1 100644 --- a/CMakePresets.json +++ b/CMakePresets.json @@ -19,10 +19,10 @@ {"name": "analysis", "configurePreset": "analysis"}, {"name": "asan", "configurePreset": "asan"}, {"name": "tsan", "configurePreset": "tsan"}, - {"name": "client", "configurePreset": "client", "targets": ["evo-client-state-tests", "evo-client", "evo-client-lifecycle-tests", "evo-client-environment-tests", "evo-client-organism-tests"]}, + {"name": "client", "configurePreset": "client", "targets": ["evo-client-state-tests", "evo-client", "evo-client-lifecycle-tests", "evo-client-environment-tests", "evo-client-organism-tests", "evo-client-ui-model-tests"]}, {"name": "client-probe", "configurePreset": "client-probe", "targets": ["evo-client-probe"]}, {"name": "network", "configurePreset": "network", "targets": ["evo-client-state-tests", "evo-network-tests", "evo-dev-session"]}, - {"name": "client-network", "configurePreset": "client-network", "targets": ["evo-client-state-tests", "evo-client", "evo-client-lifecycle-tests", "evo-client-environment-tests", "evo-client-organism-tests", "evo-network-tests", "evo-dev-session"]} + {"name": "client-network", "configurePreset": "client-network", "targets": ["evo-client-state-tests", "evo-client", "evo-client-lifecycle-tests", "evo-client-environment-tests", "evo-client-organism-tests", "evo-client-ui-model-tests", "evo-network-tests", "evo-dev-session"]} ], "testPresets": [ {"name": "debug", "configurePreset": "debug", "output": {"outputOnFailure": true}}, diff --git a/apps/evo-client/main.cpp b/apps/evo-client/main.cpp index 8837ff9..d346d61 100644 --- a/apps/evo-client/main.cpp +++ b/apps/evo-client/main.cpp @@ -1,7 +1,10 @@ #include "evo/client/application.hpp" -#include "evo/client/organism_inspector.hpp" +#include "evo/client/launcher.hpp" +#include "evo/client/selection.hpp" +#include "evo/client/ui_state.hpp" #include "evo/render/environment.hpp" #include "evo/render/organism.hpp" +#include "panels.hpp" #include "remote_session.hpp" #include #include @@ -24,12 +27,11 @@ constexpr std::int64_t fixture_z = -16000; // incident energy (never opened: missing). Unrequested fields draw hollow outlines. constexpr std::uint32_t fixture_mask = (1U << 0) | (1U << 1) | (1U << 2) | (1U << 7) | (1U << 8); constexpr unsigned frames_per_authority_tick = 60; -// Frame composition: environment bound + organisms + inspector + 5 host UI rectangles -// (capture bar, intention dot, and in remote mode the connection and intent chips). -constexpr std::size_t host_ui_rectangles = 5; -constexpr std::size_t organism_budget = evo::render::max_rectangles - - evo::render::max_environment_rectangles - - evo::client::inspector_rectangles - host_ui_rectangles; +// Frame composition: environment bound + organisms + 6 host rectangles (capture bar, +// intention dot, 4-sided selection highlight). Text and panels are the toolkit overlay. +constexpr std::size_t host_rectangles = 6; +constexpr std::size_t organism_budget = + evo::render::max_rectangles - evo::render::max_environment_rectangles - host_rectangles; // Local in-memory stand-in for authoritative region views until M9.7. It is never // persisted or published; the client presentation only copies its read-only views. struct FixtureAuthority { @@ -171,28 +173,64 @@ bool parse_count(std::string_view value, unsigned limit, unsigned& out) { const auto [end, error] = std::from_chars(value.data(), value.data() + value.size(), out); return error == std::errc{} && end == value.data() + value.size() && out != 0 && out <= limit; } +std::optional parse_point(std::string_view value) { + const auto comma = value.find(','); + unsigned x = 0, y = 0; + if (comma == std::string_view::npos || !parse_count(value.substr(0, comma), 32768, x) || + !parse_count(value.substr(comma + 1), 32768, y)) + return std::nullopt; + return evo::client::ScreenPoint{static_cast(x), static_cast(y)}; +} +void outline(std::vector& out, double l, double t, double r, double b, + double width, double height) { + const auto rect = [&](double x0, double y0, double x1, double y1) { + x0 = std::max(x0, 0.0); + y0 = std::max(y0, 0.0); + x1 = std::min(x1, width); + y1 = std::min(y1, height); + if (x1 > x0 && y1 > y0) + out.push_back({static_cast(x0), + static_cast(y0), + static_cast(x1 - x0), + static_cast(y1 - y0), + {255, 255, 255, 255}}); + }; + rect(l, t, r, t + 2); + rect(l, b - 2, r, b); + rect(l, t + 2, l + 2, b - 2); + rect(r - 2, t + 2, r, b - 2); +} +std::uint64_t milliseconds(std::chrono::steady_clock::time_point t) { + return static_cast( + std::chrono::duration_cast(t.time_since_epoch()).count()); +} } // namespace int main(int argc, char** argv) try { + using evo::client_app::Mode; evo::client::Config config; unsigned frames = 0, refresh_every = 1; - bool inspect = false; + bool start_fixture = false; + std::optional scripted_pick; + std::string screenshot; evo::render::EnvironmentDisplay display; - evo::client_app::RemoteOptions remote_options; + evo::client::ConnectForm form; + bool connect_now = false; for (int i = 1; i < argc; ++i) { const std::string_view arg{argv[i]}; if (arg == "--hidden") config.hidden = true; - else if (arg == "--inspect") - inspect = true; - else if (arg == "--connect" && i + 1 < argc) - remote_options.connect = argv[++i]; - else if (arg == "--server-name" && i + 1 < argc) - remote_options.server_name = argv[++i]; + else if (arg == "--fixture") + start_fixture = true; + else if (arg == "--connect" && i + 1 < argc) { + form.endpoint = argv[++i]; + connect_now = true; + } else if (arg == "--server-name" && i + 1 < argc) + form.server_name = argv[++i]; else if (arg == "--ca" && i + 1 < argc) - remote_options.authority = argv[++i]; + form.authority_path = argv[++i]; else if (arg == "--grants" && i + 1 < argc) - remote_options.grants = argv[++i]; + form.grants_path = argv[++i]; else if (arg == "--renderer" && i + 1 < argc) config.renderer = argv[++i]; else if (arg == "--frames" && i + 1 < argc) { @@ -206,42 +244,80 @@ int main(int argc, char** argv) try { if (!layer) return 2; display = *layer; + } else if (arg == "--pick" && i + 1 < argc) { // Engineering automation only. + scripted_pick = parse_point(argv[++i]); + if (!scripted_pick) + return 2; + } else if (arg == "--screenshot" && i + 1 < argc) { // Last frame, as BMP. + screenshot = argv[++i]; } else { std::fputs("usage: evo-client [--renderer NAME] [--hidden] [--frames 1..100000]\n" + " [--fixture | --connect HOST:PORT --server-name NAME " + "--ca FILE --grants FILE]\n" " [--layer water|nitrogen|...|heat|moisture]\n" - " [--refresh-every 1..1000] [--inspect]\n" - " [--connect HOST:PORT --server-name NAME --ca FILE " - "--grants FILE]\n", + " [--refresh-every 1..1000] [--pick X,Y] " + "[--screenshot FILE.bmp --frames N]\n" + "Without --fixture or --connect the launcher opens.\n", stderr); return 2; } } - // Remote mode (M9.7): views and intentions go through a dev session; the local - // fixture authority is not created at all. + if ((start_fixture && connect_now) || (!screenshot.empty() && frames == 0)) + return 2; + evo::client::Launcher launcher; + evo::client::UiState ui; + evo::client::Selection selection; + evo::client_app::FormBuffers buffers; + buffers.load(form); + std::optional form_error; std::optional remote; - if (remote_options.any()) { - if (!evo::client_app::remote_available || !remote_options.complete()) { - std::fputs("remote mode needs --connect, --server-name, --ca and --grants " - "(and a build with EVO_BUILD_NETWORK)\n", - stderr); - return 2; - } - remote = evo::client_app::RemoteSession::open(remote_options); - if (!remote) { - std::fputs("client session configuration error\n", stderr); - return 1; - } - } std::optional authority; - if (!remote) { - authority = make_authority(); - if (!authority) { - std::fputs("client environment fixture error\n", stderr); - return 1; - } - } evo::client::EnvironmentLayer environment; evo::client::OrganismLayer population; + std::optional disconnect_dialog; + // Validates the form and opens a fresh session; errors stay in the launcher. + const auto connect = [&](const evo::client::ConnectForm& f) { + form_error.reset(); + if constexpr (!evo::client_app::remote_available) { + form_error = evo::client::LaunchError::no_session; + return false; + } else { + const auto material = evo::client::load_connect(f); + if (!material) { + form_error = material.error(); + return false; + } + remote = evo::client_app::RemoteSession::open(*material); + if (!remote) { + form_error = evo::client::LaunchError::endpoint; + return false; + } + return launcher.begin_connect(); + } + }; + const auto enter_fixture = [&] { + if (!authority) { + authority = make_authority(); + if (!authority) + return false; + } + environment.reset(); + population.reset(); + selection.clear(); + launcher.start_fixture(); + return true; + }; + if (start_fixture && !enter_fixture()) { + std::fputs("client environment fixture error\n", stderr); + return 1; + } + if (connect_now && !connect(form)) { + std::fprintf(stderr, "client session configuration error: %s\n", + std::string{evo::client::launch_error_text( + form_error.value_or(evo::client::LaunchError::no_session))} + .c_str()); + return 1; + } auto app = evo::client::Application::open(config); if (!app) { std::fprintf(stderr, "client initialization error=%d\n", static_cast(app.error())); @@ -253,9 +329,48 @@ int main(int argc, char** argv) try { {config.width, config.height, config.width, config.height}, {}, 0.05); if (!camera) return 1; - std::puts("Arrows: pan | wheel: zoom | WASD: intention indicator | Tab: UI capture (orange)"); - std::puts("Status chips (environment, organisms): green current | amber stale | red none;" - " magenta marker: organisms truncated"); + const auto mode = [&] { + const auto phase = launcher.phase(); + if (phase == evo::client::LaunchPhase::fixture) + return Mode::fixture; + if (phase == evo::client::LaunchPhase::connected || + (phase == evo::client::LaunchPhase::connecting && launcher.ever_connected())) + return Mode::remote; + return Mode::launcher; // Choosing, failed, or the first connection attempt. + }; + const auto shown_environment = [&]() -> const evo::client::EnvironmentLayer* { + if (mode() == Mode::fixture) + return &environment; + if (mode() == Mode::remote && remote) + return &remote->environment(); + return nullptr; + }; + const auto shown_organisms = [&]() -> const evo::client::OrganismLayer* { + if (mode() == Mode::fixture) + return &population; + if (mode() == Mode::remote && remote) + return &remote->organisms(); + return nullptr; + }; + int drawn_organisms = -1; + evo::client_app::PanelActions actions; + (*app)->set_overlay([&] { + evo::client_app::PanelView view; + view.mode = mode(); + view.launcher = &launcher; + view.form_error = form_error; + view.remote_available = evo::client_app::remote_available; + view.environment = shown_environment(); + view.organisms = shown_organisms(); + view.selection = &selection; + view.ui = &ui; + if (remote && view.mode == Mode::remote) { + view.remote = remote->status(); + view.outcomes = &remote->outcomes(); + } + view.visible_organisms = drawn_organisms; + actions = evo::client_app::draw_panels(view, buffers, display); + }); std::vector boxes; std::uint64_t count = 0; auto previous = std::chrono::steady_clock::now(); @@ -268,19 +383,50 @@ int main(int argc, char** argv) try { if (state.closed) break; const auto now = std::chrono::steady_clock::now(); + static_cast(ui.advance(milliseconds(now)).has_value()); // Monotonic clock. const double seconds = std::clamp(std::chrono::duration(now - previous).count(), 0.0, 0.1); previous = now; + // Panel actions from the previous rendered frame. + if (actions.fixture && !enter_fixture()) + return 1; + if ((actions.connect || actions.retry) && connect(buffers.form())) { + selection.clear(); + } + if (actions.cancel || actions.back) { + remote.reset(); // Drops the connection; its unresolved outcomes are unknown. + launcher.cancel(); + selection.clear(); + } + if (actions.ask_disconnect && !disconnect_dialog) + if (const auto id = ui.open_dialog("Disconnect from the dev region?", + "Intentions without a final outcome will be " + "unknown. Views stop updating.")) + disconnect_dialog = *id; + if (actions.confirm_dialog && actions.confirm_dialog == disconnect_dialog && + ui.close_dialog(*actions.confirm_dialog)) { + disconnect_dialog.reset(); + remote.reset(); + launcher.cancel(); + selection.clear(); + } + if (actions.cancel_dialog && ui.close_dialog(*actions.cancel_dialog)) + disconnect_dialog.reset(); + if (actions.dismiss_notice) + static_cast(ui.dismiss(*actions.dismiss_notice)); + actions = {}; + // The launcher and modal dialogs own input: no world movement or selection. + (*app)->set_ui_capture(mode() == Mode::launcher || ui.dialog().has_value()); const auto navigation = (*app)->take_navigation(); // Local input counter; in remote mode the session sets the server tick. const auto intention = (*app)->sample_intention(count); if (!intention) return 1; - if (remote) - remote->step(now, *intention); + if (remote && launcher.phase() != evo::client::LaunchPhase::failed) + remote->step(now, *intention, ui, launcher); // The fixture authority advances at its own cadence. Presentations refresh // every N authority ticks; in between the advanced watermark shows as stale. - if (!remote && count % frames_per_authority_tick == 0) { + if (mode() == Mode::fixture && count % frames_per_authority_tick == 0) { if (count != 0 && !advance(*authority)) return 1; if ((authority->tick - 1) % refresh_every == 0) { @@ -295,6 +441,19 @@ int main(int argc, char** argv) try { !population.observe({fixture_identity, authority->tick, 1})) return 1; } + const auto* env_layer = shown_environment(); + const auto* org_layer = shown_organisms(); + const auto* env = env_layer ? env_layer->current() : nullptr; + const auto* orgs = org_layer ? org_layer->current() : nullptr; + const auto change = selection.refresh(env, orgs); + if (change == evo::client::Selection::Change::organism_gone) + static_cast(ui.notify("The selected organism is no longer present.", + evo::client::NoticeLevel::info) + .has_value()); + else if (change == evo::client::Selection::Change::cell_gone) + static_cast(ui.notify("The selected habitat cell is no longer in view.", + evo::client::NoticeLevel::info) + .has_value()); boxes.clear(); if (state.logical_width > 0 && state.logical_height > 0 && state.pixel_width > 0 && state.pixel_height > 0) { @@ -311,35 +470,52 @@ int main(int argc, char** argv) try { if (auto result = camera->zoom(std::exp2(navigation.wheel / 4), anchor); !result && result.error() != evo::client::CameraError::out_of_range) return 1; - const auto& shown_environment = remote ? remote->environment() : environment; - const auto& shown_organisms = remote ? remote->organisms() : population; + if (navigation.click) + selection.pick(*navigation.click, env, orgs, *camera); + if (scripted_pick && env != nullptr) { + selection.pick(*scripted_pick, env, orgs, *camera); + scripted_pick.reset(); + } // Copied presentation only; clipped to the viewport before float conversion. - if (!evo::render::build_environment(boxes, shown_environment.current(), - shown_environment.freshness(), *camera, display) || - !evo::render::append_organisms(boxes, organism_budget, shown_organisms.current(), - shown_organisms.freshness(), *camera)) + if (!evo::render::build_environment( + boxes, env, env_layer ? env_layer->freshness() : evo::client::Freshness::none, + *camera, display)) return 1; - // Engineering inspector: biology gauges for the hovered organism only. - if (const auto* shown = shown_organisms.current(); inspect && shown != nullptr) - if (const auto index = - evo::client::pick_organism(*shown, *camera, navigation.pointer)) - if (!evo::client::append_inspector(boxes, evo::client::inspector_rectangles, - shown->cells()[*index], *camera)) - return 1; + const auto report = evo::render::append_organisms( + boxes, organism_budget, orgs, + org_layer ? org_layer->freshness() : evo::client::Freshness::none, *camera); + if (!report) + return 1; + drawn_organisms = static_cast(report->drawn); + const double width = state.logical_width, height = state.logical_height; + if (const auto* o = selection.organism(orgs)) { + const auto b = evo::render::organism_bounds(*o, *camera); + outline(boxes, b.left - 3, b.top - 3, b.right + 3, b.bottom + 3, width, height); + } else if (const auto* c = selection.cell(env)) { + const double pitch = evo::world::cell_pitch_mm; + const auto low = camera->world_to_screen({static_cast(c->voxel.x) * pitch, + static_cast(c->voxel.y) * pitch}); + const auto high = + camera->world_to_screen({static_cast(c->voxel.x + 1) * pitch, + static_cast(c->voxel.y + 1) * pitch}); + if (low && high) + outline(boxes, low->x, high->y, high->x, low->y, width, height); + } } - boxes.push_back({8, 8, 64, 8, + boxes.push_back({8, static_cast(std::max(state.logical_height - 20, 0)), 64, 8, (*app)->ui_captured() ? evo::render::Color{240, 140, 32, 255} : evo::render::Color{64, 180, 140, 255}}); boxes.push_back({36 + static_cast(intention->move_x) / 50, - 48 - static_cast(intention->move_y) / 50, + static_cast(std::max(state.logical_height - 48, 0)) - + static_cast(intention->move_y) / 50, 8, 8, {240, 240, 240, 255}}); - if (remote) - remote->status(boxes); const auto frame = evo::render::Frame::create(boxes, {16, 20, 28, 255}); if (!frame) return 1; + if (!screenshot.empty() && count + 1 == frames && !(*app)->request_screenshot(screenshot)) + return 2; const auto result = (*app)->present(*frame); if (!result) { std::fprintf(stderr, "client frame error=%d\n", static_cast(result.error())); diff --git a/apps/evo-client/panels.cpp b/apps/evo-client/panels.cpp new file mode 100644 index 0000000..9175e52 --- /dev/null +++ b/apps/evo-client/panels.cpp @@ -0,0 +1,358 @@ +#include "panels.hpp" +#include "evo/client/labels.hpp" +#include +#include +#include +#include + +namespace evo::client_app { +namespace { +using client::LaunchPhase; +ImVec4 color(render::Color c) { + return {static_cast(c.red) / 255.0F, static_cast(c.green) / 255.0F, + static_cast(c.blue) / 255.0F, static_cast(c.alpha) / 255.0F}; +} +void copy(std::array& out, const std::string& in) { + out.fill('\0'); + std::memcpy(out.data(), in.data(), std::min(in.size(), out.size() - 1)); +} +std::string text(const std::array& in) { + return {in.begin(), std::find(in.begin(), in.end(), '\0')}; +} +void row(const char* label, const std::string& value, const std::string& unit = {}) { + ImGui::TableNextRow(); + ImGui::TableNextColumn(); + ImGui::TextUnformatted(label); + ImGui::TableNextColumn(); + ImGui::TextUnformatted(value.c_str()); + ImGui::TableNextColumn(); + ImGui::TextUnformatted(unit.c_str()); +} +void swatch(const char* id, render::Color c, const char* label) { + ImGui::ColorButton(id, color(c), ImGuiColorEditFlags_NoTooltip | ImGuiColorEditFlags_NoAlpha, + {14, 14}); + ImGui::SameLine(); + ImGui::TextUnformatted(label); +} +constexpr ImVec4 amber{0.94F, 0.67F, 0.16F, 1.0F}, red{0.95F, 0.35F, 0.35F, 1.0F}, + green{0.35F, 0.80F, 0.60F, 1.0F}; +ImVec4 freshness_color(client::Freshness f) { + return f == client::Freshness::current ? green : f == client::Freshness::stale ? amber : red; +} +const char* outcome_name(client::OutcomeState s) { + switch (s) { + case client::OutcomeState::sent: + return "sent (no reply yet)"; + case client::OutcomeState::admitted: + return "admitted (not yet durable)"; + case client::OutcomeState::rejected: + return "rejected"; + case client::OutcomeState::durable: + return "durable, no effect"; + case client::OutcomeState::not_committed: + return "not committed"; + case client::OutcomeState::unknown: + return "UNKNOWN (connection lost)"; + } + return "?"; +} +void disabled_wrapped(const char* text) { + ImGui::PushStyleColor(ImGuiCol_Text, ImGui::GetStyleColorVec4(ImGuiCol_TextDisabled)); + ImGui::TextWrapped("%s", text); + ImGui::PopStyleColor(); +} +// Fixed wording only (never echoes paths or file bytes); wraps inside the launcher. +void error_text(client::LaunchError error) { + ImGui::PushStyleColor(ImGuiCol_Text, red); + ImGui::TextWrapped("%s", std::string{client::launch_error_text(error)}.c_str()); + ImGui::PopStyleColor(); +} + +constexpr std::array layer_names{ + "Water", "Dissolved nitrogen", "Dissolved phosphorus", + "Organic carbon", "Organic nitrogen", "Organic phosphorus", + "Organic other", "Organic energy", "Incident energy", + "Heat", "Moisture (saturation)"}; + +void launcher(const PanelView& v, FormBuffers& form, PanelActions& a) { + const auto phase = v.launcher->phase(); + const auto& io = ImGui::GetIO(); + ImGui::SetNextWindowPos({io.DisplaySize.x * 0.5F, io.DisplaySize.y * 0.5F}, ImGuiCond_Always, + {0.5F, 0.5F}); + ImGui::SetNextWindowSize({520, 0}, ImGuiCond_Always); + ImGui::Begin("Aeternalis Evolution - engineering client", nullptr, + ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoCollapse); + ImGui::TextWrapped("Choose a data source. Nothing here is a game or a player account."); + ImGui::Separator(); + if (ImGui::Button("Local fixture", {160, 0})) + a.fixture = true; + ImGui::SameLine(); + ImGui::TextWrapped("In-memory stand-in: environment changes and static organisms. Not a " + "server, not an ecosystem, not authoritative."); + ImGui::Separator(); + ImGui::TextUnformatted("Connect to a dev region"); + ImGui::BeginDisabled(!v.remote_available || phase == LaunchPhase::connecting); + ImGui::InputText("Endpoint (host:port)", form.endpoint.data(), form.endpoint.size()); + ImGui::InputText("Server name", form.server_name.data(), form.server_name.size()); + ImGui::InputText("Dev CA file", form.authority.data(), form.authority.size()); + ImGui::InputText("Grant bundle file", form.grants.data(), form.grants.size()); + const bool start = phase == LaunchPhase::choosing && ImGui::Button("Connect", {160, 0}); + ImGui::EndDisabled(); + if (start) + a.connect = true; + if (!v.remote_available) + ImGui::TextColored(amber, "Remote mode needs a build with EVO_BUILD_NETWORK."); + if (v.form_error) + error_text(*v.form_error); + if (phase == LaunchPhase::connecting) { + ImGui::TextColored(amber, "Connecting (TLS handshake and grant check)..."); + if (ImGui::Button("Cancel", {120, 0})) + a.cancel = true; + } + if (phase == LaunchPhase::failed) { + error_text(v.launcher->error()); + if (ImGui::Button("Retry", {120, 0})) + a.retry = true; + ImGui::SameLine(); + if (ImGui::Button("Cancel", {120, 0})) + a.cancel = true; + } + ImGui::TextDisabled("Files are read when you connect; nothing is saved."); + ImGui::End(); +} + +void banner(const PanelView& v, PanelActions& a) { + const auto& io = ImGui::GetIO(); + ImGui::SetNextWindowPos({io.DisplaySize.x * 0.5F, 4}, ImGuiCond_Always, {0.5F, 0}); + ImGui::Begin("##mode", nullptr, + ImGuiWindowFlags_NoDecoration | ImGuiWindowFlags_AlwaysAutoResize | + ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoSavedSettings); + if (v.mode == Mode::fixture) { + ImGui::TextColored(amber, "LOCAL FIXTURE - in-memory stand-in, not authoritative"); + ImGui::SameLine(); + if (ImGui::SmallButton("Launcher")) + a.back = true; + } else { + ImGui::TextColored(v.remote && v.remote->phase == "connected" ? green : amber, + "DEV REGION - %s", v.remote ? v.remote->phase.c_str() : "?"); + ImGui::SameLine(); + if (ImGui::SmallButton("Disconnect")) + a.ask_disconnect = true; + } + ImGui::End(); +} + +void legend(const PanelView& v, render::EnvironmentDisplay& display) { + ImGui::SetNextWindowPos({8, 40}, ImGuiCond_FirstUseEver); + ImGui::SetNextWindowSize({300, 0}, ImGuiCond_FirstUseEver); + ImGui::Begin("Legend"); + int current = display.mode == render::EnvironmentDisplay::Mode::moisture + ? static_cast(world::field_count) + : static_cast(display.field); + if (ImGui::Combo("Layer", ¤t, layer_names.data(), static_cast(layer_names.size()))) { + display = current == static_cast(world::field_count) + ? render::EnvironmentDisplay{render::EnvironmentDisplay::Mode::moisture} + : render::EnvironmentDisplay{render::EnvironmentDisplay::Mode::field, + static_cast(current)}; + } + if (display.mode == render::EnvironmentDisplay::Mode::moisture) + ImGui::TextWrapped("Water saturation, linear from 0 %% (low) to 100 %% (high)."); + else + ImGui::TextWrapped("%s", client::density_scale(display.field).c_str()); + swatch("##low", render::ramp(0), "Present: low"); + ImGui::SameLine(); + swatch("##mid", render::ramp(0.5), "mid"); + ImGui::SameLine(); + swatch("##high", render::ramp(1), "high"); + swatch("##zero", render::palette::present_zero, "Present zero (black)"); + swatch("##missing", render::palette::missing_a, "Missing: checkerboard"); + swatch("##notreq", render::palette::not_requested, "Not requested: hollow outline"); + swatch("##undef", render::palette::undefined, "Undefined moisture (no capacity)"); + swatch("##stale", render::palette::stale_outline, "Stale: dimmed, amber outlines"); + ImGui::Separator(); + const auto env = v.environment ? v.environment->freshness() : client::Freshness::none; + const auto org = v.organisms ? v.organisms->freshness() : client::Freshness::none; + ImGui::TextColored(freshness_color(env), "Environment: %s", + std::string{client::freshness_name(env)}.c_str()); + ImGui::TextColored(freshness_color(org), "Organisms: %s", + std::string{client::freshness_name(org)}.c_str()); + if (v.mode == Mode::remote && v.organisms && v.organisms->current() && + v.organisms->current()->cells().empty()) + ImGui::TextWrapped("No individual organisms: this region reports pooled inventories only."); + if (v.mode == Mode::fixture) + ImGui::TextWrapped("Fixture organisms are static presentation data built from genomes."); + if (v.visible_organisms >= 0) + ImGui::Text("Organisms drawn: %d", v.visible_organisms); + disabled_wrapped("Click to select. Arrows pan, wheel zooms, WASD moves."); + ImGui::End(); +} + +void inspector(const PanelView& v) { + const auto& io = ImGui::GetIO(); + ImGui::SetNextWindowPos({io.DisplaySize.x - 8, 40}, ImGuiCond_FirstUseEver, {1, 0}); + ImGui::SetNextWindowSize({420, 0}, ImGuiCond_FirstUseEver); + ImGui::Begin("Inspector"); + const auto* env = v.environment ? v.environment->current() : nullptr; + const auto* orgs = v.organisms ? v.organisms->current() : nullptr; + const auto* organism = v.selection->organism(orgs); + const auto* cell = v.selection->cell(env); + if (organism == nullptr && cell == nullptr) { + ImGui::TextWrapped("Click an organism or habitat cell to inspect it."); + ImGui::End(); + return; + } + const auto freshness = organism ? v.organisms->freshness() : v.environment->freshness(); + if (freshness == client::Freshness::stale) + ImGui::TextColored(amber, "STALE: values are from an older revision."); + if (ImGui::BeginTable("rows", 3, ImGuiTableFlags_RowBg | ImGuiTableFlags_SizingFixedFit)) { + for (const auto& r : organism ? client::organism_rows(*organism) : client::cell_rows(*cell)) + row(r.label.c_str(), r.value, r.unit); + ImGui::EndTable(); + } + if (cell != nullptr && ImGui::BeginTable("fields", 2, ImGuiTableFlags_RowBg)) { + // Values wrap inside the column so missing/not-requested explanations stay readable. + ImGui::TableSetupColumn("field", ImGuiTableColumnFlags_WidthFixed, 150); + ImGui::TableSetupColumn("value", ImGuiTableColumnFlags_WidthStretch); + for (std::size_t k = 0; k < world::field_count; ++k) { + const auto field = static_cast(k); + const auto value = client::describe_field(*cell, field); + ImGui::TableNextRow(); + ImGui::TableNextColumn(); + ImGui::TextUnformatted(std::string{client::field_name(field)}.c_str()); + ImGui::TableNextColumn(); + const bool tinted = value.kind == client::ValueKind::missing || + value.kind == client::ValueKind::not_requested; + if (tinted) + ImGui::PushStyleColor(ImGuiCol_Text, + value.kind == client::ValueKind::missing + ? red + : ImGui::GetStyleColorVec4(ImGuiCol_TextDisabled)); + ImGui::TextWrapped("%s", value.text.c_str()); + if (tinted) + ImGui::PopStyleColor(); + } + const auto moisture = client::describe_moisture(*cell); + ImGui::TableNextRow(); + ImGui::TableNextColumn(); + ImGui::TextUnformatted("Moisture"); + ImGui::TableNextColumn(); + ImGui::TextWrapped("%s", moisture.text.c_str()); + ImGui::EndTable(); + } + ImGui::End(); +} + +void session(const PanelView& v) { + if (!v.remote) + return; + const auto& io = ImGui::GetIO(); + ImGui::SetNextWindowPos({8, io.DisplaySize.y - 8}, ImGuiCond_FirstUseEver, {0, 1}); + ImGui::SetNextWindowSize({360, 0}, ImGuiCond_FirstUseEver); + ImGui::Begin("Session"); + const auto& s = *v.remote; + if (ImGui::BeginTable("status", 3, ImGuiTableFlags_SizingFixedFit)) { + row("Connection", s.phase); + row("Session / epoch", std::to_string(s.session) + " / " + std::to_string(s.epoch)); + row("Server tick", std::to_string(s.server_tick)); + row("Durable watermark", std::to_string(s.commit_watermark)); + row("Grants left", std::to_string(s.grants_left)); + ImGui::EndTable(); + } + disabled_wrapped("Intentions (newest first; this is the record, toasts expire):"); + if (v.outcomes && + ImGui::BeginTable("outcomes", 3, ImGuiTableFlags_RowBg | ImGuiTableFlags_SizingFixedFit)) { + const auto& entries = v.outcomes->entries(); + int shown = 0; + for (auto it = entries.rbegin(); it != entries.rend() && shown < 10; ++it, ++shown) { + ImGui::TableNextRow(); + ImGui::TableNextColumn(); + ImGui::Text("#%llu", static_cast(it->sequence)); + ImGui::TableNextColumn(); + ImGui::TextUnformatted(outcome_name(it->state)); + ImGui::TableNextColumn(); + if (it->state == client::OutcomeState::durable) + ImGui::Text("tick %llu, commit %llu", static_cast(it->tick), + static_cast(it->commit_sequence)); + else if (it->state == client::OutcomeState::rejected) + ImGui::Text("status %u", static_cast(it->detail)); + } + ImGui::EndTable(); + } + ImGui::End(); +} + +void notices(const PanelView& v, PanelActions& a) { + const auto& io = ImGui::GetIO(); + float y = io.DisplaySize.y - 8; + for (const auto& n : v.ui->notices()) { + ImGui::SetNextWindowPos({io.DisplaySize.x - 8, y}, ImGuiCond_Always, {1, 1}); + ImGui::SetNextWindowSize({320, 0}, ImGuiCond_Always); + const std::string id = "##notice" + std::to_string(n.id); + ImGui::Begin(id.c_str(), nullptr, + ImGuiWindowFlags_NoDecoration | ImGuiWindowFlags_NoMove | + ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_NoFocusOnAppearing); + ImGui::TextColored(n.level == client::NoticeLevel::error ? red + : n.level == client::NoticeLevel::warning ? amber + : green, + "%s", n.text.c_str()); + ImGui::SameLine(); + if (ImGui::SmallButton(("x" + id).c_str())) + a.dismiss_notice = n.id; + y -= ImGui::GetWindowHeight() + 4; + ImGui::End(); + } + if (v.ui->evicted_notices() > 0) { + ImGui::SetNextWindowPos({io.DisplaySize.x - 8, y}, ImGuiCond_Always, {1, 1}); + ImGui::Begin("##evicted", nullptr, + ImGuiWindowFlags_NoDecoration | ImGuiWindowFlags_AlwaysAutoResize); + ImGui::TextDisabled("%llu older notices discarded", + static_cast(v.ui->evicted_notices())); + ImGui::End(); + } +} + +void dialog(const PanelView& v, PanelActions& a) { + const auto& d = v.ui->dialog(); + if (!d) + return; + const std::string id = d->title + "##dialog" + std::to_string(d->id); + ImGui::OpenPopup(id.c_str()); + if (ImGui::BeginPopupModal(id.c_str(), nullptr, ImGuiWindowFlags_AlwaysAutoResize)) { + ImGui::TextWrapped("%s", d->body.c_str()); + if (ImGui::Button("Confirm", {120, 0})) + a.confirm_dialog = d->id; + ImGui::SameLine(); + if (ImGui::Button("Cancel", {120, 0})) + a.cancel_dialog = d->id; + ImGui::EndPopup(); + } +} +} // namespace + +void FormBuffers::load(const client::ConnectForm& f) { + copy(endpoint, f.endpoint); + copy(server_name, f.server_name); + copy(authority, f.authority_path); + copy(grants, f.grants_path); +} + +client::ConnectForm FormBuffers::form() const { + return {text(endpoint), text(server_name), text(authority), text(grants)}; +} + +PanelActions draw_panels(const PanelView& view, FormBuffers& form, + render::EnvironmentDisplay& display) { + PanelActions actions; + if (view.mode == Mode::launcher) { + launcher(view, form, actions); + } else { + banner(view, actions); + legend(view, display); + inspector(view); + session(view); + } + notices(view, actions); + dialog(view, actions); + return actions; +} +} // namespace evo::client_app diff --git a/apps/evo-client/panels.hpp b/apps/evo-client/panels.hpp new file mode 100644 index 0000000..b280406 --- /dev/null +++ b/apps/evo-client/panels.hpp @@ -0,0 +1,45 @@ +#pragma once +// M9.8c engineering panels (ADR-0084). Drawn inside Application's overlay callback; +// they read presentation copies and report what the user asked for. Only this file +// pair and the platform adapter use the toolkit. +#include "evo/client/environment_view.hpp" +#include "evo/client/launcher.hpp" +#include "evo/client/organism_view.hpp" +#include "evo/client/outcome_log.hpp" +#include "evo/client/selection.hpp" +#include "evo/client/ui_state.hpp" +#include "evo/render/environment.hpp" +#include "remote_session.hpp" +#include +#include +#include + +namespace evo::client_app { +enum class Mode : std::uint8_t { launcher, fixture, remote }; +// Text-field storage for the connect form (bounded; never persisted). +struct FormBuffers { + std::array endpoint{}, server_name{}, authority{}, grants{}; + void load(const client::ConnectForm& form); + [[nodiscard]] client::ConnectForm form() const; +}; +struct PanelView { + Mode mode{Mode::launcher}; + const client::Launcher* launcher{}; + std::optional form_error; + bool remote_available{}; + const client::EnvironmentLayer* environment{}; + const client::OrganismLayer* organisms{}; + const client::Selection* selection{}; + const client::UiState* ui{}; + std::optional remote; + const client::OutcomeLog* outcomes{}; + int visible_organisms{-1}; // -1 when unknown. +}; +struct PanelActions { + bool fixture{}, connect{}, cancel{}, retry{}, back{}, ask_disconnect{}; + std::optional dismiss_notice, confirm_dialog, cancel_dialog; +}; +// Draws every panel for this frame. `display` may be changed by the layer selector. +[[nodiscard]] PanelActions draw_panels(const PanelView& view, FormBuffers& form, + render::EnvironmentDisplay& display); +} // namespace evo::client_app diff --git a/apps/evo-client/remote_session.hpp b/apps/evo-client/remote_session.hpp index 64b7456..e049c60 100644 --- a/apps/evo-client/remote_session.hpp +++ b/apps/evo-client/remote_session.hpp @@ -1,67 +1,46 @@ #pragma once -// M9.7 remote dev session for the engineering client (ADR-0083). Without -// EVO_CLIENT_NETWORK (a build without EVO_BUILD_NETWORK) remote options are refused. +// M9.7/M9.8c remote dev session for the engineering client (ADR-0083). Without +// EVO_CLIENT_NETWORK (a build without EVO_BUILD_NETWORK) remote mode is unavailable. // The client only presents copies and sends bounded intentions; it never predicts. +// Grant bytes stay inside the session client: never printed, shown or persisted. #include "evo/client/environment_view.hpp" #include "evo/client/input.hpp" +#include "evo/client/launcher.hpp" #include "evo/client/organism_view.hpp" -#include "evo/render/frame.hpp" +#include "evo/client/outcome_log.hpp" +#include "evo/client/ui_state.hpp" #include #include +#include +#include #include #include -#include #ifdef EVO_CLIENT_NETWORK #include "evo/network/session_client.hpp" -#include -#include -#include -#include -#include +#include #endif namespace evo::client_app { -struct RemoteOptions { - std::string connect, server_name, authority, grants; - [[nodiscard]] bool any() const noexcept { - return !connect.empty() || !server_name.empty() || !authority.empty() || !grants.empty(); - } - [[nodiscard]] bool complete() const noexcept { - return !connect.empty() && !server_name.empty() && !authority.empty() && !grants.empty(); - } +struct RemoteStatus { + std::string phase; // connecting / connected / reconnecting / out of grants + std::uint64_t session{}, epoch{}, server_tick{}, commit_watermark{}; + std::size_t grants_left{}; + bool welcomed{}; }; #ifdef EVO_CLIENT_NETWORK inline constexpr bool remote_available = true; +static_assert(std::is_same_v, + "the launcher's grant record is the session's grant"); class RemoteSession { public: - static std::optional open(const RemoteOptions& o) { - const auto colon = o.connect.rfind(':'); - unsigned port = 0; - if (colon == std::string::npos || colon == 0) - return std::nullopt; - const auto* digits = o.connect.data() + colon + 1; - const auto [end, error] = - std::from_chars(digits, o.connect.data() + o.connect.size(), port); - if (error != std::errc{} || end != o.connect.data() + o.connect.size() || port == 0 || - port > 65535) - return std::nullopt; - const auto bundle = read(o.grants); - if (bundle.empty() || bundle.size() % network::dev_grant_bytes != 0 || - bundle.size() / network::dev_grant_bytes > 64) - return std::nullopt; + static std::optional open(const client::ConnectMaterial& m) { network::SessionClientConfig config; - config.host = o.connect.substr(0, colon); - config.port = static_cast(port); - const auto pem = read(o.authority); - config.trust = {{pem.begin(), pem.end()}, o.server_name}; - for (std::size_t at = 0; at < bundle.size(); at += network::dev_grant_bytes) { - network::DevGrant grant{}; - std::copy_n(bundle.begin() + static_cast(at), grant.size(), - grant.begin()); - config.grants.push_back(grant); - } + config.host = m.endpoint.host; + config.port = m.endpoint.port; + config.trust = {m.authority_pem, m.server_name}; + config.grants = m.grants; auto made = network::SessionClient::create(std::move(config)); if (!made) return std::nullopt; @@ -75,9 +54,34 @@ class RemoteSession { [[nodiscard]] const client::OrganismLayer& organisms() const noexcept { return client_->organisms(); } - // Services the connection and sends the intention when its vector changed, at - // most once per received server tick (the server also rate-limits). - void step(std::chrono::steady_clock::time_point now, const client::Intention& intention) { + [[nodiscard]] const client::OutcomeLog& outcomes() const noexcept { + return log_; + } + [[nodiscard]] RemoteStatus status() const { + using network::SessionPhase; + RemoteStatus s; + const auto phase = client_->phase(); + s.phase = phase == SessionPhase::established ? "connected" + : phase == SessionPhase::exhausted ? "out of grants" + : welcomed_ ? "reconnecting" + : "connecting"; + if (const auto w = client_->welcome()) { + s.session = w->session; + s.epoch = w->epoch; + } + if (const auto v = client_->latest_view()) { + s.server_tick = v->server_tick; + s.commit_watermark = v->commit_watermark; + } + s.grants_left = client_->grants_left(); + s.welcomed = welcomed_; + return s; + } + // Services the connection; sends the intention when its vector changed, at most once + // per received server tick (the server also rate-limits). Session events update the + // outcome log (the durable record), short notifications and the launcher. + void step(std::chrono::steady_clock::time_point now, const client::Intention& intention, + client::UiState& ui, client::Launcher& launcher) { client_->poll(now); const auto view = client_->latest_view(); const bool changed = intention.move_x != sent_x_ || intention.move_y != sent_y_; @@ -86,55 +90,70 @@ class RemoteSession { sent_x_ = intention.move_x; sent_y_ = intention.move_y; sent_tick_ = view->server_tick; + log_.record({intention.sequence, client::OutcomeState::sent}); } for (const auto& e : client_->take_events()) - report(e); - } - // Connection chip and last-intention chip, below the capture bar. - void status(std::vector& out) const { - using network::SessionPhase; - const auto phase = client_->phase(); - const render::Color connection = - phase == SessionPhase::established ? render::Color{64, 180, 140, 255} - : phase == SessionPhase::exhausted ? render::Color{200, 40, 40, 255} - : render::Color{240, 170, 40, 255}; - out.push_back({8, 72, 28, 6, connection}); - out.push_back({40, 72, 6, 6, intent_}); + report(e, ui, launcher); + // Refused TCP or failed TLS produce no event; each still counts toward the + // launcher's bounded "server unreachable" before a first Welcome. + for (; unreachable_ < client_->unreachable_attempts(); ++unreachable_) + launcher.observe(client::ConnectSignal::lost); } private: - static std::vector read(const std::string& path) { - std::ifstream file{path, std::ios::binary}; - return {std::istreambuf_iterator{file}, std::istreambuf_iterator{}}; + static void notify(client::UiState& ui, const char* text, client::NoticeLevel level) { + static_cast(ui.notify(text, level).has_value()); // Bounded; overflow evicts. } - void report(const network::ClientEvent& e) { + void report(const network::ClientEvent& e, client::UiState& ui, client::Launcher& launcher) { using Kind = network::ClientEvent::Kind; - constexpr render::Color pending{240, 240, 240, 255}, durable{64, 180, 140, 255}, - refused{200, 40, 40, 255}, unknown{130, 130, 130, 255}; + using network::CloseReason; switch (e.kind) { case Kind::welcome: + welcomed_ = true; sent_tick_.reset(); // New session: resend the current intention. sent_x_ = sent_y_ = 0; + launcher.observe(client::ConnectSignal::welcome); + notify(ui, "Connected to the dev region (fresh baseline).", client::NoticeLevel::info); std::printf("session welcome session=%llu epoch=%llu tick=%llu commit=%llu\n", static_cast(e.welcome.session), static_cast(e.welcome.epoch), static_cast(e.welcome.server_tick), static_cast(e.welcome.commit_watermark)); break; - case Kind::closed: + case Kind::closed: { + const bool retry = + e.reason == CloseReason::server_shutdown || e.reason == CloseReason::capacity; + const bool lost = e.reason == CloseReason::timeout || + e.reason == CloseReason::stale_epoch || + e.reason == CloseReason::rate_limited; + launcher.observe(retry ? client::ConnectSignal::not_ready + : lost ? client::ConnectSignal::lost + : client::ConnectSignal::refused); + notify(ui, retry ? "Server not ready; retrying." : "Session closed by the server.", + retry ? client::NoticeLevel::info : client::NoticeLevel::warning); std::printf("session closed reason=%u\n", static_cast(e.reason)); break; + } case Kind::lost: + launcher.observe(client::ConnectSignal::lost); + notify(ui, "Connection lost; views are stale.", client::NoticeLevel::warning); std::puts("session lost (reconnecting with a fresh grant)"); break; case Kind::result: - intent_ = e.result.status == network::IntentStatus::admitted ? pending : refused; + log_.record({e.sequence, + e.result.status == network::IntentStatus::admitted + ? client::OutcomeState::admitted + : client::OutcomeState::rejected, + static_cast(e.result.status)}); std::printf("intent %llu status=%u\n", static_cast(e.sequence), static_cast(e.result.status)); break; case Kind::outcome: - intent_ = e.outcome.finality == network::IntentFinality::committed_no_effect ? durable - : refused; + log_.record({e.sequence, + e.outcome.finality == network::IntentFinality::committed_no_effect + ? client::OutcomeState::durable + : client::OutcomeState::not_committed, + 0, e.outcome.tick, e.outcome.commit_sequence}); std::printf("intent %llu final=%u tick=%llu commit=%llu\n", static_cast(e.sequence), static_cast(e.outcome.finality), @@ -142,29 +161,34 @@ class RemoteSession { static_cast(e.outcome.commit_sequence)); break; case Kind::unknown: - intent_ = unknown; + log_.record({e.sequence, client::OutcomeState::unknown}); std::printf("intent %llu outcome unknown (connection lost)\n", static_cast(e.sequence)); break; case Kind::backpressure: + notify(ui, "Session event backlog; reconnecting after draining.", + client::NoticeLevel::warning); std::puts("session event backlog: disconnected; draining before reconnect"); break; case Kind::exhausted: + launcher.observe(client::ConnectSignal::exhausted); std::puts("session grants exhausted; issue a new bundle to reconnect"); break; } std::fflush(stdout); } std::unique_ptr client_; + client::OutcomeLog log_; std::optional sent_tick_; + std::uint64_t unreachable_{}; std::int16_t sent_x_{}, sent_y_{}; - render::Color intent_{60, 60, 66, 255}; + bool welcomed_{}; }; #else inline constexpr bool remote_available = false; class RemoteSession { public: - static std::optional open(const RemoteOptions&) { + static std::optional open(const client::ConnectMaterial&) { return std::nullopt; } [[nodiscard]] const client::EnvironmentLayer& environment() const noexcept { @@ -173,12 +197,19 @@ class RemoteSession { [[nodiscard]] const client::OrganismLayer& organisms() const noexcept { return organisms_; } - void step(std::chrono::steady_clock::time_point, const client::Intention&) {} - void status(std::vector&) const {} + [[nodiscard]] const client::OutcomeLog& outcomes() const noexcept { + return log_; + } + [[nodiscard]] RemoteStatus status() const { + return {"unavailable in this build"}; + } + void step(std::chrono::steady_clock::time_point, const client::Intention&, client::UiState&, + client::Launcher&) {} private: client::EnvironmentLayer environment_; client::OrganismLayer organisms_; + client::OutcomeLog log_; }; #endif } // namespace evo::client_app diff --git a/cmake/ClientProbe.cmake b/cmake/ClientProbe.cmake index 332655d..8f6ca27 100644 --- a/cmake/ClientProbe.cmake +++ b/cmake/ClientProbe.cmake @@ -46,6 +46,8 @@ if(EVO_BUILD_CLIENT_PROBE) endif() if(EVO_BUILD_CLIENT) + # M9.8c: the engineering client draws its UI with the pinned toolkit (ADR-0084). + include("${PROJECT_SOURCE_DIR}/cmake/EngineeringUi.cmake") add_library(evo_render_frame STATIC src/render/frame.cpp) target_include_directories(evo_render_frame PUBLIC "${PROJECT_SOURCE_DIR}/include") evo_owned_target(evo_render_frame) @@ -56,15 +58,16 @@ if(EVO_BUILD_CLIENT) add_library(evo_render_organism STATIC src/render/organism/organism.cpp) target_link_libraries(evo_render_organism PUBLIC evo_render_environment) evo_owned_target(evo_render_organism) - add_library(evo_client_ui STATIC src/client/ui/organism_inspector.cpp) + add_library(evo_client_ui STATIC src/client/ui/organism_inspector.cpp src/client/ui/labels.cpp + src/client/ui/selection.cpp src/client/ui/launcher.cpp) target_link_libraries(evo_client_ui PUBLIC evo_render_organism) evo_owned_target(evo_client_ui) add_library(evo_client_platform STATIC src/client/platform/application.cpp src/render/sdl_renderer.cpp) target_include_directories(evo_client_platform PRIVATE "${PROJECT_SOURCE_DIR}/src") - target_link_libraries(evo_client_platform PUBLIC evo_render_frame evo_client_controls PRIVATE SDL3::SDL3) + target_link_libraries(evo_client_platform PUBLIC evo_render_frame evo_client_controls PRIVATE SDL3::SDL3 evo_imgui) evo_owned_target(evo_client_platform) - add_executable(evo-client apps/evo-client/main.cpp) - target_link_libraries(evo-client PRIVATE evo_client_platform evo_client_ui) + add_executable(evo-client apps/evo-client/main.cpp apps/evo-client/panels.cpp) + target_link_libraries(evo-client PRIVATE evo_client_platform evo_client_ui evo_imgui) if(EVO_BUILD_NETWORK) # M9.7 remote dev session mode (ADR-0083). target_link_libraries(evo-client PRIVATE evo_network_session) @@ -75,7 +78,7 @@ if(EVO_BUILD_CLIENT) if(BUILD_TESTING) add_executable(evo-client-lifecycle-tests tests/client_lifecycle.cpp tests/client_controls.cpp) target_include_directories(evo-client-lifecycle-tests PRIVATE "${PROJECT_SOURCE_DIR}/src") - target_link_libraries(evo-client-lifecycle-tests PRIVATE evo_client_platform SDL3::SDL3) + target_link_libraries(evo-client-lifecycle-tests PRIVATE evo_client_platform SDL3::SDL3 evo_imgui) evo_owned_target(evo-client-lifecycle-tests) evo_client_runtime(evo-client-lifecycle-tests) add_executable(evo-client-environment-tests tests/client_environment.cpp) @@ -86,6 +89,11 @@ if(EVO_BUILD_CLIENT) target_link_libraries(evo-client-organism-tests PRIVATE evo_client_ui) evo_owned_target(evo-client-organism-tests) add_test(NAME client-organisms COMMAND evo-client-organism-tests) + add_executable(evo-client-ui-model-tests tests/client_ui_model.cpp) + target_link_libraries(evo-client-ui-model-tests PRIVATE evo_client_ui) + evo_owned_target(evo-client-ui-model-tests) + add_test(NAME client-ui-model COMMAND evo-client-ui-model-tests) + set_tests_properties(client-ui-model PROPERTIES TIMEOUT 60 LABELS "client") set_tests_properties(client-organisms PROPERTIES TIMEOUT 60 LABELS "client") set_tests_properties(client-environment PROPERTIES TIMEOUT 60 LABELS "client") add_test(NAME client-lifecycle COMMAND evo-client-lifecycle-tests) diff --git a/cmake/EngineeringUi.cmake b/cmake/EngineeringUi.cmake index de5b6e2..251c0a3 100644 --- a/cmake/EngineeringUi.cmake +++ b/cmake/EngineeringUi.cmake @@ -1,4 +1,5 @@ # Scoped toolkit target. No toolkit types leave the private native client boundary. +include_guard(GLOBAL) include("${PROJECT_SOURCE_DIR}/tools/imgui-pin.cmake") set(imgui_source "${PROJECT_SOURCE_DIR}/build/external/imgui/imgui-${EVO_IMGUI_VERSION}") if(NOT EXISTS "${imgui_source}/evo-verified.sha256") diff --git a/deploy/docker/Dockerfile b/deploy/docker/Dockerfile index 4deb4a6..289dfa0 100644 --- a/deploy/docker/Dockerfile +++ b/deploy/docker/Dockerfile @@ -43,13 +43,13 @@ RUN cmake -P tools/prepare-sdl3.cmake \ && cmake -P tools/prepare-imgui.cmake \ && cmake --preset client-probe -DCMAKE_CXX_COMPILER=clang++-19 -DCMAKE_C_COMPILER=clang-19 \ -DEVO_BUILD_CLIENT=ON -DEVO_BUILD_UI_PROBE=ON -DEVO_ENABLE_TIDY=ON -DSDL_X11=ON -DSDL_WAYLAND=OFF \ - && cmake --build build/client-probe --target evo-client-state-tests evo-ui-probe evo-client-probe evo-client evo-client-lifecycle-tests evo-client-environment-tests evo-client-organism-tests --parallel 2 \ + && cmake --build build/client-probe --target evo-client-state-tests evo-ui-probe evo-client-probe evo-client evo-client-lifecycle-tests evo-client-environment-tests evo-client-organism-tests evo-client-ui-model-tests --parallel 2 \ && ctest --preset client-probe --no-tests=error \ && xvfb-run -a env SDL_VIDEO_DRIVER=x11 ./build/client-probe/evo-client-probe --renderer software \ && xvfb-run -a env SDL_VIDEO_DRIVER=x11 ./build/client-probe/evo-ui-probe --renderer software \ && xvfb-run -a env SDL_VIDEO_DRIVER=x11 ./build/client-probe/evo-client-lifecycle-tests \ && cmake --preset client-probe -DEVO_BUILD_CLIENT=ON -DEVO_SANITIZER=address -DEVO_ENABLE_TIDY=OFF \ - && cmake --build build/client-probe --target evo-client-state-tests evo-ui-probe evo-client evo-client-lifecycle-tests evo-client-environment-tests evo-client-organism-tests --parallel 2 \ + && cmake --build build/client-probe --target evo-client-state-tests evo-ui-probe evo-client evo-client-lifecycle-tests evo-client-environment-tests evo-client-organism-tests evo-client-ui-model-tests --parallel 2 \ && ctest --preset client-probe --no-tests=error \ && xvfb-run -a env SDL_VIDEO_DRIVER=x11 ./build/client-probe/evo-ui-probe --renderer software \ && xvfb-run -a env SDL_VIDEO_DRIVER=x11 ./build/client-probe/evo-client-lifecycle-tests diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md index 2e7303f..141c9da 100644 --- a/docs/ROADMAP.md +++ b/docs/ROADMAP.md @@ -456,8 +456,8 @@ terrain meshing or procedural creature animation is required. **M9.8a (2026-10-02):** isolated Dear ImGui 1.92.9b probe qualified on Windows/Linux; M9.8b adds bounded UI state, protected external input capture and bounded session -event delivery. Launcher and visible widget integration remain M9.8c. ADR-0084 -records both scopes. +event delivery. M9.8c integrates the launcher, legend, labelled inspector, click +selection and session panel. ADR-0084 records each scope. **M9.8 planning (2026-10-02):** user-confirmed Windows ZIP, temporary Gitea Actions artifacts, labelled engineering UI/launcher and control rebinding. See the diff --git a/docs/STATUS.md b/docs/STATUS.md index ad31cac..e619017 100644 --- a/docs/STATUS.md +++ b/docs/STATUS.md @@ -5,11 +5,13 @@ M9.8a: Dear ImGui 1.92.9b is pinned and qualified in an isolated Windows/Linux SDL3 probe (ADR-0084). M9.8b adds bounded notification/dialog state, protected external input capture and bounded session events with disconnect/drain/reconnect -backpressure. Tests and limits are recorded in engineering/VALIDATION.md. +backpressure. M9.8c adds the launcher (labelled local fixture vs dev region, +bounded errors, Retry/Cancel), legend, labelled inspector, click selection, session +panel with the intention outcome record, and visible notifications/dialog. Tests, +visual review and limits are recorded in engineering/VALIDATION.md. -Next: M9.8c launcher, visible dialogs/toasts, labelled views and click selection. -The client still displays the prior rectangle UI. Windows packages will be built -locally until a Windows runner exists. Testing is internal; 172.10.1.160 is the +Next: M9.8d rebindable controls, then packaging and qualification (9.8e-g). +Windows packages will be built locally until a Windows runner exists. Testing is internal; 172.10.1.160 is the RKE2 control-plane address. VM qualification and the cluster restart drill remain outstanding, as agreed. See engineering/M9_8_DELIVERY_PLAN.md. diff --git a/docs/adr/0081-organism-presentation.md b/docs/adr/0081-organism-presentation.md index d042a02..934f508 100644 --- a/docs/adr/0081-organism-presentation.md +++ b/docs/adr/0081-organism-presentation.md @@ -35,7 +35,9 @@ marker appears beside the organism freshness chip. Order is id order. The engineering inspector (include/evo/client/organism_inspector.hpp, src/client/ui) picks the topmost organism under the pointer using the same drawn bounds, and draws a highlight plus ten normalized phenotype gauges. It shows biology values -only; there is nothing else to show. It is opt-in (`--inspect`). +only; there is nothing else to show. It was opt-in (`--inspect`); M9.8c replaces it in +the app with the labelled toolkit Inspector (ADR-0084) using the same picking rule. +The gauge API remains a tested library component. ImGui remains optional and is **not adopted**: rectangles suffice for gauges, and a UI library would need its own dependency ADR, text/font handling and input diff --git a/docs/adr/0084-engineering-ui-toolkit.md b/docs/adr/0084-engineering-ui-toolkit.md index cf7d2d4..f59dabc 100644 --- a/docs/adr/0084-engineering-ui-toolkit.md +++ b/docs/adr/0084-engineering-ui-toolkit.md @@ -92,3 +92,18 @@ SessionClient's local event delivery is capped at 1024, reserving room for all 2 unresolved intentions plus loss/backpressure events. On backlog it disconnects, marks views stale and waits for the consumer to drain before reconnecting. Earlier queued outcomes are preserved. This changes no wire format or biological rules. + +## M9.8c integration +Accepted for the engineering client. The toolkit context is owned by the platform +`Application` (created after and destroyed before the SDL renderer, reattached on +device reset), with ini/log files disabled and the embedded bitmap font. Toolkit +events are routed before world input; `WantCaptureKeyboard`/`WantCaptureMouse` +feed the same capture path as external capture, so typing in a field or clicking +a panel never moves, pans, zooms or selects. Only the app's panels file draws +widgets; launcher/selection/label/outcome-log state stays toolkit-independent and +tested without SDL. Remote failures are reported through fixed launcher text; no +path, certificate or grant byte is displayed, logged or saved. + +`SessionClient::unreachable_attempts()` (additive API) counts connection attempts +that fail before any session event, so the launcher bounds "unreachable" without +an event per retry. No wire format, grant or biological rule changes. diff --git a/docs/architecture/CLIENT_ARCHITECTURE.md b/docs/architecture/CLIENT_ARCHITECTURE.md index 5f6543a..a0919b2 100644 --- a/docs/architecture/CLIENT_ARCHITECTURE.md +++ b/docs/architecture/CLIENT_ARCHITECTURE.md @@ -67,7 +67,8 @@ adds `client/organism_view.hpp`, `render/organism.hpp` and the engineering `client/organism_inspector.hpp`. Organism cells carry phenotype, growth, position and alive/dead only; no controller, owner or level field exists, so players and NPCs share one presentation. Rendering takes an explicit rectangle budget and -reports truncation; the inspector draws biology gauges only. ImGui is not adopted. +reports truncation; the inspector draws biology gauges only. (M9.8c replaces it in +the app with the labelled toolkit Inspector; see below.) M9.7 (ADR-0083): in remote mode the layers are owned by `network::SessionClient`, filled only from server views; on loss they stay visible but stale, and every new @@ -84,4 +85,10 @@ and one modal, independent of toolkit/render/simulation types. The native adapte protects externally requested capture from the legacy Tab shortcut. Session event backpressure preserves queued events, disconnects and resolves remaining local uncertainty as unknown, then waits for draining before reconnecting. This is not -a durable outcome-history database. The launcher/visible widgets follow in M9.8c. +a durable outcome-history database. + +M9.8c (ADR-0084) adds toolkit-independent launcher, selection, label and outcome-log +models in `src/client/ui`. Dear ImGui is confined to the platform adapter (overlay +callback, event routing first, capture flags) and `apps/evo-client/panels.cpp`; +library headers expose no toolkit type. Panels read presentation copies only and +return requested actions; the app owns sessions, fixture and selection. diff --git a/docs/engineering/CLIENT.md b/docs/engineering/CLIENT.md index 033f135..2b494a5 100644 --- a/docs/engineering/CLIENT.md +++ b/docs/engineering/CLIENT.md @@ -1,18 +1,29 @@ -# Native engineering client (M9.2–M9.7) +# Native engineering client (M9.2–M9.8c) This opens a resizable native window showing camera-controlled environment habitats -and biology-derived organisms (M9.5) from a local in-memory fixture authority. -It does not run an ecosystem, -connect to a server or implement cellular gameplay. +and organisms either from a local in-memory fixture authority or from one dev +region over an authenticated dev session. It does not run an ecosystem locally, +predict remote state or implement cellular gameplay. Contract: [client architecture](../architecture/CLIENT_ARCHITECTURE.md), ADR-0078. Camera/input: [contracts and limits](CAMERA_INPUT.md), ADR-0079. Environment: [presentation and encodings](ENVIRONMENT_RENDERING.md), ADR-0080. Organisms/inspector: [encodings and budget](ORGANISM_RENDERING.md), ADR-0081. Remote dev region: [operations](../networking/DEV_SESSION_OPERATIONS.md), ADR-0083. -`--connect HOST:PORT --server-name NAME --ca FILE --grants FILE` (preset -`client-network`) replaces the local fixture with a dev session: views come from the -region, WASD sends intentions, and chips at y=72 show the connection (green/amber/red) -and the last intention (white admitted, green durable, red rejected, grey unknown). +Engineering panels and launcher: [UI state](CLIENT_UI_STATE.md), ADR-0084. + +Without arguments a launcher opens. **Local fixture** is labelled as an in-memory +stand-in, never as a server or ecosystem. **Connect** (preset `client-network`) +reads the endpoint, server name, dev CA file and grant bundle file when pressed; +nothing is saved and no path, certificate or grant byte is shown or logged. Errors +use fixed wording. A connection with no Welcome after three failed attempts +(refused, TLS failure or timeout) or a refused grant fails with Retry/Cancel. +`--fixture` or `--connect HOST:PORT --server-name NAME --ca FILE --grants FILE` +skip the launcher (an unreadable file then exits 1). While running, a banner names +the mode (LOCAL FIXTURE or DEV REGION with its phase); Disconnect asks for +confirmation. The Session panel shows session/epoch, server tick, durable +watermark, grants left and the last ten intentions with their outcome (sent, +admitted, rejected, durable, not committed, unknown). That list is the record; +short notifications expire and can be dismissed. ## Build and run @@ -36,18 +47,24 @@ one explicit backend, without fallback. `--frames N` exits after N bounded steps window and pauses drawing. These options permit unattended smoke checks. `--layer NAME` selects the displayed field or `moisture`; `--refresh-every N` (1..1000 fixture authority ticks) delays view refresh so the stale state is visible. -`--inspect` shows biology gauges for the organism under the pointer. +`--pick X,Y` performs one scripted world click at window coordinates and +`--screenshot FILE.bmp` (requires `--frames`) saves the last frame; both exist for +unattended visual review. Usage errors exit 2, lifecycle/fixture failures exit 1, orderly exit returns 0. Engineering controls: arrow keys pan, mouse wheel zooms around the pointer, WASD -updates the small intention indicator without moving the world fixture. Tab -toggles UI capture: the top-left bar turns orange and navigation/movement input -is suppressed. Leaving capture/focus loss requires fresh presses. This is a -focus exercise, not the final player UI. The host's input tick is a local fixture -counter and is never interpreted as authoritative server time. The top-right -chips show environment then organism freshness (green current, amber stale, red -none; magenta marker: organisms truncated); the bottom-left legend shows the ramp. -The organism cluster is near (410 mm, 480 mm); zoom in with the wheel to see it. +updates the small intention indicator (sent as intentions in remote mode). A left +click without dragging selects the topmost organism, else the habitat cell, for the +Inspector; a click that lands on a panel or dismisses a notification never selects +through it. Toolkit events are processed first: while a text field is focused or +the pointer is over a panel, keys/wheel/clicks do not reach the world. Tab toggles +UI capture: the bottom-left bar turns orange and navigation/movement input is +suppressed. Leaving capture/focus loss requires fresh presses. The host's input +tick is a local fixture counter and is never interpreted as authoritative server +time. The top-right chips show environment then organism freshness (green current, +amber stale, red none; magenta marker: organisms truncated); the Legend panel +explains the layer scale and missing/zero/not-requested/stale encodings. +The fixture organism cluster is near (410 mm, 480 mm); zoom in to see it. For native X11 regression on a CI host: diff --git a/docs/engineering/CLIENT_UI_STATE.md b/docs/engineering/CLIENT_UI_STATE.md index e2c51cc..52c523e 100644 --- a/docs/engineering/CLIENT_UI_STATE.md +++ b/docs/engineering/CLIENT_UI_STATE.md @@ -1,4 +1,4 @@ -# M9.8b UI state and event bounds +# M9.8b/c UI state, launcher and event bounds Owned, toolkit-independent state; all calls on the client main thread. No authority or simulation state. Time is explicit monotonic milliseconds supplied by the host. @@ -18,5 +18,35 @@ Unprocessed wire outcomes remain unknown, never assumed failed or committed. The native adapter's externally requested capture cannot be disabled by the legacy Tab toggle. Releasing capture drains already queued input before new world actions. -Rendering dialogs/toasts and wiring toolkit capture occur with the launcher in -M9.8c; these contracts and their tests precede that integration. +M9.8c renders these through the toolkit overlay (below). + +## M9.8c launcher, selection and panels + +Toolkit-independent models (src/client/ui, tested by `client-ui-model`): + +- **Launcher** (`launcher.hpp`): phases choosing, fixture, connecting, connected, + failed. Fields are at most 1024 bytes; endpoint is `host:port` with port 1-65535. + Files are read only when Connect is pressed: the CA at most 64 KiB and PEM-shaped, + the grant bundle 1-64 whole 108-byte records. Nothing is persisted; material lives + only in the session client. Errors are an enum with fixed text that never contains + paths or file bytes. Before the first Welcome, three losses (including refused + TCP/TLS attempts, counted by `SessionClient::unreachable_attempts()`) fail as + unreachable; a refused grant or exhausted bundle fails at once. Failed offers + Retry/Cancel; Cancel drops the session (its unresolved intentions become unknown). +- **Selection** (`selection.hpp`): topmost organism under the click, else the + habitat cell, else none. A selected organism absent from the latest view is + cleared; with no view at all the selection is kept but shows nothing. +- **Labels** (`labels.hpp`): value, present zero, missing (requested, no value), not + requested and undefined moisture are distinct kinds and texts. Freshness is + printed as current, stale or none. +- **Outcome log** (`outcome_log.hpp`): last 64 intentions by sequence with sent, + admitted, rejected, durable, not committed or unknown. It is the visible record; + notifications are not. + +Native adapter (`Application`): toolkit events are processed first; while the +toolkit wants the keyboard or pointer, keys, wheel and clicks do not reach world +input. A click is a left press and release within 4 pixels that began outside any +panel. Capture changes from toolkit focus release world actions and require fresh +presses; the Tab toggle keeps its earlier ordering. The overlay callback runs after +world drawing; `request_screenshot` saves the next frame as BMP (engineering review). +Toolkit settings files and logs are disabled (`IniFilename`/`LogFilename` null). diff --git a/docs/engineering/M9_8_DELIVERY_PLAN.md b/docs/engineering/M9_8_DELIVERY_PLAN.md index 10315e4..6e8bd91 100644 --- a/docs/engineering/M9_8_DELIVERY_PLAN.md +++ b/docs/engineering/M9_8_DELIVERY_PLAN.md @@ -1,7 +1,8 @@ # M9.8 delivery plan -Status: M9.8a probe and M9.8b owned state/capture/event bounds complete, 2026-10-02; -remaining segments planned. +Status: M9.8a probe, M9.8b owned state/capture/event bounds and M9.8c launcher, +legend, labelled inspector and click selection complete, 2026-10-02; remaining +segments planned. No application UI or deployment completion is claimed. See ADR-0084 for the toolkit boundary. ## Confirmed scope diff --git a/docs/engineering/ORGANISM_RENDERING.md b/docs/engineering/ORGANISM_RENDERING.md index b68a479..36e6306 100644 --- a/docs/engineering/ORGANISM_RENDERING.md +++ b/docs/engineering/ORGANISM_RENDERING.md @@ -59,18 +59,22 @@ marker left of it means organisms were not drawn because of the frame budget. marker). If every visible organism fits at 10 rectangles, full detail is used; otherwise each visible organism is a single body; beyond the budget, organisms are counted as visible but not drawn and the marker appears. The engineering app -budgets 4096 - 2313 (environment) - 25 (inspector) - 5 (host UI) = 1753, so 1024 -organisms always fit as bodies. No textures, caches or history are kept. +budgets 4096 - 2313 (environment) - 6 (host UI: capture bar, intention dot and a +four-sided selection outline) = 1777, so 1024 organisms always fit as bodies. No textures, caches or history are kept. ## Engineering inspector -`--inspect` enables hover inspection: the topmost organism whose drawn (floored) -box contains the pointer gets a white highlight, and a bottom-right panel shows -ten gauges in order: extent (log10 over 3 decades um), total mass (12 decades fg), -membrane share, maintenance (12 decades pJ/tick), movement speed (5 decades), -ingestion rate (6 decades), conversion, realized growth, damage, thermal shortfall -(5 decades mK). The panel darkens to brown for remnants. Rectangles only: there is -no text, ImGui or input capture; this is engineering UI, not player UI. +M9.8c: a non-drag left click selects the topmost organism whose drawn (floored) +box contains the point, else the habitat cell (include/evo/client/selection.hpp). +The selection gets a white outline and the toolkit Inspector shows labelled rows +with units (include/evo/client/labels.hpp): state, voxel, offset, extent, masses, +surface, maintenance, movement, ingestion, conversion, growth, damage and thermal +shortfall. The organism id is never shown. A selection whose organism disappears +from the latest view is cleared; while no view exists it is kept. Habitat cells +list every field as a value, present zero, MISSING (requested, no value) or not +requested, and moisture as undefined when there is no capacity. The previous +rectangle gauge inspector (`--inspect`) remains a tested library component but is +no longer wired into the app. This is engineering UI, not player UI. ## Fixture population diff --git a/docs/engineering/VALIDATION.md b/docs/engineering/VALIDATION.md index 6c9f34f..d5f8e46 100644 --- a/docs/engineering/VALIDATION.md +++ b/docs/engineering/VALIDATION.md @@ -3670,3 +3670,48 @@ Final additional checks: Linux GCC state/network/lifecycle 3/3; Clang ASan/UBSan native lifecycle 1/1; clang-tidy19 on owned state/session implementation, state/network tests and native adapter/lifecycle tests passed with no owned diagnostics. Final changed-file formatting passed. + + +## 2026-10-02 — M9.8c launcher, legend, labelled inspector and click selection + +Implemented toolkit-independent launcher, selection, label and outcome-log models +(src/client/ui) and the toolkit overlay in the native adapter (events routed to the +toolkit first; its keyboard/pointer capture suppresses world keys, wheel and clicks). +The app panels show a labelled local fixture vs dev region, legend, inspector, +session status with the last ten intention outcomes, notifications and a disconnect +dialog. `--inspect` is replaced by click selection; `--pick`/`--screenshot` support +unattended review. Added `SessionClient::unreachable_attempts()` (additive). + +Tests: `client-ui-model` (endpoint/field bounds, file size/shape limits, fixed error +text without paths, launcher phases incl. cancel/retry, three-loss bound, refused +grant, exhausted bundle; selection topmost/cell/none, disappearance clears, missing +view keeps; value/zero/missing/not-requested/undefined distinct; outcome log bounds). +Lifecycle `toolkit_capture`: widget click is not a world click, drag is not a click, +focused text field captures keys, release needs fresh presses, screenshot hook. +Network `unreachable_server`: refused connects emit no events, spend no grant, count. + +Executed: Windows MSVC `client` 7/7, `network` 1/1, `client-network` 8/8 (final run +after all fixes). Linux: clang-19 client-probe with clang-tidy enabled (keep-going +build of all client targets, no owned diagnostics after fixes) and CTest 11/11; +Xvfb/X11 lifecycle, fixture (`--pick`) and launcher runs; Clang ASan/UBSan client +CTest 11/11, Xvfb lifecycle and fixture; GCC 14 client-network build and client|network +CTest 8/8; Clang ASan/UBSan network tests; clang-tidy on session client, network tests, +app main/panels (client-network); repository format check. + +Visual review (dummy driver, software renderer, BMP screenshots): launcher; fixture +with organism selected; fixture cell on the nitrogen layer (missing, present zero and +not-requested rows distinct); connect to a closed port; live dev region (WSL +development-v1 server via the M9.7 rehearsal script) with the cell inspector and +Session panel. Review found and fixed: inspector values clipped (now wrapped), +legend hint clipped, launcher error line overflow, Session table column mismatch, +and a closed port staying "Connecting" indefinitely because pre-session failures +produced no event (now bounded via the new counter; observed failing with Retry/ +Cancel). Windows reports a refused loopback connect after about two seconds. +Static tidy findings fixed: implicit widening in a lifecycle test, by-value lambda +parameter in the UI-model test. + +Limits: no manual interactive session with physical mouse/keyboard, DPI matrix, +screen reader or accessibility review; the remote review used one connect without +WASD intentions, so the outcome list was empty in the screenshot (outcome states are +covered by unit tests). No Docker/Gitea run, packaging, deployment or cluster test. +No simulation version, wire format or golden changed. diff --git a/include/evo/client/application.hpp b/include/evo/client/application.hpp index 38c89e7..b056477 100644 --- a/include/evo/client/application.hpp +++ b/include/evo/client/application.hpp @@ -3,6 +3,7 @@ #include "evo/render/frame.hpp" #include #include +#include #include #include @@ -32,6 +33,10 @@ struct WindowState { logical_height > 0 && pixel_width > 0 && pixel_height > 0; } }; +// Engineering UI callback, run once per rendered frame on the main thread after the +// immutable frame is drawn. It may call the private toolkit (ADR-0084); no toolkit +// type appears in this header. +using Overlay = std::function; // One owner, process main thread only (including destruction). No SDL owner may coexist. class Application { public: @@ -46,6 +51,11 @@ class Application { // External modal/widget capture cannot be disabled by the legacy Tab toggle. void set_ui_capture(bool captured) noexcept; [[nodiscard]] bool ui_captured() const noexcept; + void set_overlay(Overlay overlay); + // The toolkit held the pointer during the last poll (no world click, pan or zoom). + [[nodiscard]] bool ui_wants_pointer() const noexcept; + // Engineering visual review: the next rendered frame is saved as a BMP file. + [[nodiscard]] bool request_screenshot(std::string path); [[nodiscard]] Navigation take_navigation() noexcept; [[nodiscard]] std::expected sample_intention(std::uint64_t tick); // Borrows the immutable frame for this call only. Errors latch until destruction. diff --git a/include/evo/client/input.hpp b/include/evo/client/input.hpp index 5fa2a60..129e954 100644 --- a/include/evo/client/input.hpp +++ b/include/evo/client/input.hpp @@ -22,6 +22,9 @@ struct Navigation { int x{}, y{}; double wheel{}; ScreenPoint pointer{}; + // One primary click on the world (press and release, not taken by the UI), consumed + // once. Used for presentation selection only; never an authoritative command. + std::optional click; }; // Main-thread value state; no event queue or authoritative position. class InputState { @@ -39,6 +42,8 @@ class InputState { [[nodiscard]] std::expected key(Key key, bool down, bool repeat = false); [[nodiscard]] std::expected pointer(ScreenPoint point); [[nodiscard]] std::expected wheel(double steps); + // Records a world click while input is admitted and not captured; otherwise ignored. + [[nodiscard]] std::expected click(ScreenPoint point); [[nodiscard]] Navigation take_navigation() noexcept; [[nodiscard]] std::expected sample(std::uint64_t tick); @@ -48,6 +53,7 @@ class InputState { bool admitted_{false}, captured_{false}; ScreenPoint pointer_{}; double wheel_{}; + std::optional click_; std::uint64_t sequence_{}; std::optional tick_; }; diff --git a/include/evo/client/labels.hpp b/include/evo/client/labels.hpp new file mode 100644 index 0000000..db2a504 --- /dev/null +++ b/include/evo/client/labels.hpp @@ -0,0 +1,32 @@ +#pragma once +#include "evo/client/environment_view.hpp" +#include "evo/client/organism_view.hpp" +#include +#include +#include +#include + +// M9.8c readable engineering labels (toolkit-independent). Text describes copied +// presentation values only; every distinct data state keeps a distinct description. +namespace evo::client { +enum class ValueKind : std::uint8_t { value, zero, missing, not_requested, undefined }; +struct ValueText { + ValueKind kind{}; + std::string text; +}; +struct Row { + std::string label, value, unit; +}; +[[nodiscard]] std::string_view field_name(world::Field field) noexcept; +[[nodiscard]] std::string_view field_unit(world::Field field) noexcept; // "fg" or "pJ" +[[nodiscard]] std::string_view freshness_name(Freshness freshness) noexcept; +// Present values give the quantity and its density per habitat volume; zero, missing, +// not requested and undefined each have their own wording (never "0" for missing). +[[nodiscard]] ValueText describe_field(const EnvironmentCell& cell, world::Field field); +[[nodiscard]] ValueText describe_moisture(const EnvironmentCell& cell); +// Labelled rows with units for the inspector. The opaque organism id is not shown. +[[nodiscard]] std::vector organism_rows(const OrganismCell& cell); +[[nodiscard]] std::vector cell_rows(const EnvironmentCell& cell); +// The density scale the renderer's ramp uses (log2 of unit per cubic micrometre). +[[nodiscard]] std::string density_scale(world::Field field); +} // namespace evo::client diff --git a/include/evo/client/launcher.hpp b/include/evo/client/launcher.hpp new file mode 100644 index 0000000..1d217c0 --- /dev/null +++ b/include/evo/client/launcher.hpp @@ -0,0 +1,92 @@ +#pragma once +#include +#include +#include +#include +#include +#include +#include + +// M9.8c launcher model (toolkit- and network-independent). Validates what the user +// typed, loads the two credential files within bounds, and tracks the connect flow. +// Error texts are fixed: they never contain file contents, grant bytes or keys, and +// nothing here is persisted or logged. +namespace evo::client { +inline constexpr std::size_t grant_record_bytes = 108; // network::dev_grant_bytes. +inline constexpr std::size_t max_grant_records = 64; // As issued by evo-dev-session. +inline constexpr std::size_t max_authority_bytes = 65536; // One small PEM CA. +inline constexpr std::size_t max_field_bytes = 1024; // Every text field. +using GrantRecord = std::array; + +enum class LaunchError : std::uint8_t { + endpoint, + server_name, + authority_path, + grants_path, + authority_unreadable, + authority_invalid, + grants_unreadable, + grants_invalid, + grant_refused, + server_unreachable, + grants_exhausted, + no_session +}; +[[nodiscard]] std::string_view launch_error_text(LaunchError error) noexcept; + +struct ConnectForm { + std::string endpoint{"127.0.0.1:17400"}, server_name{"dev-region.evolution.test"}; + std::string authority_path, grants_path; +}; +struct Endpoint { + std::string host; + std::uint16_t port{}; +}; +struct ConnectMaterial { + Endpoint endpoint; + std::string server_name, authority_pem; + std::vector grants; +}; +// "host:port", "[ipv6]:port" or "a.b.c.d:port"; plain DNS host names only. +[[nodiscard]] std::expected parse_endpoint(std::string_view text); +[[nodiscard]] std::expected load_connect(const ConnectForm& form); + +// What the session reports while connecting, reduced to what the launcher decides on. +enum class ConnectSignal : std::uint8_t { + welcome, // A session was opened. + lost, // Transport/TLS failure or deadline before a Close. + refused, // Closed as unauthenticated/expired/duplicate: this grant cannot work. + not_ready, // Closed as server_shutdown/capacity: the server will retry later. + exhausted // No unused grant remains. +}; +enum class LaunchPhase : std::uint8_t { choosing, fixture, connecting, connected, failed }; +class Launcher { + public: + static constexpr int max_attempts_without_welcome = 3; + void start_fixture() noexcept; + // From choosing or failed (retry). The caller then creates a fresh session. + [[nodiscard]] bool begin_connect() noexcept; + // Cancel returns to choosing from connecting, connected or failed; the caller + // drops its session. Fixture mode also returns to choosing. + void cancel() noexcept; + // Lost connections after a welcome are reconnects, not failures; before any + // welcome, repeated loss means the endpoint, name or CA is wrong. + void observe(ConnectSignal signal) noexcept; + void fail(LaunchError error) noexcept; + [[nodiscard]] LaunchPhase phase() const noexcept { + return phase_; + } + [[nodiscard]] LaunchError error() const noexcept { + return error_; + } + [[nodiscard]] bool ever_connected() const noexcept { + return welcomed_; + } + + private: + LaunchPhase phase_{LaunchPhase::choosing}; + LaunchError error_{LaunchError::no_session}; + int losses_{}; + bool welcomed_{}; +}; +} // namespace evo::client diff --git a/include/evo/client/outcome_log.hpp b/include/evo/client/outcome_log.hpp new file mode 100644 index 0000000..7962c4c --- /dev/null +++ b/include/evo/client/outcome_log.hpp @@ -0,0 +1,40 @@ +#pragma once +#include +#include +#include + +// M9.8c bounded intention history for the session panel (toolkit-independent). It is +// the inspectable record; notifications may expire, this keeps the latest entries. +// Values are copied from session events; nothing here is authority. +namespace evo::client { +enum class OutcomeState : std::uint8_t { + sent, // Queued to the server; no reply yet. + admitted, // Accepted for scheduling; not yet durable. + rejected, // IntentResult other than admitted (final). + durable, // Committed with no biological effect (final). + not_committed, // The carrying input was dropped (final). + unknown // The connection ended first; the outcome is not known (final). +}; +struct OutcomeEntry { + std::uint64_t sequence{}; + OutcomeState state{}; + std::uint8_t detail{}; // IntentStatus code for rejections. + std::uint64_t tick{}, commit_sequence{}; // For durable outcomes. +}; +class OutcomeLog { + public: + static constexpr std::size_t capacity = 64; + // Updates the entry for `sequence` (newest match) or appends one, evicting the oldest. + void record(OutcomeEntry entry); + [[nodiscard]] const std::deque& entries() const noexcept { + return entries_; + } + [[nodiscard]] std::uint64_t evicted() const noexcept { + return evicted_; + } + + private: + std::deque entries_; + std::uint64_t evicted_{}; +}; +} // namespace evo::client diff --git a/include/evo/client/selection.hpp b/include/evo/client/selection.hpp new file mode 100644 index 0000000..c02333a --- /dev/null +++ b/include/evo/client/selection.hpp @@ -0,0 +1,39 @@ +#pragma once +#include "evo/client/camera.hpp" +#include "evo/client/environment_view.hpp" +#include "evo/client/organism_view.hpp" +#include +#include + +// M9.8c click selection (toolkit-independent). Selection names a presentation item by +// key (organism id or voxel) and re-resolves it against each new presentation; it +// never holds pointers into presentations across frames and selects nothing in the +// world itself. +namespace evo::client { +class Selection { + public: + enum class Kind : std::uint8_t { none, organism, cell }; + enum class Change : std::uint8_t { none, organism_gone, cell_gone }; + // Topmost organism whose drawn body contains the point wins; otherwise the habitat + // cell whose voxel contains it; otherwise the selection clears. + void pick(ScreenPoint point, const EnvironmentPresentation* environment, + const OrganismPresentation* organisms, const Camera& camera); + // Clears when the selected item is absent from a present presentation. Without a + // presentation (no view yet, reconnecting) the selection is kept but not shown. + [[nodiscard]] Change refresh(const EnvironmentPresentation* environment, + const OrganismPresentation* organisms); + void clear() noexcept { + kind_ = Kind::none; + } + [[nodiscard]] Kind kind() const noexcept { + return kind_; + } + [[nodiscard]] const OrganismCell* organism(const OrganismPresentation* organisms) const; + [[nodiscard]] const EnvironmentCell* cell(const EnvironmentPresentation* environment) const; + + private: + Kind kind_{Kind::none}; + std::uint64_t organism_{}; + world::VoxelAddress voxel_{}; +}; +} // namespace evo::client diff --git a/include/evo/network/session_client.hpp b/include/evo/network/session_client.hpp index 38d5425..2b54a3d 100644 --- a/include/evo/network/session_client.hpp +++ b/include/evo/network/session_client.hpp @@ -70,6 +70,9 @@ class SessionClient { [[nodiscard]] std::optional welcome() const noexcept; [[nodiscard]] std::optional latest_view() const noexcept; [[nodiscard]] std::size_t grants_left() const noexcept; + // Attempts that failed before any session event (TCP connect or TLS handshake), so a + // caller can bound "unreachable" without an event per retry. Never reset. + [[nodiscard]] std::uint64_t unreachable_attempts() const noexcept; // Drains at most max_events and resumes reconnect after local backpressure. [[nodiscard]] std::vector take_events(); diff --git a/src/client/input/input.cpp b/src/client/input/input.cpp index 1ce40bb..48c11b9 100644 --- a/src/client/input/input.cpp +++ b/src/client/input/input.cpp @@ -7,6 +7,7 @@ namespace evo::client { void InputState::clear() noexcept { keys_.fill(false); wheel_ = 0; + click_.reset(); } void InputState::admit(bool enabled) noexcept { if (!enabled) @@ -45,10 +46,19 @@ std::expected InputState::wheel(double steps) { Navigation InputState::take_navigation() noexcept { const Navigation result{static_cast(keys_[5]) - static_cast(keys_[4]), static_cast(keys_[7]) - static_cast(keys_[6]), wheel_, - pointer_}; + pointer_, click_}; wheel_ = 0; + click_.reset(); return result; } +std::expected InputState::click(ScreenPoint point) { + if (!std::isfinite(point.x) || !std::isfinite(point.y) || std::abs(point.x) > 32768 || + std::abs(point.y) > 32768) + return std::unexpected(InputError::invalid_pointer); + if (enabled()) + click_ = point; + return {}; +} std::expected InputState::sample(std::uint64_t tick) { if (tick_ && tick <= *tick_) return std::unexpected(InputError::stale_tick); diff --git a/src/client/platform/application.cpp b/src/client/platform/application.cpp index 5c8b66e..7fe8fb2 100644 --- a/src/client/platform/application.cpp +++ b/src/client/platform/application.cpp @@ -3,6 +3,9 @@ #define SDL_MAIN_HANDLED #include #include +#include +#include +#include #include #include @@ -31,6 +34,42 @@ std::optional input_key(SDL_Scancode code) { return std::nullopt; } } +// Private toolkit state (ADR-0084): created after the renderer, destroyed before it. +struct Toolkit { + bool context{}, platform{}, renderer{}; + Toolkit() = default; + Toolkit(const Toolkit&) = delete; + Toolkit& operator=(const Toolkit&) = delete; + ~Toolkit() { + detach_renderer(); + if (platform) + ImGui_ImplSDL3_Shutdown(); + if (context) + ImGui::DestroyContext(); + } + bool open(SDL_Window* window, SDL_Renderer* target) { + IMGUI_CHECKVERSION(); + ImGui::CreateContext(); + context = true; + auto& io = ImGui::GetIO(); + io.IniFilename = nullptr; // Nothing is persisted (no paths, no window layout). + io.LogFilename = nullptr; + if (io.Fonts->AddFontDefaultBitmap() == nullptr) + return false; + platform = ImGui_ImplSDL3_InitForSDLRenderer(window, target); + return platform && attach_renderer(target); + } + bool attach_renderer(SDL_Renderer* target) { + renderer = ImGui_ImplSDLRenderer3_Init(target); + return renderer; + } + void detach_renderer() { + if (renderer) + ImGui_ImplSDLRenderer3_Shutdown(); + renderer = false; + } +}; +constexpr float click_slop = 4; // Logical units between press and release. struct Runtime { bool acquired{false}; ~Runtime() { @@ -48,9 +87,33 @@ struct Application::Impl { std::string renderer_name; WindowState state; std::optional failure; + Toolkit toolkit; // After window/renderer: destroyed first. + Overlay overlay; InputState input; bool backlogged{false}; - bool external_capture{false}; + // Capture sources: an external modal/launcher, the legacy Tab toggle and the + // toolkit's own keyboard focus. World actions run only when none applies. + bool external_capture{false}, tab_capture{false}, toolkit_capture{false}; + bool toolkit_pointer{false}; + std::optional press; // Primary press not taken by the toolkit. + std::string screenshot; + + // `drain`: input may have queued while an external UI or toolkit widget held it, so + // that batch is discarded first. The Tab toggle is ordered within its own batch + // (CAMERA_INPUT.md): presses after it belong to the new state, no drain. + void update_capture(bool drain = true) { + const bool wanted = external_capture || tab_capture || toolkit_capture; + if (wanted == input.captured()) + return; + if (!wanted && drain) { + // Releasing capture can leave old input queued in SDL: drain that batch + // before admitting fresh world presses (no synthesized held keys). + backlogged = true; + input.admit(false); + } + input.capture(wanted); + press.reset(); + } std::expected refresh() { if (!SDL_GetWindowSize(window.get(), &state.logical_width, &state.logical_height) || @@ -74,13 +137,21 @@ WindowState Application::state() const noexcept { } void Application::set_ui_capture(bool captured) noexcept { impl_->external_capture = captured; - if (impl_->input.captured() && !captured) { - // An external UI can release capture with old input still queued in SDL. - // Drain that batch before admitting fresh world presses. - impl_->backlogged = true; - impl_->input.admit(false); - } - impl_->input.capture(captured); + if (!captured) + impl_->tab_capture = false; // An external release also ends the legacy toggle. + impl_->update_capture(); +} +void Application::set_overlay(Overlay overlay) { + impl_->overlay = std::move(overlay); +} +bool Application::ui_wants_pointer() const noexcept { + return impl_->toolkit_pointer; +} +bool Application::request_screenshot(std::string path) { + if (path.empty() || path.size() > 1024 || path.find('\0') != std::string::npos) + return false; + impl_->screenshot = std::move(path); + return true; } bool Application::ui_captured() const noexcept { return impl_->input.captured(); @@ -120,6 +191,8 @@ std::expected, Error> Application::open(const Confi impl->state.hidden = (window_flags & SDL_WINDOW_HIDDEN) != 0; if (auto result = impl->refresh(); !result) return std::unexpected(result.error()); + if (!impl->toolkit.open(impl->window.get(), impl->renderer.get())) + return std::unexpected(Error::initialization); return std::unique_ptr{new Application{std::move(impl)}}; } std::expected Application::step(const render::Frame& frame) { @@ -135,10 +208,18 @@ std::expected Application::poll_events() { return {}; p.input.admit(p.state.accepts_input() && !p.backlogged); const auto id = SDL_GetWindowID(p.window.get()); + // The toolkit's wishes from its last frame decide this batch: keyboard focus in a + // widget captures world keys; a pointer over UI cannot click, pan or zoom the world. + const auto& io = ImGui::GetIO(); + p.toolkit_capture = io.WantCaptureKeyboard; + p.toolkit_pointer = io.WantCaptureMouse; + p.update_capture(); bool reset = false; SDL_Event event{}; int count = 0; for (; count < 256 && SDL_PollEvent(&event); ++count) { + // Toolkit first: widgets see every event before world input is derived. + ImGui_ImplSDL3_ProcessEvent(&event); if (event.type == SDL_EVENT_QUIT) p.state.closed = true; if (event.type >= SDL_EVENT_WINDOW_FIRST && event.type <= SDL_EVENT_WINDOW_LAST && @@ -176,8 +257,11 @@ std::expected Application::poll_events() { event.key.windowID == id) { const bool down = event.type == SDL_EVENT_KEY_DOWN; if (event.key.scancode == SDL_SCANCODE_TAB && down && !event.key.repeat && - p.state.accepts_input() && !p.backlogged && !p.external_capture) - p.input.capture(!p.input.captured()); + p.state.accepts_input() && !p.backlogged && !p.external_capture && + !p.toolkit_capture) { + p.tab_capture = !p.tab_capture; + p.update_capture(false); + } if (const auto key = input_key(event.key.scancode)) { if (auto result = p.input.key(*key, down, event.key.repeat); !result) p.input.admit(false); @@ -187,7 +271,22 @@ std::expected Application::poll_events() { if (auto result = p.input.pointer({event.motion.x, event.motion.y}); !result) p.input.admit(false); } - if (event.type == SDL_EVENT_MOUSE_WHEEL && event.wheel.windowID == id) { + if (event.type == SDL_EVENT_MOUSE_BUTTON_DOWN && event.button.windowID == id && + event.button.button == SDL_BUTTON_LEFT) + p.press = p.toolkit_pointer || p.input.captured() + ? std::nullopt + : std::optional{{event.button.x, event.button.y}}; + if (event.type == SDL_EVENT_MOUSE_BUTTON_UP && event.button.windowID == id && + event.button.button == SDL_BUTTON_LEFT) { + // A click that operated a widget (pressed over UI) never selects through it. + if (p.press && std::abs(event.button.x - p.press->x) <= click_slop && + std::abs(event.button.y - p.press->y) <= click_slop && !p.toolkit_pointer && + !p.input.click({event.button.x, event.button.y})) + p.input.admit(false); + p.press.reset(); + } + if (event.type == SDL_EVENT_MOUSE_WHEEL && event.wheel.windowID == id && + !p.toolkit_pointer) { const double direction = event.wheel.direction == SDL_MOUSEWHEEL_FLIPPED ? -1 : 1; if (!p.input.pointer({event.wheel.mouse_x, event.wheel.mouse_y}) || !p.input.wheel(event.wheel.y * direction)) @@ -210,6 +309,7 @@ std::expected Application::poll_events() { if (p.state.closed) return {}; if (reset) { + p.toolkit.detach_renderer(); // Toolkit textures belong to the old renderer. p.renderer.reset(); auto renderer = detail::make_renderer(p.window.get(), p.renderer_name); if (!renderer) { @@ -218,6 +318,11 @@ std::expected Application::poll_events() { return std::unexpected(*p.failure); } p.renderer = std::move(*renderer); + if (!p.toolkit.attach_renderer(p.renderer.get())) { + p.failure = Error::renderer; + p.input.admit(false); + return std::unexpected(*p.failure); + } } if (auto result = p.refresh(); !result) { p.failure = result.error(); @@ -241,6 +346,27 @@ std::expected Application::present(const render::Frame& frame) { p.input.admit(false); return std::unexpected(*p.failure); } + if (p.overlay) { + // Engineering UI over the immutable frame; the callback reads copies only. + ImGui_ImplSDLRenderer3_NewFrame(); + ImGui_ImplSDL3_NewFrame(); + ImGui::NewFrame(); + p.overlay(); + ImGui::Render(); + ImGui_ImplSDLRenderer3_RenderDrawData(ImGui::GetDrawData(), p.renderer.get()); + } + if (!p.screenshot.empty()) { + // Engineering visual review only: the composed frame as an uncompressed BMP. + const std::unique_ptr pixels{ + SDL_RenderReadPixels(p.renderer.get(), nullptr), SDL_DestroySurface}; + const bool saved = pixels && SDL_SaveBMP(pixels.get(), p.screenshot.c_str()); + p.screenshot.clear(); + if (!saved) { + p.failure = Error::draw; + p.input.admit(false); + return std::unexpected(*p.failure); + } + } if (!SDL_RenderPresent(p.renderer.get())) { p.failure = Error::draw; p.input.admit(false); diff --git a/src/client/ui/labels.cpp b/src/client/ui/labels.cpp new file mode 100644 index 0000000..1920b5e --- /dev/null +++ b/src/client/ui/labels.cpp @@ -0,0 +1,151 @@ +#include "evo/client/labels.hpp" +#include "evo/render/environment.hpp" +#include "evo/world/generation.hpp" +#include +#include +#include + +namespace evo::client { +namespace { +constexpr std::array names{"Water", + "Dissolved nitrogen", + "Dissolved phosphorus", + "Organic carbon", + "Organic nitrogen", + "Organic phosphorus", + "Organic other", + "Organic energy", + "Incident energy", + "Heat"}; +std::string number(double value, const char* format = "%.4g") { + std::array text{}; + const int n = std::snprintf(text.data(), text.size(), format, value); + return n > 0 ? std::string(text.data(), static_cast(n)) : std::string{}; +} +std::string integer(std::uint64_t value) { + return std::to_string(value); +} +std::string per_thousand(std::uint32_t value) { + return number(static_cast(value) / 10.0, "%.1f") + " %"; +} +} // namespace + +std::string_view field_name(world::Field field) noexcept { + const auto k = static_cast(field); + return k < names.size() ? names.at(k) : std::string_view{"Unknown field"}; +} + +std::string_view field_unit(world::Field field) noexcept { + return static_cast(field) >= static_cast(world::Field::organic_energy) + ? std::string_view{"pJ"} + : std::string_view{"fg"}; +} + +std::string_view freshness_name(Freshness freshness) noexcept { + switch (freshness) { + case Freshness::none: + return "no view"; + case Freshness::current: + return "current"; + case Freshness::stale: + return "STALE (authority has moved on)"; + } + return "unknown"; +} + +ValueText describe_field(const EnvironmentCell& cell, world::Field field) { + const auto k = static_cast(field); + if (k >= world::field_count) + return {ValueKind::undefined, "unknown field"}; + switch (cell.presence.at(k)) { + case FieldPresence::not_requested: + return {ValueKind::not_requested, "not requested in this view"}; + case FieldPresence::missing: + return {ValueKind::missing, "MISSING (requested; the authority has no value)"}; + case FieldPresence::present: + break; + } + const auto quantity = cell.quantity.at(k); + const auto unit = std::string{field_unit(field)}; + if (quantity == 0) + return {ValueKind::zero, "0 " + unit + " (present zero)"}; + const double density = static_cast(quantity) / static_cast(cell.volume.value); + return {ValueKind::value, integer(quantity) + " " + unit + " (" + number(density) + " " + unit + + "/um3, log2 " + number(std::log2(density), "%.1f") + ")"}; +} + +ValueText describe_moisture(const EnvironmentCell& cell) { + switch (cell.moisture_status) { + case world::MoistureStatus::not_requested: + return {ValueKind::not_requested, "not requested in this view"}; + case world::MoistureStatus::missing_water: + return {ValueKind::missing, "MISSING (no water value)"}; + case world::MoistureStatus::zero_capacity: + return {ValueKind::undefined, "undefined (substrate holds no water)"}; + case world::MoistureStatus::available: + break; + } + const auto& m = cell.moisture; + const double share = + m.denominator == 0 ? 0.0 + : static_cast(m.numerator) / static_cast(m.denominator); + return {m.numerator == 0 ? ValueKind::zero : ValueKind::value, + number(share * 100.0, "%.2f") + " % saturated" + + (m.numerator == 0 ? " (present zero)" : "")}; +} + +std::vector organism_rows(const OrganismCell& cell) { + const auto& p = cell.phenotype; + return { + {"State", cell.state == OrganismState::alive ? "alive" : "dead (remnant)", ""}, + {"Voxel", + std::to_string(cell.voxel.x) + ", " + std::to_string(cell.voxel.y) + ", " + + std::to_string(cell.voxel.z), + ""}, + {"Offset in voxel", integer(cell.x.value) + ", " + integer(cell.y.value), "um"}, + {"Extent (side)", integer(p.extent), "um"}, + {"Total mass", integer(p.total_mass), "fg"}, + {"Structural mass", integer(p.structural_mass), "fg"}, + {"Membrane mass", integer(p.membrane_mass), "fg"}, + {"Surface", integer(p.surface), "um2"}, + {"Maintenance", integer(p.maintenance), "pJ/tick"}, + {"Movement speed", p.movement_speed == 0 ? "none" : integer(p.movement_speed), + p.movement_speed == 0 ? "" : "um/tick"}, + {"Ingestion rate", p.ingestion_rate == 0 ? "none" : integer(p.ingestion_rate), + p.ingestion_rate == 0 ? "" : "fg/tick"}, + {"Energy conversion", per_thousand(p.conversion_per_thousand), ""}, + {"Realized growth", per_thousand(cell.growth.realized_per_thousand), ""}, + {"Damage", per_thousand(cell.growth.damage_per_thousand), ""}, + {"Thermal shortfall", integer(p.thermal_shortfall), "mK"}, + }; +} + +std::vector cell_rows(const EnvironmentCell& cell) { + const auto material = world::material_name(1, cell.terrain_material); + const auto substrate = world::material_name(1, cell.substrate); + const auto& h = cell.habitat; + return { + {"Voxel", + std::to_string(cell.voxel.x) + ", " + std::to_string(cell.voxel.y) + ", " + + std::to_string(cell.voxel.z), + ""}, + {"Terrain material", + material ? std::string{*material} : "unknown id " + integer(cell.terrain_material.value), + ""}, + {"Terrain fill", number(100.0 * cell.terrain_fill / world::fill_scale, "%.1f"), "%"}, + {"Habitat substrate", + substrate ? std::string{*substrate} : "unknown id " + integer(cell.substrate.value), ""}, + {"Habitat box", + integer(h.width.value) + " x " + integer(h.height.value) + " x " + integer(h.depth.value), + "um"}, + {"Habitat volume", integer(cell.volume.value), "um3"}, + {"Chunk revision", integer(cell.chunk_revision), ""}, + }; +} + +std::string density_scale(world::Field field) { + const auto unit = std::string{field_unit(field)}; + return "log2(" + unit + " per um3) from " + number(render::field_log2_min, "%.0f") + " to " + + number(render::field_log2_max, "%.0f") + "; values outside are clamped to the ends"; +} +} // namespace evo::client diff --git a/src/client/ui/launcher.cpp b/src/client/ui/launcher.cpp new file mode 100644 index 0000000..d31ba39 --- /dev/null +++ b/src/client/ui/launcher.cpp @@ -0,0 +1,181 @@ +#include "evo/client/launcher.hpp" +#include +#include +#include +#include +#include +#include + +namespace evo::client { +namespace { +bool plain_text(std::string_view text) { + return !text.empty() && text.size() <= max_field_bytes && + text.find('\0') == std::string_view::npos; +} +bool dns_name(std::string_view text) { + return !text.empty() && text.size() <= 253 && std::ranges::all_of(text, [](char ch) { + return std::isalnum(static_cast(ch)) != 0 || ch == '-' || ch == '.'; + }); +} +// Reads at most `limit` bytes; anything longer is rejected, never truncated. +std::expected, LaunchError> read_bounded(const std::string& path, + std::size_t limit, + LaunchError unreadable, + LaunchError invalid) { + std::error_code error; + const auto size = std::filesystem::file_size(std::filesystem::path{path}, error); + if (error || !std::filesystem::is_regular_file(std::filesystem::path{path}, error)) + return std::unexpected(unreadable); + if (size == 0 || size > limit) + return std::unexpected(invalid); + std::ifstream file{std::filesystem::path{path}, std::ios::binary}; + std::vector bytes(static_cast(size)); + if (!file || + !file.read(reinterpret_cast(bytes.data()), static_cast(size))) + return std::unexpected(unreadable); + return bytes; +} +} // namespace + +std::string_view launch_error_text(LaunchError error) noexcept { + switch (error) { + case LaunchError::endpoint: + return "Endpoint must be host:port (port 1-65535)."; + case LaunchError::server_name: + return "Server name must be the DNS name on the server certificate."; + case LaunchError::authority_path: + return "Choose the dev CA certificate file (dev-ca.pem)."; + case LaunchError::grants_path: + return "Choose a grant bundle file issued by evo-dev-session grants."; + case LaunchError::authority_unreadable: + return "The dev CA file could not be read."; + case LaunchError::authority_invalid: + return "The dev CA file is not a PEM certificate of a plausible size."; + case LaunchError::grants_unreadable: + return "The grant bundle could not be read."; + case LaunchError::grants_invalid: + return "The grant bundle is not 1-64 whole grants."; + case LaunchError::grant_refused: + return "The server refused the grant (wrong key, world or region, expired, or already " + "used). Issue a new bundle."; + case LaunchError::server_unreachable: + return "No session: the server is unreachable or its certificate does not match the " + "CA and server name."; + case LaunchError::grants_exhausted: + return "Every grant in the bundle has been used. Issue a new bundle."; + case LaunchError::no_session: + return "Not connected."; + } + return "Unknown error."; +} + +std::expected parse_endpoint(std::string_view text) { + const auto colon = text.rfind(':'); + if (!plain_text(text) || colon == std::string_view::npos || colon == 0) + return std::unexpected(LaunchError::endpoint); + unsigned port = 0; + const auto digits = text.substr(colon + 1); + const auto [end, error] = std::from_chars(digits.data(), digits.data() + digits.size(), port); + if (error != std::errc{} || end != digits.data() + digits.size() || port == 0 || port > 65535) + return std::unexpected(LaunchError::endpoint); + auto host = std::string{text.substr(0, colon)}; + if (host.size() > 2 && host.front() == '[' && host.back() == ']') { + host = host.substr(1, host.size() - 2); + if (!std::ranges::all_of(host, [](char ch) { + return std::isxdigit(static_cast(ch)) != 0 || ch == ':' || ch == '.'; + })) + return std::unexpected(LaunchError::endpoint); + } else if (!dns_name(host)) { + return std::unexpected(LaunchError::endpoint); + } + return Endpoint{host, static_cast(port)}; +} + +std::expected load_connect(const ConnectForm& form) { + const auto endpoint = parse_endpoint(form.endpoint); + if (!endpoint) + return std::unexpected(endpoint.error()); + if (!dns_name(form.server_name)) + return std::unexpected(LaunchError::server_name); + if (!plain_text(form.authority_path)) + return std::unexpected(LaunchError::authority_path); + if (!plain_text(form.grants_path)) + return std::unexpected(LaunchError::grants_path); + const auto authority = + read_bounded(form.authority_path, max_authority_bytes, LaunchError::authority_unreadable, + LaunchError::authority_invalid); + if (!authority) + return std::unexpected(authority.error()); + std::string pem(authority->begin(), authority->end()); + if (pem.find("-----BEGIN CERTIFICATE-----") == std::string::npos || + pem.find('\0') != std::string::npos) + return std::unexpected(LaunchError::authority_invalid); + const auto bundle = read_bounded(form.grants_path, grant_record_bytes * max_grant_records, + LaunchError::grants_unreadable, LaunchError::grants_invalid); + if (!bundle) + return std::unexpected(bundle.error()); + if (bundle->size() % grant_record_bytes != 0) + return std::unexpected(LaunchError::grants_invalid); + ConnectMaterial material{*endpoint, form.server_name, std::move(pem), {}}; + for (std::size_t at = 0; at < bundle->size(); at += grant_record_bytes) { + GrantRecord grant{}; + std::copy_n(bundle->begin() + static_cast(at), grant.size(), grant.begin()); + material.grants.push_back(grant); + } + return material; +} + +void Launcher::start_fixture() noexcept { + phase_ = LaunchPhase::fixture; +} + +bool Launcher::begin_connect() noexcept { + if (phase_ != LaunchPhase::choosing && phase_ != LaunchPhase::failed) + return false; + phase_ = LaunchPhase::connecting; + error_ = LaunchError::no_session; + losses_ = 0; + welcomed_ = false; + return true; +} + +void Launcher::cancel() noexcept { + phase_ = LaunchPhase::choosing; + error_ = LaunchError::no_session; + losses_ = 0; +} + +void Launcher::observe(ConnectSignal signal) noexcept { + if (phase_ != LaunchPhase::connecting && phase_ != LaunchPhase::connected) + return; + switch (signal) { + case ConnectSignal::welcome: + phase_ = LaunchPhase::connected; + welcomed_ = true; + losses_ = 0; + return; + case ConnectSignal::lost: + if (!welcomed_ && ++losses_ >= max_attempts_without_welcome) + fail(LaunchError::server_unreachable); + else if (welcomed_) + phase_ = LaunchPhase::connecting; // Reconnecting with the next grant. + return; + case ConnectSignal::refused: + if (!welcomed_) + fail(LaunchError::grant_refused); + else + phase_ = LaunchPhase::connecting; + return; + case ConnectSignal::not_ready: + return; // The session retries with the same grant. + case ConnectSignal::exhausted: + fail(LaunchError::grants_exhausted); + return; + } +} + +void Launcher::fail(LaunchError error) noexcept { + phase_ = LaunchPhase::failed; + error_ = error; +} +} // namespace evo::client diff --git a/src/client/ui/outcome_log.cpp b/src/client/ui/outcome_log.cpp new file mode 100644 index 0000000..7bd55ff --- /dev/null +++ b/src/client/ui/outcome_log.cpp @@ -0,0 +1,20 @@ +#include "evo/client/outcome_log.hpp" +#include + +namespace evo::client { +void OutcomeLog::record(OutcomeEntry entry) { + const auto it = + std::ranges::find_if(entries_.rbegin(), entries_.rend(), + [&](const OutcomeEntry& e) { return e.sequence == entry.sequence; }); + if (it != entries_.rend()) { + *it = entry; + return; + } + if (entries_.size() >= capacity) { + entries_.pop_front(); + if (evicted_ != UINT64_MAX) + ++evicted_; + } + entries_.push_back(entry); +} +} // namespace evo::client diff --git a/src/client/ui/selection.cpp b/src/client/ui/selection.cpp new file mode 100644 index 0000000..b67f433 --- /dev/null +++ b/src/client/ui/selection.cpp @@ -0,0 +1,65 @@ +#include "evo/client/selection.hpp" +#include "evo/client/organism_inspector.hpp" +#include +#include + +namespace evo::client { +namespace { +constexpr double pitch_mm = static_cast(world::cell_pitch_mm); +} // namespace + +void Selection::pick(ScreenPoint point, const EnvironmentPresentation* environment, + const OrganismPresentation* organisms, const Camera& camera) { + if (organisms != nullptr) + if (const auto index = pick_organism(*organisms, camera, point)) { + kind_ = Kind::organism; + organism_ = organisms->cells()[*index].id; + return; + } + if (environment != nullptr) + if (const auto world = camera.screen_to_world(point)) { + const auto x = static_cast(std::floor(world->x_mm / pitch_mm)); + const auto y = static_cast(std::floor(world->y_mm / pitch_mm)); + const auto cells = environment->cells(); + const auto it = std::ranges::find_if( + cells, [&](const EnvironmentCell& c) { return c.voxel.x == x && c.voxel.y == y; }); + if (it != cells.end()) { + kind_ = Kind::cell; + voxel_ = it->voxel; + return; + } + } + kind_ = Kind::none; +} + +Selection::Change Selection::refresh(const EnvironmentPresentation* environment, + const OrganismPresentation* organisms) { + if (kind_ == Kind::organism && organisms != nullptr && this->organism(organisms) == nullptr) { + kind_ = Kind::none; + return Change::organism_gone; + } + if (kind_ == Kind::cell && environment != nullptr && cell(environment) == nullptr) { + kind_ = Kind::none; + return Change::cell_gone; + } + return Change::none; +} + +const OrganismCell* Selection::organism(const OrganismPresentation* organisms) const { + if (kind_ != Kind::organism || organisms == nullptr) + return nullptr; + const auto cells = organisms->cells(); + const auto it = + std::ranges::find_if(cells, [&](const OrganismCell& c) { return c.id == organism_; }); + return it == cells.end() ? nullptr : &*it; +} + +const EnvironmentCell* Selection::cell(const EnvironmentPresentation* environment) const { + if (kind_ != Kind::cell || environment == nullptr) + return nullptr; + const auto cells = environment->cells(); + const auto it = + std::ranges::find_if(cells, [&](const EnvironmentCell& c) { return c.voxel == voxel_; }); + return it == cells.end() ? nullptr : &*it; +} +} // namespace evo::client diff --git a/src/network/session/client.cpp b/src/network/session/client.cpp index 1b75a24..f82ad6b 100644 --- a/src/network/session/client.cpp +++ b/src/network/session/client.cpp @@ -16,6 +16,7 @@ struct SessionClient::Impl { SessionClientConfig config; std::size_t next_grant{}; + std::uint64_t unreachable{}; SessionPhase phase{SessionPhase::backoff}; Step step{Step::handshake}; Clock::time_point retry_at{}, deadline{}, last_received{}, last_sent{}, polled_at{}; @@ -34,7 +35,9 @@ struct SessionClient::Impl { bool awaiting_event_drain{}; void disconnect(Clock::time_point now, std::optional reason) { - if (step == Step::established || step == Step::awaiting_welcome || reason) + if (step != Step::established && step != Step::awaiting_welcome && !reason) + ++unreachable; + else events.push_back({reason ? ClientEvent::Kind::closed : ClientEvent::Kind::lost, {}, reason.value_or(CloseReason::normal), @@ -324,6 +327,9 @@ std::optional SessionClient::welcome() const noexcept { std::optional SessionClient::latest_view() const noexcept { return impl_->view; } +std::uint64_t SessionClient::unreachable_attempts() const noexcept { + return impl_->unreachable; +} std::size_t SessionClient::grants_left() const noexcept { return impl_->config.grants.size() - impl_->next_grant; } diff --git a/tests/client_lifecycle.cpp b/tests/client_lifecycle.cpp index ecf9bde..ca09896 100644 --- a/tests/client_lifecycle.cpp +++ b/tests/client_lifecycle.cpp @@ -4,6 +4,8 @@ #include #include #include +#include +#include #include #include #include @@ -246,12 +248,114 @@ void native_input() { CHECK(required(app->sample_intention(51)).move_y == 0); CHECK(app->present(frame) == Step::rendered); } +// M9.8c: the toolkit sees input first. A click that operates a widget never selects +// through it; keyboard focus in a text field suppresses world movement; releasing that +// focus requires a fresh key press (nothing is synthesized from held keys). +void toolkit_capture() { + const auto frame = fixture(); + auto result = Application::open({320, 240, false, "software"}); + CHECK(result); + auto app = std::move(result.value()); + CHECK(app->poll_events()); + const auto id = SDL_GetWindowID(window()); + send(SDL_EVENT_WINDOW_FOCUS_GAINED, id); + int presses = 0; + bool text_focus = false; + std::array text{}; + app->set_overlay([&] { + ImGui::SetNextWindowPos({0, 0}, ImGuiCond_Always); + ImGui::SetNextWindowSize({150, 150}, ImGuiCond_Always); + ImGui::Begin("panel", nullptr, ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize); + if (ImGui::Button("Press", {130, 40})) + ++presses; + if (text_focus) { + ImGui::SetKeyboardFocusHere(); + ImGui::InputText("name", text.data(), text.size()); + } + ImGui::End(); + }); + auto mouse = [id](SDL_EventType type, float x, float y) { + SDL_Event event{}; + event.type = type; + if (type == SDL_EVENT_MOUSE_MOTION) { + event.motion.windowID = id; + event.motion.x = x; + event.motion.y = y; + } else { + event.button.windowID = id; + event.button.button = SDL_BUTTON_LEFT; + event.button.down = type == SDL_EVENT_MOUSE_BUTTON_DOWN; + event.button.clicks = 1; + event.button.x = x; + event.button.y = y; + } + CHECK(SDL_PushEvent(&event)); + }; + const auto click = [&](float x, float y) { + mouse(SDL_EVENT_MOUSE_MOTION, x, y); + CHECK(app->poll_events() && app->present(frame) == Step::rendered); // Toolkit hovers. + mouse(SDL_EVENT_MOUSE_BUTTON_DOWN, x, y); + CHECK(app->poll_events() && app->present(frame) == Step::rendered); + mouse(SDL_EVENT_MOUSE_BUTTON_UP, x, y); + CHECK(app->poll_events() && app->present(frame) == Step::rendered); + return app->take_navigation().click; + }; + // Over the widget: the button activates once, the world sees no click. + // The panel exists before the user clicks (as every application panel does). + CHECK(app->present(frame) == Step::rendered && app->present(frame) == Step::rendered); + CHECK(!click(60, 30) && presses == 1 && app->ui_wants_pointer()); + // Open world: a click is delivered once, then consumed. + const auto world = click(260, 200); + CHECK(world && world->x == 260 && world->y == 200 && presses == 1); + CHECK(!app->take_navigation().click); + // A drag is not a click. + mouse(SDL_EVENT_MOUSE_MOTION, 260, 200); + CHECK(app->poll_events() && app->present(frame) == Step::rendered); + mouse(SDL_EVENT_MOUSE_BUTTON_DOWN, 260, 200); + mouse(SDL_EVENT_MOUSE_BUTTON_UP, 290, 200); + CHECK(app->poll_events() && !app->take_navigation().click); + + auto key = [id](SDL_Scancode scancode, bool down) { + SDL_Event event{}; + event.type = down ? SDL_EVENT_KEY_DOWN : SDL_EVENT_KEY_UP; + event.key.windowID = id; + event.key.scancode = scancode; + CHECK(SDL_PushEvent(&event)); + }; + key(SDL_SCANCODE_W, true); + CHECK(app->poll_events() && required(app->sample_intention(100)).move_y == 1000); + // A focused text field takes the keyboard: held movement stops, typing never moves. + text_focus = true; + // Focus requests take effect over the next toolkit frames; wait a bounded number. + for (int i = 0; i < 5 && !app->ui_captured(); ++i) + CHECK(app->present(frame) == Step::rendered && app->poll_events()); + CHECK(app->ui_captured()); + key(SDL_SCANCODE_W, true); + CHECK(app->poll_events() && app->ui_captured()); + CHECK(required(app->sample_intention(101)).move_y == 0); + // Focus leaves the field: capture releases, but only a fresh press moves again. + text_focus = false; // The field is no longer submitted, so it loses focus. + for (int i = 0; i < 5 && app->ui_captured(); ++i) + CHECK(app->present(frame) == Step::rendered && app->poll_events()); + CHECK(!app->ui_captured()); + CHECK(required(app->sample_intention(102)).move_y == 0); + CHECK(app->poll_events()); + key(SDL_SCANCODE_W, true); + CHECK(app->poll_events() && required(app->sample_intention(103)).move_y == 1000); + // Screenshot hook writes the composed frame (engineering visual review). + const auto shot = std::filesystem::temp_directory_path() / "evo-toolkit-capture.bmp"; + CHECK(app->request_screenshot(shot.string()) && app->present(frame) == Step::rendered); + CHECK(std::filesystem::file_size(shot) > std::uintmax_t{320} * 240); + std::filesystem::remove(shot); + CHECK(!app->request_screenshot("")); +} } // namespace int main() try { client_controls_tests(); frame_contract(); lifecycle(); native_input(); + toolkit_capture(); return 0; } catch (const std::exception& e) { std::fprintf(stderr, "%s: %s\n", e.what(), SDL_GetError()); diff --git a/tests/client_ui_model.cpp b/tests/client_ui_model.cpp new file mode 100644 index 0000000..8101922 --- /dev/null +++ b/tests/client_ui_model.cpp @@ -0,0 +1,259 @@ +// 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 "evo/client/labels.hpp" +#include "evo/client/launcher.hpp" +#include "evo/client/outcome_log.hpp" +#include "evo/client/selection.hpp" +#include +#include +#include +#include +#include +#include +#include +#include +#include + +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(__VA_ARGS__)) +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 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 cells, std::uint64_t tick = 1) { + auto p = OrganismPresentation::create({identity, tick, 0}, 0, cells); + CHECK(p); + return std::move(*p); +} + +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 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); + CHECK(loaded && loaded->grants.size() == 3 && loaded->endpoint.port == 17400); + 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(LaunchError::no_session); ++e) + CHECK(launch_error_text(static_cast(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); +} +} // namespace + +int main() try { + labels(); + selection(); + launcher(); + outcome_log(); + std::puts("client UI model tests passed"); + return 0; +} catch (const std::exception& e) { + std::fprintf(stderr, "%s\n", e.what()); + return 1; +} diff --git a/tests/network_session.cpp b/tests/network_session.cpp index 2fb8f96..48286fc 100644 --- a/tests/network_session.cpp +++ b/tests/network_session.cpp @@ -696,6 +696,25 @@ void event_backpressure() { } } // namespace +void unreachable_server() { + // Refused connects produce no events (one per retry would flood callers); the + // counter lets a launcher bound "unreachable". No grant is spent without a server. + Harness h; + h.server.reset(); + auto c = h.client(grants(7, 2, 100)); + std::vector events; + // Windows reports a refused loopback connect only after about two seconds. + const auto end = Clock::now() + std::chrono::milliseconds{10000}; + while (Clock::now() < end && c->unreachable_attempts() < 2) { + c->poll(Clock::now()); + h.collect(*c, events); + std::this_thread::sleep_for(std::chrono::milliseconds{5}); + } + CHECK(c->unreachable_attempts() >= 2); + CHECK(events.empty()); + CHECK(c->grants_left() == 2 && c->phase() == SessionPhase::backoff); +} + void session_tests() { event_backpressure(); ledger_exclusive_owner(); @@ -707,5 +726,6 @@ void session_tests() { carriers_never_alias(); grants_stay_consumed_across_restarts(); liveness(); + unreachable_server(); } } // namespace evo::network_test