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 <noreply@anthropic.com>
This commit is contained in:
dingo
2026-10-02 10:09:11 -04:00
co-authored by Claude Opus 5.5
parent a6e8094f57
commit 897055883a
36 changed files with 2106 additions and 200 deletions
+11 -1
View File
@@ -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<void, InputError> InputState::wheel(double steps) {
Navigation InputState::take_navigation() noexcept {
const Navigation result{static_cast<int>(keys_[5]) - static_cast<int>(keys_[4]),
static_cast<int>(keys_[7]) - static_cast<int>(keys_[6]), wheel_,
pointer_};
pointer_, click_};
wheel_ = 0;
click_.reset();
return result;
}
std::expected<void, InputError> 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<Intention, InputError> InputState::sample(std::uint64_t tick) {
if (tick_ && tick <= *tick_)
return std::unexpected(InputError::stale_tick);
+137 -11
View File
@@ -3,6 +3,9 @@
#define SDL_MAIN_HANDLED
#include <SDL3/SDL_main.h>
#include <cmath>
#include <imgui.h>
#include <imgui_impl_sdl3.h>
#include <imgui_impl_sdlrenderer3.h>
#include <optional>
#include <utility>
@@ -31,6 +34,42 @@ std::optional<Key> 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<Error> 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<SDL_FPoint> 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<void, Error> 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<std::unique_ptr<Application>, 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<Application>{new Application{std::move(impl)}};
}
std::expected<Step, Error> Application::step(const render::Frame& frame) {
@@ -135,10 +208,18 @@ std::expected<void, Error> 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<void, Error> 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<void, Error> 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<SDL_FPoint>{{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<void, Error> 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<void, Error> 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<Step, Error> 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<SDL_Surface, decltype(&SDL_DestroySurface)> 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);
+151
View File
@@ -0,0 +1,151 @@
#include "evo/client/labels.hpp"
#include "evo/render/environment.hpp"
#include "evo/world/generation.hpp"
#include <array>
#include <cmath>
#include <cstdio>
namespace evo::client {
namespace {
constexpr std::array<std::string_view, world::field_count> 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<char, 48> text{};
const int n = std::snprintf(text.data(), text.size(), format, value);
return n > 0 ? std::string(text.data(), static_cast<std::size_t>(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<double>(value) / 10.0, "%.1f") + " %";
}
} // namespace
std::string_view field_name(world::Field field) noexcept {
const auto k = static_cast<std::size_t>(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<std::size_t>(field) >= static_cast<std::size_t>(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<std::size_t>(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<double>(quantity) / static_cast<double>(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<double>(m.numerator) / static_cast<double>(m.denominator);
return {m.numerator == 0 ? ValueKind::zero : ValueKind::value,
number(share * 100.0, "%.2f") + " % saturated" +
(m.numerator == 0 ? " (present zero)" : "")};
}
std::vector<Row> 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<Row> 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
+181
View File
@@ -0,0 +1,181 @@
#include "evo/client/launcher.hpp"
#include <algorithm>
#include <cctype>
#include <charconv>
#include <filesystem>
#include <fstream>
#include <system_error>
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<unsigned char>(ch)) != 0 || ch == '-' || ch == '.';
});
}
// Reads at most `limit` bytes; anything longer is rejected, never truncated.
std::expected<std::vector<std::uint8_t>, 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<std::uint8_t> bytes(static_cast<std::size_t>(size));
if (!file ||
!file.read(reinterpret_cast<char*>(bytes.data()), static_cast<std::streamsize>(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<Endpoint, LaunchError> 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<unsigned char>(ch)) != 0 || ch == ':' || ch == '.';
}))
return std::unexpected(LaunchError::endpoint);
} else if (!dns_name(host)) {
return std::unexpected(LaunchError::endpoint);
}
return Endpoint{host, static_cast<std::uint16_t>(port)};
}
std::expected<ConnectMaterial, LaunchError> 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<std::ptrdiff_t>(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
+20
View File
@@ -0,0 +1,20 @@
#include "evo/client/outcome_log.hpp"
#include <algorithm>
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
+65
View File
@@ -0,0 +1,65 @@
#include "evo/client/selection.hpp"
#include "evo/client/organism_inspector.hpp"
#include <algorithm>
#include <cmath>
namespace evo::client {
namespace {
constexpr double pitch_mm = static_cast<double>(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::int64_t>(std::floor(world->x_mm / pitch_mm));
const auto y = static_cast<std::int64_t>(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