Implement M9.4 revision-tagged microscopic environment rendering

Add SDL-free owned EnvironmentPresentation copied from M6.3 views (no
store pointers or validation tokens), a single-slot EnvironmentLayer that
rejects foreign/regressed updates and reports none/current/stale against
observed authority watermarks, and a bounded camera projection with
explicit missing, not-requested, present-zero, undefined-moisture and
stale encodings (at most 2313 clipped rectangles, reused buffer).

The engineering app renders a local in-memory fixture authority with
configurable refresh cadence and layer selection. ADR-0080 records the
decision; validation evidence and limits are in VALIDATION.md.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
dingo
2026-10-01 17:45:53 -04:00
co-authored by Claude Opus 5.5
parent bb0412cd0f
commit feca07f791
20 changed files with 1393 additions and 62 deletions
+1 -1
View File
@@ -17,7 +17,7 @@
{"name": "analysis", "configurePreset": "analysis"},
{"name": "asan", "configurePreset": "asan"},
{"name": "tsan", "configurePreset": "tsan"},
{"name": "client", "configurePreset": "client", "targets": ["evo-client", "evo-client-lifecycle-tests"]},
{"name": "client", "configurePreset": "client", "targets": ["evo-client", "evo-client-lifecycle-tests", "evo-client-environment-tests"]},
{"name": "client-probe", "configurePreset": "client-probe", "targets": ["evo-client-probe"]}
],
"testPresets": [
+2
View File
@@ -172,3 +172,5 @@ 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.
M9.4 renders [revision-tagged environment views](docs/engineering/ENVIRONMENT_RENDERING.md)
with explicit missing/stale presentation from a local in-memory fixture authority.
+155 -33
View File
@@ -1,4 +1,5 @@
#include "evo/client/application.hpp"
#include "evo/render/environment.hpp"
#include <algorithm>
#include <array>
#include <charconv>
@@ -6,12 +7,117 @@
#include <cmath>
#include <cstdio>
#include <exception>
#include <memory>
#include <optional>
#include <string_view>
#include <thread>
#include <vector>
namespace {
using evo::world::Field;
constexpr evo::world::WorldIdentity fixture_identity{1, 1};
constexpr std::int64_t fixture_z = -16000;
// Water, nitrogen (never opened: missing), phosphorus (present zero), organic and
// incident energy (never opened: missing). Unrequested fields draw hollow outlines.
constexpr std::uint32_t fixture_mask = (1U << 0) | (1U << 1) | (1U << 2) | (1U << 7) | (1U << 8);
constexpr unsigned frames_per_authority_tick = 60;
// Local in-memory stand-in for authoritative region views until M9.7. It is never
// persisted or published; the client presentation only copies its read-only views.
struct FixtureAuthority {
std::unique_ptr<evo::world::FieldStore> fields;
std::unique_ptr<evo::world::ChunkStore> terrain;
std::vector<evo::world::VoxelAddress> footprint;
std::uint64_t tick{1};
};
std::optional<FixtureAuthority> make_authority() {
FixtureAuthority authority;
std::vector<evo::world::FieldSite> sites;
std::vector<std::uint64_t> water, energy;
for (std::int64_t x = -8; x < 8; ++x)
for (std::int64_t y = -4; y < 4; ++y) {
const auto ux = static_cast<std::uint64_t>(x + 8);
const auto uy = static_cast<std::uint64_t>(y + 4);
authority.footprint.push_back({x, y, fixture_z});
// Habitat boxes vary to show their boundaries inside each 1 m voxel.
const evo::world::HabitatBox box{{50000 * (ux % 4)}, {40000 * uy}, {0},
{800000 - 30000 * uy}, {500000 + 10000 * ux}, {100}};
sites.push_back({authority.footprint.back(), box, {1}});
const auto volume = box.width.value * box.height.value * box.depth.value;
water.push_back(volume >> (2 * ux / 3 + uy));
energy.push_back((ux + 1) * (uy + 1) * (volume >> 4));
}
const std::uint64_t zero = 0;
const evo::world::FieldOpening opening[]{
{Field::water, water}, {Field::phosphorus, {&zero, 1}}, {Field::organic_energy, energy}};
const evo::world::FieldDefaults defaults{{evo::accounting::Femtograms{0},
evo::accounting::Femtograms{1ULL << 50},
evo::accounting::Femtograms{0}}};
constexpr std::size_t budget = 4'000'000;
auto fields =
evo::world::FieldStore::create(fixture_identity, 1, defaults, sites, opening, budget);
auto terrain = evo::world::ChunkStore::create({}, 32, budget);
if (!fields || !terrain)
return std::nullopt;
authority.fields = std::move(*fields);
authority.terrain = std::move(*terrain);
for (const auto voxel : authority.footprint)
if (!authority.terrain->load(evo::world::split(voxel, evo::world::base_chunk_edge)->chunk))
return std::nullopt;
return authority;
}
// One conserved same-channel water move per authority tick (finite fixture stock).
bool advance(FixtureAuthority& authority) {
const auto sites = authority.fields->sites().size();
const auto from = static_cast<std::size_t>(authority.tick * 7 % sites);
const auto amount = authority.fields->read(from, Field::water);
if (!amount)
return false;
++authority.tick;
if (*amount < 8)
return true;
const auto moved = authority.fields->transfer(authority.tick, Field::water, from,
(from + 1) % sites, *amount / 8);
return moved || moved.error() == evo::world::FieldError::capacity;
}
std::optional<evo::client::EnvironmentPresentation> query(const FixtureAuthority& authority) {
const auto view = evo::world::query_environment(
*authority.fields, *authority.terrain, authority.tick, authority.footprint, fixture_mask);
if (!view)
return std::nullopt;
auto presentation = evo::client::present_environment(*view, fixture_z);
if (!presentation)
return std::nullopt;
return std::move(*presentation);
}
std::optional<evo::render::EnvironmentDisplay> parse_layer(std::string_view name) {
using Mode = evo::render::EnvironmentDisplay::Mode;
constexpr std::array<std::string_view, evo::world::field_count> names{"water",
"nitrogen",
"phosphorus",
"organic-carbon",
"organic-nitrogen",
"organic-phosphorus",
"organic-other",
"organic-energy",
"incident-energy",
"heat"};
if (name == "moisture")
return evo::render::EnvironmentDisplay{Mode::moisture};
for (std::size_t i = 0; i < names.size(); ++i)
if (name == names.at(i))
return evo::render::EnvironmentDisplay{Mode::field, static_cast<Field>(i)};
return std::nullopt;
}
bool parse_count(std::string_view value, unsigned limit, unsigned& out) {
const auto [end, error] = std::from_chars(value.data(), value.data() + value.size(), out);
return error == std::errc{} && end == value.data() + value.size() && out != 0 && out <= limit;
}
} // namespace
int main(int argc, char** argv) try {
evo::client::Config config;
unsigned frames = 0;
unsigned frames = 0, refresh_every = 1;
evo::render::EnvironmentDisplay display;
for (int i = 1; i < argc; ++i) {
const std::string_view arg{argv[i]};
if (arg == "--hidden")
@@ -19,18 +125,30 @@ int main(int argc, char** argv) try {
else if (arg == "--renderer" && i + 1 < argc)
config.renderer = argv[++i];
else if (arg == "--frames" && i + 1 < argc) {
const std::string_view value{argv[++i]};
const auto [end, error] =
std::from_chars(value.data(), value.data() + value.size(), frames);
if (error != std::errc{} || end != value.data() + value.size() || frames == 0 ||
frames > 100000)
if (!parse_count(argv[++i], 100000, frames))
return 2;
} else if (arg == "--refresh-every" && i + 1 < argc) {
if (!parse_count(argv[++i], 1000, refresh_every))
return 2;
} else if (arg == "--layer" && i + 1 < argc) {
const auto layer = parse_layer(argv[++i]);
if (!layer)
return 2;
display = *layer;
} else {
std::fputs("usage: evo-client [--renderer NAME] [--hidden] [--frames 1..100000]\n",
std::fputs("usage: evo-client [--renderer NAME] [--hidden] [--frames 1..100000]\n"
" [--layer water|nitrogen|...|heat|moisture]\n"
" [--refresh-every 1..1000]\n",
stderr);
return 2;
}
}
auto authority = make_authority();
if (!authority) {
std::fputs("client environment fixture error\n", stderr);
return 1;
}
evo::client::EnvironmentLayer environment;
auto app = evo::client::Application::open(config);
if (!app) {
std::fprintf(stderr, "client initialization error=%d\n", static_cast<int>(app.error()));
@@ -38,11 +156,13 @@ int main(int argc, char** argv) try {
}
// 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});
auto camera = evo::client::Camera::create(
{config.width, config.height, config.width, config.height}, {}, 0.05);
if (!camera)
return 1;
std::puts("Arrows: pan | wheel: zoom | WASD: intention indicator | Tab: UI capture (orange)");
std::puts("Environment chip: green current | amber stale | red no view");
std::vector<evo::render::Rectangle> boxes;
std::uint64_t count = 0;
auto previous = std::chrono::steady_clock::now();
while (frames == 0 || count < frames) {
@@ -62,7 +182,21 @@ int main(int argc, char** argv) try {
const auto intention = (*app)->sample_intention(count);
if (!intention)
return 1;
std::array<evo::render::Rectangle, 3> boxes{};
// The fixture authority advances at its own cadence. Presentations refresh
// every N authority ticks; in between the advanced watermark shows as stale.
if (count % frames_per_authority_tick == 0) {
if (count != 0 && !advance(*authority))
return 1;
if ((authority->tick - 1) % refresh_every == 0) {
auto next = query(*authority);
if (!next || !environment.accept(std::move(*next)))
return 1;
}
if (!environment.observe(
{fixture_identity, authority->tick, authority->fields->last_command()}))
return 1;
}
boxes.clear();
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,
@@ -78,31 +212,19 @@ int main(int argc, char** argv) try {
if (auto result = camera->zoom(std::exp2(navigation.wheel / 4), anchor);
!result && result.error() != evo::client::CameraError::out_of_range)
return 1;
// 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)
// Copied presentation only; clipped to the viewport before float conversion.
if (!evo::render::build_environment(boxes, environment.current(),
environment.freshness(), *camera, display))
return 1;
const double left = std::clamp(upper->x, 0.0, static_cast<double>(state.logical_width));
const double top = std::clamp(upper->y, 0.0, static_cast<double>(state.logical_height));
const double right =
std::clamp(lower->x, 0.0, static_cast<double>(state.logical_width));
const double bottom =
std::clamp(lower->y, 0.0, static_cast<double>(state.logical_height));
boxes[0] = {static_cast<float>(left),
static_cast<float>(top),
static_cast<float>(right - left),
static_cast<float>(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<float>(intention->move_x) / 50,
48 - static_cast<float>(intention->move_y) / 50,
8,
8,
{240, 240, 240, 255}};
boxes.push_back({8, 8, 64, 8,
(*app)->ui_captured() ? evo::render::Color{240, 140, 32, 255}
: evo::render::Color{64, 180, 140, 255}});
boxes.push_back({36 + static_cast<float>(intention->move_x) / 50,
48 - static_cast<float>(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;
+13 -1
View File
@@ -52,12 +52,19 @@ if(EVO_BUILD_CLIENT)
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)
# SDL-free environment presentation (M9.4): copies read-only world views, never the reverse.
add_library(evo_client_views STATIC src/client/views/environment_view.cpp)
target_link_libraries(evo_client_views PUBLIC evo::world)
evo_owned_target(evo_client_views)
add_library(evo_render_environment STATIC src/render/environment/environment.cpp)
target_link_libraries(evo_render_environment PUBLIC evo_client_views evo_client_controls evo_render_frame)
evo_owned_target(evo_render_environment)
add_library(evo_client_platform STATIC src/client/platform/application.cpp src/render/sdl_renderer.cpp)
target_include_directories(evo_client_platform PRIVATE "${PROJECT_SOURCE_DIR}/src")
target_link_libraries(evo_client_platform PUBLIC evo_render_frame evo_client_controls PRIVATE SDL3::SDL3)
evo_owned_target(evo_client_platform)
add_executable(evo-client apps/evo-client/main.cpp)
target_link_libraries(evo-client PRIVATE evo_client_platform)
target_link_libraries(evo-client PRIVATE evo_client_platform evo_render_environment)
evo_owned_target(evo-client)
evo_client_runtime(evo-client)
if(BUILD_TESTING)
@@ -66,6 +73,11 @@ if(EVO_BUILD_CLIENT)
target_link_libraries(evo-client-lifecycle-tests PRIVATE evo_client_platform SDL3::SDL3)
evo_owned_target(evo-client-lifecycle-tests)
evo_client_runtime(evo-client-lifecycle-tests)
add_executable(evo-client-environment-tests tests/client_environment.cpp)
target_link_libraries(evo-client-environment-tests PRIVATE evo_render_environment)
evo_owned_target(evo-client-environment-tests)
add_test(NAME client-environment COMMAND evo-client-environment-tests)
set_tests_properties(client-environment PROPERTIES TIMEOUT 60 LABELS "client")
add_test(NAME client-lifecycle COMMAND evo-client-lifecycle-tests)
add_test(NAME client-smoke COMMAND evo-client --renderer software --frames 3)
add_test(NAME client-init-failure COMMAND evo-client --frames 1)
+2 -2
View File
@@ -41,12 +41,12 @@ RUN apt-get update && apt-get install -y --no-install-recommends \
RUN cmake -P tools/prepare-sdl3.cmake \
&& cmake --preset client-probe -DCMAKE_CXX_COMPILER=clang++-19 \
-DEVO_BUILD_CLIENT=ON -DEVO_ENABLE_TIDY=ON -DSDL_X11=ON -DSDL_WAYLAND=OFF \
&& cmake --build build/client-probe --target evo-client-probe evo-client evo-client-lifecycle-tests --parallel 2 \
&& cmake --build build/client-probe --target evo-client-probe evo-client evo-client-lifecycle-tests evo-client-environment-tests --parallel 2 \
&& ctest --preset client-probe --no-tests=error \
&& xvfb-run -a env SDL_VIDEO_DRIVER=x11 ./build/client-probe/evo-client-probe --renderer software \
&& xvfb-run -a env SDL_VIDEO_DRIVER=x11 ./build/client-probe/evo-client-lifecycle-tests \
&& cmake --preset client-probe -DEVO_BUILD_CLIENT=ON -DEVO_SANITIZER=address -DEVO_ENABLE_TIDY=OFF \
&& cmake --build build/client-probe --target evo-client evo-client-lifecycle-tests --parallel 2 \
&& cmake --build build/client-probe --target evo-client evo-client-lifecycle-tests evo-client-environment-tests --parallel 2 \
&& ctest --preset client-probe --no-tests=error \
&& xvfb-run -a env SDL_VIDEO_DRIVER=x11 ./build/client-probe/evo-client-lifecycle-tests
+7 -1
View File
@@ -404,7 +404,13 @@ from injected events.
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.
fixture ticks, not server time.
**M9.4 status (2026-10-01):** owned revision-tagged environment presentations,
ordered freshness (none/current/stale) and bounded camera-projected rendering
with explicit missing, unrequested, present-zero and undefined encodings under
ADR-0080. A local in-memory fixture authority stands in for server views until
M9.7. Evidence in engineering/VALIDATION.md. Next gate: M9.5.
**Goal:** a native desktop cellular viewer/controller with input, camera, renderer,
readable organism/environment views and a real development-server connection.
+16 -10
View File
@@ -2,17 +2,23 @@
## Current gate — 2026-10-01
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.
M9.4 renders microscopic environment views
([ADR-0080](adr/0080-environment-presentation.md)). The client copies M6.3 views
into owned, revision-tagged presentations; `EnvironmentLayer` rejects foreign or
regressed updates and shows none/current/stale against observed authority
watermarks. Habitats, terrain cells and voxel boundaries project through the
M9.3 camera into at most 2313 clipped rectangles, with explicit missing,
not-requested, present-zero, undefined-moisture and stale encodings. See
[ENVIRONMENT_RENDERING.md](engineering/ENVIRONMENT_RENDERING.md) and
[VALIDATION.md](engineering/VALIDATION.md). Remote Gitea client execution of the
extended CI stage remains unverified locally.
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.
Next: **M9.5**, organism and debug views. The app's environment comes from a local
in-memory fixture authority, not a connected region; its tick is a fixture counter.
No deployment, simulation rules, persistent formats or world snapshots changed.
M9.3 added local-mm pan/zoom camera mapping and bounded sequence/tick input
intentions ([ADR-0079](adr/0079-camera-and-input-intentions.md)).
The sections below retain earlier milestone delivery history.
+69
View File
@@ -0,0 +1,69 @@
# ADR-0080: Revision-tagged environment presentation
## Status
Accepted for the M9.4 engineering client. Colours, ramps and thresholds are
presentation choices, not physical scales, biology or final player UI.
## Context
M6.3 views carry typed quantities, explicit absence, tick, field watermark and
per-chunk revisions, but also private store identities and validation tokens.
The renderer must not retain those, must not turn missing data into zero, and
must not grow geometry with world size. M9.7 will receive views from a server,
so the presentation boundary cannot depend on local store objects.
## Decision
Add an SDL-free, owned `EnvironmentPresentation` (include/evo/client/
environment_view.hpp): one Z slice of at most 256 copied cells, each with voxel,
chunk revision, habitat box/volume, substrate, terrain material/fill, per-field
presence (`not_requested`, `missing`, `present`) with fg/pJ quantity, and moisture
status. `create` validates mask/presence consistency, habitat geometry, slice,
strict (x, y) order and bounds; `present_environment` adapts a local M6.3 view and
copies no tokens or store pointers. The type is the transport-neutral input for
later server views; it is not a capability and never authorizes consumption.
`EnvironmentLayer` holds at most one presentation and the newest observed authority
revision (identity, tick, field watermark). It rejects other worlds/frames and any
regression of tick, field revision or a shared voxel's chunk revision; equal
revisions are accepted (new footprint). A presentation is `stale` when an observed
revision is ahead of it or the host reports failed validation; `none` when absent.
Restore/reconnect to another lineage requires explicit `reset`.
`build_environment` (include/evo/render/environment.hpp) projects cells through
the M9.3 camera into clipped logical rectangles, in cell order: terrain square,
habitat encoding, voxel outline, then a status chip and legend. Encodings: present
values on a fixed log2 density ramp (quantity/habitat um^3 over [-30, 12]); present
zero black; missing a magenta checker; not requested a hollow grey outline; zero
water capacity a distinct "undefined" colour. Stale dims fills and outlines voxels
amber; the chip is green/amber/red for current/stale/none. Small cells collapse to
one encoded rectangle. Output is at most 256*9+9 rectangles in a caller-reused
buffer; no textures, caches or per-world allocation exist.
The engineering app owns an in-memory local fixture authority (FieldStore +
ChunkStore) that performs conserved same-channel water moves via the public API and
refreshes views at a configurable cadence. It is never persisted or published and
is replaced by M9.7 server views. No new dependency, simulation rule or format.
## Alternatives considered
- Render directly from `EnvironmentView`: retains store identities/tokens and
couples the renderer to local stores; rejected.
- Auto-ranged colour scale per view: hides absolute change between refreshes.
- Textures/field images: unnecessary for 256 bounded habitats; adds GPU lifetime.
- Silently keeping the newest arrival: out-of-order updates could roll back state.
## Benefits
Explicit absence/zero/unrequested/undefined/stale presentation, bounded memory and
work, deterministic output and SDL-free tests; rendering cannot mutate resources.
## Costs
Fixed ramp clamps extreme densities; one Z slice and one field per frame. Global
field watermark marks whole views stale (ADR-0052 conservatism).
## Risks
Colour choices are not accessibility-qualified; human visual and colour-vision
review remain M9.8 work. Validation of authority revisions is only as honest as
the host/server supplying them; M9.6/9.7 must authenticate and bound them.
## Consequences
M9.5 adds organism presentation on the same frame budget; M9.7 builds
`EnvironmentPresentation` from protocol views and feeds server watermarks to
`observe`. Changing ramp/encoding semantics requires updating this ADR and tests.
+1
View File
@@ -91,3 +91,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.
- [ADR-0080: Environment presentation](0080-environment-presentation.md) - owned revision-tagged environment presentations, ordered freshness and bounded explicit missing/stale rendering.
+14 -2
View File
@@ -1,4 +1,4 @@
# Native client boundary (M9.2–M9.3)
# Native client boundary (M9.2–M9.4)
Implemented scope: desktop lifecycle and primitive presentation, not gameplay.
ADR-0077 selects SDL; ADR-0078 defines its ownership and view boundary.
@@ -9,7 +9,9 @@ flowchart LR
App --> Frame[Owned immutable render Frame]
Platform --> Render[Private SDL renderer]
Frame --> Render
Future[Later M9.4 view projection] -. copied presentation values .-> Frame
World[M6.3 EnvironmentView] -- copied once --> Views[EnvironmentPresentation / Layer]
Views --> Env[build_environment + Camera]
Env -- bounded rectangles --> Frame
```
`include/evo/client/application.hpp` and `include/evo/render/frame.hpp` contain
@@ -47,6 +49,16 @@ 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.
M9.4 ([ENVIRONMENT_RENDERING.md](../engineering/ENVIRONMENT_RENDERING.md),
ADR-0080) adds SDL-free `client/environment_view.hpp` and
`render/environment.hpp`. A presentation copies at most 256 cells of one Z slice
from a view and retains no store, token or native handle. `EnvironmentLayer`
holds one presentation, rejects foreign or regressed revisions and reports
none/current/stale against observed authority watermarks. The projection emits
at most 2313 clipped rectangles with explicit missing, unrequested, present-zero,
undefined and stale encodings. The client libraries link the headless world
library read-only; no world or simulation target links client code.
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
+4 -2
View File
@@ -44,8 +44,10 @@ No Steam ID, socket, Kubernetes API, logger clock or storage handle belongs in
the simulation state. Durable account references live in orchestration mapping.
M9.2 implements the opt-in [native client boundary](CLIENT_ARCHITECTURE.md):
copied immutable presentation frames and one main-thread platform owner. It does
not yet project biological views or connect to a region server.
copied immutable presentation frames and one main-thread platform owner. M9.4
projects owned copies of M6.3 environment views (ADR-0080); the dependency runs
world -> client views -> render only. It does not yet render organisms or connect
to a region server.
| Boundary | Owns | Must not own |
|---|---|---|
+5 -4
View File
@@ -71,8 +71,9 @@ 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
It draws a capture indicator, an intention dot and (since M9.4) the environment
fixture. 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. Input never
sends network messages, modifies the world or acts for an organism; the M9.4
fixture authority's own water moves are independent of input. M9.6 must bind intention ticks
and counters to secure sessions; the server independently validates all requests.
+14 -6
View File
@@ -1,9 +1,11 @@
# Native engineering client (M9.2–M9.3)
# Native engineering client (M9.2–M9.4)
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.
This opens a resizable native window showing camera-controlled environment habitats
from a local in-memory fixture authority (M9.4). It does not run an ecosystem,
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.
Environment: [presentation and encodings](ENVIRONMENT_RENDERING.md), ADR-0080.
## Build and run
@@ -25,14 +27,18 @@ Close the window to exit. `--renderer software` or `--renderer vulkan` requests
one explicit backend, without fallback. `--frames N` exits after N bounded steps
(including paused steps), maximum 100000; `--hidden` opens without showing the
window and pauses drawing. These options permit unattended smoke checks.
Usage errors exit 2, lifecycle failures exit 1, orderly exit returns 0.
`--layer NAME` selects the displayed field or `moisture`; `--refresh-every N`
(1..1000 fixture authority ticks) delays view refresh so the stale state is visible.
Usage errors exit 2, lifecycle/fixture failures exit 1, orderly exit returns 0.
Engineering controls: arrow keys pan, mouse wheel zooms around the pointer, WASD
updates the small intention indicator without moving the world fixture. Tab
toggles UI capture: the top-left bar turns orange and navigation/movement input
is suppressed. Leaving capture/focus loss requires fresh presses. This is a
focus exercise, not the final player UI. The host's input tick is a local fixture
counter and is never interpreted as authoritative server time.
counter and is never interpreted as authoritative server time. The top-right
chip shows environment freshness (green current, amber stale, red none); the
bottom-left legend shows the value ramp.
For native X11 regression on a CI host:
@@ -40,7 +46,9 @@ For native X11 regression on a CI host:
xvfb-run -a env SDL_VIDEO_DRIVER=x11 ./build/client/evo-client-lifecycle-tests
```
CTest uses the dummy driver. The lifecycle suite runs 32 open/destroy rounds,
CTest uses the dummy driver. `client-environment` is an SDL-free suite for
presentation validation, ordering/freshness, encodings, seams and bounds; it
prints an `environment_profile` line (rectangles, bytes, microseconds per build). The lifecycle suite runs 32 open/destroy rounds,
resize/scale queries, non-unit drawable-scale pixel checks, minimize/restore,
show/hide, focus/foreign events, reset/loss and close. Separate process checks
exercise initialization failure. Tests stay active under NDEBUG. Synthetic
+92
View File
@@ -0,0 +1,92 @@
# M9.4 microscopic environment rendering
Decision: [ADR-0080](../adr/0080-environment-presentation.md). Headers:
`include/evo/client/environment_view.hpp` (presentation values, freshness) and
`include/evo/render/environment.hpp` (rectangle projection). Neither includes SDL.
Dependency direction: world (read-only views) -> client views -> render
environment -> immutable `Frame` -> private SDL renderer. Nothing flows back.
```cpp
auto view = world::query_environment(fields, terrain, tick, footprint, mask);
auto presentation = client::present_environment(*view, slice_z); // owned copy
layer.accept(std::move(*presentation)); // rejects foreign/regressed
layer.observe({identity, authority_tick, field_watermark}); // later: stale?
render::build_environment(rects, layer.current(), layer.freshness(), camera, display);
```
## Presentation values
A presentation is one Z slice of 1..256 cells, strictly ordered by voxel (x, y),
with the source revision (world/frame, tick, field watermark) and request mask.
Cells copy chunk revision, the habitat box and volume, substrate, terrain material
and fill, per-field presence/quantity and moisture status. Validation rejects
inconsistent presence vs mask, quantities on non-present fields, habitat boxes
outside their voxel, volume mismatch, out-of-range voxels, mixed slices,
duplicates/unsorted cells and invalid saturation. No store pointer, ChunkView
token, native handle or authority capability is retained. A presentation stays
valid after its source stores are destroyed.
## Freshness and update ordering
`EnvironmentLayer` keeps at most one presentation (no history or queue) and the
newest observed authority revision. `accept` rejects another world/frame
(`foreign_world`) or any regression of tick, field watermark or a shared voxel's
chunk revision (`regressed`) without mutation. Equal revisions are accepted so a
camera-driven footprint change can replace the cells. `observe` records the
authority's latest revision (also before the first presentation); a regressed or
foreign watermark rejects. Freshness is:
| State | Meaning | Presentation |
|---|---|---|
| none | nothing accepted (or reset) | red chip, no cells |
| current | presentation equals newest observed revision | green chip |
| stale | authority advanced, or host validation failed (`mark_stale`) | amber chip, dimmed fills, amber voxel outlines |
A late presentation newer than the displayed one but older than the observed
watermark is accepted and shown stale. Restore/reconnect requires `reset`;
ADR-0052 restored stores are different owners, so their revisions need not continue.
## Encodings
Each visible cell emits: terrain square (material colour blended from void by fill;
unknown material IDs are cyan), habitat encoding, then a voxel outline when the voxel
is at least 8 logical units wide. Habitat encodings:
| Data | Encoding |
|---|---|
| present, nonzero | ramp(log2(quantity / habitat um^3) mapped from [-30, 12]) |
| present zero | black fill |
| requested but missing | 2x2 magenta/dark checker |
| not requested | hollow grey outline |
| moisture with zero water capacity | rust "undefined" fill |
| moisture available | ramp(saturation) linear in [0, 1] |
Mass is fg, energy pJ; both use density per cubic micrometre of the habitat's
effective volume. Values outside the ramp clamp to its ends; the eight-step legend
(bottom-left) shows the ramp, not physical units. Habitats under 4 logical units
collapse to one rectangle in the encoding's primary colour, so missing remains
magenta and not-requested grey. Nothing is interpolated between habitats and no
value is inferred from material IDs.
## Geometry and resource bounds
Projection uses the CAMERA_INPUT formula on voxel edges, so shared edges between
neighbouring voxels (including signed chunk seams) are computed from identical
world coordinates. Edges may lie on the exclusive world bound. Cells fully outside
the viewport emit nothing; others clip to `[0, width] x [0, height]` before float
conversion. Output is at most `256 * 9 + 9 = 2313` rectangles, within the 4096
frame limit including host UI. `build_environment` clears and reserves the
caller's buffer once; reuse keeps capacity constant. No textures or caches exist.
## Engineering app
`evo-client` hosts a local in-memory fixture authority: 16x8 habitats at z=-16000
with varied boxes, varying water and organic energy, present-zero phosphorus and
never-opened nitrogen/incident energy. Every 60 frames it advances its tick and
moves 1/8 of one site's water to a neighbour through `FieldStore::transfer`.
`--refresh-every N` (1..1000, default 1) refreshes the view every N authority ticks;
between refreshes the observed watermark shows the stale state. `--layer` selects
`water`, `nitrogen`, `phosphorus`, `organic-carbon`, `organic-nitrogen`,
`organic-phosphorus`, `organic-other`, `organic-energy`, `incident-energy`, `heat`
or `moisture`. The fixture is never persisted or published; M9.7 replaces it with
server views. It is not biology, an ecosystem or a world-generation rule.
+60
View File
@@ -3284,3 +3284,63 @@ No full headless suite or TSan rerun; owned client state remains main-thread-onl
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.
## M9.4 microscopic environment rendering — 2026-10-01
Implemented ADR-0080 and ENVIRONMENT_RENDERING.md: owned revision-tagged
`EnvironmentPresentation` copied from M6.3 views (no tokens/store pointers),
single-slot `EnvironmentLayer` ordering/freshness, and bounded camera-projected
rendering with explicit missing, not-requested, present-zero, undefined-moisture
and stale encodings. The app shows a local in-memory fixture authority (finite
same-channel water moves via `FieldStore::transfer`); it is not a server view.
Executed:
- Windows MSVC 19.44 Release via `tools/windows-check.ps1 -Preset client -Action
check` (run as a child `powershell.exe`): 4/4 labeled tests, including the new
`client-environment` suite. App runs with `--frames 240/300`, `--refresh-every
2`, `--layer organic-carbon` exited 0; `--layer bogus` exited 2;
`SDL_VIDEO_DRIVER=evo-invalid` still fails at SDL initialization (error 2),
after fixture creation, so `client-init-failure` keeps testing the SDL path.
- Linux GCC 14 Release (`build/client-probe-linux`, probe + client): 6/6 labeled
tests; native Xvfb/X11 lifecycle suite; X11 app runs (moisture, refresh 3).
- Clang 19 Debug ASan/UBSan (`build/client-asan`): 4/4 labeled tests, native X11
lifecycle, hidden X11 app (refresh 2), visible X11 moisture app and dummy-driver
nitrogen app (400 frames, refresh 3) with leak detection, no suppressions.
- clang-tidy 19 with warnings-as-errors on the four new/changed translation units:
passed after reserving a test vector, widening a test product, and annotating
two intentional out-of-range enum inputs (the rejection under test).
Repository-wide clang-format 19 check passed.
- Tests cover: synthetic known fields (exact ramp colour for log2 density -3,
present zero, missing checker geometry, hollow unrequested outline, undefined
zero-capacity moisture, collapsed small habitats); seams across chunk
boundaries -16/0/16 at three zooms, three centres and two DPI ratios, compared
with `Camera::world_to_screen`; voxels on the exclusive world bound; stale
updates (older tick, chunk-revision regression, foreign world, regressed and
pre-presentation watermarks, late-but-stale presentations, reset); failed
local validation after a field transfer; unchanged field/terrain snapshots
after presenting/rendering; presentations outliving their stores; 20 invalid
presentation shapes; 330 camera/mode/freshness combinations over 256 cells,
all within viewport, the 2313 bound, constant buffer capacity and Frame
limits including host UI.
- Profile (`environment_profile`, 256 visible cells, stale, nitrogen layer,
checker detail): 1701 rectangles; 53,248 presentation-cell bytes; 46,260-byte
reused output buffer; mean build 13.4 us (MSVC Release, this workstation),
6.6 us (GCC 14 Release, WSL2), 175 us (Clang ASan Debug). Indicative only; no
frame-time threshold is claimed.
- Visual sanity check: the fixture's output was rasterized offline for water,
stale, nitrogen (missing), moisture and organic-carbon (not requested). This
raised the not-requested outline from grey 140 to 210 for contrast with rock.
This is not human/colour-vision acceptance.
- Headless: a fresh MSVC Release directory with both client options OFF built
`evo-sim`; seed 123456 / eight entities / 1000 ticks replayed with unchanged
`d61ad5bf0c928c76`, `replay_verified=true`.
Limits: pre-existing `build/release` failed to link untouched headless objects
(unresolved MSVC STL `__std_rotate`/`__std_find_first_not_of_trivial_pos_1`),
consistent with stale objects from a different STL build; the fresh directory
above passed, and that directory was left as found. Docker/Gitea execution of the
extended `ci-client` stage was not observed locally. No full headless suite or
TSan rerun (headless sources unchanged; client state is main-thread-only). No
physical DPI, real GPU, Wayland, accessibility or human visual acceptance is
claimed. No network traffic, database, deployment or persistent format changed.
+102
View File
@@ -0,0 +1,102 @@
#pragma once
#include "evo/world/environment.hpp"
#include <array>
#include <cstddef>
#include <cstdint>
#include <expected>
#include <optional>
#include <span>
#include <vector>
namespace evo::client {
inline constexpr std::size_t max_environment_cells = world::max_environment_footprint;
// Authority revision a presentation was copied from. Not a capability or session grant.
struct EnvironmentRevision {
world::WorldIdentity identity;
std::uint64_t tick{}, field_revision{};
auto operator<=>(const EnvironmentRevision&) const = default;
};
enum class FieldPresence : std::uint8_t { not_requested, missing, present };
// Copied presentation values for one habitat in the selected Z slice. Public aggregates
// are unvalidated input; EnvironmentPresentation::create validates them.
struct EnvironmentCell {
world::VoxelAddress voxel;
std::uint64_t chunk_revision{};
world::HabitatBox habitat{};
world::CubicMicrometres volume{};
world::MaterialId substrate, terrain_material;
std::uint16_t terrain_fill{};
std::array<FieldPresence, world::field_count> presence{};
// Femtograms for mass fields, picojoules for energy fields; zero unless present.
std::array<std::uint64_t, world::field_count> quantity{};
world::MoistureStatus moisture_status{world::MoistureStatus::not_requested};
world::WaterSaturation moisture{}; // Meaningful only when moisture_status is available.
};
enum class ViewError : std::uint8_t {
invalid_view,
empty_slice,
too_many_cells,
foreign_world,
regressed
};
// Immutable owned copy; never retains world stores, chunk tokens or native handles.
class EnvironmentPresentation {
public:
[[nodiscard]] static std::expected<EnvironmentPresentation, ViewError>
create(EnvironmentRevision revision, std::uint32_t requested_mask, std::int64_t slice_z,
std::span<const EnvironmentCell> cells);
[[nodiscard]] EnvironmentRevision revision() const noexcept {
return revision_;
}
[[nodiscard]] std::uint32_t requested_mask() const noexcept {
return mask_;
}
[[nodiscard]] std::int64_t slice_z() const noexcept {
return slice_z_;
}
// Strictly ordered by voxel (x, then y), all at slice_z.
[[nodiscard]] std::span<const EnvironmentCell> cells() const noexcept {
return cells_;
}
private:
EnvironmentPresentation(EnvironmentRevision revision, std::uint32_t mask, std::int64_t z,
std::span<const EnvironmentCell> cells)
: revision_{revision}, mask_{mask}, slice_z_{z}, cells_(cells.begin(), cells.end()) {}
EnvironmentRevision revision_;
std::uint32_t mask_;
std::int64_t slice_z_;
std::vector<EnvironmentCell> cells_;
};
// Copies the samples at slice_z from a local M6.3 view. Reads only; the view's
// validation tokens and store identities are not copied.
[[nodiscard]] std::expected<EnvironmentPresentation, ViewError>
present_environment(const world::EnvironmentView& view, std::int64_t slice_z);
enum class Freshness : std::uint8_t { none, current, stale };
// Latest accepted presentation plus the newest authority revision observed.
// Bounded to one presentation; no history or update queue.
class EnvironmentLayer {
public:
// Rejects a different world/frame or any regression of tick, field revision or a
// shared voxel's chunk revision. Equal revisions are accepted (e.g. a new footprint).
[[nodiscard]] std::expected<void, ViewError> accept(EnvironmentPresentation next);
// Records that the authority has reached `latest` (also before any presentation);
// the presentation is stale while it differs from the newest observed revision.
// A different world/frame or a regressed revision rejects without mutation.
[[nodiscard]] std::expected<void, ViewError> observe(EnvironmentRevision latest);
// Host evidence (e.g. failed local validation) that the presentation is out of date.
void mark_stale() noexcept;
// Required after restore/reconnect to a different authority lineage.
void reset() noexcept;
[[nodiscard]] const EnvironmentPresentation* current() const noexcept {
return current_ ? &*current_ : nullptr;
}
[[nodiscard]] Freshness freshness() const noexcept;
private:
std::optional<EnvironmentPresentation> current_;
std::optional<EnvironmentRevision> latest_;
bool stale_{};
};
} // namespace evo::client
+46
View File
@@ -0,0 +1,46 @@
#pragma once
#include "evo/client/camera.hpp"
#include "evo/client/environment_view.hpp"
#include "evo/render/frame.hpp"
#include <cstddef>
#include <cstdint>
#include <expected>
#include <vector>
namespace evo::render {
// Per cell: terrain square, up to four habitat rectangles (fill, checker or hollow
// outline) and up to four voxel-outline rectangles; plus status and legend.
inline constexpr std::size_t environment_legend_steps = 8;
inline constexpr std::size_t max_environment_rectangles =
client::max_environment_cells * 9 + 1 + environment_legend_steps;
struct EnvironmentDisplay {
enum class Mode : std::uint8_t { field, moisture } mode{Mode::field};
world::Field field{world::Field::water}; // Used by Mode::field only.
};
// Presentation encodings, deliberately distinct from every ramp colour.
namespace palette {
inline constexpr Color present_zero{0, 0, 0, 255};
inline constexpr Color missing_a{150, 40, 150, 255}, missing_b{40, 12, 40, 255};
inline constexpr Color not_requested{210, 210, 210, 255};
inline constexpr Color undefined{150, 50, 30, 255}; // Moisture with zero water capacity.
inline constexpr Color voxel_outline{8, 10, 14, 255};
inline constexpr Color stale_outline{240, 170, 40, 255};
inline constexpr Color status_none{200, 40, 40, 255};
inline constexpr Color status_current{64, 180, 140, 255};
inline constexpr Color status_stale{240, 170, 40, 255};
} // namespace palette
// Field layers map log2(quantity / habitat volume um^3) over [-30, 12] onto the ramp,
// clamping outside it. Moisture maps saturation [0, 1] linearly. Presentation only.
inline constexpr double field_log2_min = -30, field_log2_max = 12;
[[nodiscard]] Color ramp(double t) noexcept;
[[nodiscard]] Color dim(Color color) noexcept; // Stale presentation tint.
enum class EnvironmentRenderError : std::uint8_t { invalid_display };
// Replaces `out` with logical-window rectangles clipped to the camera viewport, in
// cell order, ending with the status chip and legend. Output never exceeds
// max_environment_rectangles; reuse `out` to avoid per-frame allocation. A null
// presentation (or Freshness::none) draws only the "no environment" status.
[[nodiscard]] std::expected<void, EnvironmentRenderError>
build_environment(std::vector<Rectangle>& out, const client::EnvironmentPresentation* presentation,
client::Freshness freshness, const client::Camera& camera,
EnvironmentDisplay display);
} // namespace evo::render
+163
View File
@@ -0,0 +1,163 @@
#include "evo/client/environment_view.hpp"
#include <algorithm>
#include <utility>
#include <variant>
namespace evo::client {
namespace {
using world::MoistureStatus;
constexpr auto water = static_cast<std::size_t>(world::Field::water);
bool in_range(std::int64_t value) {
return value >= -world::voxel_limit && value < world::voxel_limit;
}
bool ordered(const EnvironmentCell& a, const EnvironmentCell& b) {
return std::pair{a.voxel.x, a.voxel.y} < std::pair{b.voxel.x, b.voxel.y};
}
bool valid_moisture(const EnvironmentCell& cell, std::uint32_t mask) {
if ((mask & (1U << water)) == 0)
return cell.moisture_status == MoistureStatus::not_requested;
switch (cell.moisture_status) {
case MoistureStatus::missing_water:
return cell.presence[water] == FieldPresence::missing;
case MoistureStatus::zero_capacity:
return cell.presence[water] == FieldPresence::present;
case MoistureStatus::available:
return cell.presence[water] == FieldPresence::present && cell.moisture.denominator != 0 &&
cell.moisture.numerator <= cell.moisture.denominator;
case MoistureStatus::not_requested:
return false;
}
return false;
}
bool valid(const EnvironmentCell& cell, std::uint32_t mask, std::int64_t z) {
if (cell.voxel.z != z || !in_range(cell.voxel.x) || !in_range(cell.voxel.y))
return false; // Any u16 fill is within fill_scale.
const auto measure = world::measure_habitat(cell.habitat);
if (!measure || measure->volume != cell.volume)
return false;
for (std::size_t k = 0; k < world::field_count; ++k) {
const bool requested = (mask & (1U << k)) != 0;
if (requested == (cell.presence[k] == FieldPresence::not_requested) ||
(cell.presence[k] != FieldPresence::present && cell.quantity[k] != 0))
return false;
}
return valid_moisture(cell, mask);
}
bool regressed(EnvironmentRevision next, EnvironmentRevision previous) {
return next.tick < previous.tick || next.field_revision < previous.field_revision;
}
// Both sides are strictly ordered by (x, y): a linear merge finds shared voxels.
bool chunk_regressed(std::span<const EnvironmentCell> next,
std::span<const EnvironmentCell> previous) {
std::size_t i = 0, j = 0;
while (i < next.size() && j < previous.size()) {
if (ordered(next[i], previous[j]))
++i;
else if (ordered(previous[j], next[i]))
++j;
else if (next[i++].chunk_revision < previous[j++].chunk_revision)
return true;
}
return false;
}
} // namespace
std::expected<EnvironmentPresentation, ViewError>
EnvironmentPresentation::create(EnvironmentRevision revision, std::uint32_t requested_mask,
std::int64_t slice_z, std::span<const EnvironmentCell> cells) {
if (requested_mask == 0 || (requested_mask & ~world::all_environment_fields) != 0 ||
!in_range(slice_z))
return std::unexpected(ViewError::invalid_view);
if (cells.empty())
return std::unexpected(ViewError::empty_slice);
if (cells.size() > max_environment_cells)
return std::unexpected(ViewError::too_many_cells);
for (std::size_t i = 0; i < cells.size(); ++i)
if (!valid(cells[i], requested_mask, slice_z) ||
(i > 0 && !ordered(cells[i - 1], cells[i])))
return std::unexpected(ViewError::invalid_view);
return EnvironmentPresentation{revision, requested_mask, slice_z, cells};
}
std::expected<EnvironmentPresentation, ViewError>
present_environment(const world::EnvironmentView& view, std::int64_t slice_z) {
std::vector<EnvironmentCell> cells;
for (const auto& sample : view.samples()) {
if (sample.voxel.z != slice_z)
continue;
EnvironmentCell cell;
cell.voxel = sample.voxel;
cell.chunk_revision = sample.chunk_revision;
cell.habitat = sample.habitat.box;
cell.volume = sample.measure.volume;
cell.substrate = sample.habitat.substrate;
cell.terrain_material = sample.terrain.material();
cell.terrain_fill = sample.terrain.fill();
cell.moisture_status = sample.moisture_status;
cell.moisture = sample.moisture.value_or(world::WaterSaturation{});
for (std::size_t k = 0; k < world::field_count; ++k) {
if ((view.requested_mask() & (1U << k)) == 0)
continue;
const auto& field = sample.fields[k];
cell.presence[k] = field ? FieldPresence::present : FieldPresence::missing;
if (field)
cell.quantity[k] = std::visit(
[](const auto& value) -> std::uint64_t {
if constexpr (std::is_same_v<std::decay_t<decltype(value)>,
world::EnvironmentMass>)
return value.amount.value;
else
return value.value;
},
*field);
}
cells.push_back(cell);
}
// World views order by (x, y, z); one Z slice therefore keeps (x, y) order.
return EnvironmentPresentation::create({view.identity(), view.tick(), view.field_revision()},
view.requested_mask(), slice_z, cells);
}
std::expected<void, ViewError> EnvironmentLayer::accept(EnvironmentPresentation next) {
const auto revision = next.revision();
if (latest_ && revision.identity != latest_->identity)
return std::unexpected(ViewError::foreign_world);
if (current_ && (regressed(revision, current_->revision()) ||
chunk_regressed(next.cells(), current_->cells())))
return std::unexpected(ViewError::regressed);
if (latest_)
latest_ = EnvironmentRevision{revision.identity, std::max(latest_->tick, revision.tick),
std::max(latest_->field_revision, revision.field_revision)};
else
latest_ = revision;
current_ = std::move(next);
stale_ = *latest_ != revision;
return {};
}
std::expected<void, ViewError> EnvironmentLayer::observe(EnvironmentRevision latest) {
if (latest_ && latest.identity != latest_->identity)
return std::unexpected(ViewError::foreign_world);
if (latest_ && regressed(latest, *latest_))
return std::unexpected(ViewError::regressed);
latest_ = latest;
stale_ = stale_ || (current_ && latest != current_->revision());
return {};
}
void EnvironmentLayer::mark_stale() noexcept {
stale_ = current_.has_value();
}
void EnvironmentLayer::reset() noexcept {
current_.reset();
latest_.reset();
stale_ = false;
}
Freshness EnvironmentLayer::freshness() const noexcept {
if (!current_)
return Freshness::none;
return stale_ ? Freshness::stale : Freshness::current;
}
} // namespace evo::client
+186
View File
@@ -0,0 +1,186 @@
#include "evo/render/environment.hpp"
#include <algorithm>
#include <array>
#include <cmath>
namespace evo::render {
namespace {
using client::FieldPresence;
using world::MoistureStatus;
constexpr double pitch = static_cast<double>(world::cell_pitch_mm);
constexpr double um_per_mm = 1000;
constexpr double detail_units = 4; // Smaller habitats collapse to one encoded rectangle.
constexpr double outline_units = 8; // Smaller voxels omit per-cell outlines.
constexpr std::array<Color, 5> stops{{{68, 1, 84, 255},
{59, 82, 139, 255},
{33, 145, 140, 255},
{94, 201, 98, 255},
{253, 231, 37, 255}}};
std::uint8_t mix(std::uint8_t a, std::uint8_t b, double t) {
return static_cast<std::uint8_t>(std::lround(a + (b - a) * t));
}
Color mix(Color a, Color b, double t) {
return {mix(a.red, b.red, t), mix(a.green, b.green, t), mix(a.blue, b.blue, t), 255};
}
Color terrain(world::MaterialId material, std::uint16_t fill) {
constexpr Color void_color{20, 24, 32, 255};
constexpr std::array<Color, 3> known{{void_color, {96, 96, 104, 255}, {120, 100, 72, 255}}};
const Color solid =
material.value < known.size() ? known.at(material.value) : Color{0, 200, 220, 255};
return mix(void_color, solid, static_cast<double>(fill) / world::fill_scale);
}
// Camera projection from CAMERA_INPUT.md, without the half-open world-point check:
// a voxel's upper edge may lie on the exclusive world bound.
struct Projection {
double centre_x, centre_y, scale, width, height;
[[nodiscard]] double x(double mm) const {
return (mm - centre_x) * scale + width / 2;
}
[[nodiscard]] double y(double mm) const {
return (centre_y - mm) * scale + height / 2;
}
};
struct Box {
double left, top, right, bottom;
};
class Emitter {
public:
Emitter(std::vector<Rectangle>& out, double width, double height, bool stale)
: out_{out}, width_{width}, height_{height}, stale_{stale} {}
void fill(Box b, Color color, bool tint = true) {
const double left = std::max(b.left, 0.0), top = std::max(b.top, 0.0);
const double right = std::min(b.right, width_), bottom = std::min(b.bottom, height_);
if (!(right > left && bottom > top))
return;
out_.push_back({static_cast<float>(left), static_cast<float>(top),
static_cast<float>(right - left), static_cast<float>(bottom - top),
tint && stale_ ? dim(color) : color});
}
void outline(Box b, Color color, bool tint = true) {
fill({b.left, b.top, b.right, b.top + 1}, color, tint);
fill({b.left, b.bottom - 1, b.right, b.bottom}, color, tint);
fill({b.left, b.top + 1, b.left + 1, b.bottom - 1}, color, tint);
fill({b.right - 1, b.top + 1, b.right, b.bottom - 1}, color, tint);
}
void checker(Box b) {
const double mid_x = (b.left + b.right) / 2, mid_y = (b.top + b.bottom) / 2;
fill({b.left, b.top, mid_x, mid_y}, palette::missing_a);
fill({mid_x, b.top, b.right, mid_y}, palette::missing_b);
fill({b.left, mid_y, mid_x, b.bottom}, palette::missing_b);
fill({mid_x, mid_y, b.right, b.bottom}, palette::missing_a);
}
private:
std::vector<Rectangle>& out_;
double width_, height_;
bool stale_;
};
enum class Encoding : std::uint8_t { value, not_requested, missing, undefined };
struct Sample {
Encoding encoding;
Color color;
};
Sample field_sample(const client::EnvironmentCell& cell, std::size_t k) {
switch (cell.presence.at(k)) {
case FieldPresence::not_requested:
return {Encoding::not_requested, palette::not_requested};
case FieldPresence::missing:
return {Encoding::missing, palette::missing_a};
case FieldPresence::present:
break;
}
if (cell.quantity.at(k) == 0)
return {Encoding::value, palette::present_zero};
const double density = std::log2(static_cast<double>(cell.quantity.at(k))) -
std::log2(static_cast<double>(cell.volume.value));
return {Encoding::value, ramp((density - field_log2_min) / (field_log2_max - field_log2_min))};
}
Sample moisture_sample(const client::EnvironmentCell& cell) {
switch (cell.moisture_status) {
case MoistureStatus::not_requested:
return {Encoding::not_requested, palette::not_requested};
case MoistureStatus::missing_water:
return {Encoding::missing, palette::missing_a};
case MoistureStatus::zero_capacity:
return {Encoding::undefined, palette::undefined};
case MoistureStatus::available:
break;
}
return {Encoding::value, ramp(static_cast<double>(cell.moisture.numerator) /
static_cast<double>(cell.moisture.denominator))};
}
} // namespace
Color ramp(double t) noexcept {
if (!(t > 0)) // Also maps NaN to the low end.
return stops.front();
if (t >= 1)
return stops.back();
const double position = t * static_cast<double>(stops.size() - 1);
const auto index = static_cast<std::size_t>(position);
return mix(stops.at(index), stops.at(index + 1), position - static_cast<double>(index));
}
Color dim(Color color) noexcept {
const auto half = [](std::uint8_t c) { return static_cast<std::uint8_t>(c / 2 + 48); };
return {half(color.red), half(color.green), half(color.blue), color.alpha};
}
std::expected<void, EnvironmentRenderError>
build_environment(std::vector<Rectangle>& out, const client::EnvironmentPresentation* presentation,
client::Freshness freshness, const client::Camera& camera,
EnvironmentDisplay display) {
if ((display.mode != EnvironmentDisplay::Mode::field &&
display.mode != EnvironmentDisplay::Mode::moisture) ||
static_cast<std::size_t>(display.field) >= world::field_count)
return std::unexpected(EnvironmentRenderError::invalid_display);
out.clear();
out.reserve(max_environment_rectangles);
const auto viewport = camera.viewport();
const double width = viewport.width, height = viewport.height;
if (freshness == client::Freshness::none)
presentation = nullptr;
const bool stale = presentation != nullptr && freshness == client::Freshness::stale;
Emitter emit{out, width, height, stale};
const Projection p{camera.centre().x_mm, camera.centre().y_mm, camera.units_per_mm(), width,
height};
if (presentation != nullptr)
for (const auto& cell : presentation->cells()) {
const double x0 = static_cast<double>(cell.voxel.x) * pitch;
const double y0 = static_cast<double>(cell.voxel.y) * pitch;
const Box voxel{p.x(x0), p.y(y0 + pitch), p.x(x0 + pitch), p.y(y0)};
if (voxel.right <= 0 || voxel.left >= width || voxel.bottom <= 0 || voxel.top >= height)
continue; // Culled before emitting anything for this cell.
emit.fill(voxel, terrain(cell.terrain_material, cell.terrain_fill));
const auto& h = cell.habitat;
const double hx = x0 + static_cast<double>(h.x.value) / um_per_mm;
const double hy = y0 + static_cast<double>(h.y.value) / um_per_mm;
const Box habitat{p.x(hx), p.y(hy + static_cast<double>(h.height.value) / um_per_mm),
p.x(hx + static_cast<double>(h.width.value) / um_per_mm), p.y(hy)};
const auto sample = display.mode == EnvironmentDisplay::Mode::field
? field_sample(cell, static_cast<std::size_t>(display.field))
: moisture_sample(cell);
const bool detail = habitat.right - habitat.left >= detail_units &&
habitat.bottom - habitat.top >= detail_units;
if (detail && sample.encoding == Encoding::missing)
emit.checker(habitat);
else if (detail && sample.encoding == Encoding::not_requested)
emit.outline(habitat, sample.color);
else
emit.fill(habitat, sample.color);
if (voxel.right - voxel.left >= outline_units)
emit.outline(voxel, stale ? palette::stale_outline : palette::voxel_outline, false);
}
const Color status = presentation == nullptr ? palette::status_none
: stale ? palette::status_stale
: palette::status_current;
emit.fill({width - 72, 8, width - 8, 16}, status, false);
for (std::size_t i = 0; i < environment_legend_steps; ++i) {
const double x = 8 + 12 * static_cast<double>(i);
emit.fill({x, height - 16, x + 12, height - 8},
ramp(static_cast<double>(i) / static_cast<double>(environment_legend_steps - 1)),
false);
}
return {};
}
} // namespace evo::render
+441
View File
@@ -0,0 +1,441 @@
#include "evo/render/environment.hpp"
#include <algorithm>
#include <array>
#include <chrono>
#include <cmath>
#include <cstdio>
#include <exception>
#include <limits>
#include <source_location>
#include <span>
#include <stdexcept>
#include <string>
#include <vector>
namespace {
using namespace evo;
using client::EnvironmentCell;
using client::FieldPresence;
using client::Freshness;
using client::ViewError;
using render::EnvironmentDisplay;
using world::Field;
constexpr world::WorldIdentity identity{7, 9};
constexpr std::size_t budget = 4'000'000;
constexpr std::int64_t slice = -16000;
constexpr std::uint32_t mask = (1U << 0) | (1U << 1) | (1U << 2) | (1U << 7);
// 500 x 250 x 10 um^3 box at (250, 500) mm inside its voxel.
constexpr world::HabitatBox box{{250000}, {500000}, {0}, {500000}, {250000}, {10}};
constexpr std::uint64_t volume = 500000ULL * 250000ULL * 10ULL;
constexpr std::uint64_t water_amount = volume / 8; // log2 density -3.
constexpr std::uint64_t rock_capacity = 1'000'000'000'000ULL;
void check(bool ok, std::source_location at = std::source_location::current()) {
if (!ok)
throw std::runtime_error("client environment line " + std::to_string(at.line()));
}
#define CHECK(...) check(static_cast<bool>(__VA_ARGS__))
template <typename T, typename E> bool refused(const std::expected<T, E>& r, E e) {
return !r && r.error() == e;
}
bool same(render::Color a, render::Color b) {
return a.red == b.red && a.green == b.green && a.blue == b.blue && a.alpha == b.alpha;
}
bool near(double a, double b, double tolerance = 1e-3) {
return std::abs(a - b) <= tolerance * std::max(1.0, std::abs(b));
}
bool rect_is(const render::Rectangle& r, double x, double y, double w, double h) {
return near(r.x, x) && near(r.y, y) && near(r.width, w) && near(r.height, h);
}
struct Stores {
std::unique_ptr<world::FieldStore> fields;
std::unique_ptr<world::ChunkStore> terrain;
std::vector<world::VoxelAddress> footprint;
};
// Sites x in [first, first+count), y = 0. Odd offsets use zero-capacity substrate 2.
Stores stores(std::int64_t first, std::int64_t count, bool full_voxel = false) {
Stores s;
std::vector<world::FieldSite> sites;
for (std::int64_t x = first; x < first + count; ++x) {
s.footprint.push_back({x, 0, slice});
const world::HabitatBox habitat =
full_voxel ? world::HabitatBox{{0}, {0}, {0}, {1000000}, {1000000}, {1}} : box;
sites.push_back({s.footprint.back(),
habitat,
{(x - first) % 2 == 0 ? std::uint16_t{1} : std::uint16_t{2}}});
}
// Zero-capacity substrate holds no water.
std::vector<std::uint64_t> water;
water.reserve(static_cast<std::size_t>(count));
for (std::int64_t i = 0; i < count; ++i)
water.push_back(i % 2 != 0 ? 0 : full_voxel ? 1000 : water_amount);
const std::uint64_t zero = 0, energy = 72;
const world::FieldOpening opening[]{{Field::water, water},
{Field::phosphorus, {&zero, 1}},
{Field::organic_energy, {&energy, 1}}};
const world::FieldDefaults defaults{{accounting::Femtograms{0},
accounting::Femtograms{rock_capacity},
accounting::Femtograms{0}}};
auto fields = world::FieldStore::create(identity, 1, defaults, sites, opening, budget);
CHECK(fields);
s.fields = std::move(*fields);
auto terrain = world::ChunkStore::create({}, 32, budget,
{{world::VolumeUnits{100}, world::VolumeUnits{100}}});
CHECK(terrain);
s.terrain = std::move(*terrain);
for (auto address : s.footprint)
CHECK(s.terrain->load(world::split(address, world::base_chunk_edge)->chunk));
return s;
}
client::EnvironmentPresentation present(const Stores& s, std::uint64_t tick,
std::size_t cells = 0) {
const std::span<const world::VoxelAddress> footprint{s.footprint.data(),
cells == 0 ? s.footprint.size() : cells};
auto view = world::query_environment(*s.fields, *s.terrain, tick, footprint, mask);
CHECK(view);
auto result = client::present_environment(*view, slice);
CHECK(result);
return std::move(*result);
}
client::Camera camera(client::Viewport viewport, client::WorldPoint centre, double scale) {
auto result = client::Camera::create(viewport, centre, scale);
CHECK(result);
return *result;
}
std::vector<render::Rectangle> build(const client::EnvironmentPresentation* p, Freshness f,
const client::Camera& c, EnvironmentDisplay d) {
std::vector<render::Rectangle> out;
CHECK(render::build_environment(out, p, f, c, d));
CHECK(out.size() <= render::max_environment_rectangles);
return out;
}
EnvironmentDisplay field(Field f) {
return {EnvironmentDisplay::Mode::field, f};
}
void known_fields() {
const auto s = stores(0, 2);
const auto p = present(s, 5);
CHECK(p.revision() == client::EnvironmentRevision{identity, 5, 0});
CHECK(p.cells().size() == 2 && p.cells()[0].volume.value == volume);
CHECK(p.cells()[0].presence[0] == FieldPresence::present &&
p.cells()[0].quantity[0] == water_amount);
CHECK(p.cells()[0].presence[1] == FieldPresence::missing && p.cells()[0].quantity[1] == 0);
CHECK(p.cells()[0].presence[3] == FieldPresence::not_requested);
// Voxel (0,0) fills a 1000x1000 viewport at 1 unit/mm; voxel (1,0) is culled.
const auto c = camera({1000, 1000, 2000, 2000}, {500, 500}, 1);
const auto water = build(&p, Freshness::current, c, field(Field::water));
CHECK(water.size() == 1 + 1 + 4 + 1 + render::environment_legend_steps);
CHECK(rect_is(water[0], 0, 0, 1000, 1000) && same(water[0].color, {96, 96, 104, 255}));
CHECK(rect_is(water[1], 250, 250, 500, 250));
CHECK(same(water[1].color, render::ramp(27.0 / 42.0))); // log2 density -3 on [-30, 12].
CHECK(rect_is(water[2], 0, 0, 1000, 1) && same(water[2].color, render::palette::voxel_outline));
CHECK(same(water[6].color, render::palette::status_current));
CHECK(rect_is(water[6], 928, 8, 64, 8));
const auto missing = build(&p, Freshness::current, c, field(Field::nitrogen));
CHECK(rect_is(missing[1], 250, 250, 250, 125) &&
same(missing[1].color, render::palette::missing_a));
CHECK(same(missing[2].color, render::palette::missing_b) &&
same(missing[3].color, render::palette::missing_b) &&
same(missing[4].color, render::palette::missing_a));
const auto unrequested = build(&p, Freshness::current, c, field(Field::organic_carbon));
for (std::size_t i = 1; i <= 4; ++i)
CHECK(same(unrequested[i].color, render::palette::not_requested));
CHECK(rect_is(unrequested[1], 250, 250, 500, 1)); // Hollow outline, not a fill.
const auto zero = build(&p, Freshness::current, c, field(Field::phosphorus));
CHECK(rect_is(zero[1], 250, 250, 500, 250) &&
same(zero[1].color, render::palette::present_zero));
const auto energy = build(&p, Freshness::current, c, field(Field::organic_energy));
CHECK(same(energy[1].color, render::ramp(0.0))); // 72 pJ / 1.25e12 um^3 clamps low.
const auto moisture = build(&p, Freshness::current, c, {EnvironmentDisplay::Mode::moisture});
CHECK(same(moisture[1].color, render::ramp(static_cast<double>(water_amount) /
static_cast<double>(rock_capacity))));
// Substrate 2 has zero water capacity: undefined, never zero or missing.
const auto right = camera({1000, 1000, 1000, 1000}, {1500, 500}, 1);
const auto undefined =
build(&p, Freshness::current, right, {EnvironmentDisplay::Mode::moisture});
CHECK(same(undefined[1].color, render::palette::undefined));
// Shrunk habitats (< 4 units) collapse encodings to one explicit rectangle.
const auto far = camera({1000, 1000, 1000, 1000}, {500, 500}, 0.005);
const auto small = build(&p, Freshness::current, far, field(Field::nitrogen));
CHECK(small.size() == 2 + 2 + 1 + render::environment_legend_steps);
CHECK(same(small[1].color, render::palette::missing_a));
CHECK(std::abs(render::ramp(0.5).green - 145) <= 1 && same(render::ramp(-1), render::ramp(0)) &&
same(render::ramp(2), render::ramp(1)) &&
same(render::ramp(std::numeric_limits<double>::quiet_NaN()), render::ramp(0)));
}
void seams() {
// Chunk seams at x = -16, 0 and 16 (edge 16), crossing negative coordinates.
const auto s = stores(-18, 36, true);
const auto p = present(s, 3);
CHECK(p.cells().size() == 36);
for (const double scale : {0.005, 0.0123, 0.0371})
for (const double centre_x : {0.0, 0.37, -731.25})
for (const client::Viewport view : {client::Viewport{1600, 400, 1600, 400},
client::Viewport{1600, 400, 2400, 1000}}) {
const auto c = camera(view, {centre_x, 500}, scale);
const auto out = build(&p, Freshness::current, c, field(Field::water));
const std::size_t group = 1000 * scale >= 8 ? 6 : 2;
CHECK(out.size() == 36 * group + 1 + render::environment_legend_steps);
for (std::size_t i = 0; i < 36; ++i) {
const auto& r = out[i * group];
const auto x = static_cast<double>(p.cells()[i].voxel.x) * 1000;
const auto left = c.world_to_screen({x, 0});
const auto right = c.world_to_screen({x + 1000, 0});
CHECK(left && right && near(r.x, left->x) && near(r.x + r.width, right->x));
CHECK(rect_is(out[i * group + 1], r.x, r.y, r.width, r.height));
if (i > 0) {
const auto& previous = out[(i - 1) * group];
CHECK(std::abs(previous.x + previous.width - r.x) <= 1e-3F);
CHECK(previous.y == r.y && previous.height == r.height);
}
}
}
// Upper world bound: a voxel's top edge lies on the exclusive camera limit.
const auto top = world::voxel_limit - 1;
EnvironmentCell cell;
cell.voxel = {top, top, 0};
cell.habitat = {{0}, {0}, {0}, {1000000}, {1000000}, {1}};
cell.volume = {1000000000000};
cell.terrain_material = {1};
cell.terrain_fill = world::fill_scale;
cell.presence[0] = FieldPresence::missing;
cell.moisture_status = world::MoistureStatus::missing_water;
const auto edge = client::EnvironmentPresentation::create({identity, 1, 0}, 1, 0, {&cell, 1});
CHECK(edge);
const double mm = static_cast<double>(top) * 1000;
const auto c = camera({100, 100, 100, 100}, {mm + 500, mm + 500}, 0.1);
const auto out = build(&*edge, Freshness::current, c, field(Field::water));
CHECK(rect_is(out[0], 0, 0, 100, 100) && out.size() == 1 + 4 + 4 + 9);
}
void freshness() {
auto s = stores(0, 4);
const auto fields_before = s.fields->snapshot();
const auto terrain_before = s.terrain->snapshot(identity);
client::EnvironmentLayer layer;
CHECK(layer.freshness() == Freshness::none && layer.current() == nullptr);
CHECK(layer.accept(present(s, 5)));
CHECK(layer.freshness() == Freshness::current && layer.current()->revision().tick == 5);
// Presenting and drawing never mutate authority state.
const auto c = camera({1000, 1000, 1000, 1000}, {500, 500}, 1);
(void)build(layer.current(), layer.freshness(), c, field(Field::water));
CHECK(s.fields->snapshot() == fields_before && s.terrain->snapshot(identity) == terrain_before);
auto view = world::query_environment(*s.fields, *s.terrain, 5, s.footprint, mask);
CHECK(view && s.fields->transfer(1, Field::water, 0, 2, 1));
CHECK(refused(world::validate_environment(*view, *s.fields, *s.terrain, 5),
world::EnvironmentError::stale_fields));
layer.mark_stale(); // Host evidence: local validation failed.
CHECK(layer.freshness() == Freshness::stale);
const auto stale = build(layer.current(), layer.freshness(), c, field(Field::water));
CHECK(same(stale[0].color, render::dim({96, 96, 104, 255})));
CHECK(same(stale[2].color, render::palette::stale_outline));
CHECK(same(stale[6].color, render::palette::status_stale));
auto newer = present(s, 6);
CHECK(newer.revision() == client::EnvironmentRevision{identity, 6, 1});
CHECK(newer.cells()[0].quantity[0] == water_amount - 1);
CHECK(layer.accept(newer) && layer.freshness() == Freshness::current);
// Out-of-order delivery of the older presentation is rejected without mutation.
CHECK(refused(layer.accept(present(s, 5)), ViewError::regressed));
CHECK(layer.current()->revision().tick == 6 && layer.freshness() == Freshness::current);
// Equal revision with a different footprint is accepted (camera moved).
CHECK(layer.accept(present(s, 6, 2)) && layer.current()->cells().size() == 2);
// Chunk revision regression for a shared voxel rejects.
auto cells = std::vector<EnvironmentCell>(layer.current()->cells().begin(),
layer.current()->cells().end());
const auto revision = layer.current()->revision();
cells[0].chunk_revision -= 1;
auto regressed = client::EnvironmentPresentation::create(revision, mask, slice, cells);
CHECK(regressed && refused(layer.accept(*regressed), ViewError::regressed));
// Foreign world/frame rejects; so do regressed watermarks.
auto foreign = client::EnvironmentPresentation::create({{7, 10}, 9, 9}, mask, slice,
layer.current()->cells());
CHECK(foreign && refused(layer.accept(*foreign), ViewError::foreign_world));
CHECK(refused(layer.observe({{8, 9}, 9, 9}), ViewError::foreign_world));
CHECK(refused(layer.observe({identity, 5, 1}), ViewError::regressed));
CHECK(layer.freshness() == Freshness::current);
CHECK(layer.observe({identity, 6, 1}) && layer.freshness() == Freshness::current);
CHECK(layer.observe({identity, 7, 1}) && layer.freshness() == Freshness::stale);
// A presentation that is newer than displayed but older than observed stays stale.
CHECK(layer.observe({identity, 9, 3}));
cells[0].chunk_revision += 1;
const auto between =
client::EnvironmentPresentation::create({identity, 8, 2}, mask, slice, cells);
CHECK(between && layer.accept(*between) && layer.freshness() == Freshness::stale);
// Watermark observed before the first presentation is retained.
client::EnvironmentLayer early;
CHECK(early.observe({identity, 9, 3}) && early.freshness() == Freshness::none);
CHECK(early.accept(*between) && early.freshness() == Freshness::stale);
early.reset();
CHECK(early.freshness() == Freshness::none && early.accept(present(s, 5)) &&
early.freshness() == Freshness::current);
early.reset();
early.mark_stale();
CHECK(early.freshness() == Freshness::none);
// The presentation is an owned copy: it outlives the stores it came from.
const auto copy = *layer.current();
s = {};
const auto after = build(&copy, Freshness::stale, c, field(Field::water));
CHECK(after.size() > 1 + render::environment_legend_steps);
}
void missing_and_invalid() {
const auto c = camera({640, 480, 640, 480}, {0, 0}, 1);
const auto none = build(nullptr, Freshness::current, c, field(Field::water));
CHECK(none.size() == 1 + render::environment_legend_steps);
CHECK(same(none[0].color, render::palette::status_none));
std::vector<render::Rectangle> out;
// Out-of-range enumerators model untrusted decoded values; rejecting them is the point.
// NOLINTNEXTLINE(clang-analyzer-optin.core.EnumCastOutOfRange)
const EnvironmentDisplay bad_field{EnvironmentDisplay::Mode::field, Field{10}};
// NOLINTNEXTLINE(clang-analyzer-optin.core.EnumCastOutOfRange)
const EnvironmentDisplay bad_mode{EnvironmentDisplay::Mode{2}, Field::water};
CHECK(refused(render::build_environment(out, nullptr, Freshness::none, c, bad_field),
render::EnvironmentRenderError::invalid_display));
CHECK(refused(render::build_environment(out, nullptr, Freshness::none, c, bad_mode),
render::EnvironmentRenderError::invalid_display));
const auto s = stores(0, 2);
const auto p = present(s, 5);
const auto hidden = build(&p, Freshness::none, c, field(Field::water));
CHECK(hidden.size() == none.size() && same(hidden[0].color, render::palette::status_none));
auto view = world::query_environment(*s.fields, *s.terrain, 5, s.footprint, mask);
CHECK(view && refused(client::present_environment(*view, slice + 1), ViewError::empty_slice));
const std::vector<EnvironmentCell> valid(p.cells().begin(), p.cells().end());
const auto revision = p.revision();
const auto create = [&](std::vector<EnvironmentCell> cells, std::uint32_t m = mask,
std::int64_t z = slice) {
return client::EnvironmentPresentation::create(revision, m, z, cells);
};
CHECK(create(valid));
CHECK(refused(create({}), ViewError::empty_slice));
CHECK(refused(create(valid, 0), ViewError::invalid_view));
CHECK(refused(create(valid, 1U << 10), ViewError::invalid_view));
CHECK(refused(create(valid, mask, world::voxel_limit), ViewError::invalid_view));
CHECK(refused(create({valid[1], valid[0]}), ViewError::invalid_view));
CHECK(refused(create({valid[0], valid[0]}), ViewError::invalid_view));
const auto broken = [&](auto mutate) {
auto cells = valid;
mutate(cells[0]);
return refused(create(cells), ViewError::invalid_view);
};
CHECK(broken([](EnvironmentCell& x) { x.voxel.z += 1; }));
CHECK(broken([](EnvironmentCell& x) { x.voxel.x = -world::voxel_limit - 1; }));
CHECK(broken([](EnvironmentCell& x) { x.habitat.x.value = 600000; }));
CHECK(broken([](EnvironmentCell& x) { x.habitat.width.value = 0; }));
CHECK(broken([](EnvironmentCell& x) { x.volume.value += 1; }));
CHECK(broken([](EnvironmentCell& x) { x.presence[3] = FieldPresence::missing; }));
CHECK(broken([](EnvironmentCell& x) { x.presence[1] = FieldPresence::not_requested; }));
CHECK(broken([](EnvironmentCell& x) { x.quantity[1] = 1; }));
CHECK(broken([](EnvironmentCell& x) { x.quantity[3] = 1; }));
CHECK(broken(
[](EnvironmentCell& x) { x.moisture_status = world::MoistureStatus::not_requested; }));
CHECK(broken([](EnvironmentCell& x) { x.moisture = {3, 2}; }));
CHECK(broken([](EnvironmentCell& x) { x.moisture = {0, 0}; }));
CHECK(broken(
[](EnvironmentCell& x) { x.moisture_status = world::MoistureStatus::missing_water; }));
std::vector<EnvironmentCell> many;
for (std::int64_t i = 0; i <= static_cast<std::int64_t>(client::max_environment_cells); ++i) {
auto cell = valid[0];
cell.voxel.x = i;
many.push_back(cell);
}
CHECK(refused(create(many), ViewError::too_many_cells));
many.pop_back();
CHECK(create(many));
}
void bounds_and_profile() {
// 256 voxels (16 x 16), every field requested; all quantities present.
std::vector<EnvironmentCell> cells;
for (std::int64_t x = -8; x < 8; ++x)
for (std::int64_t y = -8; y < 8; ++y) {
EnvironmentCell cell;
cell.voxel = {x, y, 0};
cell.habitat = box;
cell.volume = {volume};
cell.terrain_material = {static_cast<std::uint16_t>((x + y + 16) % 4)};
cell.terrain_fill = static_cast<std::uint16_t>((x + 8) * 4000);
for (std::size_t k = 0; k < world::field_count; ++k) {
const bool missing = (x + y + static_cast<std::int64_t>(k)) % 5 == 0;
cell.presence[k] = missing ? FieldPresence::missing : FieldPresence::present;
cell.quantity[k] = missing ? 0 : static_cast<std::uint64_t>((x + 9) * (y + 9)) << k;
}
cell.moisture_status = cell.presence[0] == FieldPresence::present
? world::MoistureStatus::available
: world::MoistureStatus::missing_water;
cell.moisture = {static_cast<std::uint64_t>(y + 8), 16};
cells.push_back(cell);
}
const auto p = client::EnvironmentPresentation::create({identity, 1, 1},
world::all_environment_fields, 0, cells);
CHECK(p && p->cells().size() == client::max_environment_cells);
std::vector<render::Rectangle> out;
CHECK(render::build_environment(out, &*p, Freshness::stale,
camera({1280, 1280, 1280, 1280}, {0, 0}, 0.07),
field(Field::water)));
const auto capacity = out.capacity();
CHECK(capacity >= render::max_environment_rectangles);
std::size_t largest = 0;
for (const double scale : {1e-4, 0.002, 0.07, 1.0, 50.0})
for (const client::WorldPoint centre :
{client::WorldPoint{0, 0}, {3333.5, -2500}, client::WorldPoint{900000, 900000}})
for (const auto freshness : {Freshness::current, Freshness::stale})
for (std::size_t mode = 0; mode <= world::field_count; ++mode) {
const auto display =
mode == world::field_count
? EnvironmentDisplay{EnvironmentDisplay::Mode::moisture}
: field(static_cast<Field>(mode));
const client::Viewport view{1280, 720, 2560, 1440};
CHECK(render::build_environment(out, &*p, freshness,
camera(view, centre, scale), display));
CHECK(out.size() <= render::max_environment_rectangles &&
out.capacity() == capacity);
largest = std::max(largest, out.size());
for (const auto& r : out)
CHECK(std::isfinite(r.x) && std::isfinite(r.y) && r.width > 0 &&
r.height > 0 && r.x >= 0 && r.y >= 0 && r.x + r.width <= 1280.01F &&
r.y + r.height <= 720.01F);
// The engineering host adds three UI rectangles to every frame.
std::vector<render::Rectangle> frame(out);
frame.resize(out.size() + 3, {0, 0, 1, 1, {}});
CHECK(render::Frame::create(frame));
}
CHECK(largest > std::size_t{256} * 2);
// Profile: dense visible scene, all cells with outlines and detail encodings.
const auto c = camera({1280, 1280, 1280, 1280}, {0, 0}, 0.075);
constexpr int rounds = 2000;
const auto start = std::chrono::steady_clock::now();
std::size_t total = 0;
for (int i = 0; i < rounds; ++i) {
CHECK(render::build_environment(out, &*p, Freshness::stale, c, field(Field::nitrogen)));
total += out.size();
}
const auto elapsed =
std::chrono::duration<double, std::micro>(std::chrono::steady_clock::now() - start).count();
CHECK(out.capacity() == capacity);
std::printf("environment_profile cells=%zu rectangles=%zu max_rectangles=%zu "
"presentation_cell_bytes=%zu output_capacity_bytes=%zu build_us=%.2f\n",
p->cells().size(), total / rounds, render::max_environment_rectangles,
p->cells().size() * sizeof(EnvironmentCell), capacity * sizeof(render::Rectangle),
elapsed / rounds);
}
} // namespace
int main() try {
known_fields();
seams();
freshness();
missing_and_invalid();
bounds_and_profile();
std::puts("client environment tests passed");
return 0;
} catch (const std::exception& e) {
std::fprintf(stderr, "%s\n", e.what());
return 1;
}