#pragma once // M10.5c remote dev session for the engineering client (ADR-0093, over ADR-0091/0092 // sessions). Without EVO_CLIENT_NETWORK (a build without EVO_BUILD_QUIC) remote mode is // unavailable. The client only presents copies of replicated snapshots and sends bounded // intentions; the explicit cellular trial uses reliable v10 actions and its // owner-filtered perception view. Grant bytes stay inside the session: each is handed to one // connection and wiped here; never printed, shown or persisted. // // One connection per grant (ADR-0089): a lost or closed session reconnects with the next // grant of the bundle after a growing pause (2 s .. 30 s, reset by a Welcome), which keeps // a reconnect loop inside the region's per-account attempt limit. Views come from the // newest applied snapshot. The camera follows the server's default view until the user // moves it; from then on it drives the interest (radius 7), at most every 250 ms. // // M10.6b (ADR-0094, EXPERIMENT): the session's probe marker is predicted. Each input is // recorded with the predictor and scheduled `lead` ticks ahead (adapted to refusals); each // snapshot's own marker rebases the prediction; corrections are smoothed for display. An // intention that was lost or refused is sent again once nothing is in flight and the // authority holds another vector. While following, the camera and the interest follow the // predicted marker (or, before a marker exists, the server's default view). // // M10.7b (ADR-0095): a drift-corrected tick clock (observed server ticks) times the // presentation. The own marker is drawn between ticks; other markers are interpolated // `delay` ticks behind (adaptive), extrapolated at most two ticks, then marked stale. When the // session is lost the last view stays frozen and stale: the own marker at its last // authoritative position, nothing predicted or sent. A new session starts afresh. // // M10.8c-2 (ADR-0096): a HandoffOffer (the probe crossed into another region) is followed at // once: the frozen view stays on screen, no grant is used, and the next connection goes to // the destination with the offer's ticket. A Redirect at login (the probe lives elsewhere) // is followed with a grant for that region. Grants are picked by their region claim (the // session-grant-v1 layout is public; the claim only routes, the region still verifies), so a // bundle may hold grants for several regions. #include "cellular_controls.hpp" #include "cellular_play.hpp" #include "evo/client/camera.hpp" #include "evo/client/environment_view.hpp" #include "evo/client/input.hpp" #include "evo/client/launcher.hpp" #include "evo/client/organism_view.hpp" #include "evo/client/outcome_log.hpp" #include "evo/client/ui_state.hpp" #include "evo/network/session_protocol.hpp" #include #include #include #include #include #include #include #include #ifdef EVO_CLIENT_NETWORK #include "evo/client/interpolation.hpp" #include "evo/client/motion_prediction.hpp" #include "evo/client/region_session.hpp" #include "evo/network/quic_transport.hpp" #include "evo/world/coordinates.hpp" #include #include #include #include #include #include #include #include #include #endif namespace evo::client_app { [[nodiscard]] inline std::string_view cellular_admission_message(network::AdmitStatus status) noexcept { using network::AdmitStatus; switch (status) { case AdmitStatus::admitted: return "Action accepted"; case AdmitStatus::unknown_session: return "Action refused: session is no longer active"; case AdmitStatus::stale_epoch: return "Action refused: server session changed; reconnecting may be needed"; case AdmitStatus::outside_window: return "Action refused: requested tick is outside the server window"; case AdmitStatus::rate_limited: return "Action refused: too many requests in this server window"; case AdmitStatus::replayed: return "Action refused: action sequence was already used"; case AdmitStatus::invalid_vector: return "Action refused: movement vector is invalid"; case AdmitStatus::too_many_unresolved: return "Action refused: too many earlier actions are unresolved"; case AdmitStatus::invalid_action: return "Action refused: invalid action request"; case AdmitStatus::duplicate: return "Duplicate action; waiting for its existing result"; case AdmitStatus::not_ready: return "Action refused: region is starting, recovering, or draining"; } return "Action refused: unrecognized server status"; } [[nodiscard]] inline std::string cellular_outcome_message(network::ActionResult result, std::uint64_t tick) { using network::ActionResult; switch (result) { case ActionResult::committed_no_effect: return "Action committed without a state change at tick " + std::to_string(tick); case ActionResult::not_committed: return "Action was not committed; the server made no change"; case ActionResult::pending: return "Action is still waiting for a durable result"; case ActionResult::unknown: return "The server has no durable result for this action"; case ActionResult::committed: return "Action committed at tick " + std::to_string(tick) + "; check cell position and patch stock for its effect"; } return "Action ended with an unrecognized server result"; } struct RemoteStatus { std::string phase; // connecting / connected / reconnecting / out of grants std::uint64_t session{}, epoch{}, server_tick{}, simulated_tick{}; std::size_t grants_left{}; bool welcomed{}; // Newest applied snapshot and the interest last asked for (ADR-0093). std::uint64_t snapshot_tick{}, snapshot_bytes{}; std::size_t cells{}, organisms{}; std::int64_t focus_x{}, focus_y{}, focus_z{}; bool focused{}; // The predicted probe marker (ADR-0094). bool marker{}; double marker_x_mm{}, marker_y_mm{}; std::size_t inputs_pending{}, other_markers{}; std::uint64_t lead{}, corrections{}, max_error_um{}, snaps{}; // Refusal receipts (each, whether or not the input was still pending), inputs the // predictor removed as refused or dropped as never applied, and repeated vectors. std::uint64_t refused_inputs{}, rejected_inputs{}, dropped_inputs{}, resends{}, max_pending{}; // Interpolation (ADR-0095): the current delay in ticks, markers shown stale, and whether // the whole view is a frozen copy from a lost session. double interpolation_delay{}, remote_render_tick{}; // Ticks: delay, clock - delay. std::uint64_t region{}, handoffs{}; // Region of the current session; crossings followed. std::size_t stale_markers{}; bool stale_view{}; bool cellular_trial{}; std::string cellular_action; }; // A probe marker to draw: the own one predicted and smoothed, others as replicated. struct MarkerView { double x_mm{}, y_mm{}; bool own{}; bool stale{}; // No current authority behind it (draw dimmed). bool extrapolated{}; // Continued beyond the newest snapshot (at most two ticks). bool ghost{}; // A probe being handed to this region, read-only (ADR-0096). }; #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 constexpr std::uint16_t interest_radius = 7; static constexpr double silent_ticks = 3; // Extrapolation limit (2) plus the clock's lead. // Looks the endpoint up once (blocking); nothing connects until the first step(). static std::optional open(const client::ConnectMaterial& m, bool cellular_trial = false) { const auto address = network::quic::resolve_ipv4(m.endpoint.host); if (!address || m.grants.empty()) return std::nullopt; RemoteSession session; session.transport_.server_address = *address; session.transport_.port = m.endpoint.port; session.transport_.server_name = m.server_name; session.transport_.authority_pem = m.authority_pem; session.transport_.authority_pem_file = m.authority_path; session.grants_ = m.grants; std::copy_n(m.grants.front().begin() + 32, session.account_.size(), session.account_.begin()); session.cellular_trial_ = cellular_trial; session.cellular_play_.initialize(static_cast( std::chrono::system_clock::now().time_since_epoch().count())); session.used_.assign(m.grants.size(), false); // The endpoint typed in the launcher is the first grant's region. session.target_region_ = grant_region(m.grants.front()); session.routes_[session.target_region_] = session.transport_; return session; } RemoteSession(RemoteSession&&) noexcept = default; RemoteSession& operator=(RemoteSession&&) noexcept = default; RemoteSession(const RemoteSession&) = delete; RemoteSession& operator=(const RemoteSession&) = delete; void manage_grants() { managed_grants_ = true; } [[nodiscard]] bool needs_grant(std::uint64_t utc_now) const { if (!managed_grants_) return false; if (!client_) return exhausted_ || std::ranges::all_of(used_, [](bool used) { return used; }); const auto& welcome = client_->welcome(); return client_->state() == client::RegionSessionState::established && welcome && std::max(welcome->expires_at, refreshed_until_) <= utc_now + 60 && !refresh_waiting_; } // Grants are supplied by the authenticated broker, never written to a bundle. [[nodiscard]] bool supply_grant(const client::ConnectMaterial& material) { if (!managed_grants_ || material.grants.size() != 1 || material.authority_pem != transport_.authority_pem) return false; const auto& grant = material.grants.front(); const auto serial = grant_serial(grant); if (serial < newest_serial_ || serial == UINT64_MAX || !std::equal(account_.begin(), account_.end(), grant.begin() + 32)) return false; const auto region = grant_region(grant); if (client_ && client_->state() == client::RegionSessionState::established) { if (region != region_ || !client_->refresh(grant)) return false; newest_serial_ = serial + 1; refresh_waiting_ = true; refresh_sent_at_ = Clock::now(); return true; } if (!learn_route({region, material.endpoint.host + ":" + std::to_string(material.endpoint.port), material.server_name})) return false; grants_.assign(1, grant); used_.assign(1, false); target_region_ = region; exhausted_ = false; return true; } ~RemoteSession() { if (client_) client_->close(); // Close{client_closed}; unresolved intentions stay unknown. for (auto& g : grants_) g.fill(0); if (ticket_) ticket_->fill(0); } [[nodiscard]] const client::EnvironmentLayer& environment() const noexcept { return environment_; } [[nodiscard]] const client::OrganismLayer& organisms() const noexcept { return organisms_; } [[nodiscard]] const client::OutcomeLog& outcomes() const noexcept { return log_; } [[nodiscard]] bool cellular_trial() const noexcept { return cellular_trial_; } [[nodiscard]] const network::CellularPerception* cellular_perception() const noexcept { if (!client_) return nullptr; const auto& p = client_->cellular_perception(); return p ? &*p : nullptr; } [[nodiscard]] const std::string& cellular_action_status() const noexcept { return cellular_action_status_; } [[nodiscard]] const CellularPlay& cellular_play() const noexcept { return cellular_play_; } [[nodiscard]] bool request_cellular(CellAction kind, MutationChoice choice = {}, bool become = false) { const auto lead = cellular_lead_.lead(); // A tick takes one action per account: never one a movement already named (movement // runs ahead of the lead after the lead shrinks). const auto tick = kind == CellAction::mutation ? server_tick_ : std::max(server_tick_ + lead + (sent_tick_ && *sent_tick_ == server_tick_ ? 1 : 0), cellular_sent_tick_ + 1); if (!cellular_trial_ || !cellular_play_.queue(kind, tick, choice, become)) return false; action_check_at_ = {}; if (kind != CellAction::mutation) cellular_feed_target_.reset(); return true; } [[nodiscard]] bool restart_cellular() { if (!cellular_trial_ || !cellular_play_.restart()) return false; cellular_feed_target_.reset(); birth_check_at_ = {}; cellular_action_status_ = "New life requested; waiting for the server"; return true; } void keep_cellular_unknown() { cellular_play_.keep_unknown(); } void set_cellular_controls(CellularControls controls) { cellular_controls_ = controls; } void set_cellular_feed_target( std::optional> target) noexcept { cellular_feed_target_ = target; } [[nodiscard]] auto cellular_feed_target() const noexcept { return cellular_feed_target_; } [[nodiscard]] RemoteStatus status() const { RemoteStatus s; const bool live = client_ && client_->state() == client::RegionSessionState::established; s.phase = live ? "connected" : exhausted_ ? "out of grants" : welcomed_ ? "reconnecting" : "connecting"; s.session = session_; s.epoch = epoch_; s.server_tick = server_tick_; s.simulated_tick = simulated_tick_; s.grants_left = static_cast(std::ranges::count(used_, false)); s.region = region_; s.handoffs = handoffs_; if (ticket_ || (client_ && handing_off_ && !live)) s.phase = "handing off"; s.welcomed = welcomed_; s.snapshot_tick = seen_snapshot_; s.snapshot_bytes = snapshot_bytes_ + (client_ ? client_->snapshot_bytes() : 0); if (const auto* e = environment_.current()) s.cells = e->cells().size(); if (const auto* o = organisms_.current()) s.organisms = o->cells().size(); if (sent_interest_) { s.focused = true; s.focus_x = sent_interest_->x; s.focus_y = sent_interest_->y; s.focus_z = sent_interest_->z; } for (const auto& m : markers_) { if (m.own) { s.marker = true; s.marker_x_mm = m.x_mm; s.marker_y_mm = m.y_mm; } else { ++s.other_markers; } s.stale_markers += m.stale ? 1 : 0; } s.interpolation_delay = interpolator_.delay(); s.remote_render_tick = render_tick_; s.stale_view = stale_view_; s.cellular_trial = cellular_trial_; s.cellular_action = cellular_action_status_; s.inputs_pending = predictor_.pending(); s.lead = lead_.lead(); s.corrections = predictor_.stats().corrections; s.max_error_um = predictor_.stats().max_error_um; s.snaps = smoother_.snaps(); s.rejected_inputs = predictor_.stats().rejected_inputs; s.dropped_inputs = predictor_.stats().dropped_inputs; s.max_pending = predictor_.stats().max_pending; s.resends = resends_; s.refused_inputs = refused_; return s; } // Prediction error samples since the last call (micrometres; for measurements). [[nodiscard]] std::vector take_prediction_errors() { return predictor_.take_errors(); } // Markers to draw this frame (empty without a session or snapshot). [[nodiscard]] const std::vector& markers() const noexcept { return markers_; } // Where the camera should be while it follows the server's view: the middle of the // newest snapshot's square, offered whenever it changes (the first snapshots may still // be filling in, nearest cells first). [[nodiscard]] std::optional take_recentre() { return std::exchange(recentre_, std::nullopt); } // Called every frame with the camera centre. While following, a centre other than the // one offered means the user moved the camera: from then on the camera's voxel is the // interest of the next sends. void focus(client::WorldPoint centre) { if (!std::isfinite(centre.x_mm) || !std::isfinite(centre.y_mm)) return; if (following_) { if (!offered_ || (centre.x_mm == offered_->x_mm && centre.y_mm == offered_->y_mm)) return; // Nothing shown yet, or still where the view put it. following_ = false; recentre_.reset(); } constexpr auto pitch = static_cast(world::cell_pitch_mm); constexpr double limit = 9.0e15; // Well inside int64 and the camera's own range. const double x = std::floor(centre.x_mm / pitch), y = std::floor(centre.y_mm / pitch); if (std::abs(x) > limit || std::abs(y) > limit) return; wanted_ = network::SessionInterest{static_cast(x), static_cast(y), slice_z_, interest_radius}; } // Services the connection; sends the intention when its vector changed, at most once // per server tick. Session events update the outcome log (the 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) { if (!client_ && !start(now, launcher)) return; auto& c = *client_; c.poll(now); if (const auto refreshed = c.take_refresh_result()) { refresh_waiting_ = false; if (refreshed->status == 0) // Accepted: the session now runs to the new expiry. refreshed_until_ = std::max(refreshed_until_, refreshed->expires_at); } else if (refresh_waiting_ && now - refresh_sent_at_ >= std::chrono::seconds{5}) { refresh_waiting_ = false; } if (c.state() == client::RegionSessionState::closed) { end(now, ui, launcher); return; } if (c.state() != client::RegionSessionState::established) return; if (!established_) welcome(ui, launcher); server_tick_ = c.server_tick(); if (server_tick_ != observed_tick_) { // Every watermark or snapshot tick times the clock. observed_tick_ = server_tick_; clock_.observe(server_tick_, now); } receipts(); cellular_results(); snapshot(); if (cellular_trial_) { const auto old_life = cellular_play_.life(); if (const auto& p = c.cellular_perception()) cellular_play_.observe(*p); if (const auto& ended = c.life_ended()) cellular_play_.observe_end(*ended); cellular_play_.observe_offer(c.mutation_offer()); if (old_life != cellular_play_.life()) cellular_feed_target_.reset(); service_cellular(now); send_cellular(intention); } else { send(intention); } present(now); if (wanted_ && (!sent_interest_ || *wanted_ != *sent_interest_) && now - interest_at_ >= std::chrono::milliseconds{250} && c.set_interest(*wanted_)) { sent_interest_ = wanted_; interest_at_ = now; } std::fflush(stdout); } private: using Clock = std::chrono::steady_clock; // Session sequences restart with each session; the log numbers intentions itself. struct Pending { std::uint64_t sequence{}, entry{}, tick{}; bool admitted{}; }; static constexpr std::size_t max_pending = client::OutcomeLog::capacity; RemoteSession() = default; static void notify(client::UiState& ui, const char* text, client::NoticeLevel level) { static_cast(ui.notify(text, level).has_value()); // Bounded; overflow evicts. } // Opens the next connection with the next grant; false while pausing or out of grants. // The region claim of a session-grant-v1 record (marker "EVO-GRANT", region at offset // 72), read only to route; anything else has no region (0). static std::uint64_t grant_field(const network::WireGrant& g, std::size_t at) { static constexpr std::array marker{'E', 'V', 'O', '-', 'G', 'R', 'A', 'N', 'T'}; if (!std::equal(marker.begin(), marker.end(), g.begin())) return 0; std::uint64_t v = 0; for (std::size_t i = 0; i < 8; ++i) v |= static_cast(g.at(at + i)) << (8 * i); return v; } static std::uint64_t grant_region(const network::WireGrant& g) { return grant_field(g, 72); } // Serials must rise world-wide (durable account control): never use a lower one after a // higher one, whichever region it is for. static std::uint64_t grant_serial(const network::WireGrant& g) { return grant_field(g, 48); } // How to dial a region named by an offer or redirect ("host:port" and its certificate // name), resolved once; nothing when the address cannot be used. [[nodiscard]] bool learn_route(const network::RegionAddress& a) { const auto colon = a.endpoint.rfind(':'); if (colon == std::string::npos) return false; std::uint16_t port = 0; const auto* begin = a.endpoint.data() + colon + 1; const auto* end = a.endpoint.data() + a.endpoint.size(); if (const auto [at, ec] = std::from_chars(begin, end, port); ec != std::errc{} || at != end || port == 0) return false; const auto address = network::quic::resolve_ipv4(a.endpoint.substr(0, colon)); if (!address) return false; auto route = transport_; // Same pinned CA: one world, one dev CA. route.server_address = *address; route.port = port; route.server_name = a.server_name; routes_[a.region] = std::move(route); return true; } bool start(Clock::time_point now, client::Launcher& launcher) { if (now < retry_at_) return false; client::RegionSessionClientConfig config; if (cellular_trial_) // Rules 13: v14 is v13 (deposits, light, producers, liquid motion and brake) plus the // revamp: become, emerge, exclusions, catalog offers and the body block. config.protocol_version = network::session_protocol_v14; const auto route = routes_.find(target_region_); config.transport = route != routes_.end() ? route->second : transport_; if (ticket_) { // A handoff: the ticket replaces a grant, once. config.grant = *ticket_; ticket_->fill(0); ticket_.reset(); } else { std::size_t pick = grants_.size(); for (std::size_t i = 0; i < grants_.size(); ++i) if (!used_[i] && grant_serial(grants_[i]) < newest_serial_) { grants_[i].fill(0); // Outdated by a grant already used: unusable. used_[i] = true; } for (std::size_t i = 0; i < grants_.size(); ++i) if (!used_[i] && (target_region_ == 0 || grant_region(grants_[i]) == target_region_) && (pick == grants_.size() || grant_serial(grants_[i]) < grant_serial(grants_[pick]))) pick = i; // The lowest usable serial for the region. if (pick == grants_.size()) { if (!exhausted_) { exhausted_ = true; if (!managed_grants_) { launcher.observe(client::ConnectSignal::exhausted); std::printf( "session grants for region %llu exhausted; issue a new bundle\n", static_cast(target_region_)); } } return false; } newest_serial_ = std::max(newest_serial_, grant_serial(grants_[pick]) + 1); config.grant = grants_[pick]; grants_[pick].fill(0); used_[pick] = true; } auto made = client::RegionSessionClient::connect(std::move(config), now); if (!made) { launcher.observe(client::ConnectSignal::lost); pause(now); return false; } client_ = std::move(*made); established_ = false; refreshed_until_ = 0; // A new session starts from its own welcome. refresh_waiting_ = false; return true; } void pause(Clock::time_point now) { retry_at_ = now + backoff_; backoff_ = std::min(backoff_ * 2, std::chrono::seconds{30}); } void welcome(client::UiState& ui, client::Launcher& launcher) { const auto& welcome_message = client_->welcome(); if (!welcome_message) return; const auto& w = *welcome_message; established_ = true; welcomed_ = true; backoff_ = std::chrono::seconds{2}; handing_off_ = false; if (w.epoch != epoch_ || w.region != region_) { // Another lineage or region: afresh. environment_.reset(); organisms_.reset(); seen_snapshot_ = 0; } session_ = w.session; epoch_ = w.epoch; region_ = w.region; sent_tick_.reset(); // New session: resend the current intention. sent_ = {}; sent_interest_.reset(); // The server starts from its default interest. predictor_.reset(); // A new session has a new marker. smoother_.reset(); lead_.reset(); cellular_lead_.reset(); cellular_sent_tick_ = 0; clock_.reset(); // Fresh baseline: the frozen view of a lost session is dropped. interpolator_.reset(); markers_.clear(); observed_tick_ = 0; stale_view_ = false; cellular_play_.connected(); action_check_at_ = birth_check_at_ = {}; 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\n", static_cast(w.session), static_cast(w.epoch), static_cast(w.server_tick)); } void send(const client::Intention& intention) { const network::motion::Vector want{intention.move_x, intention.move_y}; if (server_tick_ == 0 || (sent_tick_ && server_tick_ <= *sent_tick_) || predictor_.full()) return; // Resend when the authority holds another vector and nothing in flight will change // it (the last intention was lost or refused). const auto& authority = predictor_.authority(); const bool stale = authority && authority->state.vector != want && predictor_.pending() == 0; if (want == sent_ && !stale) return; const auto tick = server_tick_ + lead_.lead(); // Refused until the datagram extension is negotiated: retried next frame. const auto sequence = client_->send_intention(tick, want.x, want.y); if (!sequence) return; static_cast(predictor_.input({*sequence, tick, want})); resends_ += want == sent_ ? 1 : 0; sent_ = want; sent_tick_ = server_tick_; const auto entry = next_entry_++; log_.record({entry, client::OutcomeState::sent, 0, tick}); if (pending_.size() == max_pending) pending_.pop_front(); // Its log entry was evicted with it. pending_.push_back({*sequence, entry, tick, false}); } void send_cellular(const client::Intention& intention) { if (server_tick_ == 0 || (sent_tick_ && server_tick_ <= *sent_tick_) || !cellular_play_.fresh() || cellular_play_.life() == 0 || cellular_play_.ended()) return; // The server admits only ticks still ahead of it when the action arrives; the view // trails it by the replication delay, so schedule by the adaptive lead. // Strictly increasing even when the lead shrinks: one movement per tick. const auto tick = std::max(server_tick_ + cellular_lead_.lead(), cellular_sent_tick_ + 1); // A queued discrete action owns its tick; movement resumes after it is sent. if (const auto& p = cellular_play_.pending(); p && p->state == CellActionState::queued && p->kind != CellAction::mutation && p->tick <= tick) return; const auto steering = steer_cellular(cellular_controls_, intention, cellular_perception(), organisms_.current(), cellular_feed_target_); cellular_feed_target_ = steering.patch; const auto id = cellular_play_.allocate_id(); if (id == 0 || !client_->send_cellular_action( id, tick, steering.intention.move_x, steering.intention.move_y, cellular_feed_target_, false, false, steering.intention.brake, false, false, cellular_controls_.exclude)) return; sent_tick_ = server_tick_; cellular_sent_tick_ = tick; } void service_cellular(Clock::time_point now) { if (cellular_play_.birth_pending() && now >= birth_check_at_) { if (client_->request_primitive_life(cellular_play_.birth_request())) birth_check_at_ = now + std::chrono::seconds{2}; } const auto& pending = cellular_play_.pending(); if (!pending || now < action_check_at_) return; const auto& p = *pending; cellular_play_.rechecking(); // A refused retry cannot settle a lost original reply. bool sent = false; if (p.kind == CellAction::mutation) { sent = client_->send_cellular_mutation(p.id, p.tick, p.choice.life, p.choice.event, p.choice.offer_tick, p.choice.operator_id, p.choice.become); } else if (p.state == CellActionState::queued) { if (p.tick > server_tick_ + cellular_lead_.lead()) return; // Do not replace a movement/feeding intention already sent this tick. sent = client_->send_cellular_action( p.id, p.tick, 0, 0, {}, p.kind == CellAction::engulf, p.kind == CellAction::bud, false, p.become, p.kind == CellAction::emerge, cellular_controls_.exclude); if (sent) { sent_tick_ = server_tick_; // The discrete intention owns this tick's target. cellular_sent_tick_ = std::max(cellular_sent_tick_, p.tick); } } else { sent = client_->query_action(p.id); // A query can never bud a second time. } if (sent) { if (p.state == CellActionState::queued) cellular_play_.sent(); action_check_at_ = now + std::chrono::seconds{2}; } } void cellular_results() { for (const auto& receipt : client_->take_primitive_life_receipts()) if (receipt.status != network::AdmitStatus::admitted) cellular_action_status_ = "Birth request refused (status " + std::to_string(static_cast(receipt.status)) + ")"; for (const auto& outcome : client_->take_primitive_life_outcomes()) { if (outcome.request_id != cellular_play_.birth_request()) continue; cellular_play_.birth(outcome); switch (outcome.result) { case network::PrimitiveLifeResult::born: cellular_action_status_ = "Cell founded (life " + std::to_string(outcome.life_identity) + ")"; break; case network::PrimitiveLifeResult::insufficient_funding: cellular_action_status_ = "Birth refused: the region nursery lacks resources. " "A new account cannot restore them."; break; case network::PrimitiveLifeResult::no_placement: cellular_action_status_ = "Birth refused: no open spawn site"; break; case network::PrimitiveLifeResult::existing_life: cellular_action_status_ = "Existing cell is already bound to this account"; break; case network::PrimitiveLifeResult::cancelled: cellular_action_status_ = "Birth request cancelled"; break; case network::PrimitiveLifeResult::pending: cellular_action_status_ = "Birth is pending on the server; no new cell confirmed yet"; break; case network::PrimitiveLifeResult::unknown: cellular_action_status_ = "Birth outcome is unknown; retrying exact request"; break; } } for (const auto& receipt : client_->take_action_receipts()) { if (receipt.status == network::AdmitStatus::admitted) cellular_lead_.admitted(receipt.tick, receipt.server_tick); else if (receipt.status == network::AdmitStatus::outside_window) cellular_lead_.too_late(); // Arrived after its tick: schedule further ahead. cellular_play_.receipt(receipt); if (receipt.status != network::AdmitStatus::admitted) cellular_action_status_ = cellular_admission_message(receipt.status); } for (const auto& outcome : client_->take_action_outcomes()) { cellular_play_.outcome(outcome); cellular_action_status_ = cellular_outcome_message(outcome.result, outcome.tick); } } void receipts() { for (const auto& r : client_->take_intention_receipts()) { const auto it = std::find_if(pending_.begin(), pending_.end(), [&](const Pending& p) { return p.sequence == r.sequence; }); if (it == pending_.end()) continue; // Evicted from the bounded record already. std::printf("intent %llu status=%u\n", static_cast(it->entry), static_cast(r.status)); if (r.status == network::AdmitStatus::admitted) { log_.record({it->entry, client::OutcomeState::admitted, 0, it->tick}); it->admitted = true; lead_.admitted(it->tick, r.server_tick); } else { predictor_.rejected(r.sequence); // It never takes effect. ++refused_; if (r.status == network::AdmitStatus::outside_window) lead_.too_late(); // Arrived after its tick: schedule further ahead. log_.record({it->entry, client::OutcomeState::rejected, static_cast(r.status), it->tick}); pending_.erase(it); } } const auto s = client_->simulated(); if (!s) return; simulated_tick_ = s->tick; // Cumulative: every admitted intention up to the sequence, at or before the tick. std::erase_if(pending_, [&](const Pending& p) { if (!p.admitted || p.sequence > s->sequence || p.tick > s->tick) return false; log_.record({p.entry, client::OutcomeState::simulated, 0, p.tick}); return true; }); } void snapshot() { const auto* v = client_->view(); if (v == nullptr || v->tick == seen_snapshot_) return; seen_snapshot_ = v->tick; slice_z_ = v->slice_z; if (auto e = client_->environment()) { if (!environment_.accept(*e)) { // E.g. regressed after a restore: start afresh. environment_.reset(); static_cast(environment_.accept(std::move(*e)).has_value()); } } if (auto o = client_->organisms()) { if (!organisms_.accept(*o)) { organisms_.reset(); static_cast(organisms_.accept(std::move(*o)).has_value()); } } std::vector remote; for (const auto& m : v->markers) { if (m.own) predictor_.authoritative({v->tick, m.applied_sequence, m.state, m.area}); else remote.push_back({m.id, m.state, m.ghost}); } interpolator_.push(v->tick, remote); if (!following_ || v->environment.empty() || predictor_.authority()) return; // With a marker, present() follows it instead. const auto [lx, hx] = std::minmax_element(v->environment.begin(), v->environment.end(), [](const auto& a, const auto& b) { return a.voxel.x < b.voxel.x; }); const auto [ly, hy] = std::minmax_element(v->environment.begin(), v->environment.end(), [](const auto& a, const auto& b) { return a.voxel.y < b.voxel.y; }); constexpr auto pitch = static_cast(world::cell_pitch_mm); const client::WorldPoint middle{ (static_cast(lx->voxel.x) + static_cast(hx->voxel.x) + 1) * pitch / 2, (static_cast(ly->voxel.y) + static_cast(hy->voxel.y) + 1) * pitch / 2}; if (!offered_ || middle.x_mm != offered_->x_mm || middle.y_mm != offered_->y_mm) recentre_ = offered_ = middle; } // The predicted own marker (smoothed) and the others; while following, the camera and // the interest follow the own marker. void present(Clock::time_point now) { const double elapsed = last_present_ ? std::chrono::duration(now - *last_present_).count() : 0; last_present_ = now; markers_.clear(); interpolator_.advance(elapsed); const auto clock = clock_.at(now).value_or(static_cast(server_tick_)); // The own marker in the predicted present, between whole ticks. const auto presented = clock + static_cast(lead_.lead()); const auto whole = static_cast(std::floor(presented)); // Errors are measured only for ticks inputs are already being scheduled for. const auto predicted = predictor_.predict_between( whole, presented - static_cast(whole), whole <= server_tick_ + lead_.lead()); const auto& authority = predictor_.authority(); if (predicted && authority) { smoother_.add(predictor_.take_correction()); const auto offset = smoother_.advance(elapsed); const MarkerView own{(predicted->x + static_cast(offset.x)) / 1000, (predicted->y + static_cast(offset.y)) / 1000, true}; markers_.push_back(own); if (following_) { recentre_ = offered_ = client::WorldPoint{own.x_mm, own.y_mm}; const auto x = static_cast(std::floor(predicted->x)); const auto y = static_cast(std::floor(predicted->y)); wanted_ = network::SessionInterest{cell(x), cell(y), authority->area.z, interest_radius}; } } // Other markers in the recent past, interpolated. render_tick_ = clock - interpolator_.delay(); // A silent server freezes the clock; beyond the extrapolation limit that silence is // what makes the shown markers stale. const bool silent = clock_.silence(now).value_or(0) > silent_ticks; for (const auto& m : interpolator_.at(render_tick_)) markers_.push_back( {m.x / 1000, m.y / 1000, false, m.stale || silent, m.extrapolated, m.ghost}); } static std::int64_t cell(std::int64_t um) { constexpr auto size = network::motion::micrometres_per_cell; return um >= 0 || um % size == 0 ? um / size : (um / size) - 1; } // The connection ended: decide what the launcher hears and pause before the next grant. void end(Clock::time_point now, client::UiState& ui, client::Launcher& launcher) { using network::SessionCloseReason; const auto reason = client_->close_reason().value_or(SessionCloseReason::connection_lost); const auto offer = client_->take_handoff(); const auto redirect = client_->redirect(); const bool was_established = established_; snapshot_bytes_ += client_->snapshot_bytes(); for (const auto& p : pending_) log_.record({p.entry, client::OutcomeState::unknown, 0, p.tick}); pending_.clear(); environment_.mark_stale(); organisms_.mark_stale(); // Freeze the view as it was: the own marker at its last authoritative position, // everything stale. Nothing is predicted or sent until a new session starts afresh. const auto& authority = predictor_.authority(); std::erase_if(markers_, [](const MarkerView& m) { return m.own; }); if (authority) markers_.push_back({static_cast(authority->state.x) / 1000, static_cast(authority->state.y) / 1000, true}); for (auto& m : markers_) { m.stale = true; m.extrapolated = false; } stale_view_ = was_established || stale_view_; predictor_.reset(); // The marker ended with its session. client_.reset(); cellular_play_.disconnected(); cellular_feed_target_.reset(); established_ = false; // A crossing or a redirect is followed at once: no grant for a handoff, no pause. if (reason == SessionCloseReason::handed_off && offer && learn_route(offer->destination)) { ticket_ = offer->ticket; target_region_ = offer->destination.region; handing_off_ = true; ++handoffs_; stale_view_ = false; // A switch, not a loss: the view stays as it was. launcher.observe(client::ConnectSignal::not_ready); notify(ui, "Crossing into a neighbouring region.", client::NoticeLevel::info); std::printf("session handoff region=%llu\n", static_cast(target_region_)); retry_at_ = now; return; } if (reason == SessionCloseReason::moved && redirect && learn_route(*redirect)) { target_region_ = redirect->region; launcher.observe(client::ConnectSignal::not_ready); notify(ui, "Your probe is in another region; connecting there.", client::NoticeLevel::info); std::printf("session redirect region=%llu\n", static_cast(target_region_)); retry_at_ = now; return; } const bool not_ready = reason == SessionCloseReason::shutdown || reason == SessionCloseReason::capacity; const bool lost = reason == SessionCloseReason::connection_lost || reason == SessionCloseReason::timeout || reason == SessionCloseReason::rate_limited || reason == SessionCloseReason::stale_epoch || (was_established && reason == SessionCloseReason::expired); if (reason == SessionCloseReason::stale_grant && !was_established) { // This grant (or a newer one) was already presented, by this or another client: // only this grant is spent, so try the next one; an empty bundle ends as exhausted. launcher.observe(client::ConnectSignal::not_ready); notify(ui, "That grant was already used; trying the next one.", client::NoticeLevel::info); } else if (reason == SessionCloseReason::superseded) { // Another client holds this account's newer grant: never fight it. launcher.fail(client::LaunchError::grant_refused); notify(ui, "Another client opened a session with this account.", client::NoticeLevel::warning); } else { launcher.observe(not_ready ? client::ConnectSignal::not_ready : lost ? client::ConnectSignal::lost : client::ConnectSignal::refused); notify(ui, not_ready ? "Server not ready; retrying." : was_established ? "Session ended; reconnecting with the next grant." : "Connection attempt failed.", not_ready ? client::NoticeLevel::info : client::NoticeLevel::warning); } std::printf("session closed reason=%u\n", static_cast(reason)); pause(now); } network::quic::ClientConfig transport_; std::vector grants_; std::vector used_; std::array account_{}; bool managed_grants_{}, refresh_waiting_{}; std::uint64_t refreshed_until_{}; // Expiry from the last accepted SessionRefresh. Clock::time_point refresh_sent_at_{}; std::map routes_; // Region -> how to dial it. std::uint64_t target_region_{}, region_{}, handoffs_{}, newest_serial_{}; client::InputLead cellular_lead_; // Cellular action ticks (2..7 ahead of the view). std::uint64_t cellular_sent_tick_{}; // Newest tick a movement or discrete action named. std::optional ticket_; // A handoff ticket for the next connection. bool handing_off_{}; std::unique_ptr client_; client::EnvironmentLayer environment_; client::OrganismLayer organisms_; client::OutcomeLog log_; std::deque pending_; std::uint64_t next_entry_{1}; Clock::time_point retry_at_{}, interest_at_{}; std::chrono::seconds backoff_{2}; std::uint64_t session_{}, epoch_{}, server_tick_{}, simulated_tick_{}, seen_snapshot_{}, snapshot_bytes_{}; std::optional sent_tick_; std::optional wanted_, sent_interest_; std::optional recentre_, offered_; std::int64_t slice_z_{}; network::motion::Vector sent_; client::MotionPredictor predictor_; client::CorrectionSmoother smoother_; client::InputLead lead_; std::optional last_present_; std::uint64_t resends_{}, refused_{}; client::TickClock clock_; client::MarkerInterpolator interpolator_; std::uint64_t observed_tick_{}; double render_tick_{}; std::vector markers_; bool stale_view_{}; bool established_{}, welcomed_{}, exhausted_{}; bool following_{true}; // The camera follows the server's (default) view. bool cellular_trial_{}; CellularPlay cellular_play_; CellularControls cellular_controls_; Clock::time_point action_check_at_{}, birth_check_at_{}; std::optional> cellular_feed_target_; std::string cellular_action_status_; }; #else inline constexpr bool remote_available = false; class RemoteSession { public: void manage_grants() {} [[nodiscard]] bool needs_grant(std::uint64_t) const { return false; } [[nodiscard]] bool supply_grant(const client::ConnectMaterial&) { return false; } static std::optional open(const client::ConnectMaterial&, bool = false) { return std::nullopt; } [[nodiscard]] const client::EnvironmentLayer& environment() const noexcept { return environment_; } [[nodiscard]] const client::OrganismLayer& organisms() const noexcept { return organisms_; } [[nodiscard]] const client::OutcomeLog& outcomes() const noexcept { return log_; } [[nodiscard]] bool cellular_trial() const noexcept { return false; } [[nodiscard]] const network::CellularPerception* cellular_perception() const noexcept { return nullptr; } [[nodiscard]] const std::string& cellular_action_status() const noexcept { return action_status_; } [[nodiscard]] const CellularPlay& cellular_play() const noexcept { return cellular_play_; } [[nodiscard]] bool request_cellular(CellAction, MutationChoice = {}, bool = false) { return false; } [[nodiscard]] bool restart_cellular() { return false; } void keep_cellular_unknown() {} void set_cellular_controls(CellularControls) {} void set_cellular_feed_target(std::optional>) noexcept { } [[nodiscard]] std::optional> cellular_feed_target() const noexcept { return {}; } [[nodiscard]] RemoteStatus status() const { RemoteStatus status; status.phase = "unavailable in this build"; return status; } [[nodiscard]] std::optional take_recentre() { return std::nullopt; } [[nodiscard]] const std::vector& markers() const noexcept { return markers_; } void focus(client::WorldPoint) {} void step(std::chrono::steady_clock::time_point, const client::Intention&, client::UiState&, client::Launcher&) {} private: CellularPlay cellular_play_; std::string action_status_; client::EnvironmentLayer environment_; client::OrganismLayer organisms_; client::OutcomeLog log_; std::vector markers_; }; #endif } // namespace evo::client_app