From bb0412cd0f2d7e24e09586d1103adb72d3736218 Mon Sep 17 00:00:00 2001 From: dingo Date: Thu, 1 Oct 2026 17:26:35 -0400 Subject: [PATCH] Implement M9.3 camera navigation and bounded input intentions --- README.md | 2 + apps/evo-client/main.cpp | 77 ++++++++++- cmake/ClientProbe.cmake | 7 +- docs/ROADMAP.md | 8 +- docs/STATUS.md | 16 +-- docs/adr/0079-camera-and-input-intentions.md | 64 +++++++++ docs/adr/README.md | 1 + docs/architecture/CLIENT_ARCHITECTURE.md | 12 +- docs/engineering/CAMERA_INPUT.md | 78 +++++++++++ docs/engineering/CLIENT.md | 12 +- docs/engineering/VALIDATION.md | 44 ++++++ include/evo/client/application.hpp | 10 +- include/evo/client/camera.hpp | 48 +++++++ include/evo/client/input.hpp | 54 ++++++++ src/client/camera/camera.cpp | 101 ++++++++++++++ src/client/input/input.cpp | 64 +++++++++ src/client/platform/application.cpp | 97 +++++++++++++- tests/client_controls.cpp | 133 +++++++++++++++++++ tests/client_lifecycle.cpp | 98 ++++++++++++++ 19 files changed, 899 insertions(+), 27 deletions(-) create mode 100644 docs/adr/0079-camera-and-input-intentions.md create mode 100644 docs/engineering/CAMERA_INPUT.md create mode 100644 include/evo/client/camera.hpp create mode 100644 include/evo/client/input.hpp create mode 100644 src/client/camera/camera.cpp create mode 100644 src/client/input/input.cpp create mode 100644 tests/client_controls.cpp diff --git a/README.md b/README.md index a8963d8..2419ec0 100644 --- a/README.md +++ b/README.md @@ -170,3 +170,5 @@ The optional SDL3 probe is separate from the headless targets. See [client dependency preparation and checks](docs/engineering/CLIENT_DEPENDENCIES.md). M9.2 supplies the [native engineering client](docs/engineering/CLIENT.md), with an immutable frame boundary and tested window/resource lifecycle. +M9.3 adds [camera navigation and input intentions](docs/engineering/CAMERA_INPUT.md), +with explicit UI capture and no authoritative movement or network connection. diff --git a/apps/evo-client/main.cpp b/apps/evo-client/main.cpp index 64175a0..9d2f529 100644 --- a/apps/evo-client/main.cpp +++ b/apps/evo-client/main.cpp @@ -1,7 +1,9 @@ #include "evo/client/application.hpp" +#include #include #include #include +#include #include #include #include @@ -34,14 +36,77 @@ int main(int argc, char** argv) try { std::fprintf(stderr, "client initialization error=%d\n", static_cast(app.error())); return 1; } - // Presentation fixture only. No simulated organisms or world state. - const std::array boxes{{{24, 24, 160, 96, {64, 180, 140, 255}}}}; - const auto frame = evo::render::Frame::create(boxes, {16, 20, 28, 255}); - if (!frame) + // A minimized native window may start with no drawable area. Adopt the + // native viewport before projecting; until then use the requested size. + auto camera = + evo::client::Camera::create({config.width, config.height, config.width, config.height}); + if (!camera) return 1; - unsigned count = 0; + std::puts("Arrows: pan | wheel: zoom | WASD: intention indicator | Tab: UI capture (orange)"); + std::uint64_t count = 0; + auto previous = std::chrono::steady_clock::now(); while (frames == 0 || count < frames) { - const auto result = (*app)->step(*frame); + if (auto result = (*app)->poll_events(); !result) { + std::fprintf(stderr, "client event error=%d\n", static_cast(result.error())); + return 1; + } + const auto state = (*app)->state(); + if (state.closed) + break; + const auto now = std::chrono::steady_clock::now(); + const double seconds = + std::clamp(std::chrono::duration(now - previous).count(), 0.0, 0.1); + previous = now; + const auto navigation = (*app)->take_navigation(); + // Fixture ticks only. No server session or simulation clock exists here. + const auto intention = (*app)->sample_intention(count); + if (!intention) + return 1; + std::array boxes{}; + if (state.logical_width > 0 && state.logical_height > 0 && state.pixel_width > 0 && + state.pixel_height > 0) { + if (!camera->resize({state.logical_width, state.logical_height, state.pixel_width, + state.pixel_height})) + return 1; + if (auto result = + camera->pan({navigation.x * 400 * seconds, navigation.y * 400 * seconds}); + !result && result.error() != evo::client::CameraError::out_of_range) + return 1; + const evo::client::ScreenPoint anchor{ + std::clamp(navigation.pointer.x, 0.0, static_cast(state.logical_width)), + std::clamp(navigation.pointer.y, 0.0, static_cast(state.logical_height))}; + if (auto result = camera->zoom(std::exp2(navigation.wheel / 4), anchor); + !result && result.error() != evo::client::CameraError::out_of_range) + return 1; + // Local-mm presentation fixture only. Clip before float conversion. + const auto upper = camera->world_to_screen({-80, 48}); + const auto lower = camera->world_to_screen({80, -48}); + if (!upper || !lower) + return 1; + const double left = std::clamp(upper->x, 0.0, static_cast(state.logical_width)); + const double top = std::clamp(upper->y, 0.0, static_cast(state.logical_height)); + const double right = + std::clamp(lower->x, 0.0, static_cast(state.logical_width)); + const double bottom = + std::clamp(lower->y, 0.0, static_cast(state.logical_height)); + boxes[0] = {static_cast(left), + static_cast(top), + static_cast(right - left), + static_cast(bottom - top), + {64, 180, 140, 255}}; + } + boxes[1] = {8, 8, 64, 8, + (*app)->ui_captured() ? evo::render::Color{240, 140, 32, 255} + : evo::render::Color{64, 180, 140, 255}}; + boxes[2] = {36 + static_cast(intention->move_x) / 50, + 48 - static_cast(intention->move_y) / 50, + 8, + 8, + {240, 240, 240, 255}}; + const auto frame = evo::render::Frame::create(boxes, {16, 20, 28, 255}); + if (!frame) + return 1; + const auto result = (*app)->present(*frame); if (!result) { std::fprintf(stderr, "client frame error=%d\n", static_cast(result.error())); return 1; diff --git a/cmake/ClientProbe.cmake b/cmake/ClientProbe.cmake index ebbd440..126e103 100644 --- a/cmake/ClientProbe.cmake +++ b/cmake/ClientProbe.cmake @@ -46,19 +46,22 @@ if(EVO_BUILD_CLIENT_PROBE) endif() if(EVO_BUILD_CLIENT) + add_library(evo_client_controls STATIC src/client/camera/camera.cpp src/client/input/input.cpp) + target_include_directories(evo_client_controls PUBLIC "${PROJECT_SOURCE_DIR}/include") + evo_owned_target(evo_client_controls) 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) 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 PRIVATE SDL3::SDL3) + target_link_libraries(evo_client_platform PUBLIC evo_render_frame evo_client_controls PRIVATE SDL3::SDL3) 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_owned_target(evo-client) evo_client_runtime(evo-client) if(BUILD_TESTING) - add_executable(evo-client-lifecycle-tests tests/client_lifecycle.cpp) + 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) evo_owned_target(evo-client-lifecycle-tests) diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md index 346ae9c..7bea471 100644 --- a/docs/ROADMAP.md +++ b/docs/ROADMAP.md @@ -398,7 +398,13 @@ The added Gitea client job awaits remote verification. surface/resource lifecycle implemented under ADR-0078; Windows/Linux tests, analysis, ASan/UBSan and headless replay evidence in engineering/VALIDATION.md. Physical DPI/input and real GPU loss remain hardware qualification, not claims -from injected events. Next gate: M9.3. +from injected events. + +**M9.3 status (2026-10-01):** local-mm camera, logical/drawable conversion, +cursor-anchored zoom, bounded sequence/tick intentions and focus/UI/backlog +suppression implemented under ADR-0079. Camera round trips and native event +regressions are recorded in engineering/VALIDATION.md. The app uses local +fixture ticks, not server time. Next gate: M9.4. **Goal:** a native desktop cellular viewer/controller with input, camera, renderer, readable organism/environment views and a real development-server connection. diff --git a/docs/STATUS.md b/docs/STATUS.md index 5378afb..e606b7a 100644 --- a/docs/STATUS.md +++ b/docs/STATUS.md @@ -2,17 +2,17 @@ ## Current gate — 2026-10-01 -M9.2 adds an opt-in native `evo-client`, immutable presentation frame contract and -RAII platform/renderer lifecycle ([ADR-0078](adr/0078-native-client-lifecycle.md)). -Resize/pixel scale, focus, minimized/hidden windows, reset/loss and orderly close -are covered by Windows/Linux tests. Direct X11 linking resolves the observed -M9.1 unload allocation issue in repeated sanitizer checks. See +M9.3 adds local-mm pan/zoom camera mapping and bounded sequence/tick input +intentions ([ADR-0079](adr/0079-camera-and-input-intentions.md)). Focus loss, +UI capture/release and saturated event batches cancel held input. WASD controls +an intention indicator; arrows/wheel navigate the presentation fixture. See [CLIENT.md](engineering/CLIENT.md) and [VALIDATION.md](engineering/VALIDATION.md). Updated remote Gitea client execution remains unverified locally. -Next: **M9.3**, camera and bounded input intentions. The window displays a static -presentation fixture, not organisms or a connected world. No deployment, -simulation rules, persistent formats or world state changed in M9.2. +Next: **M9.4**, rendering microscopic environment views. The client displays a +camera-controlled fixture, not organisms or a connected world. Its tick is a +local input fixture counter. No deployment, simulation rules, persistent formats +or world state changed in M9.3. The sections below retain earlier milestone delivery history. diff --git a/docs/adr/0079-camera-and-input-intentions.md b/docs/adr/0079-camera-and-input-intentions.md new file mode 100644 index 0000000..40fcf43 --- /dev/null +++ b/docs/adr/0079-camera-and-input-intentions.md @@ -0,0 +1,64 @@ +# ADR-0079: Local camera and bounded input intentions + +## Status +Accepted for M9.3 engineering client. No movement physics, network format or tick +frequency is selected. Controls are engineering bindings, not final player UI. + +## Context +M9.2 has logical/drawable sizes but no navigation or input state. M6 views use a +caller-selected local XY habitat, measured in millimetres; pixels cannot become +authoritative positions. Focus changes can otherwise leave held movement active. + +## Decision +Use SDL-free camera and input value contracts. Camera doubles are presentation +only, in the local XY plane (+X right, +Y up), with named millimetre coordinates. +Screen coordinates are logical window units (+Y down); drawable conversion uses +independent X/Y ratios. Content scale is not applied twice. Camera resize retains +centre/zoom; cursor-anchored zoom preserves the selected world point. Reject +non-finite values, zero viewports and out-of-range operations without mutation. + +Input has fixed held-key state and bounded wheel accumulation, not an event or +command queue. WASD produces a signed quantized movement vector of norm <=1000; +arrows pan the camera and wheel zooms. UI capture (Tab in the engineering app) +and window focus/visibility gate both. Losing admission clears all held keys and +wheel state. Regaining admission requires a fresh non-repeat keydown; ignored +presses never resume by themselves. A release always clears its key. + +External UI capture release drains pending events before re-admission, and a +saturated 256-event batch similarly quarantines its remaining input until drained. + +Sampling produces one intention with a monotonically increasing sequence and +strictly increasing caller-supplied tick; suppressed input emits a neutral vector. +Invalid ticks or counter exhaustion fail without consuming sequence. No time is +read by input code. The standalone app labels its frame counter as a local input +fixture tick; M9.6 must bind this contract to validated session/tick context and +server-side admission. Never transmit native struct memory or trust client ticks. + +Split platform polling from presentation so input and camera projection use the +current viewport before drawing; retain `step(frame)` as the combined convenience. +No new dependencies. No authoritative simulation or world format changes. + +## Alternatives considered +- SDL keyboard state polling: can resurrect physically held keys after focus/UI + capture; explicit event-held state gives clear re-arm semantics. +- Mouse pixels as world coordinates: changes intent with DPI; rejected. +- Unbounded input event queue: unnecessary until session/prediction contracts exist. +- Variable simulation delta: camera pacing is presentation only, not simulation time. + +## Benefits +Testable without SDL, bounded memory, no stuck input, explicit units and sequence +semantics; camera changes cannot change biological state. + +## Costs +Local projection has finite numeric bounds and approximate floating-point round +trips. Bindings and single-window capture are deliberately narrow. + +## Risks +Synthetic events do not qualify physical keyboard layouts, IME or multi-monitor +DPI. M9.6/M10 still need authentication, tick windows, replay protection and rate +limits. This contract is neither a secure session nor a networking implementation. + +## Consequences +Public camera/input headers, host caller and tests change together. M9.4 will +project environmental data through this camera. UI capture is an explicit host +API; a future UI must set it before polling its world-input batch. diff --git a/docs/adr/README.md b/docs/adr/README.md index c407f72..9ac86cf 100644 --- a/docs/adr/README.md +++ b/docs/adr/README.md @@ -90,3 +90,4 @@ design. No unadopted candidate is a link dependency of the proof. - [ADR-0077: Scoped native client dependencies](0077-scoped-native-client-dependencies.md) - SDL 3.4.16 window/events and 2D renderer for the opt-in M9.1 probe; no simulation dependency. - [ADR-0078: Native client lifecycle](0078-native-client-lifecycle.md) - main-thread RAII application, immutable presentation frames and explicit surface/device failure handling. +- [ADR-0079: Camera and input intentions](0079-camera-and-input-intentions.md) - local-mm projection, bounded sequence/tick intentions, focus/UI capture and explicit host event ordering. diff --git a/docs/architecture/CLIENT_ARCHITECTURE.md b/docs/architecture/CLIENT_ARCHITECTURE.md index aa7456b..b09ff6c 100644 --- a/docs/architecture/CLIENT_ARCHITECTURE.md +++ b/docs/architecture/CLIENT_ARCHITECTURE.md @@ -1,4 +1,4 @@ -# Native client boundary (M9.2) +# Native client boundary (M9.2–M9.3) Implemented scope: desktop lifecycle and primitive presentation, not gameplay. ADR-0077 selects SDL; ADR-0078 defines its ownership and view boundary. @@ -23,7 +23,7 @@ main or be used/destroyed on another thread. valid until frame destruction/assignment. `Application::step(const Frame&)` borrows it for the call only; there is no queue, stored pointer or simulation mutation. Coordinates are logical window units, top-left origin, +Y down. They -are presentation units, never world millimetres. M9.3 owns world-screen mapping; +are presentation units, never world millimetres. M9.3 implements world-screen mapping; M9.4 projects environment samples. In particular, do not retain M6 validation tokens/store pointers in a renderer or serialize them as a client protocol. @@ -32,7 +32,7 @@ separately. Resizes/display changes query SDL rather than trust event payloads. Drawing scales independently by pixel/logical width and height; content scale is for future UI sizing, not a second pixel multiplier. Hidden/minimized/zero-area windows skip rendering. Focus loss disables the future input admission flag; -there are no held gameplay inputs in M9.2. Close is terminal. +M9.3 clears all held intentions on admission loss. Close is terminal. Each step consumes at most 256 events, filters window-specific events and renders one frame. Target reset needs only redraw (no cached textures). Device reset @@ -41,6 +41,12 @@ failure latch an error until destruction; no silent backend substitution or busy recovery loop. Typed errors reach the process boundary. The host paces frames outside the renderer and catches allocation/standard-library exceptions. +M9.3 also exposes separate `poll_events()` and `present(frame)` calls so camera +mapping uses current resize/input state. SDL-free camera and input contracts are +specified in [CAMERA_INPUT.md](../engineering/CAMERA_INPUT.md) and ADR-0079. +UI capture and event-backlog handling suppress held world input; sequence/tick +intentions do not confer server authority. M9.6 owns session binding. + Failure tests inject actual SDL events, including foreign window IDs, with no test-only production hooks. Real device failures and physical DPI/input require manual hardware qualification at M9.8. The native client is opt-in and never diff --git a/docs/engineering/CAMERA_INPUT.md b/docs/engineering/CAMERA_INPUT.md new file mode 100644 index 0000000..6ba9a93 --- /dev/null +++ b/docs/engineering/CAMERA_INPUT.md @@ -0,0 +1,78 @@ +# M9.3 camera and input contract + +Decision: [ADR-0079](../adr/0079-camera-and-input-intentions.md). +Headers: `include/evo/client/camera.hpp`, `input.hpp`, `application.hpp`. +No SDL types enter the camera/input contracts. Neither library mutates or links +the simulation. The world coordinate header supplies numeric bounds only. + +## Coordinates and camera + +`WorldPoint` stores presentation doubles in millimetres in a caller-selected +region-local XY plane, +Y up. Its half-open range matches M5/M6 voxel bounds +times the 1000 mm pitch: [-1048576000, 1048576000) on both axes. Do not mix +frames/worlds or silently map the old periodic particle fixture into this plane. +M6 micrometre habitat offsets require explicit conversion to mm at M9.4 projection. + +`ScreenPoint` is logical window space, top-left origin and +Y down. `PixelPoint` +is drawable space. Viewport dimensions must be 1..32768; zero/minimized surfaces +are not a camera viewport. Application skips viewport updates while zero-area. +`units_per_mm` is logical units per mm, bounded [0.0001, 10000]. Screen/pixel +conversions validate finite values within +/-1e15; world projection may be +offscreen. Clip to the viewport before converting to renderer float primitives. + +The projection is `screen_x = (world_x - centre_x) * scale + width/2` and +`screen_y = (centre_y - world_y) * scale + height/2`. Pixel conversions apply +pixel_width/width and pixel_height/height independently. Display content scale +is not a further multiplier. Round trips are approximate; tests use 1e-6 mm +tolerance for their bounded fixtures, not a global deterministic-state promise. + +Resize retains centre/zoom. Pan moves the camera in screen-axis directions by +at most 32768 logical units per component per call. Positive X moves the camera +right; positive Y moves it down. Zoom requires a positive finite factor and an +anchor inside the logical viewport. It preserves the world point under that +anchor; requests beyond zoom/world bounds reject without mutation. These are +engineering numeric limits, not biological movement or world-size rules. + +## Input and host ordering + +`InputState` has eight held-key slots, one cursor and bounded accumulated wheel +steps ([-8,8], individual inputs must be finite and within [-128,128]). Navigation +consumes wheel steps once; held pan directions persist until release/admission +loss. Pointer events require finite coordinates within +/-32768 logical units. +Invalid values reject rather than entering camera math. + +`Intention` carries sequence, tick and a signed movement vector. Cardinal +components are +/-1000, diagonals +/-707 (norm <=1000); opposite keys cancel. +This is direction/demand, never velocity, distance, energy or accepted position. +Sequences start at 1 by default; the host can seed a local stream counter but +that is not an authenticated resume grant. Successful samples require strictly +increasing ticks. Exhaustion/stale tick rejection consumes neither tick nor +sequence. Inactive input still samples a neutral intention, allowing later +session adapters to express stopped input. No pending command queue exists. + +Use `poll_events()` -> read current window/navigation -> update camera -> +`sample_intention(tick)` -> build immutable frame -> `present(frame)`. +`step(frame)` retains the combined poll/present convenience for lifecycle tests. +Focus loss, hidden/minimized/closed/failed/zero-area state, or UI capture clears +held state. A fresh non-repeat keydown is needed to re-arm; releases always +clear keys. UI code calls `set_ui_capture` before world polling. Tab toggles an +engineering capture mode in the adapter; repeats do not retoggle it. Window +close remains available while captured. + +A 256-event saturated batch clears admission. Remaining queued keydowns are +ignored until a later poll drains the backlog; the drained state remains neutral +until a fresh keydown. This prevents delayed releases from sustaining movement. +All window-specific input filters the owned SDL window ID. + +Releasing capture through the external UI API also drains the pending SDL batch +before re-admission, preventing keys queued while captured from becoming world +presses. Poll once after release, then fresh presses are admitted. The engineering +Tab toggle is processed in event order, so subsequent presses after that toggle +belong to its new capture state. + +The standalone host uses an increasing **local fixture tick**, not server time. +It draws a world-anchored rectangle, a capture indicator and an intention dot. +Camera panning uses 400 logical units/second with elapsed time clamped to 0.1 s; +wheel zoom uses 2^(steps/4). These are presentation controls. No network messages, +world modifications or organism actions occur. M9.6 must bind intention ticks +and counters to secure sessions; the server independently validates all requests. diff --git a/docs/engineering/CLIENT.md b/docs/engineering/CLIENT.md index 92a21ba..bc224f6 100644 --- a/docs/engineering/CLIENT.md +++ b/docs/engineering/CLIENT.md @@ -1,8 +1,9 @@ -# Native engineering client (M9.2) +# Native engineering client (M9.2–M9.3) -This opens a resizable native window containing a static presentation fixture. +This opens a resizable native window containing a camera-controlled presentation fixture. It does not simulate a world, connect to a server or implement cellular gameplay. Contract: [client architecture](../architecture/CLIENT_ARCHITECTURE.md), ADR-0078. +Camera/input: [contracts and limits](CAMERA_INPUT.md), ADR-0079. ## Build and run @@ -26,6 +27,13 @@ one explicit backend, without fallback. `--frames N` exits after N bounded steps window and pauses drawing. These options permit unattended smoke checks. Usage errors exit 2, lifecycle 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. + For native X11 regression on a CI host: ```sh diff --git a/docs/engineering/VALIDATION.md b/docs/engineering/VALIDATION.md index 7b4a1aa..45452f1 100644 --- a/docs/engineering/VALIDATION.md +++ b/docs/engineering/VALIDATION.md @@ -3240,3 +3240,47 @@ boundary requires single-main-thread use. Tests do not establish physical multi-monitor DPI, real keyboard/focus behavior, Wayland, hardware GPU loss or human visual acceptance. Those remain M9.3/M9.8 qualification work. No cluster operation was performed. + +## M9.3 camera and input intentions — 2026-10-01 + +Implemented ADR-0079 and CAMERA_INPUT.md: SDL-free local-mm camera and held input +state, explicit logical/pixel conversion, cursor-anchored zoom, bounded +sequence/tick intentions and polling-before-projection. The app demonstrates +arrows/wheel navigation, a WASD intention indicator and Tab UI capture. Its tick +is a local fixture counter; no server/session/authoritative movement is present. + +Executed: + +- Windows MSVC 19.44 Release via `tools/windows-check.ps1 -Preset client -Action + check`: 3/3 labeled tests passed. Native Windows lifecycle/input executable + and the final `evo-client --frames 3` smoke passed. +- Linux GCC 14 Release, existing combined probe/client build: 5/5 labeled tests + passed; native Xvfb/X11 lifecycle and input events passed. The final app-only + startup/error-reporting adjustment was additionally built/tested with MSVC and + Clang ASan below (the GCC suite preceded that adjustment). +- Clang 19 Debug ASan/UBSan: all owned camera/input/platform/app/test code built; + 3/3 labeled tests and native Xvfb/X11 tests passed with leak detection enabled, + without preload or suppressions. Final hidden/software three-frame app smoke + also passed. SDL/system libraries remain outside comprehensive instrumentation. +- Pure camera tests cover 220 world/logical/pixel round trips over four viewport/ + DPI/aspect combinations and five zoom scales (1e-6 mm tolerance for fixtures), + anchor preservation, pan direction, resize stability, NaN/infinity, numeric + limits and unchanged state after rejected operations. +- Input tests cover key release/opposites/diagonals, focus re-arm, ignored repeats, + UI capture, bounded/consumed wheel accumulation, invalid input, monotonically + increasing sequence/tick and stale/overflow rejection. Native SDL tests cover + WASD/arrows, Tab repeat, focus loss/regain, wheel direction/pointer, minimize, + saturated event batches and queued keys crossing external capture release. +- clang-tidy 19 with warnings-as-errors passed on all six changed/new translation + units; corrected a duplicated wheel-error branch. Final app-only adjustment + also passed analysis. Repository format-check passed. +- Headless Release configured with both client options OFF, rebuilt `evo-sim`, + replayed seed 123456 / eight entities / 1000 ticks: unchanged + `d61ad5bf0c928c76`, `replay_verified=true`. + +The existing client CI target now picks up the controls library and expanded +lifecycle suite automatically. Docker/Gitea execution was not observed locally. +No full headless suite or TSan rerun; owned client state remains main-thread-only. +No physical keyboard/IME, human visual, real multi-monitor DPI, Wayland or real +GPU-failure qualification is claimed from injected events and Xvfb. No network +traffic, database, world mutation or deployment operation was introduced. diff --git a/include/evo/client/application.hpp b/include/evo/client/application.hpp index 8bd56e4..cff3218 100644 --- a/include/evo/client/application.hpp +++ b/include/evo/client/application.hpp @@ -1,4 +1,5 @@ #pragma once +#include "evo/client/input.hpp" #include "evo/render/frame.hpp" #include #include @@ -27,7 +28,8 @@ struct WindowState { float content_scale{1}; bool focused{}, minimized{}, hidden{}, closed{}, failed{}; [[nodiscard]] bool accepts_input() const noexcept { - return focused && !minimized && !hidden && !closed && !failed; + return focused && !minimized && !hidden && !closed && !failed && logical_width > 0 && + logical_height > 0 && pixel_width > 0 && pixel_height > 0; } }; // One owner, process main thread only (including destruction). No SDL owner may coexist. @@ -39,6 +41,12 @@ class Application { Application(const Application&) = delete; Application& operator=(const Application&) = delete; [[nodiscard]] WindowState state() const noexcept; + [[nodiscard]] std::expected poll_events(); + [[nodiscard]] std::expected present(const render::Frame& frame); + void set_ui_capture(bool captured) noexcept; + [[nodiscard]] bool ui_captured() const noexcept; + [[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. [[nodiscard]] std::expected step(const render::Frame& frame); diff --git a/include/evo/client/camera.hpp b/include/evo/client/camera.hpp new file mode 100644 index 0000000..a9dd47a --- /dev/null +++ b/include/evo/client/camera.hpp @@ -0,0 +1,48 @@ +#pragma once +#include +#include + +namespace evo::client { +struct WorldPoint { + double x_mm{}, y_mm{}; +}; +struct ScreenPoint { + double x{}, y{}; +}; // Logical window units, not pixels. +struct PixelPoint { + double x{}, y{}; +}; +struct Viewport { + int width{}, height{}, pixel_width{}, pixel_height{}; +}; +enum class CameraError : std::uint8_t { invalid_viewport, invalid_value, out_of_range }; +class Camera { + public: + [[nodiscard]] static std::expected + create(Viewport viewport, WorldPoint centre = {}, double units_per_mm = 1); + [[nodiscard]] std::expected resize(Viewport viewport); + // Move the camera in screen-axis directions; the scene moves oppositely. + [[nodiscard]] std::expected pan(ScreenPoint delta); + [[nodiscard]] std::expected zoom(double factor, ScreenPoint anchor); + [[nodiscard]] std::expected world_to_screen(WorldPoint point) const; + [[nodiscard]] std::expected screen_to_world(ScreenPoint point) const; + [[nodiscard]] std::expected to_pixels(ScreenPoint point) const; + [[nodiscard]] std::expected from_pixels(PixelPoint point) const; + [[nodiscard]] Viewport viewport() const noexcept { + return viewport_; + } + [[nodiscard]] WorldPoint centre() const noexcept { + return centre_; + } + [[nodiscard]] double units_per_mm() const noexcept { + return scale_; + } + + private: + Camera(Viewport viewport, WorldPoint centre, double scale) + : viewport_{viewport}, centre_{centre}, scale_{scale} {} + Viewport viewport_; + WorldPoint centre_; + double scale_; +}; +} // namespace evo::client diff --git a/include/evo/client/input.hpp b/include/evo/client/input.hpp new file mode 100644 index 0000000..5fa2a60 --- /dev/null +++ b/include/evo/client/input.hpp @@ -0,0 +1,54 @@ +#pragma once +#include "evo/client/camera.hpp" +#include +#include +#include +#include + +namespace evo::client { +enum class Key : std::uint8_t { left, right, up, down, pan_left, pan_right, pan_up, pan_down }; +enum class InputError : std::uint8_t { + invalid_key, + invalid_pointer, + invalid_wheel, + stale_tick, + exhausted +}; +struct Intention { + std::uint64_t sequence{}, tick{}; + std::int16_t move_x{}, move_y{}; // Signed unit vector *1000, local XY (+Y up). +}; +struct Navigation { + int x{}, y{}; + double wheel{}; + ScreenPoint pointer{}; +}; +// Main-thread value state; no event queue or authoritative position. +class InputState { + public: + // Host-owned sequence seed, for local streams/tests; not a session resume grant. + explicit InputState(std::uint64_t last_sequence = 0) : sequence_{last_sequence} {} + void admit(bool enabled) noexcept; + void capture(bool captured) noexcept; + [[nodiscard]] bool captured() const noexcept { + return captured_; + } + [[nodiscard]] bool enabled() const noexcept { + return admitted_ && !captured_; + } + [[nodiscard]] std::expected key(Key key, bool down, bool repeat = false); + [[nodiscard]] std::expected pointer(ScreenPoint point); + [[nodiscard]] std::expected wheel(double steps); + [[nodiscard]] Navigation take_navigation() noexcept; + [[nodiscard]] std::expected sample(std::uint64_t tick); + + private: + void clear() noexcept; + std::array keys_{}; + bool admitted_{false}, captured_{false}; + ScreenPoint pointer_{}; + double wheel_{}; + std::uint64_t sequence_{}; + std::optional tick_; +}; +} // namespace evo::client diff --git a/src/client/camera/camera.cpp b/src/client/camera/camera.cpp new file mode 100644 index 0000000..e42bdbd --- /dev/null +++ b/src/client/camera/camera.cpp @@ -0,0 +1,101 @@ +#include "evo/client/camera.hpp" +#include "evo/world/coordinates.hpp" +#include + +namespace evo::client { +namespace { +constexpr double world_limit = static_cast(world::voxel_limit * world::cell_pitch_mm); +bool valid(Viewport v) { + return v.width > 0 && v.height > 0 && v.pixel_width > 0 && v.pixel_height > 0 && + v.width <= 32768 && v.height <= 32768 && v.pixel_width <= 32768 && + v.pixel_height <= 32768; +} +bool valid(WorldPoint p) { + return std::isfinite(p.x_mm) && std::isfinite(p.y_mm) && p.x_mm >= -world_limit && + p.y_mm >= -world_limit && p.x_mm < world_limit && p.y_mm < world_limit; +} +bool valid(ScreenPoint p) { + return std::isfinite(p.x) && std::isfinite(p.y) && std::abs(p.x) <= 1e15 && + std::abs(p.y) <= 1e15; +} +bool valid_scale(double scale) { + return std::isfinite(scale) && scale >= 1e-4 && scale <= 1e4; +} +} // namespace +std::expected Camera::create(Viewport viewport, WorldPoint centre, + double scale) { + if (!valid(viewport)) + return std::unexpected(CameraError::invalid_viewport); + if (!valid(centre) || !valid_scale(scale)) + return std::unexpected(CameraError::invalid_value); + return Camera{viewport, centre, scale}; +} +std::expected Camera::resize(Viewport viewport) { + if (!valid(viewport)) + return std::unexpected(CameraError::invalid_viewport); + viewport_ = viewport; + return {}; +} +std::expected Camera::world_to_screen(WorldPoint point) const { + if (!valid(point)) + return std::unexpected(CameraError::invalid_value); + return ScreenPoint{(point.x_mm - centre_.x_mm) * scale_ + viewport_.width / 2.0, + (centre_.y_mm - point.y_mm) * scale_ + viewport_.height / 2.0}; +} +std::expected Camera::screen_to_world(ScreenPoint point) const { + if (!valid(point)) + return std::unexpected(CameraError::invalid_value); + const WorldPoint result{centre_.x_mm + (point.x - viewport_.width / 2.0) / scale_, + centre_.y_mm - (point.y - viewport_.height / 2.0) / scale_}; + if (!valid(result)) + return std::unexpected(CameraError::out_of_range); + return result; +} +std::expected Camera::to_pixels(ScreenPoint point) const { + if (!valid(point)) + return std::unexpected(CameraError::invalid_value); + const PixelPoint result{point.x * viewport_.pixel_width / viewport_.width, + point.y * viewport_.pixel_height / viewport_.height}; + if (!valid(ScreenPoint{result.x, result.y})) + return std::unexpected(CameraError::out_of_range); + return result; +} +std::expected Camera::from_pixels(PixelPoint point) const { + if (!valid(ScreenPoint{point.x, point.y})) + return std::unexpected(CameraError::invalid_value); + const ScreenPoint result{point.x * viewport_.width / viewport_.pixel_width, + point.y * viewport_.height / viewport_.pixel_height}; + if (!valid(result)) + return std::unexpected(CameraError::out_of_range); + return result; +} +std::expected Camera::pan(ScreenPoint delta) { + if (!valid(delta) || std::abs(delta.x) > 32768 || std::abs(delta.y) > 32768) + return std::unexpected(CameraError::invalid_value); + const WorldPoint next{centre_.x_mm + delta.x / scale_, centre_.y_mm - delta.y / scale_}; + if (!valid(next)) + return std::unexpected(CameraError::out_of_range); + centre_ = next; + return {}; +} +std::expected Camera::zoom(double factor, ScreenPoint anchor) { + if (!std::isfinite(factor) || factor <= 0 || !valid(anchor) || anchor.x < 0 || anchor.y < 0 || + anchor.x > viewport_.width || anchor.y > viewport_.height) + return std::unexpected(CameraError::invalid_value); + const double next_scale = scale_ * factor; + if (!valid_scale(next_scale)) + return std::unexpected(CameraError::out_of_range); + if (factor == 1) + return {}; + const auto world = screen_to_world(anchor); + if (!world) + return std::unexpected(world.error()); + const WorldPoint next{world->x_mm - (anchor.x - viewport_.width / 2.0) / next_scale, + world->y_mm + (anchor.y - viewport_.height / 2.0) / next_scale}; + if (!valid(next)) + return std::unexpected(CameraError::out_of_range); + centre_ = next; + scale_ = next_scale; + return {}; +} +} // namespace evo::client diff --git a/src/client/input/input.cpp b/src/client/input/input.cpp new file mode 100644 index 0000000..1ce40bb --- /dev/null +++ b/src/client/input/input.cpp @@ -0,0 +1,64 @@ +#include "evo/client/input.hpp" +#include +#include +#include + +namespace evo::client { +void InputState::clear() noexcept { + keys_.fill(false); + wheel_ = 0; +} +void InputState::admit(bool enabled) noexcept { + if (!enabled) + clear(); + admitted_ = enabled; +} +void InputState::capture(bool captured) noexcept { + if (captured) + clear(); + captured_ = captured; +} +std::expected InputState::key(Key key, bool down, bool repeat) { + const auto index = static_cast(key); + if (index >= keys_.size()) + return std::unexpected(InputError::invalid_key); + if (!down) + keys_[index] = false; + else if (enabled() && !repeat) + keys_[index] = true; + return {}; +} +std::expected InputState::pointer(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); + pointer_ = point; + return {}; +} +std::expected InputState::wheel(double steps) { + if (!std::isfinite(steps) || std::abs(steps) > 128) + return std::unexpected(InputError::invalid_wheel); + if (enabled()) + wheel_ = std::clamp(wheel_ + steps, -8.0, 8.0); + return {}; +} +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_}; + wheel_ = 0; + return result; +} +std::expected InputState::sample(std::uint64_t tick) { + if (tick_ && tick <= *tick_) + return std::unexpected(InputError::stale_tick); + if (sequence_ == std::numeric_limits::max()) + return std::unexpected(InputError::exhausted); + const int x = static_cast(keys_[1]) - static_cast(keys_[0]); + const int y = static_cast(keys_[2]) - static_cast(keys_[3]); + const int magnitude = x != 0 && y != 0 ? 707 : 1000; + tick_ = tick; + return Intention{++sequence_, tick, static_cast(x * magnitude), + static_cast(y * magnitude)}; +} +} // namespace evo::client diff --git a/src/client/platform/application.cpp b/src/client/platform/application.cpp index c66c520..41b9c4f 100644 --- a/src/client/platform/application.cpp +++ b/src/client/platform/application.cpp @@ -9,6 +9,28 @@ namespace evo::client { namespace { bool runtime_owned = false; // Process main-thread-only contract; no hidden threads. +std::optional input_key(SDL_Scancode code) { + switch (code) { + case SDL_SCANCODE_A: + return Key::left; + case SDL_SCANCODE_D: + return Key::right; + case SDL_SCANCODE_W: + return Key::up; + case SDL_SCANCODE_S: + return Key::down; + case SDL_SCANCODE_LEFT: + return Key::pan_left; + case SDL_SCANCODE_RIGHT: + return Key::pan_right; + case SDL_SCANCODE_UP: + return Key::pan_up; + case SDL_SCANCODE_DOWN: + return Key::pan_down; + default: + return std::nullopt; + } +} struct Runtime { bool acquired{false}; ~Runtime() { @@ -26,6 +48,8 @@ struct Application::Impl { std::string renderer_name; WindowState state; std::optional failure; + InputState input; + bool backlogged{false}; std::expected refresh() { if (!SDL_GetWindowSize(window.get(), &state.logical_width, &state.logical_height) || @@ -47,6 +71,24 @@ WindowState Application::state() const noexcept { result.failed = impl_->failure.has_value(); return result; } +void Application::set_ui_capture(bool captured) noexcept { + 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); +} +bool Application::ui_captured() const noexcept { + return impl_->input.captured(); +} +Navigation Application::take_navigation() noexcept { + return impl_->input.take_navigation(); +} +std::expected Application::sample_intention(std::uint64_t tick) { + return impl_->input.sample(tick); +} std::expected, Error> Application::open(const Config& config) { if (config.width <= 0 || config.height <= 0 || config.width > 32768 || config.height > 32768 || config.renderer.size() > 64 || config.renderer.find('\0') != std::string::npos) @@ -79,15 +121,22 @@ std::expected, Error> Application::open(const Confi return std::unique_ptr{new Application{std::move(impl)}}; } std::expected Application::step(const render::Frame& frame) { + if (auto result = poll_events(); !result) + return std::unexpected(result.error()); + return present(frame); +} +std::expected Application::poll_events() { auto& p = *impl_; if (p.failure) return std::unexpected(*p.failure); if (p.state.closed) - return Step::closed; + return {}; + p.input.admit(p.state.accepts_input() && !p.backlogged); const auto id = SDL_GetWindowID(p.window.get()); bool reset = false; SDL_Event event{}; - for (int count = 0; count < 256 && SDL_PollEvent(&event); ++count) { + int count = 0; + for (; count < 256 && SDL_PollEvent(&event); ++count) { if (event.type == SDL_EVENT_QUIT) p.state.closed = true; if (event.type >= SDL_EVENT_WINDOW_FIRST && event.type <= SDL_EVENT_WINDOW_LAST && @@ -119,6 +168,29 @@ std::expected Application::step(const render::Frame& frame) { break; } } + // Admission changes clear held inputs immediately, even if focus returns in this batch. + p.input.admit(p.state.accepts_input() && !p.backlogged); + if ((event.type == SDL_EVENT_KEY_DOWN || event.type == SDL_EVENT_KEY_UP) && + 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.input.capture(!p.input.captured()); + 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); + } + } + if (event.type == SDL_EVENT_MOUSE_MOTION && event.motion.windowID == id) { + 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) { + 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)) + p.input.admit(false); + } if (event.type >= SDL_EVENT_RENDER_TARGETS_RESET && event.type <= SDL_EVENT_RENDER_DEVICE_LOST && event.render.windowID == id) { if (event.type == SDL_EVENT_RENDER_DEVICE_LOST) @@ -127,32 +199,49 @@ std::expected Application::step(const render::Frame& frame) { reset = true; } } - if (p.failure) + if (p.failure) { + p.input.admit(false); return std::unexpected(*p.failure); + } + p.backlogged = count == 256; + p.input.admit(p.state.accepts_input() && !p.backlogged); if (p.state.closed) - return Step::closed; + return {}; if (reset) { p.renderer.reset(); auto renderer = detail::make_renderer(p.window.get(), p.renderer_name); if (!renderer) { p.failure = renderer.error(); + p.input.admit(false); return std::unexpected(*p.failure); } p.renderer = std::move(*renderer); } if (auto result = p.refresh(); !result) { p.failure = result.error(); + p.input.admit(false); return std::unexpected(*p.failure); } + p.input.admit(p.state.accepts_input() && !p.backlogged); + return {}; +} +std::expected Application::present(const render::Frame& frame) { + auto& p = *impl_; + if (p.failure) + return std::unexpected(*p.failure); + if (p.state.closed) + return Step::closed; if (p.state.hidden || p.state.minimized || p.state.logical_width == 0 || p.state.logical_height == 0 || p.state.pixel_width == 0 || p.state.pixel_height == 0) return Step::paused; if (auto result = detail::draw(p.renderer.get(), frame, p.state); !result) { p.failure = result.error(); + p.input.admit(false); return std::unexpected(*p.failure); } if (!SDL_RenderPresent(p.renderer.get())) { p.failure = Error::draw; + p.input.admit(false); return std::unexpected(*p.failure); } return Step::rendered; diff --git a/tests/client_controls.cpp b/tests/client_controls.cpp new file mode 100644 index 0000000..e7dfa0a --- /dev/null +++ b/tests/client_controls.cpp @@ -0,0 +1,133 @@ +#include "evo/client/camera.hpp" +#include "evo/client/input.hpp" +#include +#include +#include +#include +#include +#include + +namespace { +using namespace evo::client; +void check(bool value, std::source_location at = std::source_location::current()) { + if (!value) + throw std::runtime_error("client controls line " + std::to_string(at.line())); +} +#define CHECK(...) check(static_cast(__VA_ARGS__)) +bool near(double a, double b) { + return std::abs(a - b) < 1e-6; +} +void camera_checks() { + constexpr std::array views{{{800, 600, 800, 600}, + {800, 600, 1600, 1200}, + {1200, 500, 1800, 1000}, + {320, 240, 640, 360}}}; + for (const auto view : views) + for (const double scale : {1e-4, 0.25, 1.0, 32.0, 1e4}) { + auto camera = Camera::create(view, {1000000, -1000000}, scale); + CHECK(camera); + for (int i = -5; i <= 5; ++i) { + const WorldPoint world{1000000 + i * 17.125, -1000000 + i * 8.375}; + const auto screen = camera->world_to_screen(world); + CHECK(screen); + const auto pixels = camera->to_pixels(*screen); + CHECK(pixels); + const auto logical = camera->from_pixels(*pixels); + CHECK(logical); + const auto restored = camera->screen_to_world(*logical); + CHECK(restored); + CHECK(near(restored->x_mm, world.x_mm) && near(restored->y_mm, world.y_mm)); + } + const auto centre = camera->world_to_screen(camera->centre()); + CHECK(centre && near(centre->x, view.width / 2.0) && + near(centre->y, view.height / 2.0)); + } + auto camera = Camera::create(views[0]); + CHECK(camera); + const ScreenPoint anchor{123, 456}; + const auto before = camera->screen_to_world(anchor); + CHECK(before); + CHECK(camera->zoom(2, anchor)); + const auto after = camera->screen_to_world(anchor); + CHECK(after && near(before->x_mm, after->x_mm) && near(before->y_mm, after->y_mm)); + CHECK(camera->zoom(0.5, anchor)); + CHECK(near(camera->centre().x_mm, 0) && near(camera->centre().y_mm, 0)); + CHECK(camera->pan({20, -10})); + CHECK(near(camera->centre().x_mm, 20) && near(camera->centre().y_mm, 10)); + CHECK(camera->resize(views[2])); + CHECK(camera->units_per_mm() == 1 && near(camera->centre().x_mm, 20)); + const double nan = std::numeric_limits::quiet_NaN(); + CHECK(!camera->resize({0, 1, 1, 1})); + CHECK(camera->viewport().width == views[2].width); + CHECK(!camera->zoom(nan, anchor) && !camera->zoom(1e10, anchor)); + CHECK(!camera->zoom(1, {-1, 5}) && !camera->pan({nan, 0})); + CHECK(!camera->pan({40000, 0})); + CHECK(!camera->screen_to_world({nan, 0})); + CHECK(!camera->world_to_screen({std::numeric_limits::infinity(), 0})); + CHECK(!camera->from_pixels({nan, 0}) && !camera->to_pixels({nan, 0})); + CHECK(camera->units_per_mm() == 1 && near(camera->centre().x_mm, 20)); + CHECK(!Camera::create(views[0], {}, 0)); + CHECK(!Camera::create(views[0], {1048576000, 0})); + auto edge = Camera::create(views[0], {1048575999, 0}); + CHECK(edge && !edge->pan({2, 0})); + CHECK(edge->centre().x_mm == 1048575999); + CHECK(!edge->screen_to_world({800, 300})); +} +Intention required(std::expected result) { + CHECK(result); + return result.value(); +} +void input_checks() { + InputState input; + CHECK(input.key(Key::up, true)); // No focus: ignored. + auto first = input.sample(0); + CHECK(first && first->sequence == 1 && first->move_y == 0 && first->tick == 0); + input.admit(true); + CHECK(input.key(Key::up, true, true)); // Repeats cannot re-arm an ignored press. + CHECK(required(input.sample(1)).move_y == 0); + CHECK(input.key(Key::up, true)); + CHECK(input.key(Key::right, true)); + const auto diagonal = input.sample(2); + CHECK(diagonal && diagonal->move_x == 707 && diagonal->move_y == 707); + CHECK(diagonal->move_x * diagonal->move_x + diagonal->move_y * diagonal->move_y <= 1000000); + CHECK(input.key(Key::right, false)); + const auto straight = input.sample(3); + CHECK(straight && straight->move_x == 0 && straight->move_y == 1000); + CHECK(input.key(Key::down, true)); + CHECK(required(input.sample(4)).move_y == 0); + CHECK(input.key(Key::pan_right, true)); + CHECK(input.pointer({20, 30}) && input.wheel(128)); + const auto nav = input.take_navigation(); + CHECK(nav.x == 1 && nav.y == 0 && nav.wheel == 8 && nav.pointer.x == 20); + CHECK(input.take_navigation().wheel == 0); + CHECK(input.wheel(3)); + input.capture(true); + CHECK(required(input.sample(5)).move_y == 0 && input.take_navigation().x == 0); + CHECK(input.key(Key::up, true) && input.wheel(4)); + input.capture(false); + CHECK(required(input.sample(6)).move_y == 0 && input.take_navigation().wheel == 0); + CHECK(input.key(Key::up, true, true)); + CHECK(required(input.sample(7)).move_y == 0); + CHECK(input.key(Key::up, false) && input.key(Key::up, true)); + CHECK(required(input.sample(8)).move_y == 1000); + input.admit(false); + input.admit(true); + CHECK(required(input.sample(9)).move_y == 0); + CHECK(!input.sample(9) && !input.sample(8)); + const auto next = input.sample(10); + CHECK(next && next->sequence == 11); + CHECK(!input.key(static_cast(255), true)); + CHECK(!input.wheel(std::numeric_limits::quiet_NaN())); + CHECK(!input.pointer({1e9, 0})); + CHECK(input.take_navigation().wheel == 0); + InputState exhausted{std::numeric_limits::max()}; + const auto failure = exhausted.sample(1); + CHECK(!failure && failure.error() == InputError::exhausted); + CHECK(input.sample(std::numeric_limits::max())); + CHECK(!input.sample(0)); +} +} // namespace +void client_controls_tests() { + camera_checks(); + input_checks(); +} diff --git a/tests/client_lifecycle.cpp b/tests/client_lifecycle.cpp index 149b598..35cfea3 100644 --- a/tests/client_lifecycle.cpp +++ b/tests/client_lifecycle.cpp @@ -10,6 +10,7 @@ #include #include +void client_controls_tests(); namespace { using namespace evo::client; void check(bool ok, std::source_location at = std::source_location::current()) { @@ -147,10 +148,107 @@ void lifecycle() { send(SDL_EVENT_QUIT, 0); CHECK((*hidden)->step(frame) == Step::closed); } +Intention required(std::expected result) { + CHECK(result); + return result.value(); +} +void native_input() { + 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); + auto key = [id](SDL_Scancode scancode, bool down, bool repeat = false) { + SDL_Event event{}; + event.type = down ? SDL_EVENT_KEY_DOWN : SDL_EVENT_KEY_UP; + event.key.windowID = id; + event.key.scancode = scancode; + event.key.repeat = repeat; + CHECK(SDL_PushEvent(&event)); + }; + key(SDL_SCANCODE_W, true); + key(SDL_SCANCODE_RIGHT, true); + CHECK(app->poll_events()); + const auto first = app->sample_intention(40); + CHECK(first && first->move_y == 1000 && first->sequence == 1 && first->tick == 40); + CHECK(app->take_navigation().x == 1); + key(SDL_SCANCODE_W, false); + CHECK(app->poll_events()); + CHECK(required(app->sample_intention(41)).move_y == 0); + key(SDL_SCANCODE_W, true); + send(SDL_EVENT_WINDOW_FOCUS_LOST, id); + send(SDL_EVENT_WINDOW_FOCUS_GAINED, id); + key(SDL_SCANCODE_W, true, true); + CHECK(app->poll_events()); + CHECK(required(app->sample_intention(42)).move_y == 0 && app->take_navigation().x == 0); + key(SDL_SCANCODE_W, true); + CHECK(app->poll_events()); + app->set_ui_capture(true); + CHECK(required(app->sample_intention(43)).move_y == 0); + key(SDL_SCANCODE_W, true); + CHECK(app->poll_events()); + app->set_ui_capture(false); + CHECK(required(app->sample_intention(44)).move_y == 0); + CHECK(app->poll_events()); + key(SDL_SCANCODE_TAB, true); + key(SDL_SCANCODE_W, true); + CHECK(app->poll_events()); + CHECK(app->ui_captured() && required(app->sample_intention(45)).move_y == 0); + key(SDL_SCANCODE_TAB, true, true); + CHECK(app->poll_events()); + CHECK(app->ui_captured()); + key(SDL_SCANCODE_TAB, false); + key(SDL_SCANCODE_TAB, true); + key(SDL_SCANCODE_W, true); + CHECK(app->poll_events()); + CHECK(!app->ui_captured() && required(app->sample_intention(46)).move_y == 1000); + // A saturated event batch cancels motion until the backlog drains. + for (int i = 0; i < 300; ++i) + key(SDL_SCANCODE_RIGHT, true); + CHECK(app->poll_events()); + CHECK(required(app->sample_intention(47)).move_y == 0 && app->take_navigation().x == 0); + CHECK(app->poll_events()); + CHECK(required(app->sample_intention(48)).move_y == 0 && app->take_navigation().x == 0); + SDL_Event wheel{}; + wheel.type = SDL_EVENT_MOUSE_WHEEL; + wheel.wheel.windowID = id; + wheel.wheel.y = 2; + wheel.wheel.mouse_x = 123; + wheel.wheel.mouse_y = 45; + wheel.wheel.direction = SDL_MOUSEWHEEL_FLIPPED; + CHECK(SDL_PushEvent(&wheel)); + CHECK(app->poll_events()); + const auto navigation = app->take_navigation(); + CHECK(navigation.wheel == -2 && navigation.pointer.x == 123 && navigation.pointer.y == 45); + app->set_ui_capture(true); + CHECK(SDL_PushEvent(&wheel)); + CHECK(app->poll_events()); + CHECK(app->take_navigation().wheel == 0); + app->set_ui_capture(false); + key(SDL_SCANCODE_W, true); + CHECK(app->poll_events()); + key(SDL_SCANCODE_W, true); + send(SDL_EVENT_WINDOW_MINIMIZED, id); + CHECK(app->poll_events()); + CHECK(required(app->sample_intention(49)).move_y == 0); + send(SDL_EVENT_WINDOW_RESTORED, id); + CHECK(app->poll_events()); + CHECK(required(app->sample_intention(50)).move_y == 0); + app->set_ui_capture(true); + key(SDL_SCANCODE_W, true); // Queued while captured; releasing capture must not replay it. + app->set_ui_capture(false); + CHECK(app->poll_events()); + CHECK(required(app->sample_intention(51)).move_y == 0); + CHECK(app->present(frame) == Step::rendered); +} } // namespace int main() try { + client_controls_tests(); frame_contract(); lifecycle(); + native_input(); return 0; } catch (const std::exception& e) { std::fprintf(stderr, "%s: %s\n", e.what(), SDL_GetError());