Compare commits
33
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2017e5685a | ||
|
|
17389b23d7 | ||
|
|
7a7ff32e14 | ||
|
|
e7046a92a1 | ||
|
|
ee1eca7571 | ||
|
|
1ca481b8f9 | ||
|
|
6d1123e172 | ||
|
|
6279a60bf7 | ||
|
|
0d71bcf5d8 | ||
|
|
a47e850bb4 | ||
|
|
455630fb39 | ||
|
|
1cf8bd08fc | ||
|
|
e9e7e8276e | ||
|
|
048268a27e | ||
|
|
ef980af125 | ||
|
|
5a64a27d17 | ||
|
|
37fb6a897d | ||
|
|
180506d414 | ||
|
|
f6493e2d1c | ||
|
|
66af7c5bb9 | ||
|
|
3c997ed236 | ||
|
|
e6a01bedcc | ||
|
|
db0a8720a6 | ||
|
|
b7f18c094b | ||
|
|
535424196e | ||
|
|
a8cd7bb415 | ||
|
|
2a3ec924de | ||
|
|
9a248c31ac | ||
|
|
2a5df1a18b | ||
|
|
aa4e271ab4 | ||
|
|
eef69caa0e | ||
|
|
09545bfe85 | ||
|
|
ce814767fb |
No files matched your search
+24
-1
@@ -44,10 +44,13 @@ add_library(settlement_core
|
||||
engine/src/colony_profile.cpp
|
||||
engine/src/command_dispatcher.cpp
|
||||
engine/src/first_colony.cpp
|
||||
engine/src/inventory_transaction.cpp
|
||||
engine/src/rules_manifest.cpp
|
||||
engine/src/save_service_win32.cpp
|
||||
engine/src/simulation_runtime.cpp
|
||||
engine/src/voxel_navigation.cpp
|
||||
engine/src/worker_pool.cpp
|
||||
engine/src/voxel_region.cpp
|
||||
engine/src/world.cpp
|
||||
engine/src/world_save.cpp
|
||||
)
|
||||
@@ -89,16 +92,21 @@ target_link_libraries(settlement_lan
|
||||
)
|
||||
|
||||
enable_language(RC)
|
||||
add_library(settlement_client STATIC app/viewer_session.cpp)
|
||||
target_include_directories(settlement_client PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/app)
|
||||
target_link_libraries(settlement_client PUBLIC settlement_core)
|
||||
add_executable(settlement_viewer WIN32
|
||||
app/d3d_scene_win32.cpp
|
||||
app/viewer_win32.cpp
|
||||
app/house_icons.rc
|
||||
)
|
||||
target_link_libraries(settlement_viewer PRIVATE settlement_lan user32 gdi32 comctl32 comdlg32 d3d11 d3dcompiler)
|
||||
target_link_libraries(settlement_viewer PRIVATE settlement_client settlement_lan user32 gdi32 comctl32 comdlg32 d3d11 d3dcompiler)
|
||||
if(MSVC)
|
||||
target_compile_options(settlement_client PRIVATE /W4 /permissive-)
|
||||
target_compile_options(settlement_lan PRIVATE /W4 /permissive-)
|
||||
target_compile_options(settlement_viewer PRIVATE $<$<COMPILE_LANGUAGE:CXX>:/W4;/permissive->)
|
||||
else()
|
||||
target_compile_options(settlement_client PRIVATE -Wall -Wextra -Wpedantic -Wconversion -Wshadow)
|
||||
target_compile_options(settlement_lan PRIVATE -Wall -Wextra -Wpedantic -Wconversion -Wshadow)
|
||||
target_link_options(settlement_viewer PRIVATE -municode)
|
||||
target_compile_options(settlement_viewer PRIVATE
|
||||
@@ -118,13 +126,17 @@ if(BUILD_TESTING)
|
||||
tests/core_tests.cpp
|
||||
tests/executor_tests.cpp
|
||||
tests/identity_tests.cpp
|
||||
tests/production_identity_tests.cpp
|
||||
tests/profile_tests.cpp
|
||||
tests/quantity_transaction_tests.cpp
|
||||
tests/replay_tests.cpp
|
||||
tests/rules_tests.cpp
|
||||
tests/runtime_tests.cpp
|
||||
tests/save_service_tests.cpp
|
||||
tests/session_tests.cpp
|
||||
tests/snapshot_tests.cpp
|
||||
tests/voxel_navigation_tests.cpp
|
||||
tests/voxel_region_tests.cpp
|
||||
tests/test_main.cpp
|
||||
)
|
||||
target_link_libraries(settlement_core_tests PRIVATE settlement_core Void::Testing)
|
||||
@@ -133,4 +145,15 @@ if(BUILD_TESTING)
|
||||
add_executable(settlement_lan_tests tests/lan_tests.cpp tests/test_main.cpp)
|
||||
target_link_libraries(settlement_lan_tests PRIVATE settlement_lan Void::Testing)
|
||||
add_test(NAME settlement_lan_tests COMMAND settlement_lan_tests)
|
||||
|
||||
add_executable(settlement_viewer_frame_smoke
|
||||
tests/viewer_frame_smoke.cpp app/d3d_scene_win32.cpp app/house_icons.rc)
|
||||
target_link_libraries(settlement_viewer_frame_smoke PRIVATE settlement_client settlement_lan
|
||||
user32 gdi32 comctl32 comdlg32 d3d11 d3dcompiler)
|
||||
add_test(NAME settlement_viewer_frame_smoke COMMAND settlement_viewer_frame_smoke)
|
||||
set_tests_properties(settlement_viewer_frame_smoke PROPERTIES TIMEOUT 90 SKIP_RETURN_CODE 77)
|
||||
|
||||
add_executable(settlement_viewer_tests tests/viewer_session_tests.cpp tests/test_main.cpp)
|
||||
target_link_libraries(settlement_viewer_tests PRIVATE settlement_client Void::Testing)
|
||||
add_test(NAME settlement_viewer_tests COMMAND settlement_viewer_tests)
|
||||
endif()
|
||||
+44
-19
@@ -486,6 +486,11 @@ float4 paint(Pixel input) : SV_Target { return float4(input.color, 1.0); }
|
||||
|
||||
} // namespace
|
||||
|
||||
class PreparedGeometry {
|
||||
public:
|
||||
Mesh mesh;
|
||||
};
|
||||
|
||||
struct D3DScene::Backend {
|
||||
ComPtr<ID3D11Device> device;
|
||||
ComPtr<ID3D11DeviceContext> context;
|
||||
@@ -501,10 +506,11 @@ struct D3DScene::Backend {
|
||||
ComPtr<ID3D11Buffer> geometry;
|
||||
UINT buffer_bytes = 0;
|
||||
int width = 0, height = 0;
|
||||
Mesh mesh;
|
||||
std::shared_ptr<const PreparedGeometry> uploaded;
|
||||
|
||||
bool resize(int w, int h) {
|
||||
if (w == width && h == height && target_view && depth_view) return true;
|
||||
uploaded.reset();
|
||||
context->OMSetRenderTargets(0, nullptr, nullptr);
|
||||
target_texture.Reset();
|
||||
target_view.Reset();
|
||||
@@ -532,7 +538,7 @@ struct D3DScene::Backend {
|
||||
return true;
|
||||
}
|
||||
|
||||
bool upload_geometry() {
|
||||
bool upload_geometry(const Mesh& mesh) {
|
||||
const auto bytes = mesh.vertices.size() * sizeof(Vertex);
|
||||
if (bytes > std::numeric_limits<UINT>::max()) return false;
|
||||
if (bytes > buffer_bytes) {
|
||||
@@ -578,7 +584,7 @@ D3DScene::D3DScene() = default;
|
||||
D3DScene::~D3DScene() = default;
|
||||
|
||||
bool D3DScene::initialize(HWND target, bool software) {
|
||||
auto graphics = std::make_unique<Backend>();
|
||||
auto graphics = std::make_shared<Backend>();
|
||||
const auto driver = software ? D3D_DRIVER_TYPE_WARP : D3D_DRIVER_TYPE_HARDWARE;
|
||||
constexpr D3D_FEATURE_LEVEL levels[] = {D3D_FEATURE_LEVEL_11_0, D3D_FEATURE_LEVEL_10_1, D3D_FEATURE_LEVEL_10_0};
|
||||
constexpr UINT flags = D3D11_CREATE_DEVICE_BGRA_SUPPORT;
|
||||
@@ -628,24 +634,41 @@ bool D3DScene::initialize(HWND target, bool software) {
|
||||
bool D3DScene::ready() const noexcept { return backend_ != nullptr; }
|
||||
void D3DScene::reset() noexcept { backend_.reset(); }
|
||||
|
||||
bool D3DScene::render(const World& world, const SceneView& view, std::vector<std::uint32_t>* capture) {
|
||||
if (!backend_ || view.width <= 0 || view.height <= 0) return false;
|
||||
auto& graphics = *backend_;
|
||||
if (!graphics.resize(view.width, view.height)) return false;
|
||||
graphics.mesh.vertices.clear();
|
||||
terrain(graphics.mesh, world, view);
|
||||
resources(graphics.mesh, world);
|
||||
construction(graphics.mesh, world, view.building_view);
|
||||
std::shared_ptr<const PreparedGeometry> D3DScene::prepare(const World& world, const SceneView& view) {
|
||||
auto prepared = std::make_shared<PreparedGeometry>();
|
||||
terrain(prepared->mesh, world, view);
|
||||
resources(prepared->mesh, world);
|
||||
construction(prepared->mesh, world, view.building_view);
|
||||
for (std::size_t index = 0; index < view.room_blueprints.size(); ++index) {
|
||||
if (view.moving_room == index) continue;
|
||||
const auto& plan = view.room_blueprints[index];
|
||||
draw_room_plan(graphics.mesh, plan, false, world.can_place_room(plan));
|
||||
draw_room_plan(prepared->mesh, plan, false, world.can_place_room(plan));
|
||||
}
|
||||
if (view.room_preview) draw_room_plan(prepared->mesh, *view.room_preview, true, view.valid_cursor);
|
||||
for (const auto& part : view.blueprint) draw_blueprint(prepared->mesh, part, false);
|
||||
if (view.preview) draw_blueprint(prepared->mesh, *view.preview, true);
|
||||
residents(prepared->mesh, world, view);
|
||||
return prepared;
|
||||
}
|
||||
|
||||
bool D3DScene::render(const World& world, const SceneView& view, std::vector<std::uint32_t>* capture) {
|
||||
if (!backend_ || view.width <= 0 || view.height <= 0) return false;
|
||||
return render(prepare(world, view), view, capture);
|
||||
}
|
||||
|
||||
bool D3DScene::render(std::shared_ptr<const PreparedGeometry> geometry, const SceneView& view,
|
||||
std::vector<std::uint32_t>* capture) {
|
||||
// Present may dispatch window messages, including destruction. Keep this
|
||||
// backend alive until the current submission has returned.
|
||||
const auto held_backend = backend_;
|
||||
if (!held_backend || !geometry || view.width <= 0 || view.height <= 0) return false;
|
||||
auto& graphics = *held_backend;
|
||||
if (!graphics.resize(view.width, view.height)) return false;
|
||||
if (graphics.uploaded != geometry) {
|
||||
if (!graphics.upload_geometry(geometry->mesh)) return false;
|
||||
graphics.uploaded = geometry;
|
||||
++uploads_;
|
||||
}
|
||||
if (view.room_preview) draw_room_plan(graphics.mesh, *view.room_preview, true, view.valid_cursor);
|
||||
for (const auto& part : view.blueprint) draw_blueprint(graphics.mesh, part, false);
|
||||
if (view.preview) draw_blueprint(graphics.mesh, *view.preview, true);
|
||||
residents(graphics.mesh, world, view);
|
||||
if (!graphics.upload_geometry()) return false;
|
||||
|
||||
auto* ctx = graphics.context.Get();
|
||||
constexpr float clear[] = {.83f, .87f, .79f, 1.f};
|
||||
@@ -666,9 +689,11 @@ bool D3DScene::render(const World& world, const SceneView& view, std::vector<std
|
||||
ctx->VSSetShader(graphics.vertex_shader.Get(), nullptr, 0);
|
||||
ctx->VSSetConstantBuffers(0, 1, graphics.camera.GetAddressOf());
|
||||
ctx->PSSetShader(graphics.pixel_shader.Get(), nullptr, 0);
|
||||
ctx->Draw(static_cast<UINT>(graphics.mesh.vertices.size()), 0);
|
||||
ctx->Draw(static_cast<UINT>(geometry->mesh.vertices.size()), 0);
|
||||
if (capture && !graphics.read_frame(*capture)) return false;
|
||||
return !graphics.swap_chain || SUCCEEDED(graphics.swap_chain->Present(0, 0));
|
||||
if (graphics.swap_chain && FAILED(graphics.swap_chain->Present(0, 0))) return false;
|
||||
++frames_;
|
||||
return true;
|
||||
}
|
||||
|
||||
} // namespace settlement::viewer
|
||||
+12
-1
@@ -40,18 +40,29 @@ struct SceneView {
|
||||
std::optional<std::size_t> moving_room;
|
||||
};
|
||||
|
||||
// Immutable CPU geometry can outlive the latest frame and any GPU backend.
|
||||
class PreparedGeometry;
|
||||
|
||||
class D3DScene {
|
||||
public:
|
||||
D3DScene();
|
||||
~D3DScene();
|
||||
D3DScene(const D3DScene&) = delete;
|
||||
D3DScene& operator=(const D3DScene&) = delete;
|
||||
bool initialize(HWND target, bool software = false);
|
||||
[[nodiscard]] bool ready() const noexcept;
|
||||
bool render(const World& world, const SceneView& view, std::vector<std::uint32_t>* capture = nullptr);
|
||||
[[nodiscard]] static std::shared_ptr<const PreparedGeometry> prepare(const World& world, const SceneView& view);
|
||||
bool render(std::shared_ptr<const PreparedGeometry> geometry, const SceneView& view,
|
||||
std::vector<std::uint32_t>* capture = nullptr);
|
||||
[[nodiscard]] std::uint64_t uploads() const noexcept { return uploads_; }
|
||||
[[nodiscard]] std::uint64_t frames() const noexcept { return frames_; }
|
||||
void reset() noexcept;
|
||||
|
||||
private:
|
||||
std::uint64_t uploads_ = 0, frames_ = 0;
|
||||
struct Backend;
|
||||
std::unique_ptr<Backend> backend_;
|
||||
std::shared_ptr<Backend> backend_;
|
||||
};
|
||||
|
||||
} // namespace settlement::viewer
|
||||
@@ -7,6 +7,8 @@
|
||||
#include <optional>
|
||||
#include <string>
|
||||
|
||||
namespace settlement { class SimulationRuntime; }
|
||||
|
||||
namespace settlement::viewer {
|
||||
|
||||
enum class LanState { Offline, Hosting, HostConnected, Connecting, GuestConnected, GuestDisconnected };
|
||||
@@ -20,6 +22,15 @@ struct LanRejection {
|
||||
GridPosition destination;
|
||||
};
|
||||
|
||||
struct LanCommandResult {
|
||||
CommandStatus status;
|
||||
CommandKind kind;
|
||||
GridPosition cell;
|
||||
std::uint8_t value;
|
||||
GridPosition destination;
|
||||
AgentId resident;
|
||||
};
|
||||
|
||||
class LanSession {
|
||||
public:
|
||||
LanSession();
|
||||
@@ -39,7 +50,14 @@ public:
|
||||
[[nodiscard]] bool submit(CommandKind kind, GridPosition cell, std::uint8_t value,
|
||||
GridPosition destination = {}, AgentId resident = 0);
|
||||
[[nodiscard]] std::optional<LanRejection> take_rejection() noexcept;
|
||||
// poll_guest pauses further sends until this one retained result is drained.
|
||||
[[nodiscard]] std::optional<LanCommandResult> take_result() noexcept;
|
||||
[[nodiscard]] std::unique_ptr<World> poll(World& world);
|
||||
// Protocol 11 accepts the compiled default rules and a 32x32 active colony.
|
||||
// Calls never wait for the owner. An admitted guest operation survives peer
|
||||
// turnover, so poll_host must continue with the same owner until it settles.
|
||||
void poll_host(SimulationRuntime& runtime);
|
||||
[[nodiscard]] std::unique_ptr<World> poll_guest();
|
||||
|
||||
private:
|
||||
struct Impl;
|
||||
|
||||
+180
-31
@@ -6,6 +6,7 @@
|
||||
|
||||
#include "lan_session.hpp"
|
||||
#include "lan_wire.hpp"
|
||||
#include "settlement/core/simulation_runtime.hpp"
|
||||
|
||||
#include <algorithm>
|
||||
#include <array>
|
||||
@@ -153,6 +154,12 @@ struct Action {
|
||||
} // namespace
|
||||
|
||||
struct LanSession::Impl {
|
||||
struct PendingCommand {
|
||||
std::future<RuntimeResult> completion;
|
||||
Void::Uuid::Uuid session;
|
||||
std::uint64_t peer_generation;
|
||||
};
|
||||
|
||||
bool winsock = false;
|
||||
Socket listener;
|
||||
Channel peer;
|
||||
@@ -167,12 +174,18 @@ struct LanSession::Impl {
|
||||
std::string notice;
|
||||
std::deque<Action> actions;
|
||||
std::optional<LanRejection> rejected_command;
|
||||
std::optional<LanCommandResult> command_result;
|
||||
bool result_backpressure = false;
|
||||
std::uint64_t guest_sequence = 0;
|
||||
Clock::time_point last_ping{};
|
||||
Clock::time_point last_snapshot{};
|
||||
std::uint64_t sent_tick = 0;
|
||||
std::uint64_t sent_host_sequence = 0;
|
||||
std::uint64_t sent_guest_sequence = 0;
|
||||
std::uint64_t peer_generation = 0;
|
||||
std::optional<Void::Uuid::Uuid> runtime_session;
|
||||
std::optional<RulesManifest> compatibility_rules;
|
||||
std::optional<PendingCommand> pending_command;
|
||||
|
||||
Impl() {
|
||||
WSADATA data{};
|
||||
@@ -185,14 +198,18 @@ struct LanSession::Impl {
|
||||
}
|
||||
|
||||
void drop_peer() noexcept {
|
||||
++peer_generation;
|
||||
peer = Channel{};
|
||||
connecting = authenticated = reject_pending = false;
|
||||
awaiting_receipt.reset();
|
||||
guest_sequence = 0;
|
||||
actions.clear();
|
||||
rejected_command.reset();
|
||||
command_result.reset();
|
||||
last_snapshot = {};
|
||||
last_ping = {};
|
||||
// pending_command belongs to the authenticated guest slot, even after
|
||||
// its socket disappears. A later peer waits for this result to settle.
|
||||
}
|
||||
|
||||
void accept_guest() {
|
||||
@@ -223,17 +240,21 @@ struct LanSession::Impl {
|
||||
connecting = false;
|
||||
}
|
||||
|
||||
void authenticate(Message message, std::string_view payload) {
|
||||
if (reject_pending) return;
|
||||
const auto hello = message == Message::Hello ? lan_wire::decode_hello(payload) : std::nullopt;
|
||||
if (!hello || hello->version != lan_wire::protocol_version || hello->key != key) {
|
||||
peer.queue(Message::Reject);
|
||||
reject_pending = true;
|
||||
return;
|
||||
}
|
||||
authenticated = true;
|
||||
notice.clear();
|
||||
}
|
||||
|
||||
void handle_host(World& world, Message message, std::string_view payload) {
|
||||
if (!authenticated) {
|
||||
if (reject_pending) return;
|
||||
const auto hello = message == Message::Hello ? lan_wire::decode_hello(payload) : std::nullopt;
|
||||
if (!hello || hello->version != lan_wire::protocol_version || hello->key != key) {
|
||||
peer.queue(Message::Reject);
|
||||
reject_pending = true;
|
||||
return;
|
||||
}
|
||||
authenticated = true;
|
||||
notice.clear();
|
||||
authenticate(message, payload);
|
||||
return;
|
||||
}
|
||||
if (message == Message::Ping && payload.empty()) return;
|
||||
@@ -244,6 +265,83 @@ struct LanSession::Impl {
|
||||
peer.queue(Message::Receipt, std::string_view(reply));
|
||||
}
|
||||
|
||||
void reply(CommandStatus status, const World& world) {
|
||||
const auto bytes = lan_wire::encode_receipt({status, world.next_command_sequence(guest_player)});
|
||||
peer.queue(Message::Receipt, std::string_view(bytes));
|
||||
}
|
||||
|
||||
void handle_runtime_host(SimulationRuntime& runtime, const PublishedSnapshot& snapshot,
|
||||
Message message, std::string_view payload) {
|
||||
if (!authenticated) {
|
||||
authenticate(message, payload);
|
||||
return;
|
||||
}
|
||||
if (message == Message::Ping && payload.empty()) return;
|
||||
const auto command = message == Message::Command ? lan_wire::decode_command(payload) : std::nullopt;
|
||||
if (!command) throw std::runtime_error("Invalid guest command.");
|
||||
if (pending_command) throw std::runtime_error("A guest command is already pending.");
|
||||
if (command->sequence != snapshot.world->next_command_sequence(guest_player)) {
|
||||
reply(CommandStatus::WrongSequence, *snapshot.world);
|
||||
return;
|
||||
}
|
||||
const auto& identity = snapshot.identity;
|
||||
const CommandEnvelope envelope{
|
||||
command_envelope_version, identity.world, identity.session, identity.city,
|
||||
snapshot.next_requests[guest_player - 1],
|
||||
CommandPayload{command->kind, command->cell, command->value, command->destination, command->resident}
|
||||
};
|
||||
auto submitted = runtime.try_submit({guest_player}, envelope);
|
||||
if (submitted.admission == RuntimeAdmission::Accepted) {
|
||||
pending_command.emplace(std::move(submitted.completion), identity.session, peer_generation);
|
||||
} else if (submitted.admission == RuntimeAdmission::Busy) {
|
||||
reply(CommandStatus::Busy, *snapshot.world);
|
||||
} else {
|
||||
throw std::runtime_error("The authoritative owner cannot accept guest commands.");
|
||||
}
|
||||
}
|
||||
|
||||
void complete_runtime_command() {
|
||||
if (!pending_command || pending_command->completion.wait_for(0s) != std::future_status::ready) return;
|
||||
auto pending = std::move(*pending_command);
|
||||
pending_command.reset();
|
||||
const auto result = pending.completion.get();
|
||||
if (pending.peer_generation != peer_generation || !authenticated ||
|
||||
!runtime_session || pending.session != *runtime_session) return;
|
||||
if (result.outcome != RuntimeOutcome::Completed || !result.receipt || !result.snapshot ||
|
||||
result.snapshot->identity.session != pending.session) {
|
||||
throw std::runtime_error("The authoritative guest command did not commit.");
|
||||
}
|
||||
const auto& receipt = *result.receipt;
|
||||
if (receipt.status == DispatchStatus::Completed) {
|
||||
reply(receipt.command_status, *result.snapshot->world);
|
||||
} else if (receipt.status == DispatchStatus::Busy) {
|
||||
reply(CommandStatus::Busy, *result.snapshot->world);
|
||||
} else {
|
||||
throw std::runtime_error("The guest command belongs to an obsolete or conflicting request.");
|
||||
}
|
||||
}
|
||||
|
||||
void bind_runtime(const RuntimeView& view) {
|
||||
if (!compatibility_rules) {
|
||||
auto rules = default_rules_manifest();
|
||||
if (!rules) throw std::runtime_error("Could not resolve the legacy LAN rules.");
|
||||
compatibility_rules = std::move(*rules);
|
||||
}
|
||||
if (view.state != RuntimeState::Running || !view.snapshot) {
|
||||
throw std::runtime_error("The authoritative owner is unavailable.");
|
||||
}
|
||||
const auto& snapshot = *view.snapshot;
|
||||
if (!snapshot.rules || *snapshot.rules != *compatibility_rules) {
|
||||
throw std::runtime_error("Protocol 11 requires the compiled default rules.");
|
||||
}
|
||||
if (!snapshot.world->scenario_active() || snapshot.world->width() != first_colony_map_size ||
|
||||
snapshot.world->height() != first_colony_map_size) {
|
||||
throw std::runtime_error("Protocol 11 requires a supported 32x32 colony.");
|
||||
}
|
||||
if (runtime_session && *runtime_session != snapshot.identity.session) drop_peer();
|
||||
runtime_session = snapshot.identity.session;
|
||||
}
|
||||
|
||||
void handle_guest(std::unique_ptr<World>& latest, Message message, std::string_view payload) {
|
||||
if (message == Message::Reject) throw std::runtime_error("Wrong game code or incompatible version.");
|
||||
if (message == Message::Snapshot) {
|
||||
@@ -264,6 +362,8 @@ struct LanSession::Impl {
|
||||
}
|
||||
const auto status = receipt->status;
|
||||
if (status > CommandStatus::Busy) throw std::runtime_error("Invalid command result.");
|
||||
command_result = LanCommandResult{status, awaiting_receipt->kind, awaiting_receipt->cell,
|
||||
awaiting_receipt->value, awaiting_receipt->destination, awaiting_receipt->resident};
|
||||
if (status != CommandStatus::Accepted) {
|
||||
rejected_command = LanRejection{status, awaiting_receipt->kind, awaiting_receipt->cell,
|
||||
awaiting_receipt->value, awaiting_receipt->destination};
|
||||
@@ -291,6 +391,7 @@ struct LanSession::Impl {
|
||||
|
||||
void send_action() {
|
||||
if (awaiting_receipt || actions.empty() || guest_sequence == 0 || peer.pending()) return;
|
||||
if (result_backpressure && command_result) return;
|
||||
const Action action = actions.front();
|
||||
const auto payload = lan_wire::encode_command(
|
||||
{guest_player, guest_sequence, action.kind, action.cell, action.value, action.destination, action.resident});
|
||||
@@ -298,6 +399,31 @@ struct LanSession::Impl {
|
||||
actions.pop_front();
|
||||
awaiting_receipt = action;
|
||||
}
|
||||
|
||||
template<class Receive, class SendHost>
|
||||
void poll_network(Receive receive, SendHost send_host, bool accept_allowed = true) {
|
||||
if (listener && accept_allowed) accept_guest();
|
||||
if (!peer.socket) return;
|
||||
const auto now = Clock::now();
|
||||
if ((!authenticated && now - peer.opened > 8s) ||
|
||||
(authenticated && now - peer.last_received > 15s)) {
|
||||
throw std::runtime_error("The peer did not respond.");
|
||||
}
|
||||
if (connecting) finish_connection();
|
||||
if (connecting) return;
|
||||
peer.receive(receive);
|
||||
if (authenticated && guest) {
|
||||
send_action();
|
||||
if (!peer.pending() && now - last_ping >= 2s) {
|
||||
peer.queue(Message::Ping);
|
||||
last_ping = now;
|
||||
}
|
||||
} else if (authenticated) {
|
||||
send_host(now);
|
||||
}
|
||||
peer.flush();
|
||||
if (reject_pending && !peer.pending()) drop_peer();
|
||||
}
|
||||
};
|
||||
|
||||
LanSession::LanSession() : impl_(std::make_unique<Impl>()) {}
|
||||
@@ -397,34 +523,57 @@ std::optional<LanRejection> LanSession::take_rejection() noexcept {
|
||||
return std::exchange(impl_->rejected_command, std::nullopt);
|
||||
}
|
||||
|
||||
std::optional<LanCommandResult> LanSession::take_result() noexcept {
|
||||
return std::exchange(impl_->command_result, std::nullopt);
|
||||
}
|
||||
|
||||
std::unique_ptr<World> LanSession::poll(World& world) {
|
||||
auto& connection = *impl_;
|
||||
connection.result_backpressure = false;
|
||||
std::unique_ptr<World> latest;
|
||||
try {
|
||||
if (connection.listener) connection.accept_guest();
|
||||
if (!connection.peer.socket) return nullptr;
|
||||
const auto now = Clock::now();
|
||||
if ((!connection.authenticated && now - connection.peer.opened > 8s) ||
|
||||
(connection.authenticated && now - connection.peer.last_received > 15s)) {
|
||||
throw std::runtime_error("The peer did not respond.");
|
||||
}
|
||||
if (connection.connecting) connection.finish_connection();
|
||||
if (connection.connecting) return nullptr;
|
||||
connection.peer.receive([&](Message message, std::string_view payload) {
|
||||
if (connection.pending_command) throw std::runtime_error("Continue polling the authoritative owner.");
|
||||
connection.poll_network([&](Message message, std::string_view payload) {
|
||||
if (connection.guest) connection.handle_guest(latest, message, payload);
|
||||
else connection.handle_host(world, message, payload);
|
||||
});
|
||||
if (connection.authenticated && connection.guest) {
|
||||
connection.send_action();
|
||||
if (!connection.peer.pending() && now - connection.last_ping >= 2s) {
|
||||
connection.peer.queue(Message::Ping);
|
||||
connection.last_ping = now;
|
||||
}
|
||||
} else if (connection.authenticated) {
|
||||
connection.send_snapshot(world, now);
|
||||
}
|
||||
connection.peer.flush();
|
||||
if (connection.reject_pending && !connection.peer.pending()) connection.drop_peer();
|
||||
}, [&](Clock::time_point now) { connection.send_snapshot(world, now); });
|
||||
} catch (const std::exception& error) {
|
||||
connection.notice = error.what();
|
||||
connection.drop_peer();
|
||||
latest.reset();
|
||||
}
|
||||
return latest;
|
||||
}
|
||||
|
||||
void LanSession::poll_host(SimulationRuntime& runtime) {
|
||||
auto& connection = *impl_;
|
||||
if (!connection.listener || connection.guest) return;
|
||||
try {
|
||||
connection.complete_runtime_command();
|
||||
// Completion may have published a newer next-request number. Re-read it
|
||||
// before admitting a reconnect or decoding any further guest intent.
|
||||
const auto view = runtime.view();
|
||||
connection.bind_runtime(view);
|
||||
connection.poll_network([&](Message message, std::string_view payload) {
|
||||
connection.handle_runtime_host(runtime, *view.snapshot, message, payload);
|
||||
}, [&](Clock::time_point now) {
|
||||
if (!connection.pending_command) connection.send_snapshot(*view.snapshot->world, now);
|
||||
}, !connection.pending_command);
|
||||
} catch (const std::exception& error) {
|
||||
connection.notice = error.what();
|
||||
connection.drop_peer();
|
||||
}
|
||||
}
|
||||
|
||||
std::unique_ptr<World> LanSession::poll_guest() {
|
||||
auto& connection = *impl_;
|
||||
connection.result_backpressure = true;
|
||||
std::unique_ptr<World> latest;
|
||||
if (!connection.guest) return nullptr;
|
||||
try {
|
||||
connection.poll_network([&](Message message, std::string_view payload) {
|
||||
connection.handle_guest(latest, message, payload);
|
||||
}, [](Clock::time_point) {});
|
||||
} catch (const std::exception& error) {
|
||||
connection.notice = error.what();
|
||||
connection.drop_peer();
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
#pragma once
|
||||
|
||||
#include <windows.h>
|
||||
#include "settlement/core/colony_profile.hpp"
|
||||
|
||||
#include <algorithm>
|
||||
#include <array>
|
||||
@@ -19,6 +20,7 @@ constexpr int title_coop_id = 1103;
|
||||
constexpr int title_exit_id = 1104;
|
||||
constexpr int title_saves_id = 1105;
|
||||
constexpr int title_open_id = 1106;
|
||||
constexpr int title_rules_id = 1107;
|
||||
|
||||
inline std::filesystem::path saves_directory() {
|
||||
const DWORD length = GetEnvironmentVariableW(L"LOCALAPPDATA", nullptr, 0);
|
||||
@@ -51,6 +53,14 @@ public:
|
||||
0, 0, 0, 0, owner, id(title_saves_id), instance, nullptr);
|
||||
open_ = CreateWindowExW(0, L"BUTTON", L"Загрузить выбранное", WS_CHILD | WS_TABSTOP | BS_OWNERDRAW,
|
||||
0, 0, 0, 0, owner, id(title_open_id), instance, nullptr);
|
||||
rules_label_ = CreateWindowExW(0, L"STATIC", L"Правила только новой колонии:", WS_CHILD,
|
||||
0, 0, 0, 0, owner, nullptr, instance, nullptr);
|
||||
rules_ = CreateWindowExW(0, L"COMBOBOX", L"Правила новой колонии",
|
||||
WS_CHILD | WS_TABSTOP | WS_VSCROLL | CBS_DROPDOWNLIST,
|
||||
0, 0, 0, 0, owner, id(title_rules_id), instance, nullptr);
|
||||
SendMessageW(rules_, CB_ADDSTRING, 0, reinterpret_cast<LPARAM>(L"Поэтапная кровать: опора и 2 ткани"));
|
||||
SendMessageW(rules_, CB_ADDSTRING, 0, reinterpret_cast<LPARAM>(L"Простая кровать: 1 доска"));
|
||||
SendMessageW(rules_, CB_SETCURSEL, 0, 0);
|
||||
list_background_ = CreateSolidBrush(RGB(44, 63, 53));
|
||||
font_ = CreateFontW(-16, 0, 0, 0, FW_NORMAL, FALSE, FALSE, FALSE, DEFAULT_CHARSET,
|
||||
OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS, CLEARTYPE_QUALITY, DEFAULT_PITCH | FF_SWISS, L"Segoe UI");
|
||||
@@ -58,6 +68,8 @@ public:
|
||||
for (const auto button : buttons_) SendMessageW(button, WM_SETFONT, font, FALSE);
|
||||
SendMessageW(saves_, WM_SETFONT, font, FALSE);
|
||||
SendMessageW(open_, WM_SETFONT, font, FALSE);
|
||||
SendMessageW(rules_label_, WM_SETFONT, font, FALSE);
|
||||
SendMessageW(rules_, WM_SETFONT, font, FALSE);
|
||||
}
|
||||
|
||||
void reload_saves() {
|
||||
@@ -90,6 +102,8 @@ public:
|
||||
for (const auto button : buttons_) ShowWindow(button, flags);
|
||||
ShowWindow(saves_, flags);
|
||||
ShowWindow(open_, flags);
|
||||
ShowWindow(rules_label_, flags);
|
||||
ShowWindow(rules_, flags);
|
||||
}
|
||||
|
||||
void update(bool can_resume, bool offline) const {
|
||||
@@ -98,6 +112,7 @@ public:
|
||||
EnableWindow(buttons_[title_browse_id - title_continue_id], offline);
|
||||
EnableWindow(open_, offline && selected_index() < saves.size());
|
||||
EnableWindow(saves_, offline);
|
||||
EnableWindow(rules_, offline);
|
||||
}
|
||||
|
||||
HBRUSH paint_list_background(HWND control, HDC dc) const {
|
||||
@@ -116,6 +131,10 @@ public:
|
||||
return saves.empty() ? std::nullopt : std::optional{saves.front().path};
|
||||
}
|
||||
|
||||
[[nodiscard]] ColonyProfile new_colony_profile() const {
|
||||
return SendMessageW(rules_, CB_GETCURSEL, 0, 0) == 1 ? ColonyProfile::PlankBeds : ColonyProfile::Default;
|
||||
}
|
||||
|
||||
void layout(int width, int height) const {
|
||||
const RECT panel = bounds(width, height);
|
||||
for (std::size_t i = 0; i < buttons_.size(); ++i) {
|
||||
@@ -123,6 +142,8 @@ public:
|
||||
}
|
||||
position(saves_, panel.left + 318, panel.top + 146, panel.right - panel.left - 346, 118);
|
||||
position(open_, panel.left + 318, panel.top + 274, panel.right - panel.left - 346, 33);
|
||||
position(rules_label_, panel.left + 28, panel.top + 358, panel.right - panel.left - 56, 23);
|
||||
position(rules_, panel.left + 28, panel.top + 383, panel.right - panel.left - 56, 100);
|
||||
}
|
||||
|
||||
void draw(HDC dc, int width, int height, const std::wstring& notice) const {
|
||||
@@ -160,7 +181,7 @@ public:
|
||||
DrawTextW(dc, saves.empty() ? L"Сохранения · список пуст" : L"Сохранения", -1,
|
||||
&saves_label, DT_SINGLELINE | DT_VCENTER);
|
||||
if (!notice.empty()) {
|
||||
RECT information{panel.left + 318, panel.top + 311, panel.right - 27, panel.bottom - 11};
|
||||
RECT information{panel.left + 318, panel.top + 311, panel.right - 27, panel.top + 355};
|
||||
DrawTextW(dc, notice.c_str(), -1, &information, DT_WORDBREAK | DT_NOPREFIX);
|
||||
}
|
||||
SetTextColor(dc, ink);
|
||||
@@ -209,7 +230,7 @@ private:
|
||||
|
||||
static RECT bounds(int width, int height) {
|
||||
constexpr int panel_width = 704;
|
||||
constexpr int panel_height = 365;
|
||||
constexpr int panel_height = 430;
|
||||
const int left = (width - panel_width) / 2;
|
||||
const int top = (height - panel_height) / 2;
|
||||
return {left, top, left + panel_width, top + panel_height};
|
||||
@@ -233,6 +254,8 @@ private:
|
||||
std::array<HWND, 5> buttons_{};
|
||||
HWND saves_ = nullptr;
|
||||
HWND open_ = nullptr;
|
||||
HWND rules_label_ = nullptr;
|
||||
HWND rules_ = nullptr;
|
||||
HBRUSH list_background_ = nullptr;
|
||||
HFONT font_ = nullptr;
|
||||
std::vector<SaveFile> saves;
|
||||
|
||||
@@ -0,0 +1,329 @@
|
||||
#include "viewer_session.hpp"
|
||||
|
||||
#include <chrono>
|
||||
#include <limits>
|
||||
#include <stdexcept>
|
||||
#include <utility>
|
||||
|
||||
namespace settlement::viewer {
|
||||
namespace {
|
||||
|
||||
template<class T>
|
||||
bool ready(std::future<T>& completion) {
|
||||
return completion.valid() && completion.wait_for(std::chrono::seconds{0}) == std::future_status::ready;
|
||||
}
|
||||
|
||||
RulesManifest supported_rules() {
|
||||
auto manifest = default_rules_manifest();
|
||||
if (!manifest) throw std::runtime_error(manifest.error().message);
|
||||
return std::move(*manifest);
|
||||
}
|
||||
|
||||
void validate_supported(const WorldCheckpoint& candidate) {
|
||||
const auto valid = validate_colony_checkpoint(candidate);
|
||||
if (!valid) throw std::runtime_error(valid.error().message);
|
||||
if (!candidate.world || candidate.world->width() != first_colony_map_size ||
|
||||
candidate.world->height() != first_colony_map_size) {
|
||||
throw std::runtime_error("This viewer opens worlds with a 32 by 32 map.");
|
||||
}
|
||||
}
|
||||
|
||||
WorldCheckpoint validated_initial(WorldCheckpoint candidate) {
|
||||
validate_supported(candidate);
|
||||
return candidate;
|
||||
}
|
||||
|
||||
WorldCheckpoint initial_colony(std::size_t workers, ColonyProfile profile = ColonyProfile::Default) {
|
||||
auto candidate = make_colony_checkpoint(profile, workers);
|
||||
if (!candidate) throw std::runtime_error(candidate.error().message);
|
||||
return std::move(*candidate);
|
||||
}
|
||||
|
||||
RuntimeOptions suspended(RuntimeOptions options) {
|
||||
options.ticking = false;
|
||||
return options;
|
||||
}
|
||||
|
||||
std::string exception_message() {
|
||||
try { throw; }
|
||||
catch (const std::exception& error) { return error.what(); }
|
||||
catch (...) { return "The operation failed."; }
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
ViewerSession::ViewerSession(std::size_t workers, ViewerSessionOptions options)
|
||||
: ViewerSession(initial_colony(workers), workers, std::move(options)) {}
|
||||
|
||||
ViewerSession::ViewerSession(WorldCheckpoint initial, std::size_t workers, ViewerSessionOptions options)
|
||||
: workers_(workers), command_capacity_(options.command_capacity),
|
||||
supported_rules_(supported_rules()),
|
||||
runtime_(validated_initial(std::move(initial)), suspended(std::move(options.runtime))),
|
||||
files_(std::move(options.files)) {
|
||||
if (command_capacity_ == 0) throw std::invalid_argument("The command queue must have capacity.");
|
||||
}
|
||||
|
||||
ViewerSession::~ViewerSession() = default;
|
||||
|
||||
std::shared_ptr<const World> ViewerSession::world() const {
|
||||
return guest_ || (changing_world_ && guest_view_) ? guest_view_ : runtime_.latest()->world;
|
||||
}
|
||||
|
||||
bool ViewerSession::can_submit() const {
|
||||
return !guest_ && !changing_world_ && runtime_.view().state == RuntimeState::Running;
|
||||
}
|
||||
|
||||
bool ViewerSession::can_host_legacy() const {
|
||||
const auto current = runtime_.view();
|
||||
return !guest_ && !changing_world_ && current.state == RuntimeState::Running &&
|
||||
current.snapshot->rules && *current.snapshot->rules == supported_rules_;
|
||||
}
|
||||
|
||||
std::optional<std::uint64_t> ViewerSession::submit(SessionPayload payload) {
|
||||
if (!can_submit()) return std::nullopt;
|
||||
for (const auto& intent : intents_) {
|
||||
if (intent.payload == payload) return intent.id;
|
||||
}
|
||||
if (intents_.size() == command_capacity_ || next_intent_ == std::numeric_limits<std::uint64_t>::max()) {
|
||||
return std::nullopt;
|
||||
}
|
||||
const auto id = next_intent_;
|
||||
intents_.push_back({id, std::move(payload)});
|
||||
++next_intent_;
|
||||
return id;
|
||||
}
|
||||
|
||||
bool ViewerSession::pending(std::uint64_t id) const noexcept {
|
||||
for (const auto& intent : intents_) if (intent.id == id) return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
LoadTicket ViewerSession::begin_change() {
|
||||
if (generation_ == std::numeric_limits<std::uint64_t>::max()) {
|
||||
throw std::overflow_error("The client operation counter is exhausted.");
|
||||
}
|
||||
auto ticket = runtime_.begin_load();
|
||||
if (!ticket) throw std::runtime_error("The simulation cannot accept a world change.");
|
||||
++generation_;
|
||||
intents_.clear();
|
||||
command_completion_ = {};
|
||||
preparing_.reset();
|
||||
installing_.reset();
|
||||
install_completion_ = {};
|
||||
events_.clear();
|
||||
changing_world_ = true;
|
||||
return *ticket;
|
||||
}
|
||||
|
||||
void ViewerSession::validate_candidate(const WorldCheckpoint& candidate) const {
|
||||
validate_supported(candidate);
|
||||
}
|
||||
|
||||
void ViewerSession::replace(WorldCheckpoint candidate) {
|
||||
validate_candidate(candidate);
|
||||
const auto ticket = begin_change();
|
||||
installing_.emplace(Installing{ticket, std::move(candidate)});
|
||||
}
|
||||
|
||||
void ViewerSession::new_colony(ColonyProfile profile) {
|
||||
replace(initial_colony(workers_, profile));
|
||||
}
|
||||
|
||||
void ViewerSession::load(const std::filesystem::path& path) {
|
||||
if (guest_) throw std::runtime_error("Only the host can load a world.");
|
||||
const auto ticket = begin_change();
|
||||
try {
|
||||
auto operation = files_.try_load(path, workers_);
|
||||
if (operation.admission != CheckpointLoadAdmission::Accepted) {
|
||||
throw std::runtime_error("The file reader is busy or unavailable. Try again.");
|
||||
}
|
||||
preparing_.emplace(Preparing{ticket, std::move(operation.completion)});
|
||||
} catch (...) {
|
||||
changing_world_ = false;
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
void ViewerSession::save(const std::filesystem::path& path) {
|
||||
if (guest_ || changing_world_) throw std::runtime_error("The current world cannot be saved yet.");
|
||||
poll_saves();
|
||||
const auto snapshot = runtime_.snapshot_for_save();
|
||||
if (!snapshot) throw std::runtime_error("Load a valid world before saving after a simulation failure.");
|
||||
// Reserve result tracking before accepting a write so allocation cannot lose
|
||||
// the newest request's completion or its originating session.
|
||||
saving_.reserve(saving_.size() + 1);
|
||||
auto operation = files_.try_save(path, *snapshot);
|
||||
if (operation.admission != SaveAdmission::Accepted) {
|
||||
throw std::runtime_error("The save queue is busy or unavailable. Try again.");
|
||||
}
|
||||
latest_save_ = operation.request_id;
|
||||
saving_.push_back({generation_, operation.request_id, (*snapshot)->identity.session,
|
||||
std::move(operation.completion)});
|
||||
}
|
||||
|
||||
void ViewerSession::enter_guest() {
|
||||
static_cast<void>(begin_change());
|
||||
guest_ = true;
|
||||
changing_world_ = false;
|
||||
guest_world_.reset();
|
||||
guest_view_.reset();
|
||||
}
|
||||
|
||||
void ViewerSession::receive_guest(std::unique_ptr<World> world) {
|
||||
if (!guest_ || !world) return;
|
||||
auto view = world->capture();
|
||||
guest_world_ = std::move(world);
|
||||
guest_view_ = std::move(view);
|
||||
}
|
||||
|
||||
void ViewerSession::leave_guest() {
|
||||
if (!guest_) return;
|
||||
if (guest_world_) {
|
||||
auto id = Void::Uuid::try_v4();
|
||||
if (!id) throw std::runtime_error("Could not create a world identity.");
|
||||
if (guest_world_->width() != first_colony_map_size || guest_world_->height() != first_colony_map_size) {
|
||||
throw std::runtime_error("This viewer opens worlds with a 32 by 32 map.");
|
||||
}
|
||||
// All fallible preparation precedes moving the last received world.
|
||||
auto rules = supported_rules_;
|
||||
const auto ticket = begin_change();
|
||||
installing_.emplace(Installing{ticket, {std::move(guest_world_), *id, 1, std::move(rules)}});
|
||||
} else {
|
||||
static_cast<void>(begin_change());
|
||||
changing_world_ = false;
|
||||
}
|
||||
guest_ = false;
|
||||
if (!changing_world_) guest_view_.reset();
|
||||
}
|
||||
|
||||
void ViewerSession::fail_change(std::string message) {
|
||||
preparing_.reset();
|
||||
installing_.reset();
|
||||
install_completion_ = {};
|
||||
changing_world_ = false;
|
||||
if (!guest_) guest_view_.reset();
|
||||
events_.push_back({ViewerEventKind::Error, 0, {}, CommandStatus::Unavailable, std::move(message)});
|
||||
}
|
||||
|
||||
void ViewerSession::poll_changes() {
|
||||
if (preparing_ && ready(preparing_->completion)) {
|
||||
const auto ticket = preparing_->ticket;
|
||||
auto prepared = preparing_->completion.get();
|
||||
preparing_.reset();
|
||||
if (runtime_.latest()->identity.session != ticket.expected_session) {
|
||||
fail_change("The load belongs to an earlier session.");
|
||||
return;
|
||||
}
|
||||
if (!prepared) {
|
||||
fail_change(prepared.error().message);
|
||||
return;
|
||||
}
|
||||
validate_candidate(*prepared);
|
||||
installing_.emplace(Installing{ticket, std::move(*prepared)});
|
||||
}
|
||||
if (installing_) {
|
||||
auto result = runtime_.try_install(installing_->ticket, installing_->candidate);
|
||||
if (result.admission == RuntimeAdmission::Accepted) {
|
||||
install_completion_ = std::move(result.completion);
|
||||
installing_.reset();
|
||||
} else if (result.admission != RuntimeAdmission::Busy) {
|
||||
fail_change("The simulation could not install this world.");
|
||||
}
|
||||
}
|
||||
if (ready(install_completion_)) {
|
||||
const auto result = install_completion_.get();
|
||||
changing_world_ = false;
|
||||
if (result.outcome == RuntimeOutcome::Completed && result.snapshot &&
|
||||
result.snapshot->identity.session == runtime_.latest()->identity.session) {
|
||||
guest_view_.reset();
|
||||
fault_reported_ = false;
|
||||
events_.push_back({ViewerEventKind::Replaced, 0, {}, CommandStatus::Unavailable, {}});
|
||||
} else {
|
||||
events_.push_back({ViewerEventKind::Error, 0, {}, CommandStatus::Unavailable,
|
||||
"The world change failed or was superseded. The current view is retained."});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void ViewerSession::poll_commands() {
|
||||
if (ready(command_completion_)) {
|
||||
auto result = command_completion_.get();
|
||||
if (!intents_.empty()) {
|
||||
auto intent = std::move(intents_.front());
|
||||
intents_.pop_front();
|
||||
const auto status = result.outcome == RuntimeOutcome::Completed && result.receipt &&
|
||||
result.receipt->status == DispatchStatus::Completed
|
||||
? result.receipt->command_status : CommandStatus::Unavailable;
|
||||
events_.push_back({ViewerEventKind::Command, intent.id, std::move(intent.payload), status, {}});
|
||||
}
|
||||
}
|
||||
if (command_completion_.valid() || intents_.empty() || !can_submit()) return;
|
||||
const auto current = runtime_.latest();
|
||||
const CommandEnvelope command{command_envelope_version, current->identity.world, current->identity.session,
|
||||
current->identity.city, current->next_requests[colony_host - 1], intents_.front().payload};
|
||||
auto result = runtime_.try_submit({colony_host}, command);
|
||||
if (result.admission == RuntimeAdmission::Accepted) {
|
||||
command_completion_ = std::move(result.completion);
|
||||
} else if (result.admission != RuntimeAdmission::Busy) {
|
||||
auto intent = std::move(intents_.front());
|
||||
intents_.pop_front();
|
||||
events_.push_back({ViewerEventKind::Command, intent.id, std::move(intent.payload), CommandStatus::Unavailable, {}});
|
||||
}
|
||||
}
|
||||
|
||||
void ViewerSession::poll_saves() {
|
||||
for (auto item = saving_.begin(); item != saving_.end();) {
|
||||
if (!ready(item->completion)) {
|
||||
++item;
|
||||
continue;
|
||||
}
|
||||
const auto result = item->completion.get();
|
||||
if (item->generation == generation_ && item->request == latest_save_ &&
|
||||
item->session == runtime_.latest()->identity.session && !guest_) {
|
||||
events_.push_back({result.succeeded() ? ViewerEventKind::Saved : ViewerEventKind::Error,
|
||||
0, {}, CommandStatus::Unavailable,
|
||||
result.succeeded() ? "" : result.visible_on_disk
|
||||
? "The new save is visible, but its final disk status could not be confirmed."
|
||||
: "The save failed. The previous slot remains available."});
|
||||
}
|
||||
item = saving_.erase(item);
|
||||
}
|
||||
}
|
||||
|
||||
void ViewerSession::poll_ticking() {
|
||||
if (ready(ticking_completion_)) {
|
||||
const auto result = ticking_completion_.get();
|
||||
// The owner applies its ticking flag even while its world is faulted.
|
||||
if (result.outcome == RuntimeOutcome::Completed || result.outcome == RuntimeOutcome::Faulted) {
|
||||
applied_ticking_ = requested_ticking_;
|
||||
}
|
||||
}
|
||||
const bool desired = desired_ticking_ && !guest_ && !changing_world_;
|
||||
if (ticking_completion_.valid() || desired == applied_ticking_) return;
|
||||
auto result = runtime_.set_ticking(desired);
|
||||
if (result.admission == RuntimeAdmission::Accepted) {
|
||||
requested_ticking_ = desired;
|
||||
ticking_completion_ = std::move(result.completion);
|
||||
}
|
||||
}
|
||||
|
||||
std::vector<ViewerEvent> ViewerSession::poll() {
|
||||
try {
|
||||
poll_changes();
|
||||
poll_commands();
|
||||
poll_saves();
|
||||
poll_ticking();
|
||||
} catch (...) {
|
||||
fail_change(exception_message());
|
||||
}
|
||||
if (!guest_ && runtime_.view().state == RuntimeState::Faulted && !fault_reported_) {
|
||||
fault_reported_ = true;
|
||||
intents_.clear();
|
||||
command_completion_ = {};
|
||||
events_.push_back({ViewerEventKind::Fault, 0, {}, CommandStatus::Unavailable,
|
||||
"The simulation stopped at its last completed state. Load a save to continue."});
|
||||
}
|
||||
return std::exchange(events_, {});
|
||||
}
|
||||
|
||||
} // namespace settlement::viewer
|
||||
@@ -0,0 +1,111 @@
|
||||
#pragma once
|
||||
|
||||
#include "settlement/core/checkpoint_files.hpp"
|
||||
#include "settlement/core/colony_profile.hpp"
|
||||
|
||||
#include <deque>
|
||||
#include <filesystem>
|
||||
#include <optional>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace settlement::viewer {
|
||||
|
||||
enum class ViewerEventKind { Replaced, Command, Saved, Error, Fault };
|
||||
|
||||
struct ViewerEvent {
|
||||
ViewerEventKind kind;
|
||||
std::uint64_t command = 0;
|
||||
std::optional<SessionPayload> payload;
|
||||
CommandStatus status = CommandStatus::Unavailable;
|
||||
std::string message;
|
||||
};
|
||||
|
||||
struct ViewerSessionOptions {
|
||||
RuntimeOptions runtime;
|
||||
CheckpointFilesOptions files;
|
||||
std::size_t command_capacity = 64;
|
||||
};
|
||||
|
||||
// Called only by the UI thread. Polling owns completion delivery; rendering holds
|
||||
// an immutable view independently of owner progress and nested window messages.
|
||||
class ViewerSession {
|
||||
public:
|
||||
explicit ViewerSession(std::size_t workers, ViewerSessionOptions options = {});
|
||||
ViewerSession(WorldCheckpoint initial, std::size_t workers, ViewerSessionOptions options = {});
|
||||
~ViewerSession();
|
||||
|
||||
[[nodiscard]] SimulationRuntime& runtime() noexcept { return runtime_; }
|
||||
[[nodiscard]] std::shared_ptr<const World> world() const;
|
||||
[[nodiscard]] bool guest() const noexcept { return guest_; }
|
||||
[[nodiscard]] bool changing_world() const noexcept { return changing_world_; }
|
||||
[[nodiscard]] bool can_submit() const;
|
||||
[[nodiscard]] bool can_host_legacy() const;
|
||||
[[nodiscard]] std::uint64_t generation() const noexcept { return generation_; }
|
||||
[[nodiscard]] std::optional<std::uint64_t> submit(SessionPayload payload);
|
||||
[[nodiscard]] bool pending(std::uint64_t id) const noexcept;
|
||||
void set_ticking(bool enabled) noexcept { desired_ticking_ = enabled; }
|
||||
[[nodiscard]] std::vector<ViewerEvent> poll();
|
||||
|
||||
void new_colony(ColonyProfile profile = ColonyProfile::Default);
|
||||
void load(const std::filesystem::path& path);
|
||||
void save(const std::filesystem::path& path);
|
||||
void enter_guest();
|
||||
void receive_guest(std::unique_ptr<World> world);
|
||||
void leave_guest();
|
||||
|
||||
private:
|
||||
struct Intent {
|
||||
std::uint64_t id;
|
||||
SessionPayload payload;
|
||||
};
|
||||
struct Preparing {
|
||||
LoadTicket ticket;
|
||||
std::future<CheckpointLoadResult> completion;
|
||||
};
|
||||
struct Installing {
|
||||
LoadTicket ticket;
|
||||
WorldCheckpoint candidate;
|
||||
};
|
||||
struct Saving {
|
||||
std::uint64_t generation;
|
||||
std::uint64_t request;
|
||||
Void::Uuid::Uuid session;
|
||||
std::future<SaveResult> completion;
|
||||
};
|
||||
[[nodiscard]] LoadTicket begin_change();
|
||||
void replace(WorldCheckpoint candidate);
|
||||
void validate_candidate(const WorldCheckpoint& candidate) const;
|
||||
void fail_change(std::string message);
|
||||
void poll_changes();
|
||||
void poll_commands();
|
||||
void poll_saves();
|
||||
void poll_ticking();
|
||||
|
||||
std::size_t workers_;
|
||||
std::size_t command_capacity_;
|
||||
RulesManifest supported_rules_;
|
||||
SimulationRuntime runtime_;
|
||||
CheckpointFiles files_;
|
||||
std::shared_ptr<const World> guest_view_;
|
||||
std::unique_ptr<World> guest_world_;
|
||||
std::deque<Intent> intents_;
|
||||
std::future<RuntimeResult> command_completion_;
|
||||
std::optional<Preparing> preparing_;
|
||||
std::optional<Installing> installing_;
|
||||
std::future<RuntimeResult> install_completion_;
|
||||
std::vector<Saving> saving_;
|
||||
std::vector<ViewerEvent> events_;
|
||||
std::future<RuntimeResult> ticking_completion_;
|
||||
bool requested_ticking_ = false;
|
||||
bool applied_ticking_ = false;
|
||||
bool desired_ticking_ = false;
|
||||
bool guest_ = false;
|
||||
bool changing_world_ = false;
|
||||
bool fault_reported_ = false;
|
||||
std::uint64_t generation_ = 1;
|
||||
std::uint64_t next_intent_ = 1;
|
||||
std::uint64_t latest_save_ = 0;
|
||||
};
|
||||
|
||||
} // namespace settlement::viewer
|
||||
+629
-271
File diff suppressed because it is too large.
Load diff
@@ -87,3 +87,15 @@ wine /tmp/stoneheart-milestones.xprJ2SVp/windows/settlement_core_tests.exe --tag
|
||||
В `cf0cc2f` объединены проверенные коммиты S19 `de38aff` и S01 `68f91a2`. После объединения под Wine 11 прошли 51 из 51 теста ядра и 4 из 4 тестов LAN, включая формат сохранений 13 и протокол 11. Независимый проверяющий сверил обе родительские версии, наследование параметров компиляции и встроенную реализацию SHA-256. [План владельца симуляции](tasks/M01-P2.md) · [Проверка библиотеки](tasks/M01-R2.md) · [Разбор отказов](tasks/M01-F2.md) · [Принятые контракты](tasks/M01-F3.md) · [Проверка S01 и S19](tasks/M01-V2.md) · [Проверка интеграции](tasks/M01-V3.md)
|
||||
|
||||
Срез S06 сохранил ссылки на склады и источники при удалении более раннего элемента. Два контрольных набора из 738 386 и 393 857 байтов совпали со старой сборкой в последовательном режиме и на 2/6/12 потоках. Второй набор включает разбор склада во время многоэтапной доставки. Изменения опубликованы отдельно в [S06 #11](https://git.faumaray.com/Lagg1ng/stoneheart_at_home/pulls/11). В `4ba64f7` также вошла фоновая подготовка старых и новых сохранений. В объединённой Windows x64-сборке под Wine прошли 106 тестов ядра и 4 LAN. Публичный аналог ограниченного чтения в Windows отслеживается в [Void/Library #9](https://git.faumaray.com/Void/Library/issues/9). [Проверка двух компонентов](tasks/M01-V8.md) · [Интеграционная проверка](tasks/M01-V9.md)
|
||||
|
||||
Хост протокола 11 теперь передаёт приказы авторитетной симуляции, а гость получает подтверждение и снимок завершённого состояния. После смены сеанса старому гостю требуется новое подключение. Старая и новая сборки обменялись приказами в обеих ролях. В `aa4e271` под Wine прошли 106 из 106 тестов ядра и 9 из 9 LAN. Отдельно проверены переподключение при незавершённом приказе и разные правила нумерации отклонённых приказов у старого клиента и нового владельца. [Ветка S16](https://git.faumaray.com/Lagg1ng/stoneheart_at_home/pulls/9) · [Проверка интеграции](tasks/M01-V10.md)
|
||||
|
||||
В `a8cd7bb` объединены заказы с постоянными ID и два варианта правил строительства кровати. Формат контрольной точки 2 сохраняет ID заказов и следующий свободный ID. Прежние контрольные точки и обычные сохранения версии 13 продолжают загружаться. Оба варианта правил прошли строительство реальных кроватей, сохранение во время доставки и сравнение продолжений на 1/2/6/12 исполнителях. В объединённой сборке под Wine прошли 122 теста ядра и 9 LAN. Аппаратная Windows ещё не проверена. [Заказы S04](../plan/systems/S04.md) · [Правила S19](../plan/systems/S19.md) · [Интеграционная проверка](tasks/M01-V11.md)
|
||||
|
||||
Клиент Windows в `db0a872` обрабатывает действия игрока по квитанциям владельца и рисует из неизменяемого снимка. Три отдельных процесса под Wine проверили создание партии, паузу в меню и окне выбора файла, запись, современное и прежнее сохранения и отказ при повреждении файла. Отдельно проверены подтверждение разбора при смене партии, сохранение гостевой колонии после неудачного переподключения и возобновление тактов после восстановления. В общей сборке прошли 122 теста ядра, 9 LAN и 10 клиента. [Клиент S18](../plan/systems/S18.md) · [Проверка с обеими родительскими ветками](tasks/M01-V10.md)
|
||||
|
||||
В `37fb6a8` объединены проверяемая передача всего груза одной остановки и выбор правил на титульном экране. Игрок может создать поселение с поэтапной сборкой кровати либо с рецептом из одной доски. При открытии сохранения восстанавливается его собственный набор правил. Испытание настоящего окна проверило оба выбора мышью и клавиатурой, файл и продолжение из нового процесса. В общей сборке под Wine прошли 136 тестов ядра, 9 LAN и 14 клиента. [Загрузка и инвентарь S06](https://git.faumaray.com/Lagg1ng/stoneheart_at_home/pulls/11) · [Клиент S18](https://git.faumaray.com/Lagg1ng/stoneheart_at_home/pulls/13) · [Совместная проверка](tasks/M01-V12.md)
|
||||
|
||||
В `048268a` две настоящие рабочие задачи завершаются в противоположном порядке. Во всех 24 воспроизведениях победитель спорной заявки и байты состояния совпали с последовательной партией. При загрузке более старого мира запоздалый результат не изменил новую партию. Windows x64 под Wine прошла 141 тест ядра, 9 LAN и 14 клиента. [Проверки S21](../plan/systems/S21.md) · [Интеграционная проверка](tasks/M01-V13.md) · [Управляемый порядок завершения в VoidLibrary](https://git.faumaray.com/Void/Library/issues/15)
|
||||
|
||||
В `455630f` камера отвечает на колесо мыши и перетаскивание, пока симуляция или запись файла задержана. Проверка настоящего окна сравнила пиксели и байты контрольной точки, воспроизвела замену мира между опросом и рисованием и проверила сохранение прежнего кадра. Под Wine прошли 141 тест ядра, 9 LAN, 14 клиента и отдельное испытание кадра с видимой цепочкой D3D11 и WARP. Проверка в нескольких процессах также подтвердила выбор и загрузку обоих рецептов кровати. Частота кадров на физическом Windows-ПК ещё не измерена. [Рендерер S17](../plan/systems/S17.md) · [Совместная проверка](tasks/M01-V13.md)
|
||||
@@ -0,0 +1,48 @@
|
||||
# Recheck production identity safety and preflight a selectable colony rule
|
||||
|
||||
Task ID: M01-F6
|
||||
Role: astra_reviewer
|
||||
Status: READY
|
||||
|
||||
## 1. Context and baseline
|
||||
Root at 60154bd. S04-01 contract in s04 checkout (4ba64f7) includes the two M01-V9 findings. In S19 M01-P4 examines new world profile selection reusing existing simple vs staged bed paths. Default built-in manifest content must remain compatible.
|
||||
|
||||
## 2. Objective and deliverables
|
||||
Immediately recheck S04 exact guards and, separately, preflight the first selectable rules behavior with a validated default/legacy compatibility policy. No actual code review or implementation.
|
||||
|
||||
## 3. Scope and non-goals
|
||||
Read-only S04-01 revised contract and S19 feature preflight. Exclude further stack/transfer/production implementation.
|
||||
|
||||
## 4. Files to inspect
|
||||
Inspect s04/docs/agent-workflow/tasks/S04-01.md sections 6–10 and World::edit_object/CommandDispatcher::apply. For S19 read M01-P4, world.cpp bed construction, legacy codec/staged flag, generator/first_colony, rules_manifest, runtime/file/load and default-only LAN contracts. Implementation worktrees outside main have direct read evidence.
|
||||
|
||||
## 5. Write ownership and coordination
|
||||
Write scope: none
|
||||
No mutations/builds/remote writes/branch ops/children or shared Serena activation. Other workers continue on their own files.
|
||||
|
||||
## 6. Implementation or investigation approach
|
||||
S04 confirm hypothetical exhaustion guards precompute post-demolition totals exactly across all affected supplies before erasing or queue changes, preserve accepted receipt semantics for proved cabin preflight Busy separately from mutation faults. Genuine v1/body1–13 and current2/14 mapping, negative checks and older file test version. Send scoped approval immediately if corrected.
|
||||
|
||||
## 7. Interfaces and data contracts
|
||||
S19 proposal: compiled default first-colony behavior stays staged recipes and two-package original frozen manifest, content digest unchanged; optional exact pinned, additive package selects existing simple/plank recipe path at world creation. Encode enacted policy in World at initialization, existing staged_beds state and manifest saved, normal creation can choose default/alternative. Add game-specific supported profile compiler using actual typed data and package closure; reject unsupported modified digest before installation by viewer, generic resolver/decoder retains broad catalog tools behavior. Important: previous v1 checkpoints and imported historical worlds could legitimately carry DEFAULT manifest with staged_beds=false, and inactive world is valid. Describe migration rule that preserves these old states/bytes; distinguish strict alternate invariant from accepted old default data, and verify clean subsequent saves on current envelope. Future S19/UI APIs and compatibility choices from M01-P4 confirmed by root prior to implementation.
|
||||
|
||||
## 8. Dependencies and integration
|
||||
S04 and S19 can use isolated branches; parent serializes shared World/factory/file semantics and S18 normal UI selector after core approval. Keep legacy LAN default-profile-only and preserve old default digest/test fixtures. Do not equate illustrative board ticks=8 with actual compiled tick count.
|
||||
|
||||
## 9. Edge cases security and performance
|
||||
Check nonempty real colony resources/producer/receipt for both bed paths, UI stone vs wood selection, immutable held snapshot and save-load continuation, partial bed materials, old format 1–13 valid imports, malformed optional profile/default unknown package gate, credible negative tests. No fabricated ACE parity.
|
||||
|
||||
## 10. Acceptance criteria
|
||||
1. Separate S04 corrected or material outstanding. 2. S19 preflight verdict with explicit compatibility and required exact negative/normal tests. 3. Record what can proceed with certainty and facts needing further root commitment.
|
||||
|
||||
## 11. Verification commands and evidence
|
||||
Read actual source/contract targets and M01-P4; compare default manifests/code and World legacy flags; no build required. Check git status/refs to identify exact code.
|
||||
|
||||
## 12. Constraints and stop conditions
|
||||
Read only. Return S04 verdict immediately then S19. No new external service or changes to accepted user scope.
|
||||
|
||||
## 13. Authorization and decisions
|
||||
Root requests follow-up after exact S04 corrections and planner-backed S19 technical preflight. User authorizes signed-off coding only through root.
|
||||
|
||||
## 14. Return format
|
||||
Return M01-F6 two scoped verdicts with evidence, precise blockers/solutions and pending real integration tests.
|
||||
@@ -0,0 +1,50 @@
|
||||
# Check the contract for atomic reserved pickups and client rule selection
|
||||
|
||||
Task ID: M01-F7
|
||||
Role: astra_reviewer
|
||||
Status: READY
|
||||
|
||||
## 1. Context and baseline
|
||||
M01 parent 9a248c3 has S19-02 compiled profile and S06-ID data. S04-01 adds production identities and body14 in isolated s04. S18-01 canonical client still in isolated s18 resolving modal input findings. M01-P5 proposed a bounded reserved-quantity pickup used by actual meal and construction stops.
|
||||
|
||||
## 2. Objective and deliverables
|
||||
Preflight the first S06 quantity transaction and bounded S18 followup that wires approved profile to the New/Load/Host UI. Return separate actionable corrections before component implementation.
|
||||
|
||||
## 3. Scope and non-goals
|
||||
The S06 step preflights a single existing storage→resident pickup atomically, including all materials at one construction stop. Later stack identity, cancel, site ownership and replay ledger remain P5-dependent. S18 selection is only New colony and coherent support/legacy compatibility; no new game settings or traffic.
|
||||
|
||||
## 4. Files to inspect
|
||||
Read root world.hpp, world.cpp functions finish_meal_step/advance_construction_delivery/take_reserved_material/finish_production, profile public API/first_colony/tests, s04 working diff and actual s18 viewer_session/viewer_win32/title_screen, LAN default gate, docs S04/S06/S18/S19 and M01-F6.
|
||||
|
||||
## 5. Write ownership and coordination
|
||||
Write scope: none
|
||||
No mutations/builds/remote posts/other agents or Serena switch. Root decides subsequent contracts and serializes worktrees/CMake changes.
|
||||
|
||||
## 6. Implementation or investigation approach
|
||||
S06 proposed NEW internal bounded reserved pickup with one validated StorageId per operation, max item_type_count distinct items (all lines at stop aggregated before any mutation), reject zero/None/unknown ID, reserved>physical, insufficient reserved/quantity or target sum overflow using Void::Numeric; commit all source counts/reserve/zero-stack removal/destination changes without further allocation or throwable effects. Success keeps meal, route cursor, order/worker behavior and v13 projection/corpora unchanged. Failure immediately leaves source+inventory and stop/actor bookkeeping unchanged; impossible invariant failure may fault owner while preserving last healthy publication. Existing non-pickup recipe paths must be accounted for. Identify any missing edge or side effect.
|
||||
|
||||
## 7. Interfaces and data contracts
|
||||
S18 followup proposed initial selector defaults staged, allows existing alternative single plank profile in title New, Continue/Open ignores current selection; factory+validator before runtime construct and after latest load prepared, preserve exact default old simple/inactive, refuse forged/extra or optional staged, both immediate and deferred legacy-host gates require exact default, failed admission leaves world/guest unchanged. Rename/conditionally hide staged base UI choices in plank-only worlds; confirm existing placement validation behavior. Verify title keyboard/mouse handling and no accidental persisted settings.
|
||||
|
||||
## 8. Dependencies and integration
|
||||
Depends on S19-02 and S18-01 review, S06-02 first consumer should merge after S04-01 with tests and version untouched. Root will own separate follow-up schema migration and M01-P5 final decisions; legacy cancellation compatibility remains.
|
||||
|
||||
## 9. Edge cases security and performance
|
||||
Check non-throwing commit including vector erase/multi-type and destination Inventory bounds, zeros/duplicates, capacity reserve for carpentry and any work cursor mutation. Check modal callbacks/error feedback, unsupported profiles advertised to LAN, save/restore exact active legacy mode.
|
||||
|
||||
## 10. Acceptance criteria
|
||||
1. Separate READY/CHANGES_REQUIRED per contract before dispatch. 2. Concrete trigger and correction for any inconsistency. 3. Exact tests that would fail on a partial batch and incorrect selection or post-load gate. The stages do not approve future implementation.
|
||||
|
||||
## 11. Verification commands and evidence
|
||||
Read-only git status/rev-parse at each worktree, scoped rg and direct source/graph coverage. Inspect /tmp/stoneheart-milestones.xprJ2SVp/profile-{tag,ctest}.log and existing client-session/GUI smoke source if needed. No new builds.
|
||||
|
||||
## 12. Constraints and stop conditions
|
||||
No new general inventory database, domain mechanics or UI expansion, no duplicate library issues. Report prerequisites immediately; defer review of actual changes until implemented. No charges/remote operations.
|
||||
|
||||
## 13. Authorization and decisions
|
||||
User authorizes all milestones, including stable single-owner items, selectable new rules, per-branch publishing and generic Void issues. Root retains mutation authority.
|
||||
|
||||
## 14. Return format
|
||||
Return M01-F7 PREFLIGHT disposition for S06 and S18 separately; exact invariants/tests and any blocking oversight backed by existing source.
|
||||
|
||||
Preflight required the pickup owner to validate the post-withdrawal occupancy and the carpentry output slot together, aggregate repeated lines, and preserve the state at pickup entry on rejection. Direct storage-to-recipe conversion keeps its own path. For profile selection, deny starting a legacy host while a replacement is pending, recheck after a modal menu, then check the installed authoritative default manifest immediately before either host call. The simple-bed house preview must describe the actual one-plank recipe for every house type.
|
||||
@@ -0,0 +1,48 @@
|
||||
# Preflight durable custody, legacy projections and replay limits
|
||||
|
||||
Task ID: M01-F8
|
||||
Role: astra_reviewer
|
||||
Status: READY
|
||||
|
||||
## 1. Context and baseline
|
||||
Root e6a01be includes production IDs, current14/outer2, compiled profiles and verified initial viewer. Quantity batch now ready in isolated s06 at a8cd7bb + changes. Detailed operational proposal from M01-P5 in NEW docs/plan/custody.md. This prescreen concerns the next persistent state model, not approval of implementation.
|
||||
|
||||
## 2. Objective and deliverables
|
||||
Examine the complete proposed data/operation/migration contract and find contradictions before assigning parallel core/codec/command owners. Provide first specific corrections quickly and feasible independent interfaces.
|
||||
|
||||
## 3. Scope and non-goals
|
||||
Only S06/S04 custody, bounded receipts, migration from raw1–14, v15/outer3, cancel and LAN legacy projection. Existing numeric/ID tickets #7/#8, duplicate support and preflight-before-mutation apply. No new gameplay or schema publishing yet.
|
||||
|
||||
## 4. Files to inspect
|
||||
Read root docs/plan/custody.md, tasks M01-P5/F6/F7, world.hpp, world.cpp, world_save.cpp (codecs, route/phase validation, old limits), checkpoint*, command_dispatcher*, simulation_runtime, actual app/lan_session_win32.cpp legacy publication and viewer costs; s06 new transaction source/consumers. Check existing fixtures and acceptance corpus.
|
||||
|
||||
## 5. Write ownership and coordination
|
||||
Write scope: none
|
||||
No mutations/builds/remote posts/other agents or Serena switch. Root owns public actions and serializes source. Look at actual code, modern replay and schema context, consulting direct worktree sources for S06.
|
||||
|
||||
## 6. Implementation or investigation approach
|
||||
Check embedded unique stack identities, split/merge and reservation movement, checked monotonic world counters and batch preflight, one owner including production input, exact custody for resources, all recipes, grants, meals, canceled work and demolition, capacity claim backed by claimed input, no double-used space. Verify same-type lines and multiple source warehouses vs number-of-item-types limit; coordinate strict modern validation with real legacy accepted data. Specify robust migration for Working site, completed orders still carrying outputs without inventing supplies, raw import opening balance and modern projection of unrepresentable payloads.
|
||||
|
||||
## 7. Interfaces and data contracts
|
||||
Admitted execution TransferId with ordinal, retained exact input+result 4096 entries <=1KiB each part, remaining earlier ordinals stale forever under high-water; root accepts schema15/outer3, checked before-effect refusal vs stored admitted rejection. Establish how an exact retry of *creation/admission itself* is recognized across crashes if caller has not yet been given a TransferId; when legitimate repeated blocked work consumes ordinals; persisted capacity/hash checks, session/world identity during timeline rollback and monitor snapshot cost.
|
||||
|
||||
## 8. Dependencies and integration
|
||||
Core/registry implementation may be parallel with fixtures/validator/serializers only after exact public/internal data shapes agreed. Recommend useful checkpoints and ownership for S06 main data, S04 ledger/cancel and S16 unsupported legacy state. Normal v13/LAN11 baseline must match; unsafe-fallback exception must be caught before session UI/network effects, preserving live host. Choose measurable memory/latency acceptance.
|
||||
|
||||
## 9. Edge cases security and performance
|
||||
Watch O(N²) owner+claim search, cross-transaction side effects after allocations fail, receipts shallow copies shared mutable in published snapshots, reparent/merge alias lifetime, callable external mutation through current prototype Inventory/Storage APIs, new IDs exhausted during split/recovery. Inspect resource-harvesting branch and raw1-8 sleep import logic. Legacy loader may accept snapshots with unused/trailing projected route metadata; avoid pathological blanket rejection of genuine saves.
|
||||
|
||||
## 10. Acceptance criteria
|
||||
1. Separate READY/CHANGES_REQUIRED plus specific contract amendments. 2. Bound request/replay/IDs and failure atomicity at ordinary world hot paths. 3. Identify data-shape necessities for accurate P5 legacy import and modern pollution rejection. 4. Specify earliest branch-safe real end-to-end migration stage. 5. Name concrete validation tests that catch each risk.
|
||||
|
||||
## 11. Verification commands and evidence
|
||||
Read-only git status/rev-parse, graph search/trace and coverage for cited root paths, direct missed ranges. Check core/profile/production/identity/construction tests and raw serializer fields; no builds necessary. Existing logs in /tmp/stoneheart-milestones.xprJ2SVp.
|
||||
|
||||
## 12. Constraints and stop conditions
|
||||
No new generic public dependency/remote issue unless actual gap separate from #7/#8 is identified; root handles filings. Stop to report actual contradictions, keep analyzing independent parts. Do not review or edit the code of another upcoming assignment.
|
||||
|
||||
## 13. Authorization and decisions
|
||||
User authorizes complete implementation; root accepted pre-admission vs admitted rejection accounting, modern CancelProduction by durable ID, raw13 UnsupportedLegacyState and retained exact 4096 receipts, immutable stacks with a single quantity source, and input-backed capacity claims, subject to technical feasibility.
|
||||
|
||||
## 14. Return format
|
||||
Return M01-F8 PREFLIGHT verdict, concise exact corrections, schema and ownership constraints, regression fixtures and performance risks.
|
||||
@@ -0,0 +1,48 @@
|
||||
# Preflight independent renderer frames and deterministic completion replay
|
||||
|
||||
Task ID: M01-F9
|
||||
Role: astra_reviewer
|
||||
Status: READY
|
||||
|
||||
## 1. Context and baseline
|
||||
Root M01 66af7c5 includes client b7f18c0, current14, S06 atomic pickup. M01-P6 planner inspected current Win32/worker paths. Actual WM_TIMER pumps every 60 ms, scene packets borrow spans and camera-only paint rebuilds flat D3D mesh, while 20 Hz runtime is independent. Replay covers serial/2/6/12 and last berry but lacks proof of opposing real computation completion and semantic divergence diagnostics.
|
||||
|
||||
## 2. Objective and deliverables
|
||||
Preflight M01-P6 proposals for S17-W01 and S21-W01 before assigning separate implementation worktrees. Return separate corrections and concrete signoff conditions.
|
||||
|
||||
## 3. Scope and non-goals
|
||||
S17 independent presentation with one retained prepared flat mesh and 16ms dirty-only visible UI timer; S21 success observer for real worker callables plus deterministic arbitration/barrier/replay reporting. No M02 voxel geometry, native 60fps claim or GPU/backend replacement.
|
||||
|
||||
## 4. Files to inspect
|
||||
Read root app/viewer_win32.cpp, app/d3d_scene_win32.hpp/.cpp, viewer_session, app timer/lifecycle, tests/replay_tests.cpp/executor_tests.cpp/runtime_tests.cpp, engine/include/settlement/core/worker_pool.hpp, engine/src/world.cpp actual stage spans and quota; docs S17/S21/M01, M01-P6 and pinned FuturePool/Testing. Inspect temporary actual client handler smoke.
|
||||
|
||||
## 5. Write ownership and coordination
|
||||
Write scope: none
|
||||
No mutations/builds/remote posts/other agents or Serena switch. Root assigns separate S17/S21 branches, and S18 owns ongoing title changes.
|
||||
|
||||
## 6. Implementation or investigation approach
|
||||
S17 verify packet owns world/camera/selection/overlay and prepared GUI inputs, UI-thread resource ownership, post-replacement pairing after pump consumes event, immutable pin across nested UI; D3D reuses existing flat GPU/CPU mesh for camera-only changes, avoid per-timer reallocation/hot spinning, hidden/title/minimized and zero-size restoration. Real actual handler test needs camera and render changes while owner/file blocked, safe destruction; respect existing WARP/offscreen/hardware capabilities and fallback HUD only.
|
||||
|
||||
## 7. Interfaces and data contracts
|
||||
S21 optional after_execute(index) on success after real callable returns, before future satisfaction; return void/value/references/move-only, same-callable exceptions including observer errors, no throwing destructor, no hook when absent. Existing Void #15 registered. Two gates for two known competitors, controlled opposing completions asserted; tests 2/6/12 + capacity1 fallback without deadlock; real generic job contest parallel, berry claim serial with parallel movement separately. Report object/field/owner/request for first divergence using public World and canonical current serializer as authority; gated old world vs queued same-world reload with fresh session and unchanged old snapshots.
|
||||
|
||||
## 8. Dependencies and integration
|
||||
S17 rendering work in new branch separate from S18 title/profile; avoid altering normal client command pumps. S21 production edit restricted to optional worker hook and tests/docs, no world mutation/codec changes. Future body15 normalize version selector after integration.
|
||||
|
||||
## 9. Edge cases security and performance
|
||||
Check exception lifetimes, reference dangling/extra move, re-entrance or UI init/failure, force order while caller coordinator blocked, guarantee test oracle actually observes completion, full terminal effects after faults/cancel. Potential thread-lifetime hang on assertion; GPU device generation invalidates cached upload after reset. Check path/store version key for camera-only frames and active overlay state.
|
||||
|
||||
## 10. Acceptance criteria
|
||||
1. Separate READY/CHANGES_REQUIRED per component. 2. Concrete prescreen decisions, testable postconditions and residual limitations. 3. Meaningful assignment in each isolated subsystem without changing the product contract.
|
||||
|
||||
## 11. Verification commands and evidence
|
||||
Use source read and graph search/trace/coverage plus direct ranges; inspect actual m01-viewer-{build,ctest,ui-smoke}.log and client_handlers_smoke.cpp. No builds.
|
||||
|
||||
## 12. Constraints and stop conditions
|
||||
Send prescreen first safe scope early. No apparent missing generic capability needs a duplicate issue; root filed Void/Library #15, immutable publication uses #5. Do not review unseen code or demand native-only validation for feasible Wine work.
|
||||
|
||||
## 13. Authorization and decisions
|
||||
User authorizes complete roadmap branches and tests; root accepts dirty-only 16ms timer, one retained flat mesh generation, optional success observation and semantic diagnostics subordinate to canonical bytes, subject to technical preflight.
|
||||
|
||||
## 14. Return format
|
||||
Return M01-F9 PREFLIGHT stage-specific verdict, corrections, exact test cases/source, bounded risks and practical blockers.
|
||||
@@ -0,0 +1,50 @@
|
||||
# Specify the first authoritative inventory and transfer operations
|
||||
|
||||
Task ID: M01-P5
|
||||
Role: astra_planner
|
||||
Status: READY
|
||||
|
||||
## 1. Context and baseline
|
||||
Root M01 2a5df1a. S06 IDs 8260e09 are integrated. The developing S04-01 converts production orders/agent links to ProductionId, current save body14/outer2 and typed legacy import. Previous M01-P3 mapped object domains, but actual quantities still live in storage/resident representations and construction drops cargo on arrival. This is the detailed technical handoff for M01.2.
|
||||
|
||||
## 2. Objective and deliverables
|
||||
Freeze a small end-to-end migration for S06-02 and S04-02 with exact authoritative ownership, identity allocation, operations and backward projection. Suggest genuinely independent implementation segments that can be dispatched before large World edits.
|
||||
|
||||
## 3. Scope and non-goals
|
||||
Focus on objects/recipes already present, order-reservations/haul/consumption/cancel/demolition, no new gameplay, extra protocols, catalog or general database. Domain-level transfer retry/retention must have explicit bounds.
|
||||
|
||||
## 4. Files to inspect
|
||||
Read root docs/plan/systems/{S04,S06}.md, M01, M01-P3, engine/include/settlement/core/world.hpp and actual Inventory/Storage definitions, engine/src/world{,_save}.cpp plus tests for logistics/production/replay and resource/food handling. Inspect s04 worktree public diff for actual ProductionId and NEW current14 schema; never modify it. Review pinned Void Numeric, upstream #7/#8 linked in docs/plan/void-library.md.
|
||||
|
||||
## 5. Write ownership and coordination
|
||||
Write scope: none
|
||||
No mutations/builds/remote posting, shared project switches or children. Parent owns root/remote and serializes World/codec ownership. Work from actual source and verified graph coverage.
|
||||
|
||||
## 6. Implementation or investigation approach
|
||||
Trace every quantity introduction, split/move, take_reserved_material, pickup, in-transit cancellation, construction worksite arrival/delivery, consumption, eating, storage demolition and factory stock. Identify minimum source of truth. Design checked before-effect atomic operations, stable nonzero StackId by world, one current owner per stack, explicit material balance opening/sink, exact held amounts, and reliable projection to old fields. Avoid persisting parallel quantity ledgers without enforced consistency. Characterize active/inactive imported orders to preserve v1–14 continuation, including mid-site delivery. Product keeps pre-existing demolition's removal of stock and records its amount/reason.
|
||||
|
||||
## 7. Interfaces and data contracts
|
||||
Give exact proposed NEW operation types, identities/high-water constraints, on-disk version steps, and API surfaces for S04 claims vs S06 actual stock. Pin behavior on outcomes AlreadyApplied/Duplicate/Conflict/Busy and stale retries even after bounded receipt retention and save/load, deterministic order vs multi-actor concurrency. Name genuine policy questions; choose bounded defaults for reversible design.
|
||||
|
||||
## 8. Dependencies and integration
|
||||
An independently testable ledger module before World integration may be parallel if it has a real consuming path and fixed grounded seam. S04-01 must integrate first for worksite references, and S19 touches only scenario setup. Summarize actual changes needed in UI for preserving displayed amounts.
|
||||
|
||||
## 9. Edge cases security and performance
|
||||
Bound memory by current existing file/collection capacities, handle zero and uint64/int quantity overflow, reserve IDs without partial mutation including splits/exhaustion, owner removal after pickup, no-free-space redirects, capacity races, negative/cross-owner dangling state, and loaded modern wrong digest. Avoid quadratic hot paths; identify realistic measurement checks.
|
||||
|
||||
## 10. Acceptance criteria
|
||||
1. Source-grounded transition and migration tables; 2. First independently deliverable task with exact scope and tests that leads to real stock; 3. Subsequent isolated work packages with complete modern migration path; 4. Leverage correct Void utilities and #7/#8 where adequate; 5. Declare present limits in legacy raw13/network11 projection.
|
||||
|
||||
## 11. Verification commands and evidence
|
||||
Use git rev-parse HEAD, actual scoped rg -n on add_item, take_reserved_material, advance_construction_delivery, finish_production, reserved_slots, item inventory and stock, scoped current/load/save comparisons, local Void pin as needed. Check graph identity/coverage for relied-on root code; isolated s04 working diff uses direct reads. No compilation required.
|
||||
|
||||
## 12. Constraints and stop conditions
|
||||
Send first technical seam early, then full report. Do not assign new IDs by vector position, silently destroy cargo on cancel, break legacy binary projections or start new worktrees/remote Git. If uncertainty materially changes the product scope, identify the specific branch and continue other evidence.
|
||||
|
||||
## 13. Authorization and decisions
|
||||
Approved M01 hard requirements and earlier planner M01-P3 permit this focused design of actual custody. Root decides integration order and product-preserving defaults. No release or merge to main.
|
||||
|
||||
## 14. Return format
|
||||
Return M01-P5 READY/PARTIAL, exact grounded operations and claimed invariants, owners/paths, test and version matrix, bounded retention/performance policy plus actionable blockers only.
|
||||
|
||||
The accepted decisions and historical format boundaries are recorded in [the custody contract](../../plan/custody.md). Source-backed corrections from preflight address creation retries, retained site stages, pending completion and representability on LAN 11.
|
||||
@@ -0,0 +1,48 @@
|
||||
# Define the remaining client frame and replay acceptance work
|
||||
|
||||
Task ID: M01-P6
|
||||
Role: astra_planner
|
||||
Status: READY
|
||||
|
||||
## 1. Context and baseline
|
||||
Root db0a872 merges S18 b7f18c0, S19 selectable rules, S04 Current14, S01 owner and legacy LAN. Actual client WM_TIMER pumps every 60 ms while camera input can invalidate on demand and scene Present uses 0. Existing replay on serial and 2/6/12, last meal, synchronous structural barriers and faulted owner recovery pass. M01 needs independent client frames and an evidenced worker completion-order adversary/first divergent IDs.
|
||||
|
||||
## 2. Objective and deliverables
|
||||
Prepare two independent real work packages for S17-W01 render frame delivery and S21-W01 deterministic replay diagnostics. Identify acceptance already satisfied vs missing. Recommend minimal source-grounded additions that can proceed alongside full S06/S04 custody.
|
||||
|
||||
## 3. Scope and non-goals
|
||||
No implementation, new M02 terrain, mesh engine overhaul, native performance claims, general benchmark infrastructure or speculative production hooks. Preserve S18 title/rules changes and S06 current schema.
|
||||
|
||||
## 4. Files to inspect
|
||||
Read docs/plan/milestones/M01.md, systems/S01,S17,S21; app/viewer_win32.cpp pump_session/scene/view/HUD/camera/modal/WM_PAINT/WM_TIMER, app/d3d_scene_win32.* and public draw interface, existing client_* smoke and tests; engine worker_pool/world scheduling/hooks, runtime/dispatcher, tests/replay_tests.cpp/executor_tests.cpp/runtime_tests.cpp, benchmarks as pertinent.
|
||||
|
||||
## 5. Write ownership and coordination
|
||||
Write scope: none
|
||||
No mutations/builds/remote/children or Serena switch. Root plans separate branches, S18 owns title and profile logic, S06/S04 own inventory world paths. Use current root graph only after coverage check and read missed lines.
|
||||
|
||||
## 6. Implementation or investigation approach
|
||||
S17 identify how to prepare/pin immutable frame data once, main+child/software/D3D and nested UI callbacks, decouple scene refresh from event/network pump and authoritative 50 ms tick, avoid busy loop/rebuilding expensive static geometry solely for unchanged state, camera movement during gated world and file work. Match existing Win32 design and keep title/minimize/pause behavior; future D3D chunk cache is M02. State how real harness could assert camera changed and original tick stayed fixed without treating Wine fps as native.
|
||||
|
||||
## 7. Interfaces and data contracts
|
||||
S21 locate how last-item/resource arbitration relates to actual parallel batches and stable tie order. Design test/harness that PROVES opposing order of completed tasks (not just ordering hook starts/sleeps) for an actual contested outcome and canonical state. If after callback needed, preserve WorkerPool completion/exception/move-only behavior and use least invasive grounded seam. Check stale results after load owner barrier, real two client idempotent and save+camera. Recommend first-divergent tick/ID (inventory/actor/job/command) reporting and repeatable command entry/tag. Avoid duplicated serializers that drift; existing current14 soon current15. Derive calls/files from source.
|
||||
|
||||
## 8. Dependencies and integration
|
||||
Align S17 renderer-owned files vs S18 title/client profiles and CMake/worker code ownership. S21 can adapt test golden canonical encoding immediately independent of future custody, document which invariants extend after body15. Flag any truly missing generic primitive and check pinned Void facilities before suggesting upstream issue.
|
||||
|
||||
## 9. Edge cases security and performance
|
||||
Check UI timers/window events after destroyed, minimized/hidden, modal subloops and GPU resource lifecycle/race. Race tests deterministic using bounded waits and release cleanup even on assertion. Never rely on exact Wine wall scheduling or declare physical 60fps. Prevent deadlocks at 2 workers or queue capacity 1.
|
||||
|
||||
## 10. Acceptance criteria
|
||||
1. Separate executable contracts with exact paths and acceptance. 2. Clear proof of forced completion and stale fencing/diagnostic usefulness. 3. Real GUI cadence event and pinning acceptance with labels and stable source ownership. 4. Mark which existing evidence suffices. 5. No broad refactors outside M01.
|
||||
|
||||
## 11. Verification commands and evidence
|
||||
Use git rev-parse HEAD; scoped graph search/trace and snippets plus coverage ranges. Read actual integrated CTest/GUI logs m01-viewer-{build,ctest,ui-smoke}.log and /tmp/stoneheart-milestones.xprJ2SVp/client_handlers_smoke.cpp. No builds needed.
|
||||
|
||||
## 12. Constraints and stop conditions
|
||||
Send first independent S17/S21 seam early. Avoid new protocol/settings, general policy changes or altering product contracts in design. No remote actions/children.
|
||||
|
||||
## 13. Authorization and decisions
|
||||
User authorizes complete roadmap and per-system development branches. Root owns product/integration/publication. Preliminary design may proceed while S18 title and S06 custody progress.
|
||||
|
||||
## 14. Return format
|
||||
Return M01-P6 READY/PARTIAL per system, current verified behavior, scope/paths, exact measurable tests, remaining gaps/dependencies and likely performance implications.
|
||||
@@ -46,3 +46,11 @@ User authorizes complete plan and system/milestone commits/MRs accumulating on r
|
||||
|
||||
## 14. Return format
|
||||
Return M01-V10 separate S16/S18 findings with actual tests, changed paths and limitations. No children.
|
||||
|
||||
The S16 adapter has been integrated at `aa4e271` (parents `60154bd` and `09545bf`). Recheck the transport, legacy codec and test blobs against the reviewed branch, confirm the absence of merge edits to the owner or file adapter, and inspect `m01-lan-{build,ctest}.log` before publication. This additional check is read-only. The combined suite passed 106 core and 9 LAN tests.
|
||||
|
||||
Stage A passed the integrated review at `aa4e271`. For stage B inspect the actual tracked and new S18 files in the `s18` worktree based at `eef69ca`, including `viewer_session`, the Win32 entry point, CMake and the viewer suite. Inspect `client-{build,ctest,ui-smoke}.log` and `client_ui_smoke.cpp` under the temporary evidence directory above. The smoke used three real viewer processes with isolated save data. Check title, modal navigation, successful and failed load, guest transitions and truthful pending-blueprint outcomes. The contract still distinguishes the initial compiled default profile from the separately scheduled S19 selection. Return a defect report or READY for S18 without changes to the checkout.
|
||||
|
||||
Stage B initially required three corrections. Recheck the finished fixes for identity after modal demolition, rejected guest rejoin preserving the retained replica, and ticking acknowledgements across fault recovery. Inspect the updated committed-quantity and request-path checks in `client_{handlers,regression}_smoke.cpp`, the corresponding `client-{handlers,regression}-smoke.log`, the final viewer build, the three-process smoke and `client-ctest.log` (99 core, 9 LAN, 10 viewer). Separate integrated audit follows when root supplies the merged ref.
|
||||
|
||||
Stage B fixes passed review and were committed as `b7f18c0`. Integrated commit `db0a872` has parents `5354241` and `b7f18c0`. Confirm that the resident panel uses approved resource/storage/production IDs while the view remains pinned, both UI and core suites register, and the merged application’s three-process smoke passed. Check `m01-viewer-{build,ctest,ui-smoke}.log` under the temporary evidence directory.
|
||||
@@ -0,0 +1,50 @@
|
||||
# Review durable order identity and compiled colony profiles
|
||||
|
||||
Task ID: M01-V11
|
||||
Role: astra_reviewer
|
||||
Status: READY
|
||||
|
||||
## 1. Context and baseline
|
||||
Independent review in two phases. S04-01 isolated worktree s04 based 4ba64f7 with production order IDs, body14 and outer checkpoint2, existing schema1 real fixture. S19-02 isolated s19 based 60154bd with first optional package/profile, old default retained. S19 and S04 are expected to touch adjacent World declarations/CMake; root will supply combined refs for final checks. Baseline S16/S06/S15 already published.
|
||||
|
||||
## 2. Objective and deliverables
|
||||
Provide separate disposition for actual S19-02 and S04-01, then for a root-supplied integrated result if requested. Alert root quickly on reproducible failure before workers retire.
|
||||
|
||||
## 3. Scope and non-goals
|
||||
S19 backend, old/new data and S04 current changes including codec, command handling, real placement/reservations and lifecycle. S18 screen/selector verification belongs to a separate client review. This review covers the public core seams that later UI calls.
|
||||
|
||||
## 4. Files to inspect
|
||||
Inspect actual tracked/untracked files in sibling worktrees /home/faumaray/Projects/stoneheart_at_home-worktrees/{s19,s04}, including all new headers/sources/tests, full surrounding world, checkpoint/readers, rules_manifest, first_colony, command_dispatcher, changed CMake and docs; baseline legacy tests + new fixtures actual consumed bytes. Read contracts S04-01/S19-02 there and root M01-F6.
|
||||
|
||||
## 5. Write ownership and coordination
|
||||
Write scope: none
|
||||
No mutations/builds/remote postings or children. Parent owns commits/resolution. Use direct scoped reads for separate worktrees, shared root graph with coverage/direct missed lines if used. Do not change project activation.
|
||||
|
||||
## 6. Implementation or investigation approach
|
||||
S19 audit exact old default manifest/hash, optional package deterministic compile of real recipes vs forged/missing/additions and unsupported profiles, factory UUID/canonical rules, no mutable after-start rule switching. Check active staged optional refusal, default raw/simple/inactive/saved historical compatibility, actual input requirements/duration simple vs staged, finished beds and room. S04 review full ID allocation, batch production scheduling incl replenishment simulated post-demolition, before/after failures transactional, exact Busy narrow no domain next seq mutation; new ID in all actor references, cancellation, finishing order and find; explicit codec boundaries, bounds/duplicates/noncanonical/high-water/dangling, v1 authentic + modern pair and replay.
|
||||
|
||||
## 7. Interfaces and data contracts
|
||||
Public profile functions colony_rules/compile_colony_rules/make_colony_checkpoint/validate_colony_checkpoint and staged/default initializers preserve calling contracts; strict profile policy only at game/client gate, generic codecs/runtime remain reusable. ProductionId 0 absent, MAX exhausted with last valid MAX-1. Compare both double dispatch (legacy/direct/modern) where relevant to tests.
|
||||
|
||||
## 8. Dependencies and integration
|
||||
Order of branch signoff independent. On integrated stage confirm the raw/outer and profile gates and all added tests coexist under root CMake/World changes. Native hardware/real LAN separate. Root will send ready marker and evidence directory for each phase; do not approve unseen results.
|
||||
|
||||
## 9. Edge cases security and performance
|
||||
Watch O(N²) references in hot/hostile save path, exhaustion partial mutations after storage erasure/cabin terrain / counters/room placements, v13 and LAN11 byte drift, accidental implicit fallback on unauthenticated or modified data, restoring historical default simple and optional staged mismatch. Confirm authentic fixtures frozen using prechange binary; never log private data.
|
||||
|
||||
## 10. Acceptance criteria
|
||||
1. Separate READY/CHANGES_REQUIRED per component with concrete reproduction and severity. 2. Compare targeted/final logs and actual old corpus bytes, not just worker report. 3. Root integration evidence after selected branches merged must identify any new cross-contract issue. 4. Document unverified native/product gaps.
|
||||
|
||||
## 11. Verification commands and evidence
|
||||
Use git -C <wt> rev-parse HEAD; git -C <wt> diff --check and --stat; read status/new paths and inspect source directly. Inspect /tmp/stoneheart-milestones.xprJ2SVp/profile-{baseline,tag,ctest,compatibility}.log and production-id-{final-tag,ctest}.log plus archived production replay/corpus logs as provided. For merge phase compare relevant actual branch/HEAD blobs and final CTest logs.
|
||||
|
||||
## 12. Constraints and stop conditions
|
||||
Give findings as soon as evidence warrants; no remote or code writes, no plan beyond requested changes. Hold component approval if final tests not yet recorded or actual source still changing. Two failed same-cause fixes escalate via root.
|
||||
|
||||
## 13. Authorization and decisions
|
||||
User authorizes roadmap/push/MRs/upstream issues; root alone owns those actions. Preflight M01-F6 explicitly passed under default simple/inactive compatibility policy and scoped capacity exception contract.
|
||||
|
||||
## 14. Return format
|
||||
Return M01-V11 S19/S04 separate verdict, file/line, trigger, actual tests/artifacts and remaining gaps. Later verify corrected diff or integrated refs when supplied.
|
||||
|
||||
Both component reviews returned READY. Audit integration commit `a8cd7bb`, parents `9a248c3` (which includes S19 `2759563`) and S04 `2a3ec92`. CMake kept both new test sources during conflict resolution. Check the merged World initialization and stable production fields, old/new checkpoint and profile behavior, selection tests using the real current encoder, and the unchanged legacy host gate. Windows x64 logs `m01-orders-profiles-{build,ctest}.log` cover 122 core and 9 LAN cases. S18 initial viewer and follow-up title selection have separate reviews. Scope here is the integrated core and runtime LAN behavior.
|
||||
@@ -0,0 +1,54 @@
|
||||
# Review atomic pickup and the title profile selection
|
||||
|
||||
Task ID: M01-V12
|
||||
Role: astra_reviewer
|
||||
Status: READY
|
||||
|
||||
## 1. Context and baseline
|
||||
S06-02 at sibling s06 a8cd7bb plus implemented checkout. Targeted quantity tag 14, whole 136 core+9 LAN at isolated branch and two prior corpora. S18-02 at sibling s18 e6a01be in progress. Each had explicit M01-F7 preflight corrections. Root will signal when to inspect S18 implementation and integrated refs.
|
||||
|
||||
## 2. Objective and deliverables
|
||||
Independently review actual atomic pickup now, title/profile integration when ready, then combined branch evidence before remote publication.
|
||||
|
||||
## 3. Scope and non-goals
|
||||
S06 subset meal/construction stop only and preserved direct recipe processing; S18 visible title selection, exact compiled acceptance/host gates, old profile compatibility. Durable custody in design F8 is separate.
|
||||
|
||||
## 4. Files to inspect
|
||||
Read root M01-F7, sibling s06 S06-02, its new inventory_transaction.hpp/.cpp, narrow World integration, actual new quantity_transaction_tests.cpp/CMake/docs, contextual World/WorldSave/Immutable runtime. For later S18-02: actual title_screen_win32/viewer_win32/viewer_session/tests, S19 factory/validator, LAN and GUI/handler smokes.
|
||||
|
||||
## 5. Write ownership and coordination
|
||||
Write scope: none
|
||||
No mutations/builds/remote posts/other agents or Serena switch. Root publishes and owns merges. Direct scoped worktree source incl untracked files mandatory; shared root graph with range checks only when relevant.
|
||||
|
||||
## 6. Implementation or investigation approach
|
||||
Pickup verify one storage at the current stop, multiple and nonadjacent duplicate line aggregation, no underflow/overflow or invalid type indexing, exact target count, checked final storage capacity including one first-ingredient output reservation at the correct stop. Late rejection leaves original count/slot inventory, routes/cursor/state from pickup entry. Ensure commit has no allocation/throw, erases correctly and preserves stack order, body14/raw13/LAN11 outputs unchanged. Ensure tests enter real meal/multistop/carpentry and runtime fault behavior and direct finish_production is preserved.
|
||||
|
||||
## 7. Interfaces and data contracts
|
||||
S18 later validate title-only New choice, accurate simple Miner description/controls, both initial and latest async candidates use accepted compiled profile & 32×32, historical default simple/staged/inactive, malformed latest after superseded prepared candidate, exact-default legacy host both immediate/deferred/after modal and explicit pending-load refusal before listener effects; S18-01 guest rollback/modal epoch and ticking fixes remain.
|
||||
|
||||
## 8. Dependencies and integration
|
||||
Send independent verdicts as available. Root may request follow-up integrated comparisons via updated refs/log paths. Wait for actual S18 ready marker; no future-code signoff.
|
||||
|
||||
## 9. Edge cases security and performance
|
||||
Check arithmetic touched only accepted input, multiple erased stack lifetime, max 11 types vs unbounded input lines, true atomic output-slot commit, current state unchanged after failures, actual compiled probes and real Win32 entry. Test data mutations must remain scoped to fixtures. Do not equate Wine with native Windows.
|
||||
|
||||
## 10. Acceptance criteria
|
||||
1. Separate READY/CHANGES_REQUIRED per component. 2. Source-grounded findings with concrete triggers/severity. 3. Confirm actual logs and golden files/GUI smoke. 4. Integrated review only when refs supplied.
|
||||
|
||||
## 11. Verification commands and evidence
|
||||
git -C <wt> status/rev-parse/diff --check; read new source and relevant tracked full contexts, /tmp/stoneheart-milestones.xprJ2SVp/quantity-{config,build,rebuild,tag-final,ctest,probe-build,golden}.log and actual checksums. S18 final logs will use client-profile-* in same temp directory.
|
||||
|
||||
## 12. Constraints and stop conditions
|
||||
No code/Git/remote changes; if a blocking defect appears report promptly, then re-review actual corrected source on request. Do not assume dry approval of new receipt registry or future schema15.
|
||||
|
||||
## 13. Authorization and decisions
|
||||
User authorizes roadmap/push/MRs/upstream issues; root owns all external actions. Prescreen fixes incorporated before implementation.
|
||||
|
||||
## 14. Return format
|
||||
Return M01-V12 separate S06/S18 verdicts, real files/paths/tests, exact remains and native caveats, later integrated check as assigned.
|
||||
|
||||
The S06 component passed and is committed as `3c997ed`. Compare integration `66af7c5` (parents `e6a01be` and `3c997ed`) to each parent. Inspect actual `m01-quantity-{build,ctest}.log`: Windows x64 under Wine passed 136 core, 9 LAN and 10 viewer tests. S18-02 is still a separate pending review.
|
||||
|
||||
The integrated S06 check passed. S18-02 now has finished production changes against `e6a01be` in the s18 checkout. Inspect both real title/handler sources in the temporary evidence directory and `client-profile-*` logs, including a real two-process title choice/save/open, normal GUI regressions, held-load Host refusal and 14 viewer cases. Validate the actual six edited files, costs and initial/async gate along with the compiled profile and LAN boundaries.
|
||||
|
||||
The S18 component passed and is committed as `180506d`. Integrated `37fb6a8` has parents `f6493e2` and `180506d`. Inspect the combined selector/quantity source against those parents, CMake and `m01-selection-{build,ctest,ui}.log`. The real application smoke used the executable in the integrated build directory.
|
||||
@@ -0,0 +1,52 @@
|
||||
# Audit deterministic completion evidence and immutable presentation frames
|
||||
|
||||
Task ID: M01-V13
|
||||
Role: astra_reviewer
|
||||
Status: READY
|
||||
|
||||
## 1. Context and baseline
|
||||
S21-01 sibling s21 at 66af7c5 with new optional success hook and actual replay/fault barrier tests; branch final pass imminent. S17-01 sibling s17 same base with immutable packet/render caching and test target in progress. Original contracts S21-01/S17-01 and preflight F9/P6. Root cumulative currently 5a64a27 includes S18-02 profile chooser.
|
||||
|
||||
## 2. Objective and deliverables
|
||||
Review CPU observer/real replay/diagnostics and independent GUI presentation as separate completed components and later combined integration. Send all actual blocking findings immediately.
|
||||
|
||||
## 3. Scope and non-goals
|
||||
S21 worker adapter and tests/diagnostics/docs; S17 frame packet creation, D3D mesh/upload, lifetime/timer and actual test path. S06 custody15 beyond scope except future compatibility noted.
|
||||
|
||||
## 4. Files to inspect
|
||||
Inspect actual tracked/untracked files and exact contracts in siblings. S21 world.hpp/world.cpp stage layout, WorkerPool submit/admit, tests/executor/replay/runtime, new diagnostics, end-to-end old corpora and logs. S17 actual Win32 handlers, scene packet and D3D, tests/viewer_frame_smoke.cpp, CMake, involved S18 session/GUI, Win32 smoke and docs.
|
||||
|
||||
## 5. Write ownership and coordination
|
||||
Write scope: none
|
||||
No mutations/builds/remote posts/other agents or Serena switch; siblings outside root graph require direct source. Check diff --check and new source separately.
|
||||
|
||||
## 6. Implementation or investigation approach
|
||||
S21 success-only invocation (void/value/reference/move-only, throws, overload and before_submit/before_execute failure), original no-hook semantics and capacity. Validate opposing actual completions (two real candidate calculations, separate driver/hook release), lower ID winner, serial berry claim vs parallel advancement, no flakiness/deadlocks, stale load barrier and modern Current14, domain mismatch reports and tests incl byte fallback; inspect fixture/scoped source and actual logs.
|
||||
|
||||
## 7. Interfaces and data contracts
|
||||
S17 after ready marker verify one immutable prepared packet held across nested callbacks even during release/install, candidate not sampled while changing before consumed Replaced, owned overlays and HUD, true camera-only reuse of prepared physical geometry and GPU upload keyed over all visuals incl reset, no extra work hidden/resized/destroyed; original camera input, GUI titles/profile and normal LAN/events still work. Check actual settled tests including two real windows, blocked file/owner, saved content, offscreen/native fallback and helper includes.
|
||||
|
||||
## 8. Dependencies and integration
|
||||
Stage A S21 ready first; stage B only on finished status, separate integrated approvals requested later. No sign-off until actual cross-component evidence and fixes are available.
|
||||
|
||||
## 9. Edge cases security and performance
|
||||
Pay particular attention to return category/dangling references, accidentally recording pre-completion, capacity1 coordinator deadlock, exceptions in optional hook, tests changing data outside owner. For S17 camera/cursor geometry keys, offscreen rendering and clipping/nested frames, pending parent/child window messages, backend recreation and save/peer replacement while rendering. Do not equate Wine with native Windows.
|
||||
|
||||
## 10. Acceptance criteria
|
||||
1. Separate READY/CHANGES_REQUIRED per component. 2. State source/trigger/severity and corrective acceptance per defect. 3. Verify actual logs with issue #15 link and stable old corpora, new frame target and prior GUI smoke. No unsupported physical 60fps claim.
|
||||
|
||||
## 11. Verification commands and evidence
|
||||
Use git -C <wt> rev-parse/status/diff --check; read new files and surrounding actual consumers. In /tmp/stoneheart-milestones.xprJ2SVp inspect s21-replay-* and s17-frame-* logs and harnesses once supplied. Eventual merged refs and logs will be appended.
|
||||
|
||||
## 12. Constraints and stop conditions
|
||||
Check actual completed source, no early approval of another component. No source/branch/Gitea changes/children. After corrective commit re-audit relevant behavior per root instructions.
|
||||
|
||||
## 13. Authorization and decisions
|
||||
User authorizes all milestone/system development and Gitea, root owns all external operations; published reusable missing completion test support upstream #15 and existing publication issue #5.
|
||||
|
||||
## 14. Return format
|
||||
Return M01-V13 S21/S17 independent findings, inspected source/logs/limits, then integrated recheck when supplied.
|
||||
|
||||
S21 branch `ef980af` passed component review. Integrated root commit `048268a` has parents `5a64a27` and `ef980af`; inspect `m01-replay-{build,ctest}.log` and check its actual merged adapter, registered suites and unchanged core/GUI. S17 code and docs have also frozen in the sibling worktree at the original base plus working source. Read the actual committed-path smoke source, all tracked edits, and `s17-frame-*` logs. Verify the corrected pre-Replaced fence and stable rendering/cache/lifecycle conditions before branch approval.
|
||||
|
||||
Final S17 integration `455630f` joins reviewed `1cf8bd0` and `e9e7e82`. Cross-check S18 title/profile/host eligibility and S17 packet replacement, timer, GPU and cleanup against both parents. The build, verbose four-target CTest and separate multi-process real profile smoke are in `m01-frame-build.log`, `m01-frame-ctest.log` and `m01-frame-profiles.log`.
|
||||
@@ -0,0 +1,48 @@
|
||||
# Review finite voxel region contracts before implementation
|
||||
|
||||
Task ID: M02-F1
|
||||
Role: astra_reviewer
|
||||
Status: READY
|
||||
|
||||
## 1. Context and baseline
|
||||
Read-only preflight of M02-P1 initial design from actual 455630f M02 worktree. The signed 32³ sparse page foundation is independent of M01 custody 539cea0 now in progress. Existing renderer already uses z as vertical height via x−y, (x+y)−z and existing viewer picks the z=0 plane. Library first M02-R1 confirmed pin 7b0fea6, upstream #11 signed division and #14 sparse atomic edits, #12 ray traversal, #13 revision readsets, #10 RNG; actual public math/binary/hash available.
|
||||
|
||||
## 2. Objective and deliverables
|
||||
Independently decide whether bounded S02 geometry/generation contract is safe to implement now. Review the later S03/normal runtime/save/presentation boundaries insofar as they constrain S02 data. Send foundation verdict early; root may later supply planner final addendum.
|
||||
|
||||
## 3. Scope and non-goals
|
||||
Only M02 correctness preflight with first S02 slice priority. No implementation, release/PR acceptance, M03+ design or approval of unchecked future code.
|
||||
|
||||
## 4. Files to inspect
|
||||
Read real M02 worktree docs/agent-workflow/tasks/M02-P1.md, M02-R1 and plans M02/S02/S03/S15/S17/S18, void-library.md; root existing world.hpp, world.cpp WorldState::capture, worker_pool, world_save and checkpoint, app/map_camera.hpp, d3d_scene_win32.cpp shader, viewer_win32.cpp pick_grid, first_colony and actual tests; private current15 in /tmp/stoneheart-milestones.xprJ2SVp/combined-custody. Inspect exact graph root only if relevant; direct sibling sources required.
|
||||
|
||||
## 5. Write ownership and coordination
|
||||
Write scope: none
|
||||
No mutations/builds/remote posting, shared project switching, user contact or children.
|
||||
|
||||
## 6. Implementation or investigation approach
|
||||
Attack proposed NEW VoxelRegion/value view with nonzero RegionId, int32 voxel xyz, finite half-open bounds, ordered key directory/sharing immutable 32³ pages, generator keyed by exact seed+version+absolute xyz, queries separate outside/unloaded/loaded air. Page publication precedes ready only at logical designated step. Edits validate all expected revisions/bounds/materials/caps/unsupported operations, finite canonical order and no partial mutation, publish touched revisions once and invalidate face neighbors without fictitious content changes. Focus on material id stability, thin bounds intersecting pages and border operations. Query correctness at both signed extremes and boundary examples, no pointer/reference mutation. Check which exact domain is expected to be represented.
|
||||
|
||||
## 7. Interfaces and data contracts
|
||||
Review ownership/constructor/geometry exposure, immutable page pointers vs mutable alias to page/cache/directory, exact all-or-nothing publication, result visibility/cache invalidation incl reads of inactive/neighbors, validity of one stable geometry revision for render and path when head changes due to activation/deactivation. Propose minimal interfaces and stable tests without duplicating future WorldState. Check D3D renderer z-up and slice/face tie contract.
|
||||
|
||||
## 8. Dependencies and integration
|
||||
Foundation worker has isolated file ownership in NEW voxel_region.hpp/cpp/test plus CMake and S02 docs. World/runtime/save protocol integrating with S15/16 requires final agreed schema and cannot clobber S06 custody15. Preserve protocol11 by explicit representability; original 2D first colony must remain readable/playable.
|
||||
|
||||
## 9. Edge cases security and performance
|
||||
Negative division at INT_MIN and max half-open bounds, dirty neighbor overflow at extreme chunk ids, seed sign/ordering/algorithm version, bounded page/batch memory and worst-case old snapshot retention, revision rollover/admission, no-op/duplicates/conflicting expectations; negative/zero ray incl edge tie, stale auth, work/tick exposure, failed chunk activation/crossing. Differentiate genre policies/materials and requested Void issues.
|
||||
|
||||
## 10. Acceptance criteria
|
||||
1. READY or BLOCKED with precise mandatory first-slice fixes and testable criteria. 2. State if parallel independent implementation is sound within compiled M02 base before M01 finished. 3. Capture edge behavior and feasible tests for generation, bounds, stale atomic recompute, immutable view, deterministic batch and subsequent consumers. 4. Mark unknown physical target verification. Do not review a future code diff prematurely.
|
||||
|
||||
## 11. Verification commands and evidence
|
||||
Read-only git status/rev-parse and source refs in the M02 and combined worktrees. Compare pinned source with M02-R1 and note no binary evidence unless reading actual existing logs. Project index root-only; direct reads for sibling files. Later CTest should use exact Windows x64 GCC16/Wine test setup in M02-P1.
|
||||
|
||||
## 12. Constraints and stop conditions
|
||||
No approval of M01 scope or M02 implementation, no code, no Git/Gitea changes/children. If a substantial missing contract is identifiable, provide counterexample and precise remedy without tacking on speculative features.
|
||||
|
||||
## 13. Authorization and decisions
|
||||
User requested end-to-end milestone implementation and library gap filing. Preflight gates first edits, not engineering judgment on reversible local choices. Root integrates findings into worker specs and owns upstream effects.
|
||||
|
||||
## 14. Return format
|
||||
Return M02-F1 preflight with earliest foundation assessment then notes for remaining consumers, actual source references, required tests and stop conditions for implementation.
|
||||
@@ -0,0 +1,48 @@
|
||||
# Design the first playable editable voxel region and its integration
|
||||
|
||||
Task ID: M02-P1
|
||||
Role: astra_planner
|
||||
Status: READY
|
||||
|
||||
## 1. Context and baseline
|
||||
The user approved implementing M00–M12 on milestone and system branches. M01 currently provides a 50 ms authoritative World, immutable snapshots, authenticated commands, released rules profiles, protocol11 and modern checkpoints. M02 worktree at 455630f has S17 immutable frames and S21 real scheduler tests. Local M01 candidate 539cea0 adds modern raw15/checkpoint3 transfer persistence. An independent pin/API audit M02-R1 at Void 7b0fea6095f603f9e1904f66dfdc7752f4be4792 found library gaps reported as Void/Library #10–14. This is a preparatory design while M01 exit evidence is in flight.
|
||||
|
||||
## 2. Objective and deliverables
|
||||
Provide actionable dependency boundaries for M02 and the first implementable S02 region/chunk/component that can be built now without conflicting with M01 custody work. Continue to cover S03, S17/S18, S15 and normal owner/runtime end to end so the first terrain output has real consumers.
|
||||
|
||||
## 3. Scope and non-goals
|
||||
Read-only milestone architecture and phased, playable acceptance. Focus limited M02 editable voxel scenario through two levels and chunk edge. Defer M03 colony storage/building changes, water, other worlds, plugin changes and release. No arbitrary lowering of approved roadmap scope or new UI product choice.
|
||||
|
||||
## 4. Files to inspect
|
||||
Inspect docs/plan/milestones/M01.md and M02.md; docs/plan/systems/{S02,S03,S15,S17,S18,S21}.md, docs/plan/void-library.md and M02-R1; engine/include/settlement/core/{world,simulation_runtime,command_dispatcher,worker_pool,deterministic_rng}.hpp and world/first_colony/world_save CPU paths; app/d3d_scene_win32.*, map_camera.hpp, viewer_win32.cpp, tests/frame/replay/identity/checkpoint. Use actual names in results. Read sibling custody.hpp and checkpoint.hpp at combined 539cea0 to avoid schema collision. No fetching private data outside project.
|
||||
|
||||
## 5. Write ownership and coordination
|
||||
Write scope: none
|
||||
No edits, branch/remote ops, builds that modify worktrees, project switch or children. Parent persists results. Root and sibling agents are working in separate checkouts. For isolated M02 use direct files and avoid changing shared Serena project.
|
||||
|
||||
## 6. Implementation or investigation approach
|
||||
Map owner/tick/frame/file architecture, deterministic generation keyed by signed world location, gates for snapshots/cache and async activation. Specify finite 32³ sparse page representation and signed Euclidean division, fatal and retriable edit paths, exact row/coordinate order, native Win32 interaction scenario, known old-save/old-LAN behavior and how these can be tested using real consumers. Identify the first S02 slice that can receive an independent concrete coding contract at once; send it early.
|
||||
|
||||
## 7. Interfaces and data contracts
|
||||
Propose NEW clear types and methods by responsibility with essentials only: region identities/int coords with z up, bounds/limits, material query/source/support+edit revision set and undo on failure, copy-on-write pages immutable to snapshots, deterministic per-chunk source and edit overlay; S03 use cases incl stable ties, minimum profile/door/stairs and consulted revision sets incl misses and neighbors; ray/pick face from D3D Y-up conversion and actual commands; M02 persistent version/generator identity; reconcile normal M01 World lifecycle, actual public source/test consumers and authored test scenario. Distinguish proposed APIs from existing ones.
|
||||
|
||||
## 8. Dependencies and integration
|
||||
Root reconciles M02-R1, planner, independent preflight and starts S02 in an isolated branch before coupling to mutable M01 sources when safe. Make ownership/dependency ordering and concrete integration points clear. Source-only private S06/S15 candidates must never be treated as published.
|
||||
|
||||
## 9. Edge cases security and performance
|
||||
Bound coordinate overflow (INT_MIN, ±32), sparse memory and checked edit count, stale/mixed revisions, border invalidation, optimistic deterministic admission/queued jobs, signed normal/cell at equally crossed faces, old saves and LAN projections of edited maps, delayed/out-of-order and corrupted chunk I/O, camera/view consistency and finite scheduling. Respect pinned Void API/tests and replacement cases for #10–14 in repository matrix.
|
||||
|
||||
## 10. Acceptance criteria
|
||||
1. Concrete HOW/WHAT for S02 first worker including new files/headers/CMake and behavioral tests with cross-boundary negative coordinates, immutable snapshots, failed multi-page edit and independent generation. 2. Bounded follow-on packages S03, authoritative/edit/tick+save, real UI and exit verification with actual dependencies. 3. Identify genuine missing library contract only after checking pin and issues. 4. Normal small scenario is visible, editable, traversable and survives save/restore across thread order.
|
||||
|
||||
## 11. Verification commands and evidence
|
||||
Read-only git -C <m02> rev-parse HEAD/status/diff and git -C /tmp/stoneheart-milestones.xprJ2SVp/combined-custody show as needed; use direct source in sibling worktrees. Give real proposed CMake GCC16 cross and CTest commands for later workers based on /tmp/stoneheart-verify.KoZwE4o8/env.sh and existing target. Native Windows cannot be asserted from Wine.
|
||||
|
||||
## 12. Constraints and stop conditions
|
||||
Stop and report if a required product choice truly blocks first slice; use reversible decisions matching approved M02 otherwise. No source mutation, speculative library ticket, user messages, or children. Do not claim test execution.
|
||||
|
||||
## 13. Authorization and decisions
|
||||
User explicitly asks to implement all milestones, reuse library APIs and file concrete gaps. Root owns all side effects. User authorization already covers bounded M02 foundation and branch/MRs.
|
||||
|
||||
## 14. Return format
|
||||
Return M02-P1 PLAN with early immediately implementable S02 slice, dependency order/ownership, immutable contracts, concrete tests/risks/source refs and remaining evidence. No approval or merge decisions.
|
||||
@@ -0,0 +1,50 @@
|
||||
# Verify library support for voxel coordinates, chunks and surface picking
|
||||
|
||||
Task ID: M02-R1
|
||||
Role: astra_researcher
|
||||
Status: READY
|
||||
|
||||
## 1. Context and baseline
|
||||
Approved game roadmap, M02 follows M01 and calls for an editable finite voxel region with 32³ chunks, consistent coordinate/picking/navigation interpretation. No M02 code or branch started. Game root current 60154bd/aa4e271, Void exact CMake pin 7b0fea6095f603f9e1904f66dfdc7752f4be4792 confirmed equal upstream HEAD, source/tests available locally.
|
||||
|
||||
## 2. Objective and deliverables
|
||||
Prepare reusable API and missing-feature evidence so S02/S03/S17 can start under the user's Void-first dependency rule when M01 entry gates settle.
|
||||
|
||||
## 3. Scope and non-goals
|
||||
Read-only M02-specific official/pinned API audit, exact target semantics and minimal verification/issue ideas. Not a game implementation, upstream write, or M02 completion claim.
|
||||
|
||||
## 4. Files to inspect
|
||||
Inspect docs/plan/milestones/M02.md, systems/S02/S03/S17, prior void-library matrix and first_colony/world terrain/render picking, deterministic_rng.hpp. Pin clone /tmp/stoneheart-verify.KoZwE4o8/candidate/_deps/void_library-src including CMake modules, include and tests. Inspect official library headers before claiming absent.
|
||||
|
||||
## 5. Write ownership and coordination
|
||||
Write scope: none
|
||||
No mutations to tracked/user data, Git/remote writes, public issue creation or children. Parent owns upstream tickets. Temporary isolated compilation probe in /tmp allowed if evidence is genuinely needed; no editing any shared build dir.
|
||||
|
||||
## 6. Implementation or investigation approach
|
||||
Determine exact public support for (1) signed 3D integer coordinates with correct floor division at negative boundaries, checked conversion, fixed-size contiguous chunk index and 6 neighbors; (2) deterministic seed/coordinate hashing and stateful portable random streams with fixed parameters and import/state or existing game RNG; (3) bounded sparse/finite chunk storage, generation version/edit delta/revisions; (4) grid DDA/voxel surface hit and path invalidation by touched chunk revision. Test/document any claimed coverage. Distinguish math primitives to use directly from game-specific policy and genuinely reusable missing capabilities. Check actual dev/test modules/adapters on Windows x64.
|
||||
|
||||
## 7. Interfaces and data contracts
|
||||
Return concrete interface names when present with source/tests at pin and what they guarantee. Root needs precise issue titles, reproducible inputs and replacement tests for actual generic gaps only; avoid a broad request to build the entire game in a shared library. Cover local coords at -1/0/31/32, extreme ranges, 3D axis convention and cross-chunk picking ties.
|
||||
|
||||
## 8. Dependencies and integration
|
||||
M01 stable world ID/epoch/snapshot/checkpoint ownership upstream, future S02 data constructor and S17 ray picking consume that. No assumption M01 fully done; preparatory research only. Confirm whether upstream moved relative to pin via read-only ref if necessary.
|
||||
|
||||
## 9. Edge cases security and performance
|
||||
Do not suggest library nondeterministic RNG for authoritative state when serialization/stream portability absent. Observe D3D renderer right-handed coordinate/picking constraints locally, storage limits and floating vs integer choices needed. Cite files, no private data outside approved repo/library.
|
||||
|
||||
## 10. Acceptance criteria
|
||||
1. Separate supported modules with test evidence vs missing subcontracts; 2. Bounded ownership and exact replacement tests for future implementation; 3. Identify native/other gaps and M02 code dependencies. 4. Relay first actionable library finding early.
|
||||
|
||||
## 11. Verification commands and evidence
|
||||
git rev-parse HEAD and git -C <pin> rev-parse HEAD, targeted rg --files and rg -n on actual symbols and tests, project graph with coverage/direct reads for current app/World when relevant. Source /tmp/stoneheart-verify.KoZwE4o8/env.sh for any standalone Windows probe, no global changes.
|
||||
|
||||
## 12. Constraints and stop conditions
|
||||
Do not open remote tickets or implement new types; notify root with exact evidence. No speculation solely from CMake module names. No further agents.
|
||||
|
||||
## 13. Authorization and decisions
|
||||
User mandates Void support/issue linkage for real gaps; root authorizes this preparatory evidence in parallel with M01 work, without marking M02 started or complete.
|
||||
|
||||
## 14. Return format
|
||||
Return M02-R1 VERIFIED/PARTIAL, pinned paths/API/test names, minimal concrete missing-feature cases and upstream lookup/filing suggestions, native/target limitations.
|
||||
|
||||
The Windows x64 probe passed under Wine 11 with GCC 16.2. Native Windows and MSVC remain unverified. Numeric, canonical little-endian Binary fields, FNV-1a, seeded raw Xoshiro output and graph traversal limits are available on this target. Each missing reusable operation has its consumer and replacement check in the [dependency matrix](../../plan/void-library.md#подготовка-воксельного-мира-m02). Upstream records cover [restorable random streams](https://git.faumaray.com/Void/Library/issues/10), [Euclidean division](https://git.faumaray.com/Void/Library/issues/11), [grid ray traversal](https://git.faumaray.com/Void/Library/issues/12), [revision dependencies](https://git.faumaray.com/Void/Library/issues/13) and [atomic sparse volume edits](https://git.faumaray.com/Void/Library/issues/14).
|
||||
@@ -0,0 +1,50 @@
|
||||
# Implement immutable finite voxel regions and atomic multi-chunk edits
|
||||
|
||||
Task ID: S02-01
|
||||
Role: astra_implementer
|
||||
Status: READY
|
||||
|
||||
## 1. Context and baseline
|
||||
Actual isolated system/s02-voxel-world at 0d71bcf, parent milestone/m02-voxel-world. M02-P1 plan and F1 independently accepted first slice. Existing first colony WorldState copied on capture and flat terrain remains, renderer z-up. Cross-toolchain CMake pin 7b0fea6095f603f9e1904f66dfdc7752f4be4792. Void Math::Numeric checked arithmetic, Binary::Writer and Hash public, signed split/atomic pages absent and tracked upstream #11/#14. M01 final custody in isolated siblings, no overlapping source needed.
|
||||
|
||||
## 2. Objective and deliverables
|
||||
Build a tested, ready-to-integrate finite authoritative voxel region with deterministic versioned terrain, signed coords and immutable chunk pages, checked all-or-nothing multi-page edits and accurate surface invalidation. The first file consumers are S03 nav queries, S17 surfaces and M02 World/serializer/activation. Freeze a usable header early and send actual declarations to root.
|
||||
|
||||
## 3. Scope and non-goals
|
||||
Only memory representation, generation, prepared page installation, querying and edits for the finite one-region M02 foundation. No unrelated RNG, terrain viewer, WorldState or format edits, S03 path solver, resource ledger, gameplay or network. Input/outcome types below are NEW and may be named idiomatically.
|
||||
|
||||
## 4. Files to inspect
|
||||
Read docs/plan/milestones/M02.md, systems/S02 + S03, dependency matrix section M02 + actual pin headers/tests for Math/Numeric, Binary and Hash. Inspect world.hpp/world.cpp capture, default 2D semantics, actual 3D shader at app/d3d_scene_win32.cpp, CMake targets and registered Void::Testing suites. S06 / S15 provisional custody data unneeded. Read M02-P1/F1.
|
||||
|
||||
## 5. Write ownership and coordination
|
||||
Write scope: NEW engine/include/settlement/core/voxel_region.hpp; NEW engine/src/voxel_region.cpp; NEW tests/voxel_region_tests.cpp; CMakeLists.txt only two source/test entries; docs/plan/systems/S02.md
|
||||
Your isolated s02 checkout only. Others work in separate WTs, do not overwrite or revert their changes. No Git/remote operations, shared Serena switch, children.
|
||||
|
||||
## 6. Implementation or investigation approach
|
||||
Define checked nonzero uint64 RegionId, int32 xyz with z-up, int64 half-open endpoints verifying within [INT32_MIN,INT32_MAX+1], strictly positive volume per axis (finite coordinate bounds need not densely allocate), chunk/local split no -INT_MIN, x-fast 32³ index. Stable material identifiers air/soil/stone, configurable bounded resident pages (default256), edit count (default4096), and actual checked staging/result/directory sizes (default allow full bounded batch). Region copies or dedicated immutable views share complete directory/pages via const ownership; no retained mutable aliases or mutable raw span. Immutable generator candidate is keyed by metadata/coords, source initialized independent of job ordering, deterministic generator1 with plausible soil surface/stone below and canonical absolute-coordinate encoding via actual Void Binary/Hash, uses no shared RNG. Mask all cells outside partial region.
|
||||
|
||||
## 7. Interfaces and data contracts
|
||||
Ordinary query distinguishes outside bounds vs unavailable vs loaded air; returns stable coordinate/read stamp matching caller lifetime. Separate pure generation/preparation from explicit all-or-nothing publication so later M02 owner controls logical tick. Region may not install result from a different region/seed/generator/coordinate or expired expectation. Keep page/availability paths usable by future persistence. A bounded atomic edit requires exact revision expectations for each touched chunk (including no-op), rejects duplicate cells, unsupported material/coords/bad expectations before publishing. Empty/all-identical edit has no changes. Sort changed cells/pages and actual neighbor invalidations canonically; increment once per truly changed page, unchanged neighbors keep material stamp, loading must be observable by dependencies. Extreme revision denies change before first effect. No need for unload until a later consumer, if implemented prevent ABA with persistent stamp. Define what finite bounds/unavailable neighbor contributes to dirty key.
|
||||
|
||||
## 8. Dependencies and integration
|
||||
Host only builds Windows; unit checks linked in actual settlement_core_tests. Root merges S02 into M02 and cumulative only after review. Need write stable header before dependent S03/S17 and alert parent if implementation materially changes contract. Other workers own old World/codec/camera, never edit those. Local implementation explicitly references Void/Library #11/#14 in S02 docs with exact replacement tests.
|
||||
|
||||
## 9. Edge cases security and performance
|
||||
Widen origins, local indexes and neighbor math before conversion; avoid INT overflow/padding/endian and unbounded directory/grid construction. Bound working + staging memory before allocations and reject insufficient limits unchanged. Stage all pages and result list before final nonthrowing swap; preserve original content/pointer/revision on bad batch, allocation failure and MAX counter. External retained snapshots own memory separately, state its limit precisely. Prefer compact materials and deterministic column generation; full active 256 pages must not cause unrelated pages to be recopied on each edit. No nondeterministic unordered serialization or generation.
|
||||
|
||||
## 10. Acceptance criteria
|
||||
1. Exact split/join and x-fast indices at INT_MIN,−33,−32,−1,0,31,32,INT_MAX incl [max,max+1) and partial negative/extreme bounds. 2. Canonical full material content and revisions independent of forward/reverse/parallel preparation, real neighboring signed coordinate continuity/golden seed, precise different availability/air. 3. Two-page edit succeeds atomically and old view unchanged; stale second/unloaded/duplicate/unknown/budget/MAX fail unchanged, unchanged writes validate expectation and do not increment; correct face vs edge neighbor invalidation across boundaries. 4. No additional unlinked generic shim outside #11/#14; real release compilation and focused/full CTest, report actual footprint/copy behavior and evidence. 5. Document useful public operations in S02 and share frozen header.
|
||||
|
||||
## 11. Verification commands and evidence
|
||||
Source /tmp/stoneheart-verify.KoZwE4o8/env.sh. From YOUR worktree configure cmake -S . -B /tmp/stoneheart-milestones.xprJ2SVp/s02-voxel-build -G Ninja --toolchain "$SETTLEMENT_VERIFY/cross.cmake" -DBUILD_TESTING=ON -DCMAKE_BUILD_TYPE=Release -DFETCHCONTENT_SOURCE_DIR_VOID_LIBRARY:PATH="$SETTLEMENT_VERIFY/candidate/_deps/void_library-src". Build with cmake --build <that dir> --parallel 6, run ctest --test-dir <that dir> --output-on-failure and your targeted tests. Evidence required. Run --tag voxel-region at your build, complete CTest -V (coordinate any real windows via root) and git diff --check; logs /tmp/stoneheart-milestones.xprJ2SVp/s02-voxel-*.log. Native Windows beyond cross tests not verified. Test revision exhaustion via meaningful persistence/import or narrow deterministic seam without exposing an unchecked arbitrary setter.
|
||||
|
||||
## 12. Constraints and stop conditions
|
||||
Do not silently expand M02 to full renderer/World or change prior save formats. If dependency contract missing, verify pin plus check existing issues, report exact consumer/guarantee and root handles any filing. Two unsuccessful same-cause fixes escalate with original contract/evidence. No publishing or other checkout edits.
|
||||
|
||||
## 13. Authorization and decisions
|
||||
User authorizes all milestone/system coding, Gitea PRs and true Void gaps. Root chose region identity and finite signed z-up cells, M02 product decisions in milestone doc; planner/preflight complete for this slice. Concrete bounded storage/container choices delegated.
|
||||
|
||||
## 14. Return format
|
||||
Return S02-01 READY or PARTIAL, early frozen API and relevant coordinate/frame assumptions, controlled failure cases, working paths, actual verification counts/measurements/limits and remaining integration seams.
|
||||
|
||||
The M02 door uses two stable non-generated cell kinds, `MaterialId::DoorClosed` and `MaterialId::DoorOpen`, appended after Air, Soil and Stone. A closed door blocks body clearance; an open door and air permit clearance. Only Soil and Stone provide standing support. Publish NEW `voxel_blocks_passage(MaterialId)` and `voxel_provides_support(MaterialId)` queries for the navigation and presentation owners. Both halves of a door can be changed in the same checked edit batch. Invalid materials remain rejected. The generator produces natural materials only, and the gameplay owner controls who may operate or mine a door. Add tests for these shared semantics, both updating over a page boundary if applicable, and tell root when the adjusted header is frozen. This prevents a second source of door geometry, occupancy and invalidation in navigation.
|
||||
@@ -0,0 +1,52 @@
|
||||
# Find and revalidate settler routes across editable voxel chunks
|
||||
|
||||
Task ID: S03-01
|
||||
Role: sol_implementer
|
||||
Status: READY
|
||||
|
||||
## 1. Context and baseline
|
||||
Actual isolated system/s03-navigation worktree at 6d1123e has frozen region API voxel_region.hpp, S02 implementation/registration arriving from sibling before testing. M02-P1/F1 reviewed source/algorithm limits; M01 flat assignment_path keys are two-dimensional and World::step advances without revalidation. S03 is disjoint from existing World and S02 implementation. Void 7b0fea6095f603f9e1904f66dfdc7752f4be4792 supplies IndexedGraphView/bfs/shortest_path_unweighted WorkLimits. Generic consulted revision sets absent, already tracked #13.
|
||||
|
||||
## 2. Objective and deliverables
|
||||
Implement tested bounded 3D ordinary-settler path query, interaction positions, consulted effective chunk revisions and transition revalidation. Ready for the authorized M02 World movement/mining owner to consume; send actual frozen public API early.
|
||||
|
||||
## 3. Scope and non-goals
|
||||
Only new voxel navigation module, real standalone tests, CMake entries and S03 docs. Use shared S02 data; leave old flat A*, World/serializer/actual HWND/drawing to their assigned M02 consumers. No new navmesh, multi-region streaming, liquids/animals or future profiles. Do not copy any unfinished S02 source.
|
||||
|
||||
## 4. Files to inspect
|
||||
Read docs/plan/milestones/M02.md, systems/S02/S03, void-library.md and M02-P1/F1/S02-01; frozen engine/include/settlement/core/voxel_region.hpp at6d1123e, root engine/src/world.cpp assignment_path/advance, headers command_dispatcher.hpp::SessionIdentity (UUID epoch), CMake/tests. Official pinned Void/Algorithms/Graph.hpp plus tests in pinned tree, see real limits, edges, start==target early success.
|
||||
|
||||
## 5. Write ownership and coordination
|
||||
Write scope: engine/include/settlement/core/voxel_navigation.hpp; engine/src/voxel_navigation.cpp; tests/voxel_navigation_tests.cpp; CMakeLists.txt; docs/plan/systems/S03.md
|
||||
First three paths are new. In CMake add only your source, test and, if needed, a link to the already enabled Void::Algorithms target.
|
||||
Other people work in separate WTs; never overwrite/revert their work, never change shared Serena project. No Git/remote ops, children, edits to S02 files, existing World or M01.
|
||||
|
||||
## 6. Implementation or investigation approach
|
||||
Represent foot at one voxel, two vertical cells clear, support directly below. 4 horizontal cardinal neighbors with level/one-step up/down, no unsupported pure flight or diagonal wall/corner clipping. Evaluate the swept body under up/down (needed headroom over raised/descending transition). Reuse S02 voxel_blocks_passage/voxel_provides_support and stamps; DoorOpen+air passable, DoorClosed blocked; soil/stone support only. A stair flight is a sequence of supported steps. Provide single-hop validation and standing check from same queries as solver, and separate API for adjacent accessible task interactions (range/line of contact cannot mine through wall/above unreachable geometric separation).
|
||||
|
||||
## 7. Interfaces and data contracts
|
||||
NEW request/result includes region and session/incarnation from existing actual UUID type, bounded search volume/goals (deterministic ties), route/current to goal route semantics documented, cost, failure reason, sorted deduplicated consulted chunk stamps incl support/head/blocked/unavailable neighbours, and stale check via Region.matches + owner session. An unrelated edit must preserve result. Opening previously unavailable gateway invalidates negative result, same ID and numeric revisions after world reload still require new session. Distinguish invalid inputs, truly unreachable, unavailable/awaiting activation, boundary/budget and cancellation errors. Small finite known search uses Void::Algorithms::bfs or shortest_path on bounded IndexedGraphView; respect start==goal check before library fast path. For multi-goal choose canonical shortest (distance then stable coordinate and neighbor order); restrict result to reachable interaction positions. Do not allocate full coordinate extent on sparse huge region. Check vertex count, edges/step/aggregate scratch, size_t/int64 computations and bound read-set. Non-exhaustive clipping/budget must not masquerade as proven unreachable.
|
||||
|
||||
## 8. Dependencies and integration
|
||||
Parent gives compiled S02 implementation and test registration via local merge after worktree is sealed when ready. Can compile your TUs against header first; no mock replaces genuine final evidence. Future M02 authority, persistence, frame/picking will use foot positions/goal and read stamps. Protocol11/legacy file unaffected. Local revision set #13 to be linked with its exact replacement tests in S03.
|
||||
|
||||
## 9. Edge cases security and performance
|
||||
Include INT extremes/partial bounds/overflow, headroom at source+destination, missing vertical support in a different page, start==same blocked target, path/missing pages and time/epoch; cannot mutate captured VoxelRegion. Keep memory bounded by explicit realistic work limits; e.g. 256*32³ cells must not allocate 136MiB per worker to traverse a four-cell corridor. Check allocation failure/too many input goals gracefully. Avoid per-node heap allocations for bounded neighbor enumeration where appropriate. No hiding application bugs in arbitrary timeout/different path cost.
|
||||
|
||||
## 10. Acceptance criteria
|
||||
1. Real S02 volume route through two-cell open door and cross-chunk stair to upper interaction; closed door/headwall/no support block and reason. 2. Remove next future support while traveler still safe, route/stamps stale, next-hop rejects; reopen, route returns; unrelated chunk change preserves validation; unavailable-to-loaded negative becomes stale; new session stale. 3. Stable exact cost/goal/tie path on small fixtures vs independent exhaustive reference + multiple worker schedules, direct same-goal invalid case. 4. Explicit bounded-limit behavior before dense allocation/partial proof, integer extremes and deterministic sorted queried stamps. 5. Real cross-build/full tests with S02 and docs issue linkage.
|
||||
|
||||
## 11. Verification commands and evidence
|
||||
Source /tmp/stoneheart-verify.KoZwE4o8/env.sh. From YOUR worktree configure cmake -S . -B /tmp/stoneheart-milestones.xprJ2SVp/s03-navigation-build -G Ninja --toolchain "$SETTLEMENT_VERIFY/cross.cmake" -DBUILD_TESTING=ON -DCMAKE_BUILD_TYPE=Release -DFETCHCONTENT_SOURCE_DIR_VOID_LIBRARY:PATH="$SETTLEMENT_VERIFY/candidate/_deps/void_library-src". Build with cmake --build <that dir> --parallel 6, run ctest --test-dir <that dir> --output-on-failure and your targeted tests. Evidence required. After link run --tag voxel-navigation, full ctest -V and git diff --check with /tmp/stoneheart-milestones.xprJ2SVp/s03-voxel-*.log. Native Windows unavailable. Before full interactive CTest contact root to avoid simultaneous keyboard-driven smoke test.
|
||||
|
||||
## 12. Constraints and stop conditions
|
||||
No invented S02 or Void API; if integration contract insufficient, send precise new dependency to root and continue self-contained cases. No alternate user workflow, new external tickets, or duplicate library pathfinder. Two unsuccessful same-cause attempts escalate. No remote or children.
|
||||
|
||||
## 13. Authorization and decisions
|
||||
User requested all milestone/system coding, actual upstream library gaps and per-branch MRs. M02 architecture accepted ordinary one-cell-wide/two-tall profile, one step max; root handles publishing.
|
||||
|
||||
## 14. Return format
|
||||
Return S03-01 READY or PARTIAL, early stable interface for M02 owner, actual code/test limits, work bounds and cross-branch evidence including cross-boundary route/invalidation and distinct failure outcomes.
|
||||
|
||||
Review at `7a7ff32` found a confirmed negative-result bug. On a solid, loaded z=0 floor a downward candidate may sample an unloaded z=-1 support while the known solid destination foot conclusively forbids the transition. A two-high closed wall then appears to be waiting for unrelated activation. Retain the actual sampled stamps but classify missing data as a potential frontier only if the corresponding transition, standing goal or reachable continuation cannot already be ruled out. Add the walled-floor regression and a positive genuinely unavailable frontier. Check analogous search-boundary handling and real interaction targets. Keep the existing signature and scoped files.
|
||||
Independent interaction clipping finding at `17389b2`: a known blocked list of in-window contacts does not prove a global negative when additional valid interaction candidates lie outside the finite window and the reached search frontier can leave it. Reproduce in a flat 8×8×4 fixture, start (1,1,1), search upper.x=4, target stone (3,3,1), blockers (2,3,2), (3,2,2), (3,4,2) and (3,3,3). With a reachable contact at (4,3,1) the narrow search returns SearchBoundary; upper.x=6 must reach it. Preserve all prior fixed direct-goal and unknown-frontier contracts. Include cases without any traversable exit and with an unavailable exit, freeze actual before/after code and run 13 previous focused cases, new regression and full CTest under the shared GUI lock.
|
||||
@@ -0,0 +1,50 @@
|
||||
# Persist production order identities and allocate complete command batches atomically
|
||||
|
||||
Task ID: S04-01
|
||||
Role: astra_implementer
|
||||
Status: READY
|
||||
|
||||
## 1. Context and baseline
|
||||
Exclusive /home/faumaray/Projects/stoneheart_at_home-worktrees/s04 system/s04-jobs-reservations base 4ba64f7. WorldState includes capture, S06 durable storage/node refs. S15 envelope v1 accepts raw World v1–13. M01-P3/V9 identified all insertion and refusal paths including storage demolition replenishment and LegacyCabinPayload in S16. Upstream durable allocator #7.
|
||||
|
||||
## 2. Objective and deliverables
|
||||
Give every production order a persistent World-scoped ID, remove stored positional production references, preserve identity history in modern checkpoints while keeping original saves/wire exact, and make all order-allocating business commands reject exhaustion without partial effects.
|
||||
|
||||
## 3. Scope and non-goals
|
||||
Production identity, high-water mark, ABI/caller migration, modern raw/envelope generation and validated v1 import. Keep zero none, leave new stack/ownership/transfer records and broad economy behavior to later slices. Preserve historical default formatting/encoding and v11 public network.
|
||||
|
||||
## 4. Files to inspect
|
||||
Inspect world.hpp, world.cpp all insertion/erase/use sites and missing_carpentry_orders, world_save.cpp body/validate, checkpoint.cpp/.hpp/checkpoint_files.cpp, command_dispatcher.cpp catches LegacyCabinPayload, viewer resident detail, existing tests and old baselines. F3/F5, M01-P3/V9. Inspect/preserve exact pinned Void Numeric/Binary/Crypto and prior deterministic corpus.
|
||||
|
||||
## 5. Write ownership and coordination
|
||||
Write scope: engine/include/settlement/core/world.hpp; engine/src/world.cpp; engine/src/world_save.cpp; engine/include/settlement/core/checkpoint.hpp; engine/src/checkpoint.cpp; engine/src/command_dispatcher.cpp (only legacy cabin exhausted outcome); app/viewer_win32.cpp (resident production details only); tests/core_tests.cpp; tests/identity_tests.cpp; tests/replay_tests.cpp; tests/production_identity_tests.cpp (NEW); tests/checkpoint_tests.cpp; tests/checkpoint_file_tests.cpp; tests/session_tests.cpp; CMakeLists.txt; docs/plan/systems/S04.md
|
||||
Only touch listed affected tests/callers as needed. Other owners touch UI, files, profiles elsewhere. You are not alone; root integrates branches. Do not edit other worktrees/Git/Serena.
|
||||
|
||||
## 6. Implementation or investigation approach
|
||||
Add real ProductionId, immutable order identity, WorldState::next_production_id_, Agent::production_id (0 absent), bounded sorted lookup, erase without index repair. Centralize all order insertion incl queue_production and both direct PlaceRoom loops. Calculate exact whole ID requirement and incrementable successors before any command/domain side effect. Single and multi-order (bed, loom, workshop, rooms/furnishings, direct cabin and implicit replenishments) precheck numeric exhaustion as well as vector allocation. MAX terminal valid, last allocatable MAX-1. Calculate EXACT post-demolition missing carpentry counts across products/requirements WITHOUT erasing/mutating storage first, reserve all IDs before deleting stock or appending any order. If full batch cannot fit return nonmutating Busy with exact old storage/stock/sequence and counters. For LegacyCabinPayload use explicit testable pre-mutation exhaustion result/exception, narrowly translate THIS proven refusal to completed Busy in CommandDispatcher::apply, retain exact repeat while session remains healthy. Do not catch a generic error that could follow partial mutation. Other unexpected errors use F3 fault boundary. Avoid duplicated independent registries.
|
||||
|
||||
## 7. Interfaces and data contracts
|
||||
Default World::write_save(std::ostream&) still emits exact v13 bytes and historical positional links, old callers incl LAN11 unchanged. Add explicit modern World write mode v14 (new actual enum or method) using same codec/body, include stable refs / order IDs/high-water; now World::read_save handles appropriately. Checkpoint encode becomes schema2/modern body14. Decode authentic schema1/inner1–13 and schema2/inner14 only, verify signature & checksum using common codec, latest high-water after deleting last/highest/all survives. Historical import assigns IDs deterministically in vector order with next > live max; no new UUID on modern reload. Validate sorted unique nonzero ProductionIds, strictly larger next (MAX valid), referenced target existence/state before indexing. Keep envelope magic unchanged. Old file-adapter test hardcodes unsupported next value 2: change to actually unsupported value and retain a true pre-change v1 fixture, not just changing expected bytes. Tell root exact frozen API early.
|
||||
|
||||
## 8. Dependencies and integration
|
||||
Root owns final merge. S18 worker also touches UI but not resident-detail lookup; S19 profiles separate. File reader matches same signature and uses generic decode; ensure outer/inner pairing tests even when attacker recalculates both checksums. Registry consumers continue using const World. Use existing checked arithmetic; local implementation+replacement link Void/Library #7 in docs and allocation source where useful.
|
||||
|
||||
## 9. Edge cases security and performance
|
||||
Avoid O(N²) repeated scans of million-record parsed data; legacy index projection/import bounded as in S06. Active resident must keep same original order when lower deleted. All domain normal refusal keeps previous capacity/contents/command seq; last accepted identifier remains unaffected by vector erasure, world capture or save. Ensure no different command arbitration/legacy behavior on ordinary non-exhaustion. Preserve legal old v1–v13 payload behavior. Do not overwrite any user save.
|
||||
|
||||
## 10. Acceptance criteria
|
||||
1. Deleting lower/highest/all orders followed by v2 reload + allocating another never reuses IDs, actual mid-haul agent remains bound; corrupt ID/dangling/current combinations rejected. 2. MAX/MAX-1 single and multi batch incl room/cabin/stock demolition with multiple products, verify byte-identical complete current state/unchanged seq after Busy, and exact replayed cabin Busy with healthy runtime. 3. Authentic checkpoint v1 lower inner and v13 accepted, wrong pairing incl v1/14, v2/13 rejected with valid checksums. 4. Per-tick MODERN canonical replay including ID state across serial/2/6/12, old default v13/legacy benchmark data compare exact. 5. All cross suites pass.
|
||||
|
||||
## 11. Verification commands and evidence
|
||||
Source /tmp/stoneheart-verify.KoZwE4o8/env.sh. From YOUR worktree configure cmake -S . -B /tmp/stoneheart-milestones.xprJ2SVp/production-id-build -G Ninja --toolchain "$SETTLEMENT_VERIFY/cross.cmake" -DBUILD_TESTING=ON -DCMAKE_BUILD_TYPE=Release -DFETCHCONTENT_SOURCE_DIR_VOID_LIBRARY:PATH="$SETTLEMENT_VERIFY/candidate/_deps/void_library-src". Build with cmake --build <that dir> --parallel 6, run ctest --test-dir <that dir> --output-on-failure and your targeted tests. Evidence required. Run wine <dir>/settlement_core_tests.exe --tag production-id, full verbose CTest, git diff --check; fixed binary compatibility corpora at /tmp/stoneheart-milestones.xprJ2SVp/old-trajectory.bin and identity-compat-old.bin, baseline 4ba64f7 artifacts. Save logs production-id-*. No synthetic recreation of a golden old checkpoint with the new encoder.
|
||||
|
||||
## 12. Constraints and stop conditions
|
||||
No broad rewrite or custom replacement for supported Void primitives, branch changes or further agents. If existing unknown pre/post mutation exception means a Busy lie, stop and send contract+counterexample. After two failed repairs raise distinct hypothesis with evidence.
|
||||
|
||||
## 13. Authorization and decisions
|
||||
User authorizes all milestone/system features, commits/push and merge requests. M01-V9 requested exact demolition and cabin corrections; parent obtains narrow preflight recheck before dispatch. Root owns all side effects.
|
||||
|
||||
## 14. Return format
|
||||
Return S04-01 READY/BLOCKED, public format and ID APIs, actual coverage of all allocation sites, clean failure outcomes, compatibility corpora hashes/tests, and remaining later custody/native risks. No children/commits/push.
|
||||
|
||||
The middle-of-delivery assertion in `tests/snapshot_tests.cpp` also reads the removed production index. The implementer owns its equivalent check of the stored nonzero production ID.
|
||||
@@ -0,0 +1,50 @@
|
||||
# Apply a complete reserved pickup to one resident atomically
|
||||
|
||||
Task ID: S06-02
|
||||
Role: sol_implementer
|
||||
Status: READY
|
||||
|
||||
## 1. Context and baseline
|
||||
Isolated system/s06-logistics worktree s06 at a8cd7bb (S04 ProductionId/current14, S19 selectable rules, S06 stable StorageId). Meals and construction stops call take_reserved_material then Inventory::add, and a carpentry output reserves a new storage slot at its first ingredient pickup. Earlier M01-P5/F7 require whole-stop preflight. Existing finish_production also calls take_reserved_material for direct storage→recipe consumption, a different operation.
|
||||
|
||||
## 2. Objective and deliverables
|
||||
Implement checked all-or-nothing physical pickup in both real meal and construction stop paths, including a carpentry output slot when applicable. Retain normal simulation bytes/timing. Cover overflows, split duplicate material entries and late failure before mutation.
|
||||
|
||||
## 3. Scope and non-goals
|
||||
No save version, StackId, worksite ownership, reservation ID, journal, general-purpose database or protocol change in this slice. Keep existing direct recipe consumption in finish_production. Stage only future work in appropriate system notes.
|
||||
|
||||
## 4. Files to inspect
|
||||
Read engine/include/settlement/core/world.hpp Inventory/Storage/ItemStack/MaterialReservation, engine/src/world.cpp named consumers, world_save.cpp validation/legacy split records, tests identity/production_identity/core/replay, and S06 documentation/linked Void #8. Consult pin include/Void/Math/Numeric.hpp checked_add/sub. Root baseline cumulative a8cd7bb.
|
||||
|
||||
## 5. Write ownership and coordination
|
||||
Write scope: engine/src/world.cpp (narrow meal/construction stop pickup and related local helper); NEW engine/include/settlement/core/inventory_transaction.hpp and engine/src/inventory_transaction.cpp if needed for a shared testable operation; NEW tests/quantity_transaction_tests.cpp; CMakeLists.txt only source and test entries; docs/plan/systems/S06.md
|
||||
Exclusive to your isolated s06 worktree. Others work in sibling worktrees. Do not revert others' changes or edit unrelated methods/world_save/UI or shared Serena state. Root owns Git and remote.
|
||||
|
||||
## 6. Implementation or investigation approach
|
||||
Use one bounded operation over a single Storage and resident Inventory, evaluating present source/reserved counts, aggregate duplicate participating lines per type, and checked destination increments. If using the whole order span, choose only lines at the current storage; a missing/zero/invalid selection fails. Reject invalid types/None, zero amount, overflows, insufficient reserved or count and reserved>physical. Preserve source stack order, prune zero stacks without allocation; prevent throws between first and last logical writes. Use the existing checked Numeric API. For carpentry precompute reserved_slots successor and ensure post-withdrawal total_items+reserved_slots<=capacity before any quantity write; move commit/route/cursor only after success. No per-line mutating call before complete preflight. Failures observed by the owner must preserve last healthy publication. Avoid needless repeated lookup/allocations.
|
||||
|
||||
## 7. Interfaces and data contracts
|
||||
Prefer one simple domain function returning std::expected<void,typed quantity diagnostic>; exact type and header naming locally flexible. Application entry precondition is pickup-function entry: World::step may already advance walking position/route_cursor earlier in the tick. On pickup rejection, no additional stop, inventory, reserved slots/stock, route replacement or state transition; never publish partial transfer. Cover zero/foreign-only or out-of-range data; existing legitimate repeated material entries aggregate. Raw13/LAN11 layout stays byte exact and modern Current14 shape stays the same.
|
||||
|
||||
## 8. Dependencies and integration
|
||||
Root owns merging this branch to milestone/integration and cross-branch checks. P5 future durable IDs and reservations will consume this operation. S04-01 and S19-02 are already present; S18 UI can proceed independently.
|
||||
|
||||
## 9. Edge cases security and performance
|
||||
Data bounds as provided by old loader; max distinct types item_type_count, avoid allocating proportional to a user-provided count. Do not wrap at uint32 max on destination, source/slot arithmetic or sum. Source storage count/metadata may be inconsistent on direct test input; fail safely. No total mutable parallel ledger. Minimize impact on World::step hot path.
|
||||
|
||||
## 10. Acceptance criteria
|
||||
1. Source/dest byte-equivalent on success for valid meal and multi-material/multistop/carpentry paths, tested from production code. 2. A two-item stop late failure plus cumulative duplicate and destination overflow leaves all stock/reserved/capacity/inventory unchanged. 3. Successful exact depletion removes zero stack, respects source order and reserve slot. 4. Replay serial/2/6/12 modern checks and both old byte corpora unchanged. 5. Document limits separately from future custody and link Void #8 replacement.
|
||||
|
||||
## 11. Verification commands and evidence
|
||||
Source /tmp/stoneheart-verify.KoZwE4o8/env.sh. From YOUR worktree configure cmake -S . -B /tmp/stoneheart-milestones.xprJ2SVp/quantity-build -G Ninja --toolchain "$SETTLEMENT_VERIFY/cross.cmake" -DBUILD_TESTING=ON -DCMAKE_BUILD_TYPE=Release -DFETCHCONTENT_SOURCE_DIR_VOID_LIBRARY:PATH="$SETTLEMENT_VERIFY/candidate/_deps/void_library-src". Build with cmake --build <that dir> --parallel 6, run ctest --test-dir <that dir> --output-on-failure and your targeted tests. Evidence required. Use --tag quantity-transfer on new tests, CTest -V, git diff --check; /tmp/stoneheart-milestones.xprJ2SVp/old-trajectory.bin and identity-compat-old.bin old golden outputs were checked by s04 (portable projection probe sources in same directory). Keep verification logs quantity-* in that temp root.
|
||||
|
||||
## 12. Constraints and stop conditions
|
||||
Do not fake output inventories for finish_production or weaken legacy validity, add unrelated changes or use unbounded copies. Alert root if actual code contradicts the contract. Root owns commit/push/MRs/upstream issues. After two failed same-cause repairs escalate; no children.
|
||||
|
||||
## 13. Authorization and decisions
|
||||
Approved M01 item conservation and per-system development. F7 corrective terms are included above. Conditional batch issue Void/Library #8 already registered; parent owns external tracking.
|
||||
|
||||
## 14. Return format
|
||||
Return S06-02 READY or PARTIAL, owned files, exact tradeoffs/failure boundary, actual tests/golden output, any native and deferred full-custody limitations. No Git/remote operations.
|
||||
|
||||
F7 corrections are binding. Item indices are checked against 1..item_type_count before using type−1. Aggregate nonadjacent duplicate lines, handle an absent stack, and preserve the original first material's storage as the output source even when it is visited after another stop. No stale iterators may survive zero-stack removal. Include valid exact UINT32_MAX destination count, multiple erasures with unrelated surviving stacks, full storage freeing exactly one carpentry output slot, invalid slot/capacity state rejected before physical transfer, and direct storage→output production compatibility.
|
||||
@@ -0,0 +1,50 @@
|
||||
# Serve compatible LAN clients from the immutable authoritative runtime
|
||||
|
||||
Task ID: S16-02
|
||||
Role: sol_implementer
|
||||
Status: READY
|
||||
|
||||
## 1. Context and baseline
|
||||
Exclusive /home/faumaray/Projects/stoneheart_at_home-worktrees/s16, system/s16-authority fast-forwarded to 8c4c1fe. Existing LanSession::poll(World&) protocol11 is tested (4 cases/baseline binary interop). Runtime and command dispatcher new headers exist. M01-F4 identified manifest and outstanding-command reconnect gates, included below.
|
||||
|
||||
## 2. Objective and deliverables
|
||||
Add production host polling that consumes immutable runtime views and submits authenticated guest actions to the owner asynchronously. Add guest-only polling usable by a view-only client, preserve current hardcoded two slots and old packet format.
|
||||
|
||||
## 3. Scope and non-goals
|
||||
Legacy LAN11 compatibility adapter and actual loopback tests. No public new protocol/version or remote rollout, no new internet exposure. Preserve existing poll(World&) entry/fixtures for old API clients. Viewer source is owned separately.
|
||||
|
||||
## 4. Files to inspect
|
||||
Inspect app/lan_session.hpp, app/lan_session_win32.cpp, app/lan_wire.hpp/.cpp, tests/lan_tests.cpp, simulation_runtime.hpp, command_dispatcher.hpp, world.hpp, rules_manifest.hpp, docs/plan/systems/S16.md. Read /tmp/stoneheart-verify.KoZwE4o8/interop.cpp/.py for existing binary interop.
|
||||
|
||||
## 5. Write ownership and coordination
|
||||
Write scope: app/lan_session.hpp; app/lan_session_win32.cpp; tests/lan_tests.cpp; docs/plan/systems/S16.md
|
||||
If an identified shared codec change is necessary, contact root first; no data layout redesign. Other workers own Win32 viewer/core. You are not alone, do not change Git/Serena/other worktrees.
|
||||
|
||||
## 6. Implementation or investigation approach
|
||||
NEW poll_host(SimulationRuntime&) and poll_guest() (or equally explicit) for real viewer. Wire11 Hello carries no manifest/epoch, so allow ONLY default compatibility manifest (verified frozen identity); close incompatible connection before exposing a snapshot/command. Bind host session incarnation; detecting replacement drops peer & requires new hello before serving new world. Existing TCP framing/auth and slot validation retained. Read current immutable published World and prepare v13 snapshots with current bounds. No direct mutation in new host path. Screen sends one action at a time; bound hostile/pipelined volume, keep pings/timeouts/disconnect progress, never wait on a long owner while polling socket. Serialize one outstanding valid command per authenticated guest slot.
|
||||
|
||||
## 7. Interfaces and data contracts
|
||||
Wire request IDs are legacy World::next_command_sequence(guest), only accepted gameplay increments them. Modern envelope number from committed PublishedSnapshot::next_requests[guest] also advances on domain rejection. Precheck wire sequence without mutating state; old wrong-sequence -> expected number. Submit trusted guest=2, verified UUIDs/world/city/version, exact payload; report the correct legacy result and next wire sequence only from corresponding committed runtime result. Reject unsupported actions using existing authority. Track one outstanding admitted operation across TCP disconnect/rebind; suppress old-connection replies by connection generation, hold/reconcile its completion before next guest's sequence or authentication/publication is used, prevent reusing in-flight modern request number. On epoch change fence old future before new peer bind. No borrowed runtime pointer persisted. Expose status to viewer on incompatible rules/fault. Send early public signatures.
|
||||
|
||||
## 8. Dependencies and integration
|
||||
Root owns actual Win32 viewer integration. Runtime consumers now available at baseline; old standalone overload remains tested. Add only in-process loopback tests using random port/loopback flag. Reuse existing socket implementation and avoid duplicate dispatch/snapshot logic. Legacy reader file/body remains format13 and lower limits; world with unsupported future schema must be rejected explicitly in later change.
|
||||
|
||||
## 9. Edge cases security and performance
|
||||
On Busy/Closed/Faulted/superseded/out-of-order preserve protocol-correct old next id and prevent lost reported effects. Guest can correct a rejected action using same old number. Do not retain retired peer's optimistic blueprint metadata. Check long owner tick does not block server pings/poll; settled work from old peer cannot reply to a new one. Enforce bounded admission and no logs of join codes. Test a publication at same tick.
|
||||
|
||||
## 10. Acceptance criteria
|
||||
1. Old-style genuine guest joins runtime-owned host and receives actual committed world; user action, domain rejection and corrected next command preserve legacy sequences. 2. Deliberately blocked/delayed command, disconnect/reconnect, no old receipt to new peer, sequential guest slot safely resumes. 3. New epoch and non-default manifest refuse or reauthenticate before any legacy snapshot. 4. Both existing LAN11 fixtures and old API work; deterministic cross-version loopback including old guest executable. 5. Real x64 tests and warning status.
|
||||
|
||||
## 11. Verification commands and evidence
|
||||
Source /tmp/stoneheart-verify.KoZwE4o8/env.sh. From YOUR worktree configure cmake -S . -B /tmp/stoneheart-milestones.xprJ2SVp/lan-owner-build -G Ninja --toolchain "$SETTLEMENT_VERIFY/cross.cmake" -DBUILD_TESTING=ON -DCMAKE_BUILD_TYPE=Release -DFETCHCONTENT_SOURCE_DIR_VOID_LIBRARY:PATH="$SETTLEMENT_VERIFY/candidate/_deps/void_library-src". Build with cmake --build <that dir> --parallel 6, run ctest --test-dir <that dir> --output-on-failure and your targeted tests. Evidence required. Run wine <dir>/settlement_lan_tests.exe --tag lan (or registered runtime LAN tag plus full target), verbose CTest, git diff --check. Logs lan-owner-*. Root can stage external original-binary harness if needed.
|
||||
|
||||
## 12. Constraints and stop conditions
|
||||
No changes to socket reachability, authentication standards, new transport, UI or unrelated game state. Two failed fixes for the same defect -> send evidence and changed hypothesis to root. No children/Git/remote mutations.
|
||||
|
||||
## 13. Authorization and decisions
|
||||
User approved milestone/system work, commits/PRs/accumulation. M01-F3/F4 require authenticated owner entry and preserved old-wire rules. Root handles final integration.
|
||||
|
||||
## 14. Return format
|
||||
Return S16-02 status, early exact caller entry points, peer/session tracking contracts, actual test evidence/counts/interop and any native limitations.
|
||||
|
||||
The client also needs positive acknowledgements to remove committed draft parts. The approved preferred guest interface exposes `take_result()` with the full accepted or rejected intent, including resident ID. Retain one completion until the preferred caller drains it, clear stale results across connection generations and preserve legacy `take_rejection()` behavior. The loopback cases cover accepted and rejected results.
|
||||
@@ -0,0 +1,48 @@
|
||||
# Prepare immutable client frames and present camera changes independently
|
||||
|
||||
Task ID: S17-01
|
||||
Role: astra_implementer
|
||||
Status: READY
|
||||
|
||||
## 1. Context and baseline
|
||||
Isolated system/s17-rendering at 66af7c5 includes reviewed S18-01 client. app/viewer_win32.cpp has a 60 ms session/network timer, parent+child paints retain an old pointer but still dereference changing globals and SceneView spans live blueprint vectors. D3DScene::render presently regenerates flat geometry even on camera-only paints. S18-02 alters title/host gates and bed text in another worktree. M01-P6/F9 advise independent dirty-only 16ms frame sampling and strict install boundary.
|
||||
|
||||
## 2. Objective and deliverables
|
||||
Implement S17-W01 normal Windows entry: scene and HUD consume one immutable prepared client packet including owned overlays, camera and pinned snapshot; camera frames can render while 20 Hz world step or file/load busy. Coalesce invalidation and reuse geometry on view-only changes.
|
||||
|
||||
## 3. Scope and non-goals
|
||||
Existing flat game map, hardware Direct3D/WARP and error HUD only. No M02 chunk meshes, new camera settings, render thread, input/protocol changes or 60fps hardware claim. Preserve current viewer/rooms/blueprints/colony UX and all baseline harnesses.
|
||||
|
||||
## 4. Files to inspect
|
||||
Inspect app/viewer_win32.cpp scene_window and main WndProc, WM_TIMER/PAINT/DESTROY, camera wheel/drags, pump_session, draft/room render, title/minimize/resize, D3DScene in app/d3d_scene_win32.hpp/.cpp, map_camera, actual /tmp/stoneheart-milestones.xprJ2SVp/client_handlers_smoke.cpp. CMake/tests WARP/capture availability, app/viewer_session member changing_world/poll_changes.
|
||||
|
||||
## 5. Write ownership and coordination
|
||||
Write scope: app/viewer_win32.cpp (drawing, camera invalidation, timer/pump sequencing only); app/d3d_scene_win32.{hpp,cpp}; NEW app/viewer_frame.hpp/.cpp if useful; NEW tests/viewer_frame_smoke.cpp; CMakeLists.txt limited to registering frame test/owned sources; docs/plan/systems/S17.md
|
||||
Other branches own title/profile and stock; do not revert others' changes or switch Serena. Exclusive isolated s17 checkout. No Git/remote operations, further agents or unrelated app changes.
|
||||
|
||||
## 6. Implementation or investigation approach
|
||||
Prepare owned immutable presentation data on UI thread, derive HUD/selection/cursor/room validity and existing geometry from exactly one accepted world and copied relevant overlay state. Avoid borrowed spans into mutable UI across nested WM_PAINT or an overwritten single scratch buffer. Main and child paint each pin packet locally; no global world deref to render. Frame timer and camera/window invalidation independently drive dirty visible frames; keep existing 60ms LAN/control pump. While session->changing_world() keep prior presented world/frame including null, even if runtime.latest has already installed newer; release new world only after pump consumes Replaced, resets overlays/camera and updates identity. Guest/epoch transitions likewise cannot mix old work and new overlays. Sample ordinary healthy revisions with stable client identity.
|
||||
|
||||
## 7. Interfaces and data contracts
|
||||
Keep one current flat geometry version keyed by world identity/snapshot and all overlay/selected/cursor/BuildingView inputs. Camera-only or size-only change regenerates only camera/projection constants; account for resize/device/backend reset invalidating GPU upload. Explicit immutable geometry ownership shared by packets retained by readers; stale packets can render consistently even after newer packet then reuse correct upload. No work on hidden/title/minimized/zero sizes. On restoration or failed/recreated backend request fresh frame. No busy loop or full mesh rebuild/upload for unchanged view. Preserve existing D3DScene::render callers or update only within ownership. RAII for paint/DC and timers/shutdown.
|
||||
|
||||
## 8. Dependencies and integration
|
||||
Integration root will merge separately from S18 title+host. Avoid code dependencies on S06 custody changes, S21 hooks. Reuse Void owner snapshot (#5) and current D3D facilities; GPU resource ownership remains in renderer. Do not copy fixture include paths from other worktrees into repo. There is no GDI world renderer to invent in this scope.
|
||||
|
||||
## 9. Edge cases security and performance
|
||||
Check nested dialog/WM_PAINT while replacements happen, applied room/draft vector lifetime, same-world rollback or new UUID taking same tick, mouse cursor remains coherent re camera zoom and changes may legitimately affect preview geometry, no blocked owner/file calls on presentation thread. Render failure presents current HUD error and recoverable state. Graphics-test availability must be explicit, tests need bounded cleanup and skip/report only genuine backend unavailability.
|
||||
|
||||
## 10. Acceptance criteria
|
||||
1. Durable actual regression target (repo-relative source paths) observes fresh render and actual input camera/zoom/drag while owner worker and file writer blocked; original tick/canonical snapshot preserved. 2. Frame timer alone advances camera frame without event timer. 3. Held old packet remains renderable with old overlays across nested install; new packet resets correctly; exact saved snapshot content. 4. Geometry/upload reuse on pure camera/unchanged, title/hide/minimize/0-size/restore/destruct, device reset semantics; WARP/offscreen capture/real UI as available. 5. All original UI, core and LAN checks still pass.
|
||||
|
||||
## 11. Verification commands and evidence
|
||||
Source /tmp/stoneheart-verify.KoZwE4o8/env.sh. From YOUR worktree configure cmake -S . -B /tmp/stoneheart-milestones.xprJ2SVp/s17-frame-build -G Ninja --toolchain "$SETTLEMENT_VERIFY/cross.cmake" -DBUILD_TESTING=ON -DCMAKE_BUILD_TYPE=Release -DFETCHCONTENT_SOURCE_DIR_VOID_LIBRARY:PATH="$SETTLEMENT_VERIFY/candidate/_deps/void_library-src". Build with cmake --build <that dir> --parallel 6, run ctest --test-dir <that dir> --output-on-failure and your targeted tests. Evidence required. CTest -V, git diff --check; source actual Wine GUI/D3D environment from env.sh. Add/verify focused new real frame smoke and existing UI regressions (three-process/temp harness with isolated LOCALAPPDATA, no user data). Use s17-frame-* logs and report observed device/driver.
|
||||
|
||||
## 12. Constraints and stop conditions
|
||||
Stop if independent-frame scheduling would require replacing app/renderer architecture or mutating unrelated title/guest controls. Ask root on genuine scope change; after two failed same-cause fixes escalate with evidence. No M02 feature additions, Git/remote or children.
|
||||
|
||||
## 13. Authorization and decisions
|
||||
User authorizes complete roadmap on system/milestone branches. Root approved independent dirty-only 16ms sampling, immutable packet, one flat geometry generation and no unsourced performance claims. F9 requires explicit pre-Replaced candidate fence.
|
||||
|
||||
## 14. Return format
|
||||
Return S17-01 READY or PARTIAL, actual owned changes/normal paths, packet/geometry lifetime, render/repaint file/worker evidence, exact logs/native limits. Send frozen smoke seam early.
|
||||
@@ -0,0 +1,48 @@
|
||||
# Drive the Win32 client from committed world views and async results
|
||||
|
||||
Task ID: S18-01
|
||||
Role: astra_implementer
|
||||
Status: READY
|
||||
|
||||
## 1. Context and baseline
|
||||
Exclusive /home/faumaray/Projects/stoneheart_at_home-worktrees/s18 system/s18-client at 512c9ef. Runtime reviewed at 7979fff and M01 8c4c1fe. S15-03 and S16-02 are in separate worktrees and root will supply reviewed commits to this checkout before final build. S18-W01 owns separating snapshot reads and command submission from window handlers. M01-F4 identified title/menu, lifetime, admission and rules gates.
|
||||
|
||||
## 2. Objective and deliverables
|
||||
Wire the actual Win32 viewer to the single-owner runtime for offline play and hosting, immutable guest view, bounded async command handling and real background checkpoint save/load. Keep title/new/continue, legacy scenario/cabin controls and LAN guest usable.
|
||||
|
||||
## 3. Scope and non-goals
|
||||
Normal Windows app entry points plus focused testable client-state handling. This first S18 slice does not include unrelated keyboard/scale/sound settings, new internet protocol or UI for metadata-only rule selections. Show only supported default-profile new games; S19 adds genuine selectable behavior separately.
|
||||
|
||||
## 4. Files to inspect
|
||||
Read app/viewer_win32.cpp all session lifecycle/menu/paint/blueprint/command handlers, app/title_screen_win32.hpp, D3D const World entry, LAN and CheckpointFiles headers in sibling s16/s15, frozen simulation_runtime.hpp/impl, raw world factory/first_colony, and existing tests/smoke source /tmp/stoneheart-verify.KoZwE4o8/viewer_smoke.cpp. Watch S06-01 resident detail index access intentionally owned by another worktree.
|
||||
|
||||
## 5. Write ownership and coordination
|
||||
Write scope: app/viewer_win32.cpp; app/viewer_session.hpp and app/viewer_session.cpp (NEW if needed for testable state); tests/viewer_session_tests.cpp (NEW); CMakeLists.txt (viewer_session target/tests only); docs/plan/systems/S18.md
|
||||
Do not edit other worktrees, shared Serena or Git, or overhaul unrelated UI. Keep resident-detail lookup changes minimal where S06 branch also edits one line; parent integrates. Native normal entry is mandatory.
|
||||
|
||||
## 6. Implementation or investigation approach
|
||||
One window-lifetime owner runtime where possible. New/reset/load install prepared WorldCheckpoint with fresh incarnation; reuse the long-lived runtime or retire former owners off UI without joins, keeping retirement bounded. Guest reads latest received world immutably, never steps/applies; suspend local owner when guest, fence pending UI/authority. Preserve playable disconnected/leave behavior: keep last received guest World privately owned to import into a fresh local session on deliberate leave if prior behavior allows continuing that colony. Fresh first colony uses nonnil stable UUID+resolved default manifest. Gate viewer installs to exact supported compiled-rules profile/32x32 dimensions, preserve legacy imported world. Use consistent shared const world/view per frame and protect raw references across nested window messages/modal confirmations by pin or revalidate after dialogs. Render/HUD paths must stay safe on title with no world. WM_TIMER pumps file/network/runtime completions and reconciles desired ticking state BEFORE ANY title/offline/file-dialog/UI early return. Never step/serialize mutable World on UI. File picker is normal modal selection; picker open affects presentation pause without blocking owner polling or completion processing. Anchor title/hidden, pause-menu, file-dialog, guest/host and shared World::paused semantics to existing user-facing choices; no flood of set_ticking when unchanged or Busy. Fault visible, rendering last head and explicit load still usable.
|
||||
|
||||
## 7. Interfaces and data contracts
|
||||
Expected seam: S15 CheckpointFiles(options) with try_save(path,shared_ptr<const PublishedSnapshot>), try_load(path,workers,mode) → admission/request/future<expected<WorldCheckpoint,CheckpointFileDiagnostic>>, one process-level instance, survives reset across slots. Viewer obtains snapshot_for_save(), tracks completion by request+epoch, only reports latest relevant result. At selected load intent issue runtime begin_load even if ensuing file decode fails so stale older prepare cannot undo latest request; file result independent, filter UI ticket/generation+epoch, install checks again, preserve display on invalid/busy/superseded. S16 provides void poll_host(SimulationRuntime&) and unique_ptr<World> poll_guest(); guest presentation stores owned snapshot only, legacy standalone poll(World&) is for old consumers. Attach local controls/host and legacy cabin to modern CommandEnvelope, trusted host slot, via ONE bounded per-client intent queue and at most one runtime submission awaiting reply; allocate number from latest committed next_requests, never consume on Busy; retries do not duplicate. Pending blueprint/room IDs or exact generation-marked metadata ensure only an actually accepted part is cleared, rejected/busy remains editable, repeated click cannot resubmit pending. Other accepted-only statuses after commit. On reset/join/load, disconnect or retired epoch fence stale results and preserve unrelated current edits. Explicit local effects and connection authority; no GTK/web UI.
|
||||
|
||||
## 8. Dependencies and integration
|
||||
Root merges reviewed S15/S16 deps into s18 checkout before final build; send dependency requests early. Development may start on public seam/logical model; verify actual source before final compile. F4 corrections per exact contract. Existing tests and external Wine UI smoke must still run. Current UI actions should remain meaningful. No fake alternate rules advertising. Preserve old compatible file extension/recent saves and existing no-guest-save host policy.
|
||||
|
||||
## 9. Edge cases security and performance
|
||||
UI must remain responsive during deliberately long tick/file write, complete results on title/modal loops, avoid dereferencing stale selected_agent pointer, actively fence prior session commands/loads, avoid starving owner and don't freeze on reset/new/join. No stateful dangling callbacks on WM_DESTROY; orderly shutdown can drain on app exit. Queue memory and ongoing operations bounded by documented capacity. No unchecked exceptions escaping Win32 callbacks or stale feedback after generation change. Use deterministic gates for tests; actual end-to-end app path observable.
|
||||
|
||||
## 10. Acceptance criteria
|
||||
1. Launch actual viewer, start and advance local colony; deferred owner command incl cabin, pause/unpause while at same tick; no WM_TIMER direct world->step/World::apply_command. 2. Open modern and old saves from title, save during progress, update status only on newest completion; malformed/superseded/unsupported rule loads preserve current session. 3. UI reader can repaint/pan while owner/writer blocked; no synchronous join resetting/joining. 4. Host and guest continue through correct polling and domain-rejection/blueprint sequencing; stale queued intent/load cannot affect new session. 5. All Windows x64 tests and real viewer smoke, including title load if possible, with recorded native gaps.
|
||||
|
||||
## 11. Verification commands and evidence
|
||||
Source /tmp/stoneheart-verify.KoZwE4o8/env.sh. From YOUR worktree configure cmake -S . -B /tmp/stoneheart-milestones.xprJ2SVp/client-build -G Ninja --toolchain "$SETTLEMENT_VERIFY/cross.cmake" -DBUILD_TESTING=ON -DCMAKE_BUILD_TYPE=Release -DFETCHCONTENT_SOURCE_DIR_VOID_LIBRARY:PATH="$SETTLEMENT_VERIFY/candidate/_deps/void_library-src". Build with cmake --build <that dir> --parallel 6, run ctest --test-dir <that dir> --output-on-failure and your targeted tests. Evidence required. Run wine <dir>/settlement_core_tests.exe or viewer suite as actually registered, CTest -V, git diff --check. Reuse local isolated Win32 smoke harness for real viewer title/new/close and extend temporary harness for title/save/load as feasible; no disk writes to real user saves. Keep logs client-*.
|
||||
|
||||
## 12. Constraints and stop conditions
|
||||
No edits to S06, raw game rules, runtime, file service or LAN wire. Stop if exact external API differs or a product decision is needed, continue independent work. After two failed repairs of the same issue escalate. No children/Git/remote mutations.
|
||||
|
||||
## 13. Authorization and decisions
|
||||
User authorizes all milestones, per-system branches, commits/push and merge requests. F3/F4 and subsequent corrective recheck apply; parent owns branch merges/remote publication, no release.
|
||||
|
||||
## 14. Return format
|
||||
Return S18-01 status, actual changed behavior/lifetime/queue and gates, owned files, exact tests and Win32 smoke evidence, pending native validation. Communicate frozen helper/normal UI entry paths early.
|
||||
@@ -0,0 +1,48 @@
|
||||
# Select supported rules when starting a colony in the Win32 client
|
||||
|
||||
Task ID: S18-02
|
||||
Role: sol_implementer
|
||||
Status: READY
|
||||
|
||||
## 1. Context and baseline
|
||||
Isolated s18 worktree after root fast-forwards to db0a872 or a descendant containing the reviewed b7f18c0 client and 2759563 compiled profiles. S18-01 uses a long-lived runtime, exact default-only constructor/load, healthy views, transactional guest admission and fresh session identity. S19 core factory and validator already run the two real cost chains. M01-F6/F7 require validating initial, asynchronous and legacy hosts.
|
||||
|
||||
## 2. Objective and deliverables
|
||||
Make the actual Russian title screen offer staged beds (default) or one-plank beds for a new colony, apply the selected compiled rules to the new world, reload either supported profile exactly, and restrict LAN protocol 11 to default rules before any network side effect.
|
||||
|
||||
## 3. Scope and non-goals
|
||||
Only S18 profile selection/validation and accurate colony presentation. Preserve general S19 resolver, format1–14, LAN bridge/wire, legacy guest leave and unrelated keyboard/settings. Initial factory default stays staged, UI title selection is local to this process and only affects New.
|
||||
|
||||
## 4. Files to inspect
|
||||
Read root/s18 actual app/title_screen_win32.hpp, viewer_win32.cpp, viewer_session.hpp/.cpp, tests/viewer_session_tests.cpp, colony_profile.hpp/.cpp (colony_rules, compile_colony_rules, make_colony_checkpoint, validate_colony_checkpoint), S19 profile_tests and S18/S19 docs. Inspect LAN direct and deferred host event paths BEFORE making changes, current supported_rules_ also supplies legacy guest import. Actual smoke sources client_{ui,handlers,regression}_smoke.cpp in temp.
|
||||
|
||||
## 5. Write ownership and coordination
|
||||
Write scope: app/title_screen_win32.hpp; app/viewer_win32.cpp (title/new/host/bed labels only); app/viewer_session.hpp and .cpp (factory/validator/host readiness); tests/viewer_session_tests.cpp; docs/plan/systems/S18.md
|
||||
Isolated s18 only. Other workers edit separate branches. Do not revert others' changes or modify CMake/other components. Root owns all Git/remote operations. Distinct test build directory.
|
||||
|
||||
## 6. Implementation or investigation approach
|
||||
Use one accessible native control for a clearly labeled New-only choice, ensure keyboard (focus/Tab/arrows/Space/Enter as appropriate) and mouse operate at supported dimensions. Preserve title layout/order and new/continue/save list. Factory creates a new UUID and selected actual world; Continue/Open ignore current selector. Run candidate validation for both supplied initial and replacement/latest prepared loads before owner install and preserve current 32×32 restriction. Preserve default simple/inactive historical modes. Display correct cost including Miner house in simple profile; hide staged foundation material controls when simple.
|
||||
|
||||
## 7. Interfaces and data contracts
|
||||
Host immediate path must reject if changing_world or the current authoritative publication does not have exact default rules. Recheck after returning from modal menu before opening a listener; deferred path revalidate the newly installed publication immediately before network start. Error preserves active world/local file operation/peer. Existing default simple legacy world can host if other established gates pass. Legacy guest import still uses exact frozen default. Do not expose optional rules via old wire. Keep S18-01 fresh ticket/epoch gating and bounded queues.
|
||||
|
||||
## 8. Dependencies and integration
|
||||
Root owns fast-forward to integrated base before starting. Backend S19 and first viewer are independently accepted. New choice has real compiled behavior. Future S17 render-timer changes are separately owned; avoid edits to WM_TIMER or D3D unless a real unexpected dependency is reported.
|
||||
|
||||
## 9. Edge cases security and performance
|
||||
Reject unknown/forged/extra manifests, optional+staged, unusable dimensions/identity before any effect. Restore valid default raw simple, active optional simple and authentic old saves. A superseded valid load followed by failing newest must keep current world. Titles with small width/DPI should retain usable label/control. No external files in real saves, never open real network beyond loopback.
|
||||
|
||||
## 10. Acceptance criteria
|
||||
1. Real title New creates both variants (including exact selected manifest in saved checkpoint and visible costs). 2. Continue/Open preserve saved choice despite different selection, exact default old inactive/simple accepted. 3. Bad initial/load gate leaves session/world untouched. 4. Immediate/deferred legacy Host refusal before listener or peer change, including held optional load over old default. 5. Existing ten viewer tests, integration CTest and prior three-process/handler regressions still pass.
|
||||
|
||||
## 11. Verification commands and evidence
|
||||
Source /tmp/stoneheart-verify.KoZwE4o8/env.sh. From YOUR worktree configure cmake -S . -B /tmp/stoneheart-milestones.xprJ2SVp/client-profiles-build -G Ninja --toolchain "$SETTLEMENT_VERIFY/cross.cmake" -DBUILD_TESTING=ON -DCMAKE_BUILD_TYPE=Release -DFETCHCONTENT_SOURCE_DIR_VOID_LIBRARY:PATH="$SETTLEMENT_VERIFY/candidate/_deps/void_library-src". Build with cmake --build <that dir> --parallel 6, run ctest --test-dir <that dir> --output-on-failure and your targeted tests. Evidence required. Run CTest -V, viewer suite selectors as actually registered and git diff --check. Run an actual GUI smoke with isolated LOCALAPPDATA, exercise both choices with mouse/key, New, save/open with opposite selector, confirm actual stored manifest/bed mode. Extend /tmp smoke only as appropriate and record client-profile-* source/logs. Named current published checks are baselines.
|
||||
|
||||
## 12. Constraints and stop conditions
|
||||
Do not change staged vs simple game costs or default digest, add fake settings, change wire or unrelated app controls. No lowering exact-default admission. If title input cannot be exercised with available Windows/Wine tooling, describe specific gap and continue core meaningful checks. No children/commits/push; two failed same-cause fixes escalate.
|
||||
|
||||
## 13. Authorization and decisions
|
||||
User asked for complete milestones/system branches and actual compatible module selection. M01-F7 recorded corrective host gate and accurate simple Miner description. Root owns external side effects. Existing upstream #4 tracks generic resolution.
|
||||
|
||||
## 14. Return format
|
||||
Return S18-02 READY/PARTIAL, actual chosen title control + normal flow, exception/load/LAN boundaries, paths, commands/logs and any native UI caveats.
|
||||
@@ -0,0 +1,48 @@
|
||||
# Prove deterministic arbitration under opposing worker completion orders
|
||||
|
||||
Task ID: S21-01
|
||||
Role: astra_implementer
|
||||
Status: READY
|
||||
|
||||
## 1. Context and baseline
|
||||
Isolated system/s21-verification at 66af7c5. World assign_idle_agents calculates independent candidates for idle residents then assigns competing jobs in stable order. Meal claim is serial before parallel movement. Existing replay compares Current14 state for 1/2/6/12, last meal and mid-delivery plus capacity1; scheduler hooks currently before_submit/before_execute only. M01-P6/F9 request an observer of actual returns and readable divergence reports.
|
||||
|
||||
## 2. Objective and deliverables
|
||||
Implement a minimal optional success observer in the real WorkerPool adapter, prove opposite actual calculation completions and deterministic arbitration, and report first divergence through domain facts tied to canonical bytes. Verify runtime install waits for outstanding work and fresh session fences stale results.
|
||||
|
||||
## 3. Scope and non-goals
|
||||
WorkerPool instrumentation, tests and S21 verification docs only. No World scheduling/codec/receipt semantic changes, no synthetic exploit inputs or unrelated rendering/milestone changes. Native Windows hardware separate.
|
||||
|
||||
## 4. Files to inspect
|
||||
Read engine/include/settlement/core/worker_pool.hpp, engine/src/worker_pool.cpp/world.cpp (actual partitions and meal selection), runtime source, tests/{executor,replay,runtime}_tests.cpp, M01-P6/F9 and S21. Void FuturePool/Testing at pinned clone and issue #15.
|
||||
|
||||
## 5. Write ownership and coordination
|
||||
Write scope: engine/include/settlement/core/worker_pool.hpp; tests/executor_tests.cpp; tests/replay_tests.cpp; tests/runtime_tests.cpp; NEW tests/replay_diagnostics.hpp only if useful; docs/plan/systems/S21.md
|
||||
Isolated s21 only. Other agents own sibling source. No CMake mutations, shared project switch, children/Git/remote changes. Root integrates.
|
||||
|
||||
## 6. Implementation or investigation approach
|
||||
NEW optional WorkerPoolOptions::after_execute(index), success-only after callable returns before result future ready. Account for optional observer alone in submission indexing. Preserve original no-hook path and hook/call behavior for void, values, lvalue refs, move-only closures/results and exceptions on worker + inline fallback. Observer exceptions reach corresponding future; no throwing destructor. Test using separate driver and bounded CV gate for two known submissions; release on all exit paths. Only block task B until A has actually returned (post hook), then reverse. Never wait for all tasks/lanes or rely on sleeps/scheduling chance.
|
||||
|
||||
## 7. Interfaces and data contracts
|
||||
Fresh two-resident/one real reachable WorkJob scenario, opposite completion traces must be observed even with max_admitted1 on a separate driver, 2/6/12. Verify deterministic winner and each future state equal serial canonical Current14. Last berry serial claim test/cargo/movement preserve independent one-winner evidence, do not claim parallel meal arbitration. Add old worker held, queue same-world earlier load, verify old view remains readable/install pending until drained, replacement identity fresh, old request rejected, current state intact after further fence.
|
||||
|
||||
## 8. Dependencies and integration
|
||||
Test-local semantic reporting only when canonical byte comparison differs (existing Current14 encoder remains oracle). Include seed/scenario, attempt/tick, concurrency/schedule, load, stable first differing entity/property and expected/actual, command/receipt player/number/status/revision or byte-offset fallback. Actor/job/storage stack as owner plus type for current14; support absent/extra records. Test at least stock/job/command divergences individually and equal-case. Later body15 will extend this; don't introduce alternate persistence schema. Reuse existing helpers/tests.
|
||||
|
||||
## 9. Edge cases security and performance
|
||||
Bound waits even on CI; each branch releases gates before destroying/joining pool; no assertion library calls from worker threads. Keep hook captures alive; no mutex while running user callbacks. When no selector installed, no new allocations/counters per job. Tested genuine Submit paths including inline. No simulated full native performance claim.
|
||||
|
||||
## 10. Acceptance criteria
|
||||
1. Tests fail when completion acknowledgement incorrectly moves to start, schedules traces must be opposite and canonical states match. 2. Observer sees returned value/reference/void, exceptions incl hook and overload, callable ownership preserved. 3. Reload barrier stale work/commands and snapshot fencing checked. 4. Domain diagnostics exercised with expected entity ID/field/receipt context. 5. All CTest, corpus, focused tags and docs checks pass.
|
||||
|
||||
## 11. Verification commands and evidence
|
||||
Source /tmp/stoneheart-verify.KoZwE4o8/env.sh. From YOUR worktree configure cmake -S . -B /tmp/stoneheart-milestones.xprJ2SVp/s21-replay-build -G Ninja --toolchain "$SETTLEMENT_VERIFY/cross.cmake" -DBUILD_TESTING=ON -DCMAKE_BUILD_TYPE=Release -DFETCHCONTENT_SOURCE_DIR_VOID_LIBRARY:PATH="$SETTLEMENT_VERIFY/candidate/_deps/void_library-src". Build with cmake --build <that dir> --parallel 6, run ctest --test-dir <that dir> --output-on-failure and your targeted tests. Evidence required. Run CTest -V and --tag executor, --tag replay and --tag runtime under Wine; record s21-replay-* logs and commands. Old normal corpus should remain unchanged, use available trajectory probes as appropriate. Actual checks rather than latency claims.
|
||||
|
||||
## 12. Constraints and stop conditions
|
||||
Stop if index pair cannot be tied to real first job-choice partition: identify actual code and adjust fixture, no pretend success. No global installation or unrelated changes. Two failed same-cause fixes escalate. No children/Git/remote writes.
|
||||
|
||||
## 13. Authorization and decisions
|
||||
User authorizes complete M01 and separate S21 system branch; root approved test-only success observer and strict canonical oracle. [Void/Library completion test facility](https://git.faumaray.com/Void/Library/issues/15) documents the replacement test. Root publishes.
|
||||
|
||||
## 14. Return format
|
||||
Return S21-01 READY/PARTIAL, bounded integration/worker semantics, branch files, tests with actual opposing traces/diagnostic cases/corpus, native limits.
|
||||
@@ -0,0 +1,53 @@
|
||||
# Владение грузом во время работ M01
|
||||
|
||||
Формат 14 уже различает заказы по постоянным ID. Следующий срез [S06](systems/S06.md) и [S04](systems/S04.md) вводит имущество, требования к нему и результат передачи. Это контракт реализации для текущих игровых действий. [План этапа](milestones/M01.md) · [Проверка действующего кода](../agent-workflow/tasks/M01-P5.md)
|
||||
|
||||
## Имущество и резервы
|
||||
|
||||
Каждый непустой стек имеет ID мира и одного владельца — склад, жителя или входной запас конкретного производственного заказа. Количество хранится у владельца. Резерв ссылается на него и задаёт удерживаемое количество. Отдельные резервы удерживают рабочее место, источник добычи и место для результата. Счётчики доступности склада и источника можно восстановить из действующих резервов. Требование рецепта описывает затраты отдельно от имущества.
|
||||
|
||||
Целый стек, переходящий в пустой слот, сохраняет ID. При разделении ID остаётся у исходного остатка, а новая часть получает отдельный ID. При объединении сохраняется ID стека получателя. Ссылки резервов на перемещённое количество обновляются той же операцией. Для каждого вида ID свой восстанавливаемый счётчик. Ноль означает отсутствие ссылки, а `UINT64_MAX` у следующего ID — исчерпание. Выделение всей группы проверяется до изменения мира. [Void/Library #7](https://git.faumaray.com/Void/Library/issues/7)
|
||||
|
||||
Назначение работника закрепляет все материалы, рабочее место и вместимость вместе. Для плотника место под результат может обеспечивать зарезервированный входной материал в том же складе. Резерв места ссылается на конкретный резерв материала. Одна единица обеспечивает только одно место. При получении этого материала на освободившееся место устанавливается обычный резерв. До окончания работы запоминается и исходный склад, чтобы прежние команды перемещения и разбора выдавали согласованный отказ после получения груза.
|
||||
|
||||
| Событие | Изменение владения |
|
||||
|---|---|
|
||||
| Стартовые запасы и добыча | Начисление создаёт количество у склада либо жителя. Для добычи в тот же момент уменьшается исчерпаемый запас источника. |
|
||||
| Получение материалов | Все позиции текущей остановки переходят со склада к жителю. При отказе любой позиции весь груз остаётся на месте. |
|
||||
| Прибытие на стройку | Материалы переходят к заказу. Пока идёт работа, у площадки есть собственный входной запас. |
|
||||
| Завершение рецепта, монтаж, еда | На одном шаге списываются входы, учитывается причина и при необходимости создаётся результат. |
|
||||
| Отмена до получения | Освобождаются требования к складу, рабочему месту и исполнителю. |
|
||||
| Отмена в пути или на площадке | Груз остаётся у жителя либо возвращается ему со стройки. Уже установленные части здания сохраняются. Житель возвращает все виды груза, ожидая место при заполнении складов. |
|
||||
| Разбор свободного склада | Оставшиеся запасы списываются с причиной разбора и точным количеством каждого вида. |
|
||||
|
||||
Когда время работы истекло, а завершение временно невозможно, исполнение сохраняет состояние ожидания завершения и нулевой остаток времени. Новый шаг повторяет проверку с очередным номером операции. Так при исчерпании ID или переполнении не происходит повторного уменьшения нулевого таймера и частичной выдачи результата.
|
||||
|
||||
Для каждого вида предмета проверяется баланс. Начальный остаток, начисление, добыча и производство равны сумме имущества у всех текущих владельцев и списаний на сырьё, монтаж, питание и разбор. Счётчики источников и расходов используют проверяемую арифметику. Эта проверка выполняется при загрузке и в тестах. [Void/Library #8](https://git.faumaray.com/Void/Library/issues/8)
|
||||
|
||||
## Исполнение и повтор
|
||||
|
||||
У создания исполнения заранее известен ключ из ID жителя и его следующего номера назначения. Нумерация начинается с 1. При успешном принятии мир одной операцией выдаёт `TransferId`, сохраняет данные запроса и его результат и увеличивает номер назначения. Потеря ответа не может назначить ту же работу повторно. Нехватка ID, места или материалов до принятия оставляет оба счётчика прежними. Последующие шаги используют пару из `TransferId` и очередного номера операции. Отказ принятого шага меняет только журнал повтора. Повтор с исходными данными возвращает прежний результат, с изменёнными — конфликт.
|
||||
|
||||
Хранятся последние 4096 результатов в порядке применения. Для каждого результата закодированные запрос и ответ ограничены 1024 байтами каждый. После вытеснения прежний номер распознаётся по следующему номеру шага действующего исполнения или по границе выданных ID завершённых исполнений. Устаревший запрос не может повторно переместить имущество. У жителя не более одного действующего исполнения. Резервы одинакового предмета могут относиться к разным складам; размер набора проверяется по фактическим ограничениям игры. Полные проверки и измерения размера снимка входят в приёмку.
|
||||
|
||||
Действующие ссылки должны разрешаться к существующим объектам. Историческая квитанция может содержать уже израсходованный стек или удалённый заказ. Загрузчик проверяет её вид, согласованность полей и диапазоны выданных ID. Пары схемы и тела проверяются по отдельности для всех трёх поколений сохранений.
|
||||
|
||||
Явная отмена относится к современному приказу по `ProductionId`, с проверками города, инкарнации и номера запроса. Житель с возвращаемым грузом сохраняет своё исполнение до сдачи последней единицы. Если у кровати уже установлено основание или существует действующий ткацкий станок, отмена сохраняет площадку под прежним ID и приостанавливает следующие работы. Явное возобновление продолжает с сохранённой стадии. Завершённая кровать сохраняет назначение владельцу. Для старых `DemolishObject` и `MoveObject` продолжают действовать прежние отказы при занятом источнике, складе или кровати. [Контракт команд](systems/S16.md)
|
||||
|
||||
## Сохранение и миграция
|
||||
|
||||
Планируемая контрольная точка схемы 3 использует тело версии 15. В нём сохраняются реальные ID, владельцы, незавершённые исполнения, резервы, результаты повторов и баланс. Повтор ID, лишний владелец, пропавший источник или несовпадающий баланс отклоняют кандидата до смены текущей партии.
|
||||
|
||||
| Вход | Восстановление |
|
||||
|---|---|
|
||||
| Тела 1–13 и контрольная точка схемы 1 | Проверить исторические поля и контрольную сумму. Сопоставить позиционные ссылки постоянным ID. |
|
||||
| Тело 14 и схема 2 | Сохранить имеющиеся ID заказов и следующий ID, восстановить остальное имущество из действительных старых данных. |
|
||||
| Материалы в пути | Уже посещённые остановки соответствуют грузу жителя. Оставшиеся материалы удерживаются у склада. |
|
||||
| Начатая работа с доставленным материалом | В старом формате прибытие убирало материалы из инвентаря жителя. Восстановить вход площадки по проверенному действующему рецепту, затем посчитать начальный баланс. |
|
||||
| Добытчик, перевозчик, голодный житель | Восстановить фактический груз, удержание места, резерв источника или еды в соответствии с сохранённой стадией. |
|
||||
|
||||
При переносе старого активного задания ему назначается первое поколение, а следующий номер назначения жителя устанавливается в 2. Для свободного жителя следующее назначение начинается с 1. Запрос от уже перенесённого поколения без исторической квитанции получает ответ об устаревшем номере.
|
||||
|
||||
Обычная партия сохраняет побайтовый экспорт 13 и протокол LAN 11. Для отменённой стройки житель может нести несколько видов материалов без доступного склада. Даже одна доска без связанного с ней заказа может не иметь представления в старом состоянии перевозки. Кодек сообщает `UnsupportedLegacyState` до записи первого байта. Это относится также к приостановленной площадке и другим несовместимым сочетаниям состояния. Современная контрольная точка сохраняет партию полностью. Хост проверяет представимость до допуска гостя, разбора приказа и выдачи снимка. При отказе совместимый гость получает отказ в подключении или отключается, а хост продолжает игру.
|
||||
|
||||
Приёмка охватывает остановки до получения, между складами, на площадке, при отмене и при ожидании свободного места; исчерпание ID и числовые границы; точный повтор до и после загрузки; старые двоичные наборы; сравнение каждого такта на последовательном исполнителе и 2/6/12 потоках. В контрольном сценарии с 500 жителями дополнительно измеряются снимок, размер сохранения и операции при 10 000 стеках и 2 000 заказах.
|
||||
@@ -22,6 +22,18 @@
|
||||
|
||||
## Проверки и выход
|
||||
|
||||
### Контракты первой реализации
|
||||
|
||||
Воксели имеют знаковые 32-битные координаты, высота растёт по оси `z`. Границы конечного региона задаются полуинтервалами с 64-битными концами, чтобы в них можно было включить последний положительный воксель. Чанк содержит 32³ ячеек; быстрее всего меняется индекс `x`. Отдельные результаты чтения обозначают воздух, недоступный чанк и координату за пределами региона. Генератор получает версию, seed и абсолютные координаты. Порядок подготовки страниц не влияет на материал.
|
||||
|
||||
Снимок региона разделяет неизменяемые страницы. Операция проверяет все ожидаемые ревизии, размер и бюджет до публикации. Пустая операция или запись прежнего материала сохраняет ревизию после проверки ожиданий. Дублированная координата отклоняет весь запрос. Изменение на грани оповещает соседний чанк, сохраняя его собственную ревизию материала. Реализация и проверки замены библиотечным API связаны с задачами о [знаковых координатах](https://git.faumaray.com/Void/Library/issues/11), [транзакциях страниц](https://git.faumaray.com/Void/Library/issues/14) и [зависимостях по ревизиям](https://git.faumaray.com/Void/Library/issues/13).
|
||||
|
||||
Житель занимает одну клетку в плане и две по высоте, поднимается на одну ступень. Поиск учитывает опору, свободное место для головы, дверь и соседние чанки, включая чтения, из-за которых путь не найден. Перед очередным перемещением житель перепроверяет переход. Удаление следующей ступени сохраняет его собственную позицию, груз и цель. Поиск через ещё не подготовленный чанк либо за пределами бюджета имеет отдельный результат.
|
||||
|
||||
Добыча создаёт авторитетный заказ с доступной соседней рабочей позицией. При завершении мир заранее проверяет правку и возможность зачислить материал по правилам S06. Удаление грунта и передача добычи выполняются одной операцией. Если для добычи нет места, заказ ждёт с указанием причины. Повтор принятой команды находит исходный заказ. Режим тестовой колонии имеет собственный манифест с версией генератора и определениями материалов.
|
||||
|
||||
Координатор принимает подготовленные чанки на назначенной границе такта в порядке координат. Во время ожидания он обслуживает загрузку и завершение программы. В сохранение попадают требуемые чанки, назначения работ и безопасная позиция после правки. Прежние колонии сохраняют прежнюю геометрию на высоте ноль. Форматы нового региона согласуются с подтверждённой версией сохранений M01. Текущий шейдер уже проецирует высоту `z`; луч выбора и видимый срез должны пользоваться той же проекцией. [Проектирование](../../agent-workflow/tasks/M02-P1.md) · [Проверка контрактов](../../agent-workflow/tasks/M02-F1.md)
|
||||
|
||||
- Житель проходит через вход, поднимается и работает на верхнем этаже. Закрытая стена не считается проходом. После перекрытия маршрута он строит обход либо показывает недоступность.
|
||||
- Игрок выкапывает тоннель и изменяет опору у края чанка. Геометрия, выбор мышью и проход согласованы с обеих сторон границы после сохранения и загрузки.
|
||||
- При перестановке порядка чтения и генерации журнал команд создаёт одинаковое состояние на каждом такте. Повреждённые данные не публикуются как загруженный чанк.
|
||||
|
||||
@@ -10,6 +10,34 @@
|
||||
|
||||
## Данные и ответственность
|
||||
|
||||
### Исполняемая основа ограниченного региона
|
||||
|
||||
`VoxelRegion` хранит ненулевой ID, seed, версию генератора и границы. Ячейки имеют знаковые координаты `int32`, а концы полуинтервалов используют `int64`, включая верхнюю границу `INT32_MAX + 1`. Деление на размер чанка округляет вниз, поэтому координата −1 попадает в чанк −1 и локальную ячейку 31. Индекс внутри страницы вычисляется как `x + 32 * (y + 32 * z)`. Результат `sample()` различает загруженный воздух, недоступную страницу и выход за границы. [Публичный контракт](../../../engine/include/settlement/core/voxel_region.hpp) · [Реализация](../../../engine/src/voxel_region.cpp)
|
||||
|
||||
Копия региона разделяет каталог и страницы через неизменяемые объекты. `directory()` возвращает владеющую ссылку на прежний каталог. Изменение создаёт новый каталог и копирует затронутые страницы. Срок жизни снимка охватывает все его материалы. Номер региона и `ChunkStamp` связывают чтение с состоянием доступности и ревизией страницы. Владелец мира дополнительно проверяет инкарнацию сеанса при загрузке партии.
|
||||
|
||||
`prepare_generated()` независимо готовит страницу генератора 1. Он кодирует seed, версию и координаты опорных столбцов в little-endian через `Void::Binary::Writer`, затем использует FNV-1a из `Void::Hash`. Интерполяция сетки с шагом 16 даёт высоты от −8 до 8. Верхние три слоя состоят из почвы, нижние — из камня. Соседние столбцы по горизонтальной оси отличаются по высоте максимум на одну ячейку. Область вне частичного чанка заполнена воздухом. Для seed 42 чанк (−1, −1, −1) имеет FNV-1a `13302332479434111011`; этот результат отдельно воспроизведён по закодированным полям. Подготовка не меняет каталог региона.
|
||||
|
||||
`prepare_restored()` проверяет полный размер страницы, ненулевую ревизию, материалы и воздух за границами, затем копирует данные вызывающего кода. `activate()` принимает весь набор подготовленных страниц одной операцией. Она проверяет точный дескриптор региона, дубликаты, бюджет и отсутствие уже опубликованной страницы. `edit()` проверяет ожидаемую ревизию каждой ячейки, даже если материал уже совпадает. Повтор координаты отклоняет весь запрос. Пустая и тождественная запись сохраняют ревизии. Исчерпанная ревизия запрещает изменение страницы. Все новые страницы, каталог и результат готовятся до публикации. При отказе прежние указатели, материалы и ревизии сохраняются.
|
||||
|
||||
Список изменённых чанков упорядочен по координатам `x,y,z`; список ячеек — по мировым координатам. Правка на грани добавляет пересекающего регион соседа в `dirty_chunks`. Это касается и недоступных соседей. Диагонали не включаются. Неизменившийся сосед сохраняет свою ревизию материала. Активация страницы оповещает все её соседние грани. Выгрузка страниц появится с отдельным контрактом сохранения их ревизий.
|
||||
|
||||
| Материал | Значение | Проход | Опора |
|
||||
| --- | --- | --- | --- |
|
||||
| Воздух | 0 | Свободен | Нет |
|
||||
| Почва | 1 | Занят | Есть |
|
||||
| Камень | 2 | Занят | Есть |
|
||||
| Закрытая дверь | 3 | Занят | Нет |
|
||||
| Открытая дверь | 4 | Свободен | Нет |
|
||||
|
||||
Навигация и изображение используют общие `voxel_blocks_passage()` и `voxel_provides_support()`. Генератор создаёт природные материалы. Игровая команда определяет право изменить дверь и обновляет обе её ячейки одной операцией, в том числе через границу страниц.
|
||||
|
||||
По умолчанию разрешены 256 страниц и 4096 ячеек в запросе. Лимиты полезных данных резидентного региона и одной транзакции равны 16 МиБ каждый. Проверяемая арифметика учитывает объекты страниц, каталог, сортируемый запрос, временную страницу и массивы результата до их выделения. На проверенной Windows x64-сборке страница занимает 32 776 байтов, запись каталога — 32 байта, каталог с 256 страницами — 8 398 872 байта. Служебные данные распределителя, подготовленные страницы и старые снимки, удерживаемые потребителями, имеют отдельный расход памяти. Будущий владелец ограничивает число таких потребителей.
|
||||
|
||||
Проверки `--tag voxel-region` покрывают отрицательные и предельные координаты, частичные страницы, порядок завершения настоящих задач на 2/6/12 исполнителях, границы двери, загрузку, точный отказ целого набора и неизменяемые снимки. На заполненном каталоге правка одной ячейки сохранила прежние 255 страниц. Отдельная программа по очереди вызвала отказ каждого выделения памяти при генерации, восстановлении, активации и правке двух страниц; все отказы сохранили прежний каталог. Переход на библиотечную реализацию должен повторить эти проверки. [Тесты региона](../../../tests/voxel_region_tests.cpp) · [Знаковая арифметика в VoidLibrary](https://git.faumaray.com/Void/Library/issues/11) · [Атомарные страницы в VoidLibrary](https://git.faumaray.com/Void/Library/issues/14)
|
||||
|
||||
Windows x64 Release с GCC 16.2 под Wine 11 прошла 14 проверок региона и весь CTest — 155 тестов ядра, 9 LAN, 14 клиента и испытание кадра с видимым D3D11 и WARP. В одном прогоне подготовка и активация 256 страниц заняли 57 917 мкс, правка одной ячейки — 11 мкс. Это измерение относится к данному прогону под Wine. Нативная Windows и аппаратная частота кадров ещё не проверены.
|
||||
|
||||
| Новый контракт | Содержимое и владелец |
|
||||
| --- | --- |
|
||||
| Позиция мира | Постоянный ID региона и знаковые целочисленные координаты вокселя. Вертикальная ось — `z`, горизонтальная плоскость — `x,y`. |
|
||||
|
||||
@@ -8,6 +8,34 @@
|
||||
|
||||
В прототипе есть A*, фиксированный порядок соседей и кэш запросов. Изменение проходимости инвалидирует маршруты. Тесты проверяют проход через отверстие в стене и открытие ранее недоступной шахты. Карта использует двумерную позицию, а маршрут хранится последовательностью клеток внутри жителя. [Мир](../../../engine/src/world.cpp) · [Типы](../../../engine/include/settlement/core/world.hpp) · [Тесты маршрутов](../../../tests/core_tests.cpp)
|
||||
|
||||
## Первый исполняемый срез M02
|
||||
|
||||
Модуль `voxel_navigation` работает с неизменяемым `VoxelRegion`. `voxel_standing` проверяет опору, клетку ног и клетку головы. `voxel_transition` использует те же проверки для одного горизонтального перехода с подъёмом или спуском на одну клетку. При изменении высоты дополнительно проверяется объём, через который проходит голова. Закрытая дверь препятствует движению, открытая дверь допускает проход. Земля и камень предоставляют опору. [Интерфейс](../../../engine/include/settlement/core/voxel_navigation.hpp) · [Реализация](../../../engine/src/voxel_navigation.cpp)
|
||||
|
||||
`find_voxel_path` получает ID региона, UUID текущей инкарнации, старт, множество целей и явное окно поиска. Путь содержит очередные позиции после старта. Его стоимость равна числу переходов. При равной стоимости выбирается первая цель в порядке координат, соседи каждой позиции перечисляются в том же порядке. Поиск использует `Void::Algorithms::bfs` из закреплённой версии библиотеки. Множество вершин относится к заданному окну, список соседей вычисляется по запросу. До выделения массивов проверяется полный размер окна. Разреженный регион с большой протяжённостью требует меньшего окна для конкретной задачи.
|
||||
|
||||
`find_voxel_interaction_path` строит доступные позиции контакта с указанной клеткой. К ней должна примыкать грань тела жителя. Цель может находиться у ног, у головы, под ногами или непосредственно над головой. Цель должна быть загружена. Право добывать материал, менять дверь и удалять опору проверяет владелец работы. Выбранная позиция взаимодействия и следующий переход доступны для повторной проверки перед действием.
|
||||
|
||||
Позиции контакта за пределами окна поиска сохраняются для проверки отрицательного ответа. Если такой контакт допускает размещение жителя, достигнутый допустимый выход из окна даёт `SearchBoundary`, а достигнутый неопределённый переход требует загрузки данных. При известном отсутствии выхода результат остаётся `Unreachable`. Заблокированные контакты внутри окна не доказывают недоступность всех внешних позиций. Общий предел целей учитывает и пропущенные контакты.
|
||||
|
||||
Каждый ответ содержит `VoxelReadSet` с ID региона, инкарнацией и упорядоченными уникальными ревизиями прочитанных чанков. В набор входят опора, свободное место над головой, заблокированные соседи и недоступные страницы. `current` проверяет тот же сеанс и все эти ревизии. Загрузка недоступной страницы делает прежний отрицательный ответ устаревшим. Правка непрочитанного чанка сохраняет ответ пригодным. Сам ответ и его маршрут удерживают собственные данные. Для замены локального набора библиотечным повторить проверки опоры через границу чанка, открытия прохода, загрузки страницы и смены инкарнации. [Void/Library #13](https://git.faumaray.com/Void/Library/issues/13)
|
||||
|
||||
Найденный путь является кратчайшим среди известных переходов в заданном окне. Отрицательный ответ различает доказанную недоступность, недостающие данные и возможность выхода за границу окна. Отдельные результаты обозначают исчерпание бюджета, отмену, неверный запрос и отказ выделения памяти. До быстрого случая совпавших старта и цели проверяется геометрия тела. Применяющий результат код должен проверять и его статус, и актуальность набора чтений.
|
||||
|
||||
Недостающие данные требуют ожидания, когда они могут продолжить путь из уже достигнутой позиции. Известная сплошная стена или занятая клетка ног окончательно запрещает переход, даже если его проверка прочитала недоступную опору. Прочитанные ревизии сохраняются в ответе. Недоступная цель за доказанно непроходимой стеной сама по себе не создаёт достижимый проход. Выход за окно учитывается после проверки допустимого перехода через его границу.
|
||||
|
||||
Пределы по умолчанию составляют 65 536 вершин, 1 000 000 шагов алгоритма, 4 000 000 чтений клеток, 64 цели, 4096 ревизий и 8 МиБ рабочих данных. Бюджет учитывает четыре массива `size_t` и посещённость из Void BFS, собираемый маршрут и зарезервированный набор ревизий. Список соседей из 12 элементов находится в стеке. Владелец сохраняет входные данные запроса и страницы мира отдельно. Измерение памяти распределителя и принудительный отказ системного распределителя остаются отдельными проверками.
|
||||
|
||||
Ёмкости проверяются также против `vector::max_size()`. Непредставимая ёмкость возвращает `LimitExceeded` через каждую из четырёх публичных операций. Проверка с `max_dependencies = max_size() + 1` и максимальным байтовым бюджетом воспроизводит этот отказ без выделения указанной памяти.
|
||||
|
||||
Селектор `--tag voxel-navigation` проверяет двухклеточную дверь, ступени на границе `x=31/32` и работу наверху, удаление следующей опоры, прежний неизменяемый снимок, место для головы, недоступную опору через отрицательную границу по высоте, постороннюю правку, смену сеанса и предельные координаты. Стоимости сравниваются с независимым полным обходом 16 малых плоских карт. Запросы в настоящем пуле с 2, 6 и 12 потоками дают те же маршруты и ревизии. [Проверки](../../../tests/voxel_navigation_tests.cpp)
|
||||
|
||||
На совместной базе S02 `e7046a9` сборка Windows x64 GCC 16.2 и все десять проверок навигации прошли под Wine 11. Полный `ctest -V` прошёл четыре набора с 165 случаями ядра, 9 LAN, 14 клиента и испытанием кадра с видимой цепочкой D3D11 и WARP. Проверка заняла 4,66 с. Нативная Windows и связь навигации с исполнением работ в `World` проверяются при последующей интеграции M02.
|
||||
|
||||
Проверка замечаний к `7a7ff32` воспроизвела ожидание отсутствующей страницы под сплошным полом и исключение `vector::reserve` при непредставимой ёмкости. После исправления прошли 13 проверок навигации и четыре полных набора с 168 случаями ядра, 9 LAN, 14 клиента и испытанием кадра за 4,61 с. Отдельно проверены недоступная цель за известной стеной, загруженная цель взаимодействия за ней, запрещённый переход за границу окна и настоящий ожидающий загрузки проход. Один предыдущий полный прогон встретил прежнюю проверку немедленного допуска при восстановлении клиента после сбоя, `viewer_session_tests.cpp:363`. Повтор этого набора и итоговый полный прогон прошли. Проверяемый файл клиента в этом срезе не изменялся.
|
||||
|
||||
Проверка замечания к `17389b2` воспроизвела ложную недоступность при единственном пригодном контакте за границей окна. После исправления узкое окно возвращает `SearchBoundary`, расширенное достигает той же позиции контакта. Изолированный старт и незагруженный проход проверены отдельно. Под Wine прошли 14 проверок навигации и полный `ctest -V` с блокировкой общего интерактивного окружения. Все четыре набора прошли, включая 169 случаев ядра, 9 LAN, 14 клиента и испытание кадра за 4,74 с.
|
||||
|
||||
## Пространственная модель
|
||||
|
||||
Позицию и материал предоставляет [S02](S02.md). Профиль движения определяет объём тела, высоту шага и разрешённые переходы. Для M02 нужен профиль обычного поселенца, движение по опоре, ступеням и лестницам. Особые способы движения добавляются вместе с соответствующими животными и боевыми участниками.
|
||||
|
||||
@@ -6,7 +6,19 @@
|
||||
|
||||
## Исходное состояние
|
||||
|
||||
В текущем `World` общие, ресурсные и производственные задания назначаются разными методами. Ресурсные работы имеют индекс кандидатов по профессиям. Производство перебирает заказы и склады, проверяет занятость позиции и резервирует сырьё после выбора жителя. В ссылках на материалы и остановки используются индексы контейнеров. Тесты проверяют резервирование, доставку и сохранение незавершённых работ. [Назначение работ](../../../engine/src/world.cpp) · [Структуры заказов](../../../engine/include/settlement/core/world.hpp) · [Тесты](../../../tests/core_tests.cpp)
|
||||
В текущем `World` общие, ресурсные и производственные задания назначаются разными методами. Ресурсные работы имеют индекс кандидатов по профессиям. Производство перебирает заказы и склады, проверяет занятость позиции и резервирует сырьё после выбора жителя. Материалы и остановки хранят `StorageId`, источники — `ResourceNodeId`, назначения производства — `ProductionId`. Тесты проверяют резервирование, доставку и сохранение незавершённых работ. [Назначение работ](../../../engine/src/world.cpp) · [Структуры заказов](../../../engine/include/settlement/core/world.hpp) · [Тесты](../../../tests/core_tests.cpp)
|
||||
|
||||
## Реализованный срез S04-01: идентичность производства
|
||||
|
||||
У `ProductionOrder` появился постоянный `ProductionId`, а житель хранит `production_id` (`0` означает отсутствие назначения). Единственный счётчик `next_production_id_` входит в копируемое состояние мира. Заказы остаются отсортированными по ID, поиск выполняется через `lower_bound`; удаление нижнего заказа не требует исправлять ссылки жителей. Присвоенный ID не меняется в течение жизни заказа.
|
||||
|
||||
Все вставки, включая обстановку и клетки комнаты, проходят общий метод. До первого изменения проверяются ID и вместимость вектора для всей группы: кровать, ткацкий станок, комната с мебелью, дом и замещающие столярные заказы при сносе склада. Снос вычисляет нехватку каждого затронутого изделия по запасам **после** предполагаемого удаления, учитывая другие склады и уже существующие заказы, затем резервирует всю группу. Недостаток ID возвращает `Busy` без потери запасов, изменения заказов или номера команды. Последний выдаваемый ID — `UINT64_MAX - 1`; `UINT64_MAX` остаётся допустимым исчерпанным счётчиком. Прямой `queue_cabin` сообщает такую проверенную до изменений нехватку через `ProductionCapacityError`; диспетчер сохраняет повторяемый результат `Completed/Busy`, а runtime продолжает принимать команды.
|
||||
|
||||
`World::write_save(stream)` сохраняет прежний формат 13 и позиционные ссылки для совместимости, включая LAN 11. Явный `WorldSaveFormat::Current14` записывает настоящие ID производства, складов и источников, а также следующий ID производства. Новые checkpoint используют внешнюю схему 2 и тело 14. Схема 1 принимает тела 1–13; несовместимые пары отклоняются даже при корректных контрольных суммах. Импорт старого тела назначает производству ID по порядку записей; современные сохранения сохраняют историю выдачи после удаления последнего, максимального или всех заказов. Чтение проверяет ненулевые упорядоченные ID, следующий ID и ссылки до разыменования; новые проверки не добавляют квадратичный поиск.
|
||||
|
||||
Используются закреплённые `Void::Numeric::checked_add`, Binary и Crypto из `7b0fea6095f603f9e1904f66dfdc7752f4be4792`. Отдельного библиотечного восстанавливаемого генератора ID пока нет: [Void/Library #7](https://git.faumaray.com/Void/Library/issues/7). Локальную проверку и продвижение счётчика в `World::reserve_production` / `append_production` можно заменить после подтверждения того же поведения на Windows x64, включая групповую проверку и исчерпание.
|
||||
|
||||
Проверки: [production_identity_tests.cpp](../../../tests/production_identity_tests.cpp), [checkpoint_tests.cpp](../../../tests/checkpoint_tests.cpp), [replay_tests.cpp](../../../tests/replay_tests.cpp). Срез проверен Windows x64 GCC 16.2 через Wine: 9 проверок `--tag production-id`, полный verbose CTest — 115 core и 4 LAN. Replay сравнивает тело 14 на каждом такте в serial/2/6/12, включая сохранение в пути и дырку в ID. Существующие двоичные эталоны формата 13 совпали во всех четырёх режимах: 738386 байт (`d50ce3f5cd339e2c87c83cb599075813caf86c6384e5caaab776d57e4b727cc7`) и 393857 байт (`05972620f0ce29b1f6a3ebdd0315eb2e9faebc6629dfe38d0e804b19d86b7b0f`). Сохранён настоящий checkpoint схемы 1, полученный старым encoder до изменения. Нативный запуск Windows и MSVC не выполнялись. Общие поручения, самостоятельные ID резервов, передача владения и отмена груза остаются последующими срезами S04/S06.
|
||||
|
||||
## Данные и владение
|
||||
|
||||
|
||||
@@ -60,12 +60,22 @@ S06 владеет фактическими количествами, содер
|
||||
|
||||
## VoidLibrary и приёмка
|
||||
|
||||
[Контракт имущества M01](../custody.md) описывает владение при подборе и сдаче, возврат материалов, повтор операции и перенос старых сохранений.
|
||||
|
||||
Первый срез M01 хранит в жителях, требованиях материалов и остановках доставки постоянные `ResourceNodeId` и `StorageId`. Ноль означает отсутствие ссылки. Удаление более раннего склада или узла сохраняет цель активной работы. Списки объектов упорядочены по ID, чтение использует двоичный поиск. Формат 13 продолжает хранить прежние позиции. Загрузчик удерживает их во временном буфере, проверяет порядок ID и переводит в постоянные ссылки до проверки состояния мира. [Модель](../../../engine/include/settlement/core/world.hpp) · [Кодек](../../../engine/src/world_save.cpp)
|
||||
|
||||
Счётчик со значением `UINT64_MAX` обозначает исчерпание. Последний выдаваемый ID равен `UINT64_MAX - 1`. Фабрики и команды проверяют следующий ID через закреплённый `Void::Numeric::checked_add` до изменения объектов и геометрии. Фабрика сообщает `overflow_error`, команда возвращает `Busy` и сохраняет номер следующей команды. Общая возможность восстанавливаемого счётчика предложена в [Void/Library #7](https://git.faumaray.com/Void/Library/issues/7). Переход на неё проверяется независимыми мирами, сохранением после удаления объектов и отказом у верхней границы.
|
||||
|
||||
Семь проверок `--tag identity` под Wine покрывают удаление более ранних объектов при переноске, доставку с двух складов, кладовую, засев без склада, готовую продукцию плотника, границы счётчиков и недопустимые старые ссылки. Загруженные копии продолжают совпадать потактно в последовательном режиме и на 2/6/12 потоках, включая контрольную точку с правилами и удерживаемый снимок. Постоянные ID производственных заказов, стеков, резервов и передач входят в последующие срезы. Для общего резервирования и переноса количеств зарегистрирован [Void/Library #8](https://git.faumaray.com/Void/Library/issues/8). [Исполняемые проверки](../../../tests/identity_tests.cpp)
|
||||
|
||||
Срез S06-02 переводит физическое получение еды и материалов одной остановки на `withdraw_reserved_materials`. Операция объединяет все строки текущего склада по типу, включая несмежные повторы; строки остальных остановок не участвуют. До первого изменения проверяются ненулевой ID склада, выбранные типы и положительные количества, существование отсортированных уникальных стеков, `reserved <= count`, достаточность резерва, вместимость и проверяемые суммы источника и личного инвентаря. Счётчик назначения может достичь ровно `UINT32_MAX`. Фиксированные массивы ограничены числом типов; получение не выделяет память, удаление нескольких опустевших стеков сохраняет порядок остальных. [Контракт операции](../../../engine/include/settlement/core/inventory_transaction.hpp) · [Реализация](../../../engine/src/inventory_transaction.cpp)
|
||||
|
||||
Плотник в той же операции резервирует место для результата на складе **первого ингредиента**, даже если этот склад посещается позже другой остановки. Проверка учитывает освобождающееся место; полный склад может обменять последнюю единицу сырья на одно зарезервированное место. При отказе не меняются количества, резерв места, остановка, маршрут и состояние жителя относительно входа в получение. Перед ним `World::step` уже мог продвинуть движение или потребности. Ошибка нарушенного предусловия поднимается владельцу симуляции; runtime сохраняет последнюю здоровую публикацию и блокирует сохранение повреждённого кандидата. Прямое преобразование сырья в продукт в `finish_production` остаётся отдельной операцией и не получает гарантию атомарного преобразования рецепта. Форматы 13, LAN 11 и Current14 не меняются. [Вызовы получения](../../../engine/src/world.cpp) · [Проверки `quantity-transfer`](../../../tests/quantity_transaction_tests.cpp)
|
||||
|
||||
В закреплённом Void `7b0fea6095f603f9e1904f66dfdc7752f4be4792` используется платформенно независимая `Void::Numeric::checked_add/checked_sub`; `Storage::Batch` относится к ключам движка хранения и не меняет игровые структуры в памяти. Локальный перенос связан с [Void/Library #8](https://git.faumaray.com/Void/Library/issues/8). Условие замены — повторить проверки позднего отказа всего набора, несмежных повторов, пределов арифметики, полного склада плотника и реальных еды/доставки/публикации на Windows x64, затем сравнить продолжения и старые байтовые эталоны. Этот срез не вводит ID стеков, резервов и передач, журнал или идемпотентность: повторное получение отсеивает существующий курсор остановки, а долговременный учёт владельца груза остаётся будущей работой S06-A/S04.
|
||||
|
||||
Проверка S06-02: сборка GCC 16.2 Windows x64 Release и запуск под Wine; 14/14 проверок `quantity-transfer`, полный CTest — 136/136 core и 9/9 LAN, включая современные сохранения и повтор на 1/2/6/12 исполнителях. Оба старых байтовых корпуса (`old-trajectory.bin`, `identity-compat-old.bin`) совпали с проекцией формата 13 на всех четырёх режимах. Нативный запуск Windows и MSVC отдельно не проверялись.
|
||||
|
||||
Применять существующие подходящие средства контейнеров, проверяемой арифметики, сериализации и результатов из [VoidLibrary](../void-library.md). Для отсутствующей возможности перед локальной реализацией найти либо создать issue в `Void/Library` и указать ссылку в задаче и коде.
|
||||
|
||||
- Два заказа запрашивают последнюю единицу ресурса. Только один получает резерв, свободный запас остаётся неотрицательным.
|
||||
|
||||
@@ -47,6 +47,12 @@
|
||||
|
||||
## Приёмка
|
||||
|
||||
Клиент Windows может обслуживать хост через `LanSession::poll_host(SimulationRuntime&)`, а гостя — через `poll_guest()`. Хост читает опубликованный снимок и отправляет команду доверенного слота 2 владельцу мира. Сетевой опрос продолжает работу, пока симуляция завершает приказ. `take_result()` возвращает гостю результат вместе с исходными параметрами намерения. До чтения результата следующая команда гостя остаётся в ограниченной очереди. [Сетевой интерфейс](../../../app/lan_session.hpp)
|
||||
|
||||
Совместимый протокол 11 допускает точный встроенный набор правил и активную колонию 32×32. После смены инкарнации соединение проходит вход заново. Принятая операция слота сохраняется при разрыве TCP. Новое подключение ждёт её завершения, затем получает актуальные номера команд. Ответ прежнего подключения отбрасывается. Обычный отказ игры сохраняет старый сетевой номер, а номер конверта владельца продвигается.
|
||||
|
||||
Пять проверок `--tag lan-owner` под Wine покрывают квитанции, заполнение очереди, совмещённые пакеты, переподключение при задержанной публикации, откат с незавершённой командой и отказ при несовместимых правилах. Отдельный двоичный клиент прототипа подтвердил обмен в обоих направлениях с новым хостом и гостем. Проверка физической Windows и двух машин остаётся частью сетевой приёмки. [Сценарии](../../../tests/lan_tests.cpp)
|
||||
|
||||
Первый исполняемый срез — диспетчер одного города. Транспорт передаёт доверенный слот отдельно от конверта команды. Для каждого слота диспетчер хранит точные результаты принятых и отклонённых приказов, сверяет содержимое повтора и отсеивает команды прежней инкарнации. По умолчанию после 65 536 записей в слоте новые запросы получают ответ о занятости. Сохранённые ответы доступны до конца инкарнации. Копия журнала позволяет владельцу мира публиковать результат только после успешного изменения. [Диспетчер](../../../engine/include/settlement/core/command_dispatcher.hpp) · [Условие замены на Void](https://git.faumaray.com/Void/Library/issues/6)
|
||||
|
||||
Селектор `--tag session` под Wine выполнил десять проверок, включая двух клиентов, конфликт данных повтора, откат с новой инкарнацией и отказ до/после изменения. Сценарий из 700 тактов сверяет эталон и 2/6/12 потоков. Подключение окна и сетевого транспорта к владельцу мира входит в следующий срез M01. [Сценарии](../../../tests/session_tests.cpp)
|
||||
|
||||
@@ -1,10 +1,33 @@
|
||||
# S17. D3D11-рендеринг, камера и визуальное состояние
|
||||
|
||||
Статус — план реализации. Клиент должен показывать редактируемый объёмный мир, позволять выбрать нужный этаж и сохранять отзывчивость во время симуляции, сохранения и сетевого обмена. Рендер развивается с [M01](../milestones/M01.md) до приёмки [M11](../milestones/M11.md). Главная ранняя сцена — [дом на склоне M03](../milestones/M03.md). [Мастер-план](../../../PLAN.md) · [Реестр паритета](../parity.md)
|
||||
Статус — S17-W01 реализован и проверен в Windows x64/Wine; ожидает независимой приёмки. Остальные этапы — план реализации. Клиент должен показывать редактируемый объёмный мир, позволять выбрать нужный этаж и сохранять отзывчивость во время симуляции, сохранения и сетевого обмена. Рендер развивается с [M01](../milestones/M01.md) до приёмки [M11](../milestones/M11.md). Главная ранняя сцена — [дом на склоне M03](../milestones/M03.md). [Мастер-план](../../../PLAN.md) · [Реестр паритета](../parity.md)
|
||||
|
||||
## Исходное состояние
|
||||
|
||||
`D3DScene::render` принимает `const World&`, заново собирает геометрию карты, ресурсов, построек и жителей, загружает её и вызывает D3D11. `SceneView` хранит положение камеры, выбор и предпросмотр. Вызов происходит из `WM_PAINT`, а симуляция — из `WM_TIMER` того же окна. Основой нового клиента остаётся имеющийся Win32/D3D11-путь. [Интерфейс сцены](../../../app/d3d_scene_win32.hpp) · [Текущий рендер](../../../app/d3d_scene_win32.cpp)
|
||||
S17-W01 сохраняет существующую плоскую карту и Win32/D3D11. `PreparedFrame` удерживает один принятый `World`, параметры камеры и области, копии чертежей/комнат, выбор и предпросмотр, готовую CPU-геометрию, строки HUD и собственный шрифт. Главная и дочерняя `WM_PAINT` сначала удерживают весь пакет, затем рисуют без обращения к живому миру или векторам редактирования. [Подготовка кадров](../../../app/viewer_win32.cpp) · [Интерфейс сцены](../../../app/d3d_scene_win32.hpp)
|
||||
|
||||
Отдельный таймер 16 мс выбирает актуальный кадр только для видимой ненулевой игровой области и при изменениях. Таймер управления/LAN остаётся 60 мс, владелец симуляции — 50 мс. Это частоты обслуживания, а не утверждение о физической частоте экрана. Камера и размеры не пересобирают плоскую CPU-геометрию; неизменённая геометрия повторно не загружается на GPU. Размер render target, пересоздание устройства или возврат к удержанному старому пакету требуют соответствующей загрузки.
|
||||
|
||||
Ключ геометрии учитывает удержанный снимок мира, курсор и его допустимость, переносимый объект, жителя, все поля чертежей/комнат и предпросмотра, режим крыши/стен и переносимую комнату. Сравнение удерживаемых объектов снимков различает новые публикации даже при одинаковом такте. Пакеты владеют CPU-геометрией совместно; у renderer остаётся только текущая GPU-загрузка. Старый пакет можно отрисовать после нового или после сброса backend.
|
||||
|
||||
Пока `ViewerSession::changing_world()` истинно, прежнее представление сохраняется, включая отсутствие мира. Фоновая публикация между проверкой future и чтением мира не выпускает кандидата в UI. Только обработанный `Replaced` сбрасывает чертежи, выбор и камеру перед подготовкой замены. Подготовка приостанавливается внутри обработки событий и отрисовки; вложенная инвалидизация остаётся запросом следующего кадра. `BeginPaint` и временные DC/bitmap имеют RAII, backend удерживается до возврата из `Present`. При отказе остаётся HUD ошибки с восстановлением через повторный вход из меню; резервного GDI-рендера карты нет.
|
||||
|
||||
### Проверка S17-W01
|
||||
|
||||
Постоянная CMake/CTest-цель `settlement_viewer_frame_smoke` использует относительный include реального обработчика и настоящие главное/дочернее окна. [Тест](../../../tests/viewer_frame_smoke.cpp) проверяет:
|
||||
|
||||
- колесо и оба перетаскивания с изменением кадра/пикселей, когда настоящий рабочий `World` и запись файла `WriteStage` удерживаются барьерами; таймер событий в этой части не вызывается;
|
||||
- неизменность полного канонического снимка и такта, повторное использование CPU/GPU-геометрии, побайтовое равенство сохранённого checkpoint исходному `World` и метаданным;
|
||||
- отдельный удержанный файловый reader, старые комнаты/чертежи после редактирования, вложенные paint и незатерянную инвалидизацию;
|
||||
- публикацию установки после `poll()` до чтения мира, вложенные paint в этом промежутке, сохранение прежнего/нулевого представления до `Replaced`;
|
||||
- скрытие, минимизацию, меню, восстановление последней публикации, изменение размера, нулевую область, ошибку и повторный запуск renderer, отрисовку старого пакета после сброса backend;
|
||||
- разрушение окна внутри paint и игнорирование оставшихся таймерных сообщений.
|
||||
|
||||
Сборка: GCC 16.2 MinGW, Release, закреплённая VoidLibrary `7b0fea6095f603f9e1904f66dfdc7752f4be4792`, `BUILD_TESTING=ON`. Проверка: `cmake --build <build> --parallel 6`, `ctest --test-dir <build> -V`, `git diff --check`. В Wine 11 с доступным DISPLAY работают видимый swap chain и offscreen WARP; проба DXGI сообщает «ATI Radeon HD 5600 Series» для обоих типов устройств. Это имя адаптера Wine, а не подтверждение физического GPU. Если устройства отсутствуют, smoke возвращает CTest skip 77; отказ renderer при доступном устройстве считается ошибкой.
|
||||
|
||||
Дополнительно прошли прежние UI-прогоны: blueprint/room handlers, отказ команд и сохранность чертежей, загрузка/выход из гостя, rollback LAN-диалогов, три настоящих процесса viewer с изолированным `LOCALAPPDATA`, меню, реальный file picker, современное и прежнее сохранение. Нативная Windows, физическая потеря устройства, 1080p60/p95 и будущая воксельная геометрия здесь не проверялись. Тест отказа renderer намеренно подаёт неподходящий viewport и проверяет штатный HUD/повторный вход.
|
||||
|
||||
Общий примитив публикации остаётся связан с [Void/Library #5](https://git.faumaray.com/Void/Library/issues/5). При его появлении заменить локальное владение только после тех же проверок старого пакета, вложенной установки и срока жизни геометрии. `PreparedFrame` и игровые правила формирования HUD остаются клиентскими данными.
|
||||
|
||||
## Границы данных и потоков
|
||||
|
||||
@@ -16,7 +39,7 @@
|
||||
|
||||
## Последовательность реализации
|
||||
|
||||
1. **S17-W01, M01.** Ввести публикацию снимков и самостоятельный цикл кадров. Перенести обращения к миру из обработчиков отрисовки в подготовку снимка. Проверить работу камеры при искусственно долгом такте.
|
||||
1. **S17-W01, M01 — реализовано, ожидает приёмки.** Неизменяемый пакет, отдельный таймер кадра и проверки камеры при удержанном рабочем/файловом вводе-выводе описаны выше.
|
||||
2. **S17-W02, M02.** Построить геометрию изменившихся чанков и обработку общих граней. Добавить отсечение невидимых областей и приоритет ближних участков. В тесте редактировать грань между двумя чанками и проверять отсутствие щели и дублирующей поверхности.
|
||||
3. **S17-W03, M02–M03.** Добавить вращение, масштабирование вокруг указателя, выбор по лучу и срез высоты. Выбор возвращает регион, клетку, грань и ревизию, по которым интерфейс формирует намерение. При подтверждении симуляция проверяет действие на актуальной геометрии.
|
||||
4. **S17-W04, M03–M07.** Разделить статическую геометрию, жителей, предметы и эффекты. Интерполировать визуальные позы между подтверждёнными тактами. Подключить оригинальные модели, анимацию, освещение, время суток и читаемую индикацию работы.
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# S18. Интерфейс, управление и обратная связь
|
||||
|
||||
Статус — план реализации. Интерфейс должен давать игроку понятный путь от выбора правил до устойчивого города и объяснять препятствия в работе жителей. Первый полный путь проверяется в [M03](../milestones/M03.md), сетевые состояния — в [M09](../milestones/M09.md), доступность и установка — в [M11](../milestones/M11.md). [Мастер-план](../../../PLAN.md) · [Реестр паритета](../parity.md)
|
||||
Статус — первый срез S18-W01 и выбор двух встроенных правил S18-02 реализованы: существующий Win32-клиент читает опубликованные снимки и получает результаты команд и файловых операций асинхронно. Остальные части интерфейса остаются планом. Интерфейс должен давать игроку понятный путь от выбора правил до устойчивого города и объяснять препятствия в работе жителей. Первый полный путь проверяется в [M03](../milestones/M03.md), сетевые состояния — в [M09](../milestones/M09.md), доступность и установка — в [M11](../milestones/M11.md). [Мастер-план](../../../PLAN.md) · [Реестр паритета](../parity.md)
|
||||
|
||||
## Исходное состояние
|
||||
|
||||
@@ -16,6 +16,20 @@
|
||||
|
||||
## Последовательность реализации
|
||||
|
||||
Первый срез S18-W01 отделяет владение миром от оконных обработчиков через [ViewerSession](../../../app/viewer_session.hpp). Один `SimulationRuntime` и один `CheckpointFiles` живут до выхода из приложения. Новый мир, загрузка и выход гостя устанавливают подготовленное состояние через билет загрузки с новой инкарнацией; долгий тик не требует ожидания или остановки прежнего потока в окне. Отображение удерживает неизменяемый мир, а гость сохраняет последнее полученное состояние для продолжения после явного выхода из сети. Начальное, непосредственно заменяемое и последнее подготовленное состояние проходят `validate_colony_checkpoint` из [S19](S19.md) до установки и дополнительно ограничены картой 32×32. Допускаются только точные встроенные составы стандартной колонии и `settlement.plankbeds`; неизвестный, лишний или изменённый пакет, пустой мир, нулевой идентификатор либо поэтапная кровать с простыми правилами отклоняются с сохранением текущего мира.
|
||||
|
||||
На настоящем главном экране нативный список «Правила только новой колонии» выбирает поэтапную кровать с опорой и тканью (исходный выбор) либо простую кровать из одной доски. Выбор живёт в процессе и применяется только кнопкой «Новая колония»: `make_colony_checkpoint` создаёт соответствующий мир, новый UUID и точный манифест. «Продолжить», список сохранений и выбор файла восстанавливают правила самого сохранения. Исторический стандартный мир с простыми кроватями, поэтапными кроватями или без активного сценария принимается без смены режима. В простом режиме описания всех готовых домов, включая дом шахтёра, показывают одну доску; выбор деревянной/каменной опоры скрыт.
|
||||
|
||||
Старый LAN-протокол 11 допускает только точный стандартный манифест из текущей авторитетной публикации. Проверка выполняется при выборе Host после возврата из модального меню, а для отложенного создания — повторно перед запуском сети после установки мира. Пока ожидается любая смена мира, Host отклоняется без замены мира, отмены загрузки или изменения сетевого объекта. Даже если опубликованный старый мир стандартный, ожидающая загрузка простых правил не открывает слушатель. Выход старого гостя по-прежнему присваивает полученному миру замороженные стандартные правила; формат LAN не расширен.
|
||||
|
||||
Локальная очередь ограничена 64 намерениями и одной отправленной командой. Номер запроса берётся из подтверждённого снимка; занятая очередь владельца оставляет намерение для повтора. Чертёж комнаты, мебели или старого домика удаляется только после принятого результата. Отказ сохраняет возможность редактирования, повторное нажатие не дублирует ожидающую операцию. Гостевые квитанции сопоставляются с ограниченной очередью отправок и поколением сессии. Таймер обслуживает завершения также на главном экране и внутри модальных меню. Одиночная пауза и выбор файла приостанавливают игровое время; меню хозяина сохраняет существующее сетевое поведение.
|
||||
|
||||
Сохранение удерживает здоровый опубликованный снимок, а общий файловый сервис сохраняет порядок записей через смену мира. Только последняя актуальная операция обновляет сообщение. Любая новая попытка загрузки сначала отменяет актуальность предыдущего билета, включая попытку открыть повреждённый или отсутствующий файл. Сбой симуляции оставляет последний подтверждённый вид и возможность явной загрузки. [Файлы и восстановление](S15.md) · [Сетевой адаптер](S16.md) · [Проверки состояния клиента](../../../tests/viewer_session_tests.cpp)
|
||||
|
||||
Проверка среза: сборка Windows x64 GCC 16.2; Wine 11, verbose CTest — 99 проверок ядра, 9 LAN и 10 состояния клиента. Отдельный прогон настоящего `settlement_viewer.exe` прошёл создание колонии, движение времени, подтверждённую смену приоритета, модальную паузу, выбор файла сохранения, продолжение партии, загрузку нового формата через главное меню в новом процессе, отказ повреждённого файла, загрузку старого формата из списка и штатное закрытие трёх процессов. Сохранения размещались в отдельном временном `LOCALAPPDATA`. Дополнительный Win32-прогон настоящих обработчиков проверил отказ и повтор чертежа, принятую комнату при переносе другой комнаты, старый домик через общий журнал, отрисовку и сохранение при заблокированном тике, смену мира и гостя без ожидания тика. Регрессионный прогон проверил отказ ошибочного повторного подключения с сохранением полученной колонии, откат при отказе владельца после подготовки соединения и запрет подтверждения сноса во время ожидающей загрузки. Отдельная проверка состояния клиента покрывает остановку после сбоя, успешную загрузку и возобновление тиков. Нативная Windows, доступность и визуальная проверка масштабирования остаются отдельной приёмкой; настройки масштаба, клавиш и звука за пределами этого среза.
|
||||
|
||||
Проверка S18-02: повторная Windows x64 GCC 16.2 сборка и verbose CTest под Wine 11 — 122 проверки ядра, 9 LAN и 14 состояния клиента. Четыре новые проверки покрывают оба профиля при создании/сохранении/повторной загрузке, начальные и асинхронные отказы манифестов и идентификаторов, отмену актуальности старой правильной загрузки последующей несовместимой, исторические режимы и стандартный импорт гостя. Отдельный прогон настоящего приложения в изолированном `LOCALAPPDATA` проверяет окно 775×640, Tab/стрелки и мышь в нативном списке, мышь/Space на «Новая колония», точные манифесты и режимы в реальных сохранениях, продолжение, список и диалог открытия при противоположном выборе новых правил. Новый процесс возвращает стандартный выбор новой колонии и открывает последнее сохранение с простыми правилами. Прогон настоящих обработчиков удерживает загрузку простого мира поверх стандартного при прямом Host и Host из модального меню, проверяет сохранение мира/билета/сетевого объекта/кода/порта и отсутствие слушателя; отложенный Host повторно отклоняет несовместимую установленную публикацию. Проверены скрытие опор и описание дома шахтёра. Нативная Windows, экранный диктор и повышенный DPI остаются отдельной приёмкой.
|
||||
|
||||
1. **S18-W01, M01–M02.** Отделить чтение снимков и отправку команд от Win32-обработчиков. Определить модель состояния инструмента, выделения и отмены. Добавить настройку масштаба, клавиш и звука с проверкой конфликтов назначений.
|
||||
2. **S18-W02, M02–M03.** Собрать путь демо. Игрок размечает склон, ставит склад, выбирает этаж, редактирует дом, видит материалы и подтверждает строительство. Затем назначает мебель, проверяет потребности жителей и сохраняет незавершённую работу.
|
||||
3. **S18-W03, M04–M06.** Добавить панели рабочих очередей, профессий, запасов и торговых сделок. Фильтры и сортировки устойчиво сохраняют выбранный объект при обновлении снимка. Список населения ведёт к жителю или объясняет его нахождение в другом регионе.
|
||||
@@ -42,7 +56,7 @@
|
||||
|
||||
## VoidLibrary
|
||||
|
||||
Сверить доступные возможности конфигурации, строк, Unicode, коллекций, наблюдаемости и диспетчеризации в закреплённой VoidLibrary. Использовать подходящую реализацию. Для отсутствующей возможности до локальной реализации найти или открыть issue в `Void/Library`, указав необходимое поведение и Windows-проверку. Наличие библиотеки не переносит авторитет игровой команды из симуляции в интерфейс. [Матрица VoidLibrary](../void-library.md)
|
||||
Сверить доступные возможности конфигурации, строк, Unicode, коллекций, наблюдаемости и диспетчеризации в закреплённой VoidLibrary. Использовать подходящую реализацию. Для отсутствующей возможности до локальной реализации найти или открыть issue в `Void/Library`, указав необходимое поведение и Windows-проверку. Срез использует `SimulationRuntime` и `CheckpointFiles` поверх закреплённой версии `7b0fea6095f603f9e1904f66dfdc7752f4be4792`, без нового исполнителя. Выбор S18-02 использует готовые фабрику и проверку профилей S19; общий пробел разрешения пакетов связан с [Void/Library #4](https://git.faumaray.com/Void/Library/issues/4). Схема игровых правил и нативные контролы остаются у игры. Повторно используются связанные пробелы [Void/Library #5](https://git.faumaray.com/Void/Library/issues/5) для удержания опубликованного состояния и [#6](https://git.faumaray.com/Void/Library/issues/6) для результатов команд. Условие будущей замены — сохранить проверенные отказы очереди, отсечение старой инкарнации, результат отклонённой команды и удержание предыдущего снимка. Наличие библиотеки не переносит авторитет игровой команды из симуляции в интерфейс. [Матрица VoidLibrary](../void-library.md)
|
||||
|
||||
## Приёмка
|
||||
|
||||
|
||||
@@ -73,3 +73,80 @@ powershell.exe -NoProfile -ExecutionPolicy Bypass -File .\build.ps1
|
||||
Текущие тесты используют `Void::Testing`. Перед собственным runner, профилировщиком, таймером, журналом и форматом отчёта проверить существующие возможности VoidLibrary. Использовать подходящую реализацию. Для отсутствующей возможности найти или создать issue в `Void/Library`, приложить воспроизводимый пример нужного поведения и связать локальную реализацию с issue. [Матрица VoidLibrary](../void-library.md)
|
||||
|
||||
Система принята, когда каждый обязательный сценарий имеет команду запуска либо точную ручную процедуру, исходный мир, фактический результат и границы среды. Финальный отчёт различает кросс-сборку, Wine, нативную Windows, физические ПК и измерения GPU. Готовность пакета подтверждается запуском из поставки с её библиотеками и материалами. [Сохранения](S15.md) · [Сеть](S16.md) · [Происхождение материалов](S20.md)
|
||||
|
||||
## M01: наблюдаемый порядок завершения (S21-01)
|
||||
|
||||
Проверка подготовлена поверх `66af7c5` в `system/s21-verification`. Закреплённый
|
||||
Void `7b0fea6095f603f9e1904f66dfdc7752f4be4792` предоставляет `FuturePool::try_submit`
|
||||
с сохранением отклонённого callable и доставкой исключений через future. Его
|
||||
`Testing::DeterministicRun` управляет тестовыми действиями; он не наблюдает возврат
|
||||
реального `World` callable. Поэтому локальный `WorkerPoolOptions::after_execute(index)`
|
||||
вызывается после успешного возврата callable, перед готовностью future. Исключение
|
||||
наблюдателя попадает в тот же future; ошибка до исполнения или внутри callable
|
||||
не вызывает наблюдателя. Без хуков остаётся прежняя ветка без счётчика отправок.
|
||||
[Реализация](../../../engine/include/settlement/core/worker_pool.hpp) ·
|
||||
[Контракт замены Void/Library#15](https://git.faumaray.com/Void/Library/issues/15).
|
||||
|
||||
Условие замены локального наблюдателя библиотечным — сохранить проверяемые возврат
|
||||
`void`, значения, lvalue-ссылки, move-only результата и callable, ровно одно
|
||||
успешное уведомление, исключения и исполнение при переполнении на координаторе.
|
||||
[ExecutorTests](../../../tests/executor_tests.cpp) дополнительно удерживает сам
|
||||
наблюдатель и проверяет, что future ещё не готов. Перенос уведомления к началу
|
||||
вызова нарушает проверку завершённого действия.
|
||||
|
||||
[ReplayTests](../../../tests/replay_tests.cpp) использует два отдельных сценария:
|
||||
|
||||
- Seed 101, два жителя в `(5,1)`, одно достижимое общее задание в `(1,1)`.
|
||||
При 2/6/12 потоках первые отправки 0 и 1 — реальные независимые вычисления
|
||||
`choose_jobs` для жителей 0 и 1. Контроллер разрешает первый расчёт, ждёт его
|
||||
`after_execute`, затем разрешает второй. Получены обе последовательности
|
||||
`A->B` и `B->A`; владельцем задания остаётся житель с меньшим стабильным ID.
|
||||
- Seed 97, два голодных жителя и одна ягода. Здесь общих заданий нет, поэтому
|
||||
отправки 0 и 1 — стадии продвижения жителей. Захват еды выполняется
|
||||
последовательно в `assign_meals` до этих стадий. Проверяются противоположные
|
||||
завершения продвижения, один владелец, сохранность ягоды и ровно одно потребление;
|
||||
параллельный арбитраж еды этим сценарием не заявляется.
|
||||
|
||||
Оба сценария проверены с `max_admitted=4096` и `1`. Контроллер находится вне
|
||||
координатора, который при переполнении сам может ждать в inline callable.
|
||||
Ожидания ограничены пятью секундами; scope guard всегда открывает ворота до
|
||||
ожидания координатора или разрушения пула. Каждая из 24 конфигураций сравнивает
|
||||
все 40 тактов с последовательным эталоном через настоящий `Current14` writer.
|
||||
Лог содержит фактическую последовательность завершений каждой конфигурации.
|
||||
|
||||
[RuntimeTests](../../../tests/runtime_tests.cpp) удерживает старую задачу во время
|
||||
постановки загрузки того же сохранения в очередь. Пока задача удержана, доступны
|
||||
старый неизменяемый снимок и захват сохранения, а установка и старая команда ещё
|
||||
не завершены. Перед захватом кандидата проверяется равенство числа начатых и
|
||||
вернувшихся задач. После установки меняется session, старая команда получает
|
||||
`StaleSession`; дополнительный барьер и следующий такт подтверждают неизменность
|
||||
старого снимка и соответствие нового мира эталону.
|
||||
|
||||
[Test-local диагностика](../../../tests/replay_diagnostics.hpp) сначала сравнивает
|
||||
канонические байты. Только при несовпадении она показывает первый различающийся
|
||||
публичный факт: ID жителя/задания/производства, поле, expected/actual; для запасов —
|
||||
владельца и тип предмета; для команд — игрока и следующую последовательность.
|
||||
Сравнение квитанций содержит игрока, номер команды, статус, tick и revision.
|
||||
Контекст включает первый обнаруженный tick/attempt, seed мира, число потоков,
|
||||
расписание, состояние загрузки и предел допуска. Непокрытое публичной проекцией
|
||||
поле получает смещение и значения байта. Это диагностическая проекция, а не
|
||||
второй кодек или альтернативный критерий равенства. Отдельно проверены равенство,
|
||||
ошибки запаса/задания/команды/квитанции, лишний ID и байтовый fallback.
|
||||
|
||||
Проверка 2 декабря 2026 года: Windows x64 Release кросс-сборка GCC 16.2.0,
|
||||
выполнение Wine 11.0. CTest `-V`: 3/3 цели, 141 core + 9 LAN + 10 viewer тестов.
|
||||
Отдельные теги: executor 10/10, replay 8/8, runtime 11/11. Логи:
|
||||
`/tmp/stoneheart-milestones.xprJ2SVp/s21-replay-{configure,build,ctest,executor,replay,runtime}.log`.
|
||||
Повторная окончательная сборка/CTest: `s21-replay-final-build.log`, `s21-replay-final-ctest.log` (3/3, 18,35 с).
|
||||
Два внешних probe собраны заново против этой библиотеки; при 1/2/6/12 потоках
|
||||
`cmp` подтвердил совпадение обоих исторических корпусов:
|
||||
|
||||
- `trajectory.cpp`: 361 такт, 5 приёмов пищи; SHA-256
|
||||
`d50ce3f5cd339e2c87c83cb599075813caf86c6384e5caaab776d57e4b727cc7`.
|
||||
- `identity-compat.cpp`: доставка и строительство после удаления других объектов;
|
||||
SHA-256 `05972620f0ce29b1f6a3ebdd0315eb2e9faebc6629dfe38d0e804b19d86b7b0f`.
|
||||
|
||||
Логи probe: `s21-replay-probe-build.log`, `s21-replay-golden.log` в том же каталоге.
|
||||
Физическая Windows, длительная нагрузка и производительность GPU здесь не проверялись.
|
||||
Serena/граф были связаны с основным checkout; для изолированного worktree использована
|
||||
прямая проверка исходников без переключения общего проекта и без заявления о покрытии графом.
|
||||
@@ -15,7 +15,7 @@
|
||||
|
||||
## Срез на 2 декабря 2026 года
|
||||
|
||||
Игра закрепляет Void Library 1.2.3 на коммите `7b0fea6095f603f9e1904f66dfdc7752f4be4792`. На момент проверки `main` указывал на тот же коммит. CMake игры явно выбирает `Binary` и `Core`, а при включённых тестах ещё `Testing`. Для следующих модулей проверены исходники закреплённой версии. Их включение и измерения в итоговой Windows-сборке входят в соответствующие этапы.
|
||||
Игра закрепляет Void Library 1.2.3 на коммите `7b0fea6095f603f9e1904f66dfdc7752f4be4792`. На момент проверки `main` указывал на тот же коммит. Windows-сборка M01 выбирает `Algorithms`, `Async`, `Binary`, `Core`, `Crypto`, `Data`, `Math`, `Text` и `Time`. При сборке тестов добавляется `Testing`. [Настройки зависимости](../../CMakeLists.txt)
|
||||
|
||||
| Задача игры | Что есть в VoidLibrary | Решение и граница применимости |
|
||||
|---|---|---|
|
||||
@@ -49,4 +49,18 @@
|
||||
|
||||
У текущего `settlement::WorkerPool` есть отправка функции, получение future, число потоков и ожидание принятых работ при завершении. Сверить эти четыре операции с `ThreadExecutor + FuturePool`. Начать перенос с эталонной партии, затем испытать переполнение, частичный запуск и остановку. При переполнении симуляция должна выполнить тот же набор логических работ с тем же результатом. Выбранный вариант измерить на малой партии и на нагруженном городе. Существующие тесты Void проверяют поведение утилит, игровые тесты должны дополнительно сравнить хеши мира. [Текущий пул](../../engine/src/worker_pool.cpp) · [Проверки FuturePool](https://git.faumaray.com/Void/Library/src/commit/7b0fea6095f603f9e1904f66dfdc7752f4be4792/tests/standalone/Async/FuturePool.cpp) · [Проверки запуска потоков](https://git.faumaray.com/Void/Library/src/commit/7b0fea6095f603f9e1904f66dfdc7752f4be4792/tests/standalone/Async/ThreadExecutor.cpp)
|
||||
|
||||
## Подготовка воксельного мира M02
|
||||
|
||||
Для проверки порядка завершения реальных вычислений [S21](systems/S21.md) использует работающий `FuturePool`. У `Testing::DeterministicRun` есть очередь управляемых тестовых действий. Для потактного теста игры требуется отдельно зарегистрировать возврат конкретной функции исполнителя, переставить две такие операции и проверить тот же результат мира на 2/6/12 потоках и при заполненной очереди. Предложение относится к тестовому адаптеру реальных задач. [Void/Library #15](https://git.faumaray.com/Void/Library/issues/15) · [Адаптер исполнения игры](../../engine/include/settlement/core/worker_pool.hpp)
|
||||
|
||||
Для будущей генерации и навигации проверены публичные заголовки и тесты того же pin. Отдельная программа, собранная для Windows x64 GCC 16.2, прошла под Wine 11. Проверены граничная арифметика, побайтовый FNV-1a, начальное значение Xoshiro256 для seed 42, очередность обхода графа и ограничение объёма поиска. Координаты и seed можно кодировать фиксированными полями через `Binary::Writer::writeLittle` и хешировать средствами `Void::Hash`. Для равных приоритетов поиска порядок задаёт клиент. [Задание исследования](../agent-workflow/tasks/M02-R1.md) · [Числовые операции](https://git.faumaray.com/Void/Library/src/commit/7b0fea6095f603f9e1904f66dfdc7752f4be4792/include/Void/Math/Numeric.hpp)
|
||||
|
||||
| Запрос в Void/Library | Локальный потребитель и проверка замены |
|
||||
|---|---|
|
||||
| [Восстановление потока RNG и воспроизводимый выбор целого, #10](https://git.faumaray.com/Void/Library/issues/10) | [Генератор прототипа](../../engine/include/settlement/core/deterministic_rng.hpp) и [S02](systems/S02.md). Сохранять алгоритм и версию генератора. Сверить фиксированные значения последовательности, продолжение после смешанных вызовов и независимость двух потоков. Исторический SplitMix64 должен воспроизводить старый ландшафт. |
|
||||
| [Частное и остаток для знаковых координат, #11](https://git.faumaray.com/Void/Library/issues/11) | [S02](systems/S02.md). У `checked_div(-1,32)` результат 0. Для чанка требуются чанк −1 и локальная координата 31. Проверить обе стороны каждой границы и предельные значения знакового типа. |
|
||||
| [Обход вокселей лучом, #12](https://git.faumaray.com/Void/Library/issues/12) | [S17](systems/S17.md). Проверить выбранную ячейку и грань при попадании в угол 32³ с обеих сторон, на отрицательных координатах и при ограничении длины. Камера и отсечение высоты принадлежат клиенту. |
|
||||
| [Набор прочитанных ревизий, #13](https://git.faumaray.com/Void/Library/issues/13) | [Маршруты S03](systems/S03.md) и [геометрия S17](systems/S17.md). Смена опоры в соседнем чанке сбрасывает маршрут, открытие границы делает прежний отрицательный ответ устаревшим, а правка непрочитанного чанка сохраняет результат. При смене инкарнации результат устаревает целиком. |
|
||||
| [Ограниченные разреженные объёмы и атомарные правки страниц, #14](https://git.faumaray.com/Void/Library/issues/14) | [Каталог чанков S02](systems/S02.md). Проверить изменение двух чанков одной командой, точный отказ при устаревшей ревизии либо исчерпанном бюджете и воспроизводимый порядок дельт. Генератор, материалы и такт активации остаются в игре. |
|
||||
|
||||
[Мастер-план](../../PLAN.md)
|
||||
@@ -15,7 +15,7 @@
|
||||
|
||||
namespace settlement {
|
||||
|
||||
inline constexpr std::uint32_t checkpoint_version = 1;
|
||||
inline constexpr std::uint32_t checkpoint_version = 2;
|
||||
inline constexpr std::string_view checkpoint_signature = "STHCHKPT";
|
||||
inline constexpr std::size_t max_checkpoint_body_bytes = 128 * 1024 * 1024;
|
||||
inline constexpr std::size_t max_checkpoint_metadata_bytes = 64 * 1024;
|
||||
@@ -47,10 +47,11 @@ struct WorldCheckpoint {
|
||||
RulesManifest rules;
|
||||
};
|
||||
|
||||
// Version 1 stores magic, schema, metadata length and body length, then world UUID,
|
||||
// Both schemas store magic, schema, metadata length and body length, then world UUID,
|
||||
// city, tick, rules fingerprint and the sorted complete package closure. Each
|
||||
// package stores its ID, exact version and SHA-256. The body uses World's save
|
||||
// codec. A final SHA-256 covers every preceding byte. Integers are little-endian.
|
||||
// codec: schema 1 accepts legacy bodies 1–13; schema 2 requires body 14.
|
||||
// A final SHA-256 covers every preceding byte. Integers are little-endian.
|
||||
// The caller holds a stable World for the entire synchronous encode operation.
|
||||
[[nodiscard]] std::expected<std::string, CheckpointDiagnostic> encode_checkpoint(
|
||||
const World& world, Void::Uuid::Uuid world_id, std::uint64_t city,
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
#pragma once
|
||||
|
||||
#include "settlement/core/world.hpp"
|
||||
|
||||
#include <expected>
|
||||
#include <span>
|
||||
|
||||
namespace settlement {
|
||||
|
||||
enum class QuantityTransferError {
|
||||
InvalidStorage,
|
||||
InvalidMaterial,
|
||||
MissingSelection,
|
||||
InvalidStock,
|
||||
InsufficientStock,
|
||||
Overflow,
|
||||
Capacity,
|
||||
};
|
||||
|
||||
// Pick up all lines for source.id; other delivery stops are left alone. Failure
|
||||
// leaves both owners unchanged. Optional output capacity is reserved in the same
|
||||
// commit, after accounting for the space freed by the pickup. No allocation.
|
||||
// This is one physical pickup, not an idempotent transfer or recipe conversion.
|
||||
[[nodiscard]] std::expected<void, QuantityTransferError> withdraw_reserved_materials(
|
||||
Storage& source, Inventory& destination, std::span<const MaterialReservation> materials,
|
||||
bool reserve_output_slot = false) noexcept;
|
||||
|
||||
} // namespace settlement
|
||||
@@ -0,0 +1,84 @@
|
||||
#pragma once
|
||||
|
||||
#include "settlement/core/voxel_region.hpp"
|
||||
#include <Void/Core/Uuid.hpp>
|
||||
#include <cstddef>
|
||||
#include <optional>
|
||||
#include <span>
|
||||
#include <stop_token>
|
||||
#include <vector>
|
||||
|
||||
namespace settlement {
|
||||
|
||||
enum class VoxelNavigationStatus {
|
||||
Reachable, Unreachable, Unavailable, SearchBoundary, LimitExceeded,
|
||||
Cancelled, InvalidInput, AllocationFailed
|
||||
};
|
||||
|
||||
struct VoxelNavigationLimits {
|
||||
std::size_t max_vertices = 65'536;
|
||||
std::size_t max_steps = 1'000'000;
|
||||
std::size_t max_samples = 4'000'000;
|
||||
std::size_t max_scratch_bytes = 8 * 1024 * 1024;
|
||||
std::size_t max_goals = 64;
|
||||
std::size_t max_dependencies = 4096;
|
||||
};
|
||||
|
||||
struct VoxelReadSet {
|
||||
RegionId region = 0;
|
||||
Void::Uuid::Uuid session;
|
||||
// Sorted unique chunk coordinates, including blocked and unavailable reads.
|
||||
std::vector<ChunkStamp> chunks;
|
||||
[[nodiscard]] bool current(const VoxelRegion& world, const Void::Uuid::Uuid& epoch) const noexcept;
|
||||
};
|
||||
|
||||
struct VoxelTraversalResult {
|
||||
VoxelNavigationStatus status = VoxelNavigationStatus::InvalidInput;
|
||||
VoxelReadSet consulted;
|
||||
};
|
||||
|
||||
struct VoxelPathRequest {
|
||||
RegionId region = 0;
|
||||
Void::Uuid::Uuid session;
|
||||
VoxelPosition start;
|
||||
// The caller chooses a finite search window contained in the region.
|
||||
VoxelBounds search_bounds;
|
||||
std::vector<VoxelPosition> goals;
|
||||
VoxelNavigationLimits limits;
|
||||
};
|
||||
|
||||
struct VoxelPathResult {
|
||||
VoxelNavigationStatus status = VoxelNavigationStatus::InvalidInput;
|
||||
std::optional<VoxelPosition> goal;
|
||||
// Excludes start, includes goal. An already satisfied goal has an empty route.
|
||||
std::vector<VoxelPosition> route;
|
||||
std::size_t cost = 0;
|
||||
std::size_t visited = 0;
|
||||
VoxelReadSet consulted;
|
||||
};
|
||||
|
||||
// Ordinary settlers occupy the foot cell and the cell above, with solid support
|
||||
// below. A transition is one cardinal horizontal move and at most one step.
|
||||
[[nodiscard]] VoxelTraversalResult voxel_standing(
|
||||
const VoxelRegion& world, const Void::Uuid::Uuid& session, VoxelPosition foot,
|
||||
VoxelNavigationLimits limits = {}, std::stop_token stop = {});
|
||||
[[nodiscard]] VoxelTraversalResult voxel_transition(
|
||||
const VoxelRegion& world, const Void::Uuid::Uuid& session,
|
||||
VoxelPosition from, VoxelPosition to, VoxelNavigationLimits limits = {},
|
||||
std::stop_token stop = {});
|
||||
|
||||
// Finds a shortest known route within the requested window. Equal costs choose
|
||||
// the lexicographically first goal; each vertex's neighbors use coordinate order.
|
||||
// A negative result distinguishes missing chunks and an escapable window edge.
|
||||
[[nodiscard]] VoxelPathResult find_voxel_path(
|
||||
const VoxelRegion& world, const VoxelPathRequest& request, std::stop_token stop = {});
|
||||
|
||||
// Candidate feet touch the target by a face of either body cell, or stand one
|
||||
// cell above / two below it. The target must be loaded. Work policy stays with
|
||||
// the owner; navigation only proves contact and a supported clear body volume.
|
||||
// request.goals is ignored; the same bounds, identity and limits apply.
|
||||
[[nodiscard]] VoxelPathResult find_voxel_interaction_path(
|
||||
const VoxelRegion& world, const VoxelPathRequest& request,
|
||||
VoxelPosition target, std::stop_token stop = {});
|
||||
|
||||
} // namespace settlement
|
||||
@@ -0,0 +1,168 @@
|
||||
#pragma once
|
||||
|
||||
#include <array>
|
||||
#include <compare>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <expected>
|
||||
#include <memory>
|
||||
#include <optional>
|
||||
#include <span>
|
||||
#include <vector>
|
||||
|
||||
namespace settlement {
|
||||
|
||||
using RegionId = std::uint64_t;
|
||||
inline constexpr std::int32_t voxel_chunk_side = 32;
|
||||
inline constexpr std::size_t voxel_chunk_cells = 32 * 32 * 32;
|
||||
inline constexpr std::uint32_t voxel_generator_version = 1;
|
||||
|
||||
struct VoxelPosition {
|
||||
std::int32_t x = 0, y = 0, z = 0;
|
||||
auto operator<=>(const VoxelPosition&) const = default;
|
||||
};
|
||||
struct ChunkCoordinate {
|
||||
std::int32_t x = 0, y = 0, z = 0;
|
||||
auto operator<=>(const ChunkCoordinate&) const = default;
|
||||
};
|
||||
struct VoxelEndpoint {
|
||||
std::int64_t x = 0, y = 0, z = 0;
|
||||
bool operator==(const VoxelEndpoint&) const = default;
|
||||
};
|
||||
struct VoxelBounds {
|
||||
VoxelEndpoint lower, upper;
|
||||
[[nodiscard]] bool contains(VoxelPosition position) const noexcept;
|
||||
bool operator==(const VoxelBounds&) const = default;
|
||||
};
|
||||
struct LocalVoxel {
|
||||
std::uint8_t x = 0, y = 0, z = 0;
|
||||
bool operator==(const LocalVoxel&) const = default;
|
||||
};
|
||||
struct VoxelAddress {
|
||||
ChunkCoordinate chunk;
|
||||
LocalVoxel local;
|
||||
};
|
||||
|
||||
[[nodiscard]] VoxelAddress split_voxel(VoxelPosition position) noexcept;
|
||||
[[nodiscard]] std::optional<VoxelPosition> join_voxel(ChunkCoordinate chunk, LocalVoxel local) noexcept;
|
||||
[[nodiscard]] std::optional<std::size_t> voxel_index(LocalVoxel local) noexcept;
|
||||
|
||||
enum class MaterialId : std::uint8_t { Air = 0, Soil = 1, Stone = 2, DoorClosed = 3, DoorOpen = 4 };
|
||||
[[nodiscard]] bool valid_voxel_material(MaterialId material) noexcept;
|
||||
[[nodiscard]] bool voxel_blocks_passage(MaterialId material) noexcept;
|
||||
[[nodiscard]] bool voxel_provides_support(MaterialId material) noexcept;
|
||||
|
||||
struct VoxelRegionDescriptor {
|
||||
RegionId id = 0;
|
||||
std::uint64_t seed = 0;
|
||||
std::uint32_t generator_version = voxel_generator_version;
|
||||
VoxelBounds bounds;
|
||||
bool operator==(const VoxelRegionDescriptor&) const = default;
|
||||
};
|
||||
struct VoxelLimits {
|
||||
std::size_t max_resident_chunks = 256;
|
||||
std::size_t max_edit_cells = 4096;
|
||||
// Budgets charge object and vector payloads. Allocator bookkeeping and
|
||||
// snapshots/prepared pages retained by the caller have separate lifetimes.
|
||||
std::size_t max_resident_bytes = 16 * 1024 * 1024;
|
||||
std::size_t max_transaction_bytes = 16 * 1024 * 1024;
|
||||
};
|
||||
enum class VoxelAvailability : std::uint8_t { Outside, Unavailable, Loaded };
|
||||
struct ChunkStamp {
|
||||
RegionId region = 0;
|
||||
ChunkCoordinate coordinate;
|
||||
VoxelAvailability availability = VoxelAvailability::Unavailable;
|
||||
std::uint64_t revision = 0;
|
||||
bool operator==(const ChunkStamp&) const = default;
|
||||
};
|
||||
struct VoxelSample {
|
||||
VoxelAvailability availability = VoxelAvailability::Outside;
|
||||
MaterialId material = MaterialId::Air;
|
||||
ChunkStamp stamp;
|
||||
};
|
||||
|
||||
class VoxelChunk {
|
||||
public:
|
||||
[[nodiscard]] std::uint64_t revision() const noexcept { return revision_; }
|
||||
[[nodiscard]] std::span<const MaterialId, voxel_chunk_cells> cells() const noexcept { return cells_; }
|
||||
private:
|
||||
friend class VoxelRegion;
|
||||
VoxelChunk(std::uint64_t revision, std::span<const MaterialId, voxel_chunk_cells> cells);
|
||||
std::uint64_t revision_;
|
||||
std::array<MaterialId, voxel_chunk_cells> cells_;
|
||||
};
|
||||
struct VoxelChunkEntry {
|
||||
ChunkCoordinate coordinate;
|
||||
std::shared_ptr<const VoxelChunk> chunk;
|
||||
};
|
||||
using VoxelDirectory = std::vector<VoxelChunkEntry>;
|
||||
|
||||
class PreparedVoxelChunk {
|
||||
public:
|
||||
[[nodiscard]] const VoxelRegionDescriptor& descriptor() const noexcept { return descriptor_; }
|
||||
[[nodiscard]] ChunkCoordinate coordinate() const noexcept { return coordinate_; }
|
||||
[[nodiscard]] const std::shared_ptr<const VoxelChunk>& chunk() const noexcept { return chunk_; }
|
||||
private:
|
||||
friend class VoxelRegion;
|
||||
PreparedVoxelChunk(VoxelRegionDescriptor descriptor, ChunkCoordinate coordinate,
|
||||
std::shared_ptr<const VoxelChunk> chunk);
|
||||
VoxelRegionDescriptor descriptor_;
|
||||
ChunkCoordinate coordinate_;
|
||||
std::shared_ptr<const VoxelChunk> chunk_;
|
||||
};
|
||||
|
||||
enum class VoxelError : std::uint8_t {
|
||||
InvalidCoordinate, InvalidMaterial, InvalidRevision, InvalidSource,
|
||||
Duplicate, Unavailable, Stale, RevisionExhausted, LimitExceeded, AllocationFailed
|
||||
};
|
||||
struct VoxelEdit {
|
||||
VoxelPosition position;
|
||||
MaterialId material = MaterialId::Air;
|
||||
std::uint64_t expected_revision = 0;
|
||||
};
|
||||
struct VoxelChange {
|
||||
VoxelPosition position;
|
||||
MaterialId before = MaterialId::Air;
|
||||
MaterialId after = MaterialId::Air;
|
||||
bool operator==(const VoxelChange&) const = default;
|
||||
};
|
||||
struct VoxelCommit {
|
||||
std::vector<ChunkStamp> changed_chunks;
|
||||
std::vector<VoxelChange> changed_cells;
|
||||
// Changed chunks and intersecting face-neighbors, including unavailable
|
||||
// neighbors. Unchanged neighbors keep their own material revision.
|
||||
std::vector<ChunkCoordinate> dirty_chunks;
|
||||
};
|
||||
|
||||
// Copies retain the complete immutable directory. A reader keeps its own copy
|
||||
// while the single owner publishes changes. Session identity fences snapshots
|
||||
// across save/load; this layer does not unload or reuse chunk revisions.
|
||||
class VoxelRegion {
|
||||
public:
|
||||
explicit VoxelRegion(VoxelRegionDescriptor descriptor, VoxelLimits limits = {});
|
||||
[[nodiscard]] const VoxelRegionDescriptor& descriptor() const noexcept { return descriptor_; }
|
||||
[[nodiscard]] const VoxelLimits& limits() const noexcept { return limits_; }
|
||||
[[nodiscard]] std::shared_ptr<const VoxelDirectory> directory() const noexcept { return directory_; }
|
||||
[[nodiscard]] std::size_t resident_bytes() const noexcept;
|
||||
[[nodiscard]] bool intersects(ChunkCoordinate coordinate) const noexcept;
|
||||
[[nodiscard]] ChunkStamp chunk_stamp(ChunkCoordinate coordinate) const noexcept;
|
||||
[[nodiscard]] bool matches(const ChunkStamp& stamp) const noexcept;
|
||||
[[nodiscard]] VoxelSample sample(VoxelPosition position) const noexcept;
|
||||
|
||||
[[nodiscard]] std::expected<PreparedVoxelChunk, VoxelError> prepare_generated(ChunkCoordinate coordinate) const;
|
||||
// Validated, deep-copied import for persistence, including exhausted valid
|
||||
// revisions. Cells outside a partial region must be canonical air.
|
||||
[[nodiscard]] std::expected<PreparedVoxelChunk, VoxelError> prepare_restored(
|
||||
ChunkCoordinate coordinate, std::uint64_t revision, std::span<const MaterialId> cells) const;
|
||||
// Activation only accepts unavailable chunks from this exact descriptor.
|
||||
// Every candidate is installed together or the directory is preserved.
|
||||
[[nodiscard]] std::expected<VoxelCommit, VoxelError> activate(std::span<const PreparedVoxelChunk> candidates);
|
||||
[[nodiscard]] std::expected<VoxelCommit, VoxelError> edit(std::span<const VoxelEdit> edits);
|
||||
|
||||
private:
|
||||
VoxelRegionDescriptor descriptor_;
|
||||
VoxelLimits limits_;
|
||||
std::shared_ptr<const VoxelDirectory> directory_;
|
||||
};
|
||||
|
||||
} // namespace settlement
|
||||
@@ -21,6 +21,9 @@ struct WorkerPoolOptions {
|
||||
std::function<void(std::size_t)> before_worker_start;
|
||||
std::function<void(std::size_t)> before_submit;
|
||||
std::function<void(std::size_t)> before_execute;
|
||||
// Success-only observation after invocation returns, before future readiness.
|
||||
// A throwing observer fails that future. Replacement contract: Void/Library#15.
|
||||
std::function<void(std::size_t)> after_execute;
|
||||
};
|
||||
|
||||
class WorkerPool {
|
||||
@@ -38,12 +41,22 @@ public:
|
||||
if (executor_->is_executor_thread()) {
|
||||
throw std::logic_error("cannot submit nested work to the same worker pool");
|
||||
}
|
||||
if (options_.before_submit || options_.before_execute) {
|
||||
if (options_.before_submit || options_.before_execute || options_.after_execute) {
|
||||
const auto index = submission_index_.fetch_add(1, std::memory_order_relaxed);
|
||||
if (options_.before_submit) options_.before_submit(index);
|
||||
return admit([this, index, function = std::forward<Function>(function)]() mutable -> decltype(auto) {
|
||||
return admit([this, index, function = std::forward<Function>(function)]() mutable
|
||||
-> std::invoke_result_t<Function> {
|
||||
if (options_.before_execute) options_.before_execute(index);
|
||||
return std::invoke(function);
|
||||
if (!options_.after_execute) return std::invoke(function);
|
||||
using Result = std::invoke_result_t<Function>;
|
||||
if constexpr (std::is_void_v<Result>) {
|
||||
std::invoke(function);
|
||||
options_.after_execute(index);
|
||||
} else {
|
||||
Result result = std::invoke(function);
|
||||
options_.after_execute(index);
|
||||
return result;
|
||||
}
|
||||
});
|
||||
}
|
||||
return admit(std::forward<Function>(function));
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
#include <iosfwd>
|
||||
#include <memory>
|
||||
#include <optional>
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
#include <unordered_map>
|
||||
#include <vector>
|
||||
@@ -19,6 +20,15 @@ using AgentId = std::uint64_t;
|
||||
using JobId = std::uint64_t;
|
||||
using ResourceNodeId = std::uint64_t;
|
||||
using StorageId = std::uint64_t;
|
||||
using ProductionId = std::uint64_t;
|
||||
|
||||
enum class WorldSaveFormat : std::uint32_t { Legacy13 = 13, Current14 = 14 };
|
||||
|
||||
// Raised only by a complete production-ID preflight, before any domain effects.
|
||||
class ProductionCapacityError : public std::overflow_error {
|
||||
public:
|
||||
ProductionCapacityError() : std::overflow_error("production identities exhausted") {}
|
||||
};
|
||||
|
||||
struct GridPosition {
|
||||
std::int32_t x = 0;
|
||||
@@ -244,7 +254,7 @@ struct Agent {
|
||||
StorageId storage_id = 0;
|
||||
Inventory inventory;
|
||||
std::vector<GridPosition> haul_route;
|
||||
std::size_t production_index = no_entity_index;
|
||||
ProductionId production_id = 0;
|
||||
std::uint16_t hunger = 0;
|
||||
std::uint16_t fatigue = 0;
|
||||
bool resting_on_ground = false;
|
||||
@@ -331,6 +341,7 @@ struct ConstructionStop {
|
||||
};
|
||||
|
||||
struct ProductionOrder {
|
||||
ProductionId id = 0; // Assigned once on insertion; never changed during its lifetime.
|
||||
GridPosition position;
|
||||
RecipeId recipe;
|
||||
JobState state = JobState::Available;
|
||||
@@ -370,6 +381,7 @@ struct WorldState {
|
||||
JobId next_job_id_ = 1;
|
||||
std::uint64_t next_resource_node_id_ = 1;
|
||||
std::uint64_t next_storage_id_ = 1;
|
||||
ProductionId next_production_id_ = 1;
|
||||
std::vector<std::uint8_t> blocked_;
|
||||
std::vector<Agent> agents_;
|
||||
std::vector<WorkJob> jobs_;
|
||||
@@ -430,7 +442,9 @@ public:
|
||||
[[nodiscard]] ScenarioProgress scenario_progress() const noexcept;
|
||||
void step(TickProfile* profile = nullptr);
|
||||
void write_svg(const std::string& path) const;
|
||||
void write_save(std::ostream& stream) const;
|
||||
// Legacy13 preserves the historical positional wire format. Current14 also
|
||||
// preserves production identities and their allocation history after deletion.
|
||||
void write_save(std::ostream& stream, WorldSaveFormat format = WorldSaveFormat::Legacy13) const;
|
||||
// Called by the owner after every stage has drained. The independent copy
|
||||
// can be retained by readers on other threads while the owner advances.
|
||||
[[nodiscard]] std::shared_ptr<const World> capture() const;
|
||||
@@ -447,6 +461,7 @@ public:
|
||||
[[nodiscard]] const std::vector<ResourceNode>& resource_nodes() const noexcept;
|
||||
[[nodiscard]] const std::vector<Storage>& storages() const noexcept;
|
||||
[[nodiscard]] const Storage* find_storage(StorageId id) const noexcept;
|
||||
[[nodiscard]] const ProductionOrder* find_production(ProductionId id) const noexcept;
|
||||
[[nodiscard]] const ResourceNode* find_resource_node(ResourceNodeId id) const noexcept;
|
||||
[[nodiscard]] const std::vector<ProductionOrder>& production_orders() const noexcept;
|
||||
[[nodiscard]] const ProductionOrder* assigned_bed(AgentId agent) const noexcept;
|
||||
@@ -469,6 +484,9 @@ private:
|
||||
};
|
||||
|
||||
[[nodiscard]] Storage& storage_by_id(StorageId id);
|
||||
[[nodiscard]] ProductionOrder& production_by_id(ProductionId id);
|
||||
[[nodiscard]] bool reserve_production(std::size_t count);
|
||||
void append_production(ProductionOrder order);
|
||||
[[nodiscard]] ResourceNode& resource_node_by_id(ResourceNodeId id);
|
||||
[[nodiscard]] std::size_t cell_index(GridPosition position) const noexcept;
|
||||
[[nodiscard]] PathResult find_path(GridPosition start, GridPosition goal) const;
|
||||
@@ -483,7 +501,8 @@ private:
|
||||
void finish_rest_step(Agent& agent);
|
||||
void advance_construction_delivery(Agent& agent);
|
||||
void finish_production(Agent& agent);
|
||||
[[nodiscard]] std::size_t missing_carpentry_orders(ItemType product, std::size_t new_installations = 0) const;
|
||||
[[nodiscard]] std::size_t missing_carpentry_orders(ItemType product, std::size_t new_installations = 0,
|
||||
StorageId excluded_storage = 0) const;
|
||||
void update_scenario();
|
||||
[[nodiscard]] bool resting_at(GridPosition position, AgentId except = 0) const noexcept;
|
||||
[[nodiscard]] bool ground_rest_cell(GridPosition position, AgentId agent) const noexcept;
|
||||
|
||||
@@ -165,7 +165,7 @@ std::expected<std::string, CheckpointDiagnostic> encode_checkpoint(
|
||||
fail(CheckpointError::LimitExceeded, "metadata_length", "Checkpoint metadata exceeds 64 KiB.");
|
||||
}
|
||||
std::ostringstream stream(std::ios::binary);
|
||||
world.write_save(stream);
|
||||
world.write_save(stream, WorldSaveFormat::Current14);
|
||||
auto body = std::move(stream).str();
|
||||
if (body.size() > max_checkpoint_body_bytes) {
|
||||
fail(CheckpointError::LimitExceeded, "body_length", "Checkpoint world exceeds 128 MiB.");
|
||||
@@ -212,7 +212,8 @@ std::expected<WorldCheckpoint, CheckpointDiagnostic> decode_checkpoint(
|
||||
if (!std::ranges::equal(get_bytes(header, checkpoint_signature.size(), "magic"), wire_bytes(checkpoint_signature))) {
|
||||
fail(CheckpointError::InvalidFrame, "magic", "Checkpoint signature does not match.");
|
||||
}
|
||||
if (get<std::uint32_t>(header, "version") != checkpoint_version) {
|
||||
const auto schema = get<std::uint32_t>(header, "version");
|
||||
if (schema != 1 && schema != checkpoint_version) {
|
||||
fail(CheckpointError::UnsupportedVersion, "version", "Checkpoint schema is not supported.");
|
||||
}
|
||||
const auto metadata_size = get<std::uint32_t>(header, "metadata_length");
|
||||
@@ -263,6 +264,15 @@ std::expected<WorldCheckpoint, CheckpointDiagnostic> decode_checkpoint(
|
||||
}
|
||||
auto rules = validate_rules(saved, fingerprint, installed);
|
||||
const auto body = bytes.substr(header_size + metadata_size, static_cast<std::size_t>(body_size));
|
||||
if (body.size() < 12 || body.substr(0, 8) != "SETTLERS") {
|
||||
fail(CheckpointError::InvalidWorld, "world.version", "Checkpoint world header is invalid.");
|
||||
}
|
||||
Void::Binary::Reader body_header(wire_bytes(body).subspan(8, 4));
|
||||
const auto body_version = get<std::uint32_t>(body_header, "world.version");
|
||||
if ((schema == 1 && (body_version < 1 || body_version > 13)) ||
|
||||
(schema == 2 && body_version != 14)) {
|
||||
fail(CheckpointError::InvalidWorld, "world.version", "Checkpoint schema and world version do not match.");
|
||||
}
|
||||
std::ispanstream stream(std::span<const char>{body.data(), body.size()});
|
||||
auto world = World::read_save(stream, workers, mode);
|
||||
if (world->tick() != tick) {
|
||||
|
||||
@@ -78,6 +78,8 @@ CommandStatus CommandDispatcher::apply(World& world, TrustedClient client, const
|
||||
const auto& payload = std::get<LegacyCabinPayload>(command.payload);
|
||||
try {
|
||||
world.queue_cabin(payload.cell, payload.sawmill, payload.stonecutter);
|
||||
} catch (const ProductionCapacityError&) {
|
||||
return CommandStatus::Busy;
|
||||
} catch (const std::invalid_argument&) {
|
||||
return CommandStatus::InvalidTarget;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,88 @@
|
||||
#include "settlement/core/inventory_transaction.hpp"
|
||||
|
||||
#include <Void/Math/Numeric.hpp>
|
||||
|
||||
#include <algorithm>
|
||||
#include <array>
|
||||
#include <type_traits>
|
||||
|
||||
namespace settlement {
|
||||
|
||||
// Replace the conditional in-memory batch when Void/Library #8 supplies this
|
||||
// contract: https://git.faumaray.com/Void/Library/issues/8
|
||||
std::expected<void, QuantityTransferError> withdraw_reserved_materials(
|
||||
Storage& source, Inventory& destination, std::span<const MaterialReservation> materials,
|
||||
bool reserve_output_slot) noexcept {
|
||||
using Error = QuantityTransferError;
|
||||
if (source.id == 0 || source.kind > StorageKind::Pantry) return std::unexpected(Error::InvalidStorage);
|
||||
|
||||
std::array<std::uint32_t, item_type_count> amounts{};
|
||||
bool selected = false;
|
||||
std::uint64_t withdrawn = 0;
|
||||
for (const auto& material : materials) {
|
||||
if (material.storage_id != source.id) continue;
|
||||
const auto type = static_cast<std::size_t>(material.type);
|
||||
if (type == 0 || type > item_type_count || material.count == 0) {
|
||||
return std::unexpected(Error::InvalidMaterial);
|
||||
}
|
||||
const auto amount = Void::Numeric::checked_add(amounts[type - 1], material.count);
|
||||
const auto total = Void::Numeric::checked_add(withdrawn, std::uint64_t{material.count});
|
||||
if (!amount || !total) return std::unexpected(Error::Overflow);
|
||||
amounts[type - 1] = *amount;
|
||||
withdrawn = *total;
|
||||
selected = true;
|
||||
}
|
||||
if (!selected) return std::unexpected(Error::MissingSelection);
|
||||
|
||||
// Validate the entire source before indexing or changing any stack. Its
|
||||
// sorted unique representation bounds all subsequent work by item_type_count.
|
||||
auto previous = ItemType::None;
|
||||
std::uint64_t total_items = 0;
|
||||
std::array<bool, item_type_count> present{};
|
||||
for (const auto& stack : source.items) {
|
||||
const auto type = static_cast<std::size_t>(stack.type);
|
||||
if (type == 0 || type > item_type_count || stack.type <= previous ||
|
||||
!source.accepts(stack.type) || stack.count == 0 || stack.reserved > stack.count) {
|
||||
return std::unexpected(Error::InvalidStock);
|
||||
}
|
||||
previous = stack.type;
|
||||
present[type - 1] = true;
|
||||
const auto total = Void::Numeric::checked_add(total_items, std::uint64_t{stack.count});
|
||||
if (!total) return std::unexpected(Error::Overflow);
|
||||
total_items = *total;
|
||||
if (amounts[type - 1] > stack.reserved || amounts[type - 1] > stack.count) {
|
||||
return std::unexpected(Error::InsufficientStock);
|
||||
}
|
||||
}
|
||||
for (std::size_t i = 0; i < amounts.size(); ++i) {
|
||||
if (amounts[i] == 0) continue;
|
||||
if (!present[i]) return std::unexpected(Error::InsufficientStock);
|
||||
if (!Void::Numeric::checked_add(destination.item_count(static_cast<ItemType>(i + 1)), amounts[i])) {
|
||||
return std::unexpected(Error::Overflow);
|
||||
}
|
||||
}
|
||||
|
||||
const auto occupied = Void::Numeric::checked_add(total_items, std::uint64_t{source.reserved_slots});
|
||||
if (!occupied || source.capacity == 0 || *occupied > source.capacity) return std::unexpected(Error::Capacity);
|
||||
const auto slots = Void::Numeric::checked_add(source.reserved_slots, std::uint32_t{reserve_output_slot});
|
||||
if (!slots) return std::unexpected(Error::Overflow);
|
||||
const auto remaining = Void::Numeric::checked_sub(total_items, withdrawn);
|
||||
if (!remaining) return std::unexpected(Error::InsufficientStock);
|
||||
const auto final_occupied = Void::Numeric::checked_add(*remaining, std::uint64_t{*slots});
|
||||
if (!final_occupied || *final_occupied > source.capacity) return std::unexpected(Error::Capacity);
|
||||
|
||||
// All operations after this point are nonthrowing. No stack iterator survives
|
||||
// compaction, which removes every depleted stack while retaining source order.
|
||||
static_assert(std::is_nothrow_move_assignable_v<ItemStack> && std::is_nothrow_destructible_v<ItemStack>);
|
||||
for (auto& stack : source.items) {
|
||||
const auto amount = amounts[static_cast<std::size_t>(stack.type) - 1];
|
||||
stack.count -= amount;
|
||||
stack.reserved -= amount;
|
||||
if (amount != 0) destination.add(stack.type, amount);
|
||||
}
|
||||
std::erase_if(source.items, [](const ItemStack& stack) noexcept { return stack.count == 0; });
|
||||
source.reserved_slots = *slots;
|
||||
return {};
|
||||
}
|
||||
|
||||
} // namespace settlement
|
||||
@@ -0,0 +1,306 @@
|
||||
#include "settlement/core/voxel_navigation.hpp"
|
||||
#include <Void/Algorithms/Graph.hpp>
|
||||
#include <Void/Math/Numeric.hpp>
|
||||
#include <algorithm>
|
||||
#include <array>
|
||||
#include <cstdint>
|
||||
#include <limits>
|
||||
#include <new>
|
||||
#include <stdexcept>
|
||||
|
||||
namespace settlement {
|
||||
namespace {
|
||||
using Status = VoxelNavigationStatus;
|
||||
struct NavigationFailure { Status status; };
|
||||
|
||||
std::optional<VoxelPosition> offset(VoxelPosition p, int x, int y, int z) noexcept {
|
||||
const auto nx = std::int64_t{p.x} + x, ny = std::int64_t{p.y} + y, nz = std::int64_t{p.z} + z;
|
||||
constexpr auto low = std::numeric_limits<std::int32_t>::min();
|
||||
constexpr auto high = std::numeric_limits<std::int32_t>::max();
|
||||
if (nx < low || nx > high || ny < low || ny > high || nz < low || nz > high) return {};
|
||||
return VoxelPosition{static_cast<std::int32_t>(nx), static_cast<std::int32_t>(ny), static_cast<std::int32_t>(nz)};
|
||||
}
|
||||
|
||||
bool valid_bounds(const VoxelBounds& b, const VoxelBounds& region) noexcept {
|
||||
return b.lower.x < b.upper.x && b.lower.y < b.upper.y && b.lower.z < b.upper.z &&
|
||||
b.lower.x >= region.lower.x && b.lower.y >= region.lower.y && b.lower.z >= region.lower.z &&
|
||||
b.upper.x <= region.upper.x && b.upper.y <= region.upper.y && b.upper.z <= region.upper.z;
|
||||
}
|
||||
|
||||
class Queries {
|
||||
public:
|
||||
Queries(const VoxelRegion& world, const Void::Uuid::Uuid& session,
|
||||
VoxelNavigationLimits limits, std::stop_token stop)
|
||||
: world_(world), limits_(limits), stop_(stop), reads{world.descriptor().id, session, {}} {
|
||||
if (session.is_nil()) throw NavigationFailure{Status::InvalidInput};
|
||||
if (limits.max_dependencies > reads.chunks.max_size()) throw NavigationFailure{Status::LimitExceeded};
|
||||
const auto bytes = Void::Numeric::checked_mul(limits.max_dependencies, sizeof(ChunkStamp));
|
||||
if (!bytes || *bytes > limits.max_scratch_bytes) throw NavigationFailure{Status::LimitExceeded};
|
||||
reads.chunks.reserve(limits.max_dependencies);
|
||||
}
|
||||
|
||||
VoxelSample sample(VoxelPosition p) {
|
||||
if (stop_.stop_requested()) throw NavigationFailure{Status::Cancelled};
|
||||
if (samples_ == limits_.max_samples) throw NavigationFailure{Status::LimitExceeded};
|
||||
++samples_;
|
||||
auto value = world_.sample(p);
|
||||
auto at = std::lower_bound(reads.chunks.begin(), reads.chunks.end(), value.stamp.coordinate,
|
||||
[](const auto& stamp, const auto& coordinate) { return stamp.coordinate < coordinate; });
|
||||
if (at == reads.chunks.end() || at->coordinate != value.stamp.coordinate) {
|
||||
if (reads.chunks.size() == limits_.max_dependencies) throw NavigationFailure{Status::LimitExceeded};
|
||||
reads.chunks.insert(at, value.stamp);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
Status standing(VoxelPosition foot) {
|
||||
const auto above = offset(foot, 0, 0, 1), below = offset(foot, 0, 0, -1);
|
||||
if (!above || !below) return Status::Unreachable;
|
||||
const auto body = sample(foot), head = sample(*above), support = sample(*below);
|
||||
// A known obstruction is conclusive even if another cell is unavailable.
|
||||
if (body.availability == VoxelAvailability::Outside || head.availability == VoxelAvailability::Outside ||
|
||||
support.availability == VoxelAvailability::Outside ||
|
||||
(body.availability == VoxelAvailability::Loaded && voxel_blocks_passage(body.material)) ||
|
||||
(head.availability == VoxelAvailability::Loaded && voxel_blocks_passage(head.material)) ||
|
||||
(support.availability == VoxelAvailability::Loaded && !voxel_provides_support(support.material))) return Status::Unreachable;
|
||||
if (body.availability == VoxelAvailability::Unavailable || head.availability == VoxelAvailability::Unavailable ||
|
||||
support.availability == VoxelAvailability::Unavailable) return Status::Unavailable;
|
||||
return Status::Reachable;
|
||||
}
|
||||
|
||||
Status transition(VoxelPosition from, VoxelPosition to) {
|
||||
const auto dx = std::int64_t{to.x} - from.x, dy = std::int64_t{to.y} - from.y;
|
||||
const auto dz = std::int64_t{to.z} - from.z;
|
||||
if (!((dx == -1 || dx == 1) && dy == 0) && !((dy == -1 || dy == 1) && dx == 0)) return Status::Unreachable;
|
||||
if (dz < -1 || dz > 1) return Status::Unreachable;
|
||||
const auto first = standing(from), second = standing(to);
|
||||
Status swept = Status::Reachable;
|
||||
if (dz != 0) {
|
||||
const auto upper = offset(dz > 0 ? from : to, 0, 0, 2);
|
||||
if (!upper) return Status::Unreachable;
|
||||
const auto cell = sample(*upper);
|
||||
if (cell.availability == VoxelAvailability::Outside ||
|
||||
(cell.availability == VoxelAvailability::Loaded && voxel_blocks_passage(cell.material))) swept = Status::Unreachable;
|
||||
else if (cell.availability == VoxelAvailability::Unavailable) swept = Status::Unavailable;
|
||||
}
|
||||
if (first == Status::Unreachable || second == Status::Unreachable || swept == Status::Unreachable) return Status::Unreachable;
|
||||
if (first == Status::Unavailable || second == Status::Unavailable || swept == Status::Unavailable) return Status::Unavailable;
|
||||
return Status::Reachable;
|
||||
}
|
||||
|
||||
const VoxelRegion& world_;
|
||||
VoxelNavigationLimits limits_;
|
||||
std::stop_token stop_;
|
||||
VoxelReadSet reads;
|
||||
private:
|
||||
std::size_t samples_ = 0;
|
||||
};
|
||||
|
||||
struct NeighborList {
|
||||
std::array<std::size_t, 12> values{};
|
||||
std::size_t size = 0;
|
||||
auto begin() const { return values.begin(); }
|
||||
auto end() const { return values.begin() + static_cast<std::ptrdiff_t>(size); }
|
||||
};
|
||||
|
||||
class WalkingGraph {
|
||||
public:
|
||||
WalkingGraph(Queries& queries, VoxelBounds bounds, std::size_t sx, std::size_t sy, std::size_t count)
|
||||
: queries_(queries), bounds_(bounds), sx_(sx), sy_(sy), count_(count) {}
|
||||
std::size_t vertex_count() const noexcept { return count_; }
|
||||
std::size_t index(VoxelPosition p) const noexcept {
|
||||
return static_cast<std::size_t>(std::int64_t{p.x} - bounds_.lower.x) + sx_ *
|
||||
(static_cast<std::size_t>(std::int64_t{p.y} - bounds_.lower.y) + sy_ *
|
||||
static_cast<std::size_t>(std::int64_t{p.z} - bounds_.lower.z));
|
||||
}
|
||||
VoxelPosition position(std::size_t i) const noexcept {
|
||||
return {static_cast<std::int32_t>(bounds_.lower.x + static_cast<std::int64_t>(i % sx_)),
|
||||
static_cast<std::int32_t>(bounds_.lower.y + static_cast<std::int64_t>((i / sx_) % sy_)),
|
||||
static_cast<std::int32_t>(bounds_.lower.z + static_cast<std::int64_t>(i / (sx_ * sy_)))};
|
||||
}
|
||||
NeighborList neighbors(std::size_t i) const {
|
||||
NeighborList result;
|
||||
const auto from = position(i);
|
||||
// This is lexicographic VoxelPosition order, including all step heights.
|
||||
constexpr std::array<std::array<int, 2>, 4> directions{{{-1, 0}, {0, -1}, {0, 1}, {1, 0}}};
|
||||
for (auto direction : directions) for (int dz = -1; dz <= 1; ++dz) {
|
||||
const auto to = offset(from, direction[0], direction[1], dz);
|
||||
if (!to) continue;
|
||||
const auto state = queries_.transition(from, *to);
|
||||
// Only inconclusive edges out of reached vertices can extend the
|
||||
// search into missing data. Raw reads may already have been ruled
|
||||
// out by a known wall, floor or obstructed swept body volume.
|
||||
if (state == Status::Unavailable) unavailable = true;
|
||||
if (state != Status::Reachable) continue;
|
||||
if (!bounds_.contains(*to)) { boundary = true; continue; }
|
||||
result.values[result.size++] = index(*to);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
mutable bool boundary = false;
|
||||
mutable bool unavailable = false;
|
||||
private:
|
||||
Queries& queries_;
|
||||
VoxelBounds bounds_;
|
||||
std::size_t sx_, sy_, count_;
|
||||
};
|
||||
|
||||
VoxelPathResult search(Queries& queries, const VoxelPathRequest& request,
|
||||
std::span<const VoxelPosition> goals, std::span<const VoxelPosition> omitted = {}) {
|
||||
VoxelPathResult result;
|
||||
if (goals.empty() && omitted.empty()) return result;
|
||||
const auto& limits = request.limits;
|
||||
if (omitted.size() > limits.max_goals || goals.size() > limits.max_goals - omitted.size()) {
|
||||
result.status = Status::LimitExceeded; return result;
|
||||
}
|
||||
for (auto goal : goals) if (!request.search_bounds.contains(goal)) return result;
|
||||
const auto sx = static_cast<std::size_t>(request.search_bounds.upper.x - request.search_bounds.lower.x);
|
||||
const auto sy = static_cast<std::size_t>(request.search_bounds.upper.y - request.search_bounds.lower.y);
|
||||
const auto sz = static_cast<std::size_t>(request.search_bounds.upper.z - request.search_bounds.lower.z);
|
||||
const auto count = Void::Numeric::checked_mul(sx, sy).and_then(
|
||||
[sz](auto xy) { return Void::Numeric::checked_mul(xy, sz); });
|
||||
// Void BFS retains four size_t vectors plus visited. Route construction and
|
||||
// the read-set reserve coexist with them. No adjacency matrix is allocated.
|
||||
const auto vertex_bytes = count.and_then([](auto size) {
|
||||
return Void::Numeric::checked_mul(size, 4 * sizeof(std::size_t) + 1 + sizeof(VoxelPosition));
|
||||
});
|
||||
const auto read_bytes = Void::Numeric::checked_mul(limits.max_dependencies, sizeof(ChunkStamp));
|
||||
if (!count || *count > limits.max_vertices || !vertex_bytes || !read_bytes ||
|
||||
*count > std::vector<std::size_t>{}.max_size() ||
|
||||
*count > std::vector<std::uint8_t>{}.max_size() ||
|
||||
*count > std::vector<VoxelPosition>{}.max_size()) {
|
||||
result.status = Status::LimitExceeded; return result;
|
||||
}
|
||||
const auto bytes = Void::Numeric::checked_add(*vertex_bytes, *read_bytes);
|
||||
if (!bytes || *bytes > limits.max_scratch_bytes) {
|
||||
result.status = Status::LimitExceeded; return result;
|
||||
}
|
||||
const auto start_state = queries.standing(request.start);
|
||||
if (start_state != Status::Reachable) { result.status = start_state; return result; }
|
||||
WalkingGraph graph(queries, request.search_bounds, sx, sy, *count);
|
||||
const Void::Algorithms::WorkLimits work{
|
||||
limits.max_vertices, limits.max_steps, limits.max_scratch_bytes - *read_bytes, 1};
|
||||
auto traversal = Void::Algorithms::bfs(graph, graph.index(request.start), work, queries.stop_);
|
||||
if (!traversal) {
|
||||
result.status = traversal.error().code == Void::Algorithms::AlgorithmError::Code::cancelled ? Status::Cancelled : Status::LimitExceeded;
|
||||
return result;
|
||||
}
|
||||
result.visited = traversal->order.size();
|
||||
std::size_t distance = Void::Algorithms::TraversalResult::npos;
|
||||
bool possible_goal = false;
|
||||
for (auto goal : goals) {
|
||||
// Explicit validation also covers the library's start==target fast path.
|
||||
const auto standing = queries.standing(goal);
|
||||
possible_goal = possible_goal || standing != Status::Unreachable;
|
||||
if (standing != Status::Reachable) continue;
|
||||
const auto cost = traversal->depth[graph.index(goal)];
|
||||
if (cost < distance || (cost == distance && cost != Void::Algorithms::TraversalResult::npos &&
|
||||
(!result.goal || goal < *result.goal))) { distance = cost; result.goal = goal; }
|
||||
}
|
||||
if (!result.goal) {
|
||||
// Interaction contacts outside the selected window still matter to a
|
||||
// global negative. Their feasibility cannot manufacture a frontier;
|
||||
// BFS must also have reached a valid exit or an unresolved transition.
|
||||
for (auto goal : omitted) {
|
||||
const auto standing = queries.standing(goal);
|
||||
possible_goal = possible_goal || standing != Status::Unreachable;
|
||||
}
|
||||
result.status = Status::Unreachable;
|
||||
if (possible_goal) {
|
||||
if (graph.unavailable) result.status = Status::Unavailable;
|
||||
else if (graph.boundary) result.status = Status::SearchBoundary;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
result.status = Status::Reachable;
|
||||
result.cost = distance;
|
||||
result.route.reserve(distance);
|
||||
auto vertex = graph.index(*result.goal);
|
||||
const auto start = graph.index(request.start);
|
||||
while (vertex != start) {
|
||||
result.route.push_back(graph.position(vertex));
|
||||
vertex = traversal->parent[vertex];
|
||||
}
|
||||
std::reverse(result.route.begin(), result.route.end());
|
||||
return result;
|
||||
}
|
||||
|
||||
template<class Function>
|
||||
VoxelTraversalResult check(const VoxelRegion& world, const Void::Uuid::Uuid& session,
|
||||
VoxelNavigationLimits limits, std::stop_token stop, Function&& function) {
|
||||
VoxelTraversalResult result;
|
||||
result.consulted = {world.descriptor().id, session, {}};
|
||||
try {
|
||||
Queries queries(world, session, limits, stop);
|
||||
try { result.status = function(queries); }
|
||||
catch (const NavigationFailure& failure) { result.status = failure.status; }
|
||||
result.consulted = std::move(queries.reads);
|
||||
} catch (const NavigationFailure& failure) { result.status = failure.status; }
|
||||
catch (const std::length_error&) { result.status = Status::LimitExceeded; }
|
||||
catch (const std::bad_alloc&) { result.status = Status::AllocationFailed; }
|
||||
return result;
|
||||
}
|
||||
|
||||
VoxelPathResult path(const VoxelRegion& world, const VoxelPathRequest& request,
|
||||
std::optional<VoxelPosition> target, std::stop_token stop) {
|
||||
VoxelPathResult result;
|
||||
result.consulted = {world.descriptor().id, request.session, {}};
|
||||
if (request.region != world.descriptor().id || request.session.is_nil() ||
|
||||
!valid_bounds(request.search_bounds, world.descriptor().bounds) ||
|
||||
!request.search_bounds.contains(request.start)) return result;
|
||||
try {
|
||||
Queries queries(world, request.session, request.limits, stop);
|
||||
try {
|
||||
if (target) {
|
||||
const auto cell = queries.sample(*target);
|
||||
if (cell.availability != VoxelAvailability::Loaded) {
|
||||
result.status = cell.availability == VoxelAvailability::Unavailable ? Status::Unavailable : Status::InvalidInput;
|
||||
} else {
|
||||
std::array<VoxelPosition, 10> goals{};
|
||||
std::array<VoxelPosition, 10> omitted{};
|
||||
std::size_t size = 0, omitted_size = 0;
|
||||
const auto add_goal = [&](std::optional<VoxelPosition> goal) {
|
||||
if (!goal) return;
|
||||
if (request.search_bounds.contains(*goal)) goals[size++] = *goal;
|
||||
else omitted[omitted_size++] = *goal;
|
||||
};
|
||||
constexpr std::array<std::array<int, 2>, 4> directions{{{-1, 0}, {0, -1}, {0, 1}, {1, 0}}};
|
||||
for (auto direction : directions) for (int dz : {-1, 0}) {
|
||||
add_goal(offset(*target, direction[0], direction[1], dz));
|
||||
}
|
||||
for (int dz : {-2, 1}) {
|
||||
add_goal(offset(*target, 0, 0, dz));
|
||||
}
|
||||
result = search(queries, request, std::span(goals.data(), size),
|
||||
std::span(omitted.data(), omitted_size));
|
||||
}
|
||||
} else result = search(queries, request, request.goals);
|
||||
} catch (const NavigationFailure& failure) { result.status = failure.status; }
|
||||
result.consulted = std::move(queries.reads);
|
||||
} catch (const NavigationFailure& failure) { result.status = failure.status; }
|
||||
catch (const std::length_error&) { result.status = Status::LimitExceeded; }
|
||||
catch (const std::bad_alloc&) { result.status = Status::AllocationFailed; }
|
||||
return result;
|
||||
}
|
||||
} // namespace
|
||||
|
||||
bool VoxelReadSet::current(const VoxelRegion& world, const Void::Uuid::Uuid& epoch) const noexcept {
|
||||
return region == world.descriptor().id && !session.is_nil() && epoch == session &&
|
||||
std::all_of(chunks.begin(), chunks.end(), [&](const auto& stamp) { return world.matches(stamp); });
|
||||
}
|
||||
VoxelTraversalResult voxel_standing(const VoxelRegion& world, const Void::Uuid::Uuid& session,
|
||||
VoxelPosition foot, VoxelNavigationLimits limits, std::stop_token stop) {
|
||||
return check(world, session, limits, stop, [&](Queries& queries) { return queries.standing(foot); });
|
||||
}
|
||||
VoxelTraversalResult voxel_transition(const VoxelRegion& world, const Void::Uuid::Uuid& session,
|
||||
VoxelPosition from, VoxelPosition to, VoxelNavigationLimits limits, std::stop_token stop) {
|
||||
return check(world, session, limits, stop, [&](Queries& queries) { return queries.transition(from, to); });
|
||||
}
|
||||
VoxelPathResult find_voxel_path(const VoxelRegion& world, const VoxelPathRequest& request, std::stop_token stop) {
|
||||
return path(world, request, {}, stop);
|
||||
}
|
||||
VoxelPathResult find_voxel_interaction_path(const VoxelRegion& world, const VoxelPathRequest& request,
|
||||
VoxelPosition target, std::stop_token stop) {
|
||||
return path(world, request, target, stop);
|
||||
}
|
||||
} // namespace settlement
|
||||
@@ -0,0 +1,383 @@
|
||||
#include "settlement/core/voxel_region.hpp"
|
||||
|
||||
#include <Void/Binary/Writer.hpp>
|
||||
#include <Void/Core/Hash.hpp>
|
||||
#include <Void/Math/Numeric.hpp>
|
||||
|
||||
#include <algorithm>
|
||||
#include <limits>
|
||||
#include <new>
|
||||
#include <stdexcept>
|
||||
#include <utility>
|
||||
|
||||
namespace settlement {
|
||||
namespace {
|
||||
constexpr auto coordinate_min = std::int64_t{std::numeric_limits<std::int32_t>::min()};
|
||||
constexpr auto coordinate_end = std::int64_t{std::numeric_limits<std::int32_t>::max()} + 1;
|
||||
|
||||
bool valid_interval(std::int64_t lower, std::int64_t upper) noexcept {
|
||||
return lower >= coordinate_min && upper <= coordinate_end && lower < upper;
|
||||
}
|
||||
std::pair<std::int32_t, std::uint8_t> split_axis(std::int32_t value) noexcept {
|
||||
auto chunk = value / voxel_chunk_side;
|
||||
auto local = value % voxel_chunk_side;
|
||||
if (local < 0) {
|
||||
--chunk;
|
||||
local += voxel_chunk_side;
|
||||
}
|
||||
return {chunk, static_cast<std::uint8_t>(local)};
|
||||
}
|
||||
VoxelEndpoint chunk_origin(ChunkCoordinate coordinate) noexcept {
|
||||
return {std::int64_t{coordinate.x} * voxel_chunk_side,
|
||||
std::int64_t{coordinate.y} * voxel_chunk_side,
|
||||
std::int64_t{coordinate.z} * voxel_chunk_side};
|
||||
}
|
||||
bool overlapping_axis(std::int64_t origin, std::int64_t lower, std::int64_t upper) noexcept {
|
||||
return origin < upper && origin + voxel_chunk_side > lower;
|
||||
}
|
||||
auto find_chunk(const VoxelDirectory& directory, ChunkCoordinate coordinate) noexcept {
|
||||
return std::lower_bound(directory.begin(), directory.end(), coordinate,
|
||||
[](const auto& entry, auto key) { return entry.coordinate < key; });
|
||||
}
|
||||
class PayloadBudget {
|
||||
public:
|
||||
explicit PayloadBudget(std::size_t limit) : remaining_(limit) {}
|
||||
bool take(std::size_t count, std::size_t size) noexcept {
|
||||
const auto bytes = Void::Numeric::checked_mul(count, size);
|
||||
if (!bytes || *bytes > remaining_) return false;
|
||||
remaining_ -= *bytes;
|
||||
return true;
|
||||
}
|
||||
private:
|
||||
std::size_t remaining_;
|
||||
};
|
||||
|
||||
std::uint64_t terrain_hash(std::uint64_t seed, std::int64_t x, std::int64_t y) {
|
||||
std::array<std::byte, 40> bytes{};
|
||||
Void::Binary::Writer writer(bytes);
|
||||
if (!writer.writeLittle(seed) || !writer.writeLittle(voxel_generator_version) ||
|
||||
!writer.writeLittle(std::uint32_t{1}) || !writer.writeLittle(x) ||
|
||||
!writer.writeLittle(y) || !writer.writeLittle(std::int64_t{0})) {
|
||||
throw std::logic_error("voxel generator field layout exceeds its fixed buffer");
|
||||
}
|
||||
return Void::Hash::fnv1a64(writer.written());
|
||||
}
|
||||
std::int64_t surface_height(std::uint64_t seed, std::int32_t x, std::int32_t y) {
|
||||
// Interpolate absolute lattice columns to keep adjacent heights within one
|
||||
// voxel. Widened lattice endpoints also cover the final int32 column.
|
||||
const auto lattice = [](std::int32_t value) {
|
||||
std::int64_t quotient = value / 16;
|
||||
if (value % 16 < 0) --quotient;
|
||||
return quotient * 16;
|
||||
};
|
||||
const auto x0 = lattice(x), y0 = lattice(y);
|
||||
const auto dx = std::int64_t{x} - x0, dy = std::int64_t{y} - y0;
|
||||
const auto height = [seed](std::int64_t a, std::int64_t b) {
|
||||
return static_cast<std::int64_t>(terrain_hash(seed, a, b) % 17) - 8;
|
||||
};
|
||||
const auto numerator = height(x0, y0) * (16 - dx) * (16 - dy) +
|
||||
height(x0 + 16, y0) * dx * (16 - dy) +
|
||||
height(x0, y0 + 16) * (16 - dx) * dy + height(x0 + 16, y0 + 16) * dx * dy;
|
||||
auto result = numerator / 256;
|
||||
if (numerator % 256 < 0) --result;
|
||||
return result;
|
||||
}
|
||||
void add_neighbor(const VoxelRegion& region, std::vector<ChunkCoordinate>& dirty,
|
||||
ChunkCoordinate coordinate, int axis, int delta) {
|
||||
std::array<std::int64_t, 3> values{coordinate.x, coordinate.y, coordinate.z};
|
||||
values[static_cast<std::size_t>(axis)] += delta;
|
||||
if (values[static_cast<std::size_t>(axis)] < coordinate_min ||
|
||||
values[static_cast<std::size_t>(axis)] >= coordinate_end) return;
|
||||
const ChunkCoordinate neighbor{static_cast<std::int32_t>(values[0]),
|
||||
static_cast<std::int32_t>(values[1]), static_cast<std::int32_t>(values[2])};
|
||||
if (region.intersects(neighbor)) dirty.push_back(neighbor);
|
||||
}
|
||||
void canonicalize(std::vector<ChunkCoordinate>& coordinates) {
|
||||
std::sort(coordinates.begin(), coordinates.end());
|
||||
coordinates.erase(std::unique(coordinates.begin(), coordinates.end()), coordinates.end());
|
||||
}
|
||||
} // namespace
|
||||
|
||||
bool VoxelBounds::contains(VoxelPosition position) const noexcept {
|
||||
return position.x >= lower.x && position.x < upper.x &&
|
||||
position.y >= lower.y && position.y < upper.y &&
|
||||
position.z >= lower.z && position.z < upper.z;
|
||||
}
|
||||
VoxelAddress split_voxel(VoxelPosition position) noexcept {
|
||||
const auto [cx, lx] = split_axis(position.x);
|
||||
const auto [cy, ly] = split_axis(position.y);
|
||||
const auto [cz, lz] = split_axis(position.z);
|
||||
return {{cx, cy, cz}, {lx, ly, lz}};
|
||||
}
|
||||
std::optional<std::size_t> voxel_index(LocalVoxel local) noexcept {
|
||||
if (local.x >= voxel_chunk_side || local.y >= voxel_chunk_side || local.z >= voxel_chunk_side) return {};
|
||||
return std::size_t{local.x} + 32 * (std::size_t{local.y} + 32 * std::size_t{local.z});
|
||||
}
|
||||
std::optional<VoxelPosition> join_voxel(ChunkCoordinate chunk, LocalVoxel local) noexcept {
|
||||
if (!voxel_index(local)) return {};
|
||||
const auto origin = chunk_origin(chunk);
|
||||
const auto x = origin.x + local.x, y = origin.y + local.y, z = origin.z + local.z;
|
||||
if (x < coordinate_min || x >= coordinate_end || y < coordinate_min || y >= coordinate_end ||
|
||||
z < coordinate_min || z >= coordinate_end) return {};
|
||||
return VoxelPosition{static_cast<std::int32_t>(x), static_cast<std::int32_t>(y), static_cast<std::int32_t>(z)};
|
||||
}
|
||||
bool valid_voxel_material(MaterialId material) noexcept {
|
||||
return material >= MaterialId::Air && material <= MaterialId::DoorOpen;
|
||||
}
|
||||
bool voxel_blocks_passage(MaterialId material) noexcept {
|
||||
return material == MaterialId::Soil || material == MaterialId::Stone || material == MaterialId::DoorClosed;
|
||||
}
|
||||
bool voxel_provides_support(MaterialId material) noexcept {
|
||||
return material == MaterialId::Soil || material == MaterialId::Stone;
|
||||
}
|
||||
|
||||
VoxelChunk::VoxelChunk(std::uint64_t revision, std::span<const MaterialId, voxel_chunk_cells> cells)
|
||||
: revision_(revision) {
|
||||
std::copy(cells.begin(), cells.end(), cells_.begin());
|
||||
}
|
||||
PreparedVoxelChunk::PreparedVoxelChunk(VoxelRegionDescriptor descriptor, ChunkCoordinate coordinate,
|
||||
std::shared_ptr<const VoxelChunk> chunk)
|
||||
: descriptor_(descriptor), coordinate_(coordinate), chunk_(std::move(chunk)) {}
|
||||
|
||||
VoxelRegion::VoxelRegion(VoxelRegionDescriptor descriptor, VoxelLimits limits)
|
||||
: descriptor_(descriptor), limits_(limits) {
|
||||
const auto& bounds = descriptor.bounds;
|
||||
if (!descriptor.id || descriptor.generator_version != voxel_generator_version ||
|
||||
!valid_interval(bounds.lower.x, bounds.upper.x) || !valid_interval(bounds.lower.y, bounds.upper.y) ||
|
||||
!valid_interval(bounds.lower.z, bounds.upper.z) || !limits.max_resident_chunks || !limits.max_edit_cells ||
|
||||
limits.max_resident_bytes < sizeof(VoxelDirectory) || !limits.max_transaction_bytes) {
|
||||
throw std::invalid_argument("invalid voxel region descriptor or limits");
|
||||
}
|
||||
directory_ = std::make_shared<const VoxelDirectory>();
|
||||
}
|
||||
std::size_t VoxelRegion::resident_bytes() const noexcept {
|
||||
return sizeof(VoxelDirectory) + directory_->size() * (sizeof(VoxelChunkEntry) + sizeof(VoxelChunk));
|
||||
}
|
||||
bool VoxelRegion::intersects(ChunkCoordinate coordinate) const noexcept {
|
||||
const auto origin = chunk_origin(coordinate);
|
||||
const auto& bounds = descriptor_.bounds;
|
||||
return overlapping_axis(origin.x, bounds.lower.x, bounds.upper.x) &&
|
||||
overlapping_axis(origin.y, bounds.lower.y, bounds.upper.y) &&
|
||||
overlapping_axis(origin.z, bounds.lower.z, bounds.upper.z);
|
||||
}
|
||||
ChunkStamp VoxelRegion::chunk_stamp(ChunkCoordinate coordinate) const noexcept {
|
||||
ChunkStamp result{descriptor_.id, coordinate, VoxelAvailability::Outside, 0};
|
||||
if (!intersects(coordinate)) return result;
|
||||
const auto entry = find_chunk(*directory_, coordinate);
|
||||
result.availability = VoxelAvailability::Unavailable;
|
||||
if (entry != directory_->end() && entry->coordinate == coordinate) {
|
||||
result.availability = VoxelAvailability::Loaded;
|
||||
result.revision = entry->chunk->revision();
|
||||
}
|
||||
return result;
|
||||
}
|
||||
bool VoxelRegion::matches(const ChunkStamp& stamp) const noexcept {
|
||||
return chunk_stamp(stamp.coordinate) == stamp;
|
||||
}
|
||||
VoxelSample VoxelRegion::sample(VoxelPosition position) const noexcept {
|
||||
const auto address = split_voxel(position);
|
||||
VoxelSample result{VoxelAvailability::Outside, MaterialId::Air, chunk_stamp(address.chunk)};
|
||||
if (!descriptor_.bounds.contains(position)) return result;
|
||||
result.availability = result.stamp.availability;
|
||||
if (result.availability == VoxelAvailability::Loaded) {
|
||||
result.material = find_chunk(*directory_, address.chunk)->chunk->cells()[*voxel_index(address.local)];
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
std::expected<PreparedVoxelChunk, VoxelError> VoxelRegion::prepare_generated(ChunkCoordinate coordinate) const {
|
||||
if (!intersects(coordinate)) return std::unexpected(VoxelError::InvalidCoordinate);
|
||||
PayloadBudget budget(limits_.max_transaction_bytes);
|
||||
if (!budget.take(1, sizeof(VoxelChunk)) || !budget.take(voxel_chunk_cells, sizeof(MaterialId))) {
|
||||
return std::unexpected(VoxelError::LimitExceeded);
|
||||
}
|
||||
try {
|
||||
std::array<MaterialId, voxel_chunk_cells> cells{};
|
||||
const auto origin = chunk_origin(coordinate);
|
||||
for (std::int32_t y = 0; y < voxel_chunk_side; ++y) {
|
||||
for (std::int32_t x = 0; x < voxel_chunk_side; ++x) {
|
||||
const auto px = static_cast<std::int32_t>(origin.x + x);
|
||||
const auto py = static_cast<std::int32_t>(origin.y + y);
|
||||
const auto height = surface_height(descriptor_.seed, px, py);
|
||||
for (std::int32_t z = 0; z < voxel_chunk_side; ++z) {
|
||||
const VoxelPosition position{px, py, static_cast<std::int32_t>(origin.z + z)};
|
||||
if (!descriptor_.bounds.contains(position) || position.z > height) continue;
|
||||
const auto material = position.z > height - 3 ? MaterialId::Soil : MaterialId::Stone;
|
||||
const auto index = static_cast<std::size_t>(x + 32 * (y + 32 * z));
|
||||
cells[index] = material;
|
||||
}
|
||||
}
|
||||
}
|
||||
auto chunk = std::shared_ptr<const VoxelChunk>(new const VoxelChunk(1, cells));
|
||||
return PreparedVoxelChunk(descriptor_, coordinate, std::move(chunk));
|
||||
} catch (const std::bad_alloc&) {
|
||||
return std::unexpected(VoxelError::AllocationFailed);
|
||||
}
|
||||
}
|
||||
std::expected<PreparedVoxelChunk, VoxelError> VoxelRegion::prepare_restored(
|
||||
ChunkCoordinate coordinate, std::uint64_t revision, std::span<const MaterialId> cells) const {
|
||||
if (!intersects(coordinate)) return std::unexpected(VoxelError::InvalidCoordinate);
|
||||
if (!revision) return std::unexpected(VoxelError::InvalidRevision);
|
||||
if (cells.size() != voxel_chunk_cells) return std::unexpected(VoxelError::InvalidSource);
|
||||
if (limits_.max_transaction_bytes < sizeof(VoxelChunk)) return std::unexpected(VoxelError::LimitExceeded);
|
||||
for (std::size_t i = 0; i < cells.size(); ++i) {
|
||||
if (!valid_voxel_material(cells[i])) return std::unexpected(VoxelError::InvalidMaterial);
|
||||
const auto position = join_voxel(coordinate,
|
||||
{static_cast<std::uint8_t>(i % 32), static_cast<std::uint8_t>((i / 32) % 32),
|
||||
static_cast<std::uint8_t>(i / 1024)});
|
||||
if (!position || (!descriptor_.bounds.contains(*position) && cells[i] != MaterialId::Air)) {
|
||||
return std::unexpected(VoxelError::InvalidCoordinate);
|
||||
}
|
||||
}
|
||||
try {
|
||||
const std::span<const MaterialId, voxel_chunk_cells> fixed(cells.data(), voxel_chunk_cells);
|
||||
auto chunk = std::shared_ptr<const VoxelChunk>(new const VoxelChunk(revision, fixed));
|
||||
return PreparedVoxelChunk(descriptor_, coordinate, std::move(chunk));
|
||||
} catch (const std::bad_alloc&) {
|
||||
return std::unexpected(VoxelError::AllocationFailed);
|
||||
}
|
||||
}
|
||||
|
||||
std::expected<VoxelCommit, VoxelError> VoxelRegion::activate(std::span<const PreparedVoxelChunk> candidates) {
|
||||
if (candidates.empty()) return VoxelCommit{};
|
||||
if (candidates.size() > limits_.max_resident_chunks - directory_->size()) {
|
||||
return std::unexpected(VoxelError::LimitExceeded);
|
||||
}
|
||||
const auto count = directory_->size() + candidates.size();
|
||||
PayloadBudget resident(limits_.max_resident_bytes);
|
||||
PayloadBudget staging(limits_.max_transaction_bytes);
|
||||
const auto dirty_count = Void::Numeric::checked_mul(candidates.size(), std::size_t{7});
|
||||
if (!dirty_count || !resident.take(1, sizeof(VoxelDirectory)) ||
|
||||
!resident.take(count, sizeof(VoxelChunkEntry) + sizeof(VoxelChunk)) ||
|
||||
!staging.take(1, sizeof(VoxelDirectory)) || !staging.take(count, sizeof(VoxelChunkEntry)) ||
|
||||
!staging.take(candidates.size(), sizeof(VoxelChunk) + sizeof(ChunkStamp)) ||
|
||||
!staging.take(*dirty_count, sizeof(ChunkCoordinate))) {
|
||||
return std::unexpected(VoxelError::LimitExceeded);
|
||||
}
|
||||
try {
|
||||
auto next = std::make_shared<VoxelDirectory>();
|
||||
next->reserve(count);
|
||||
next->insert(next->end(), directory_->begin(), directory_->end());
|
||||
VoxelCommit result;
|
||||
result.changed_chunks.reserve(candidates.size());
|
||||
result.dirty_chunks.reserve(*dirty_count);
|
||||
for (const auto& candidate : candidates) {
|
||||
if (candidate.descriptor_ != descriptor_ || !candidate.chunk_ || !intersects(candidate.coordinate_)) {
|
||||
return std::unexpected(VoxelError::InvalidSource);
|
||||
}
|
||||
if (chunk_stamp(candidate.coordinate_).availability != VoxelAvailability::Unavailable) {
|
||||
return std::unexpected(VoxelError::Stale);
|
||||
}
|
||||
next->push_back({candidate.coordinate_, candidate.chunk_});
|
||||
result.changed_chunks.push_back({descriptor_.id, candidate.coordinate_,
|
||||
VoxelAvailability::Loaded, candidate.chunk_->revision()});
|
||||
result.dirty_chunks.push_back(candidate.coordinate_);
|
||||
for (int axis = 0; axis < 3; ++axis) {
|
||||
add_neighbor(*this, result.dirty_chunks, candidate.coordinate_, axis, -1);
|
||||
add_neighbor(*this, result.dirty_chunks, candidate.coordinate_, axis, 1);
|
||||
}
|
||||
}
|
||||
std::sort(next->begin(), next->end(), [](const auto& a, const auto& b) { return a.coordinate < b.coordinate; });
|
||||
for (std::size_t i = 1; i < next->size(); ++i) {
|
||||
if ((*next)[i - 1].coordinate == (*next)[i].coordinate) return std::unexpected(VoxelError::Duplicate);
|
||||
}
|
||||
std::sort(result.changed_chunks.begin(), result.changed_chunks.end(),
|
||||
[](const auto& a, const auto& b) { return a.coordinate < b.coordinate; });
|
||||
canonicalize(result.dirty_chunks);
|
||||
std::shared_ptr<const VoxelDirectory> publication(std::move(next));
|
||||
directory_.swap(publication);
|
||||
return result;
|
||||
} catch (const std::bad_alloc&) {
|
||||
return std::unexpected(VoxelError::AllocationFailed);
|
||||
}
|
||||
}
|
||||
|
||||
std::expected<VoxelCommit, VoxelError> VoxelRegion::edit(std::span<const VoxelEdit> edits) {
|
||||
if (edits.empty()) return VoxelCommit{};
|
||||
if (edits.size() > limits_.max_edit_cells) return std::unexpected(VoxelError::LimitExceeded);
|
||||
PayloadBudget staging(limits_.max_transaction_bytes);
|
||||
if (!staging.take(edits.size(), sizeof(VoxelEdit))) return std::unexpected(VoxelError::LimitExceeded);
|
||||
try {
|
||||
std::vector<VoxelEdit> ordered(edits.begin(), edits.end());
|
||||
std::sort(ordered.begin(), ordered.end(), [](const auto& a, const auto& b) {
|
||||
const auto ca = split_voxel(a.position).chunk, cb = split_voxel(b.position).chunk;
|
||||
return ca == cb ? a.position < b.position : ca < cb;
|
||||
});
|
||||
std::size_t changed_pages = 0, changed_cells = 0;
|
||||
std::optional<ChunkCoordinate> last_changed;
|
||||
for (std::size_t i = 0; i < ordered.size(); ++i) {
|
||||
const auto& change = ordered[i];
|
||||
if (i && ordered[i - 1].position == change.position) return std::unexpected(VoxelError::Duplicate);
|
||||
if (!valid_voxel_material(change.material)) return std::unexpected(VoxelError::InvalidMaterial);
|
||||
const auto current = sample(change.position);
|
||||
if (current.availability == VoxelAvailability::Outside) return std::unexpected(VoxelError::InvalidCoordinate);
|
||||
if (current.availability == VoxelAvailability::Unavailable) return std::unexpected(VoxelError::Unavailable);
|
||||
if (current.stamp.revision != change.expected_revision) return std::unexpected(VoxelError::Stale);
|
||||
if (current.material == change.material) continue;
|
||||
if (current.stamp.revision == std::numeric_limits<std::uint64_t>::max()) {
|
||||
return std::unexpected(VoxelError::RevisionExhausted);
|
||||
}
|
||||
++changed_cells;
|
||||
if (!last_changed || *last_changed != current.stamp.coordinate) {
|
||||
++changed_pages;
|
||||
last_changed = current.stamp.coordinate;
|
||||
}
|
||||
}
|
||||
if (!changed_cells) return VoxelCommit{};
|
||||
const auto dirty_count = Void::Numeric::checked_mul(changed_cells, std::size_t{4});
|
||||
if (!dirty_count || !staging.take(1, sizeof(VoxelDirectory)) ||
|
||||
!staging.take(directory_->size(), sizeof(VoxelChunkEntry)) ||
|
||||
!staging.take(changed_pages, sizeof(VoxelChunk) + sizeof(ChunkStamp)) ||
|
||||
!staging.take(voxel_chunk_cells, sizeof(MaterialId)) ||
|
||||
!staging.take(changed_cells, sizeof(VoxelChange)) ||
|
||||
!staging.take(*dirty_count, sizeof(ChunkCoordinate))) {
|
||||
return std::unexpected(VoxelError::LimitExceeded);
|
||||
}
|
||||
auto next = std::make_shared<VoxelDirectory>(*directory_);
|
||||
VoxelCommit result;
|
||||
result.changed_cells.reserve(changed_cells);
|
||||
result.changed_chunks.reserve(changed_pages);
|
||||
result.dirty_chunks.reserve(*dirty_count);
|
||||
for (std::size_t first = 0; first < ordered.size();) {
|
||||
const auto coordinate = split_voxel(ordered[first].position).chunk;
|
||||
auto last = first + 1;
|
||||
while (last < ordered.size() && split_voxel(ordered[last].position).chunk == coordinate) ++last;
|
||||
const auto old = find_chunk(*directory_, coordinate);
|
||||
std::array<MaterialId, voxel_chunk_cells> cells;
|
||||
std::copy(old->chunk->cells().begin(), old->chunk->cells().end(), cells.begin());
|
||||
const auto count_before = result.changed_cells.size();
|
||||
for (auto i = first; i < last; ++i) {
|
||||
const auto& change = ordered[i];
|
||||
const auto local = split_voxel(change.position).local;
|
||||
auto& material = cells[*voxel_index(local)];
|
||||
if (material == change.material) continue;
|
||||
result.changed_cells.push_back({change.position, material, change.material});
|
||||
material = change.material;
|
||||
result.dirty_chunks.push_back(coordinate);
|
||||
const std::array<std::uint8_t, 3> axes{local.x, local.y, local.z};
|
||||
for (int axis = 0; axis < 3; ++axis) {
|
||||
if (axes[static_cast<std::size_t>(axis)] == 0) add_neighbor(*this, result.dirty_chunks, coordinate, axis, -1);
|
||||
if (axes[static_cast<std::size_t>(axis)] == 31) add_neighbor(*this, result.dirty_chunks, coordinate, axis, 1);
|
||||
}
|
||||
}
|
||||
if (result.changed_cells.size() != count_before) {
|
||||
const auto revision = old->chunk->revision() + 1;
|
||||
auto chunk = std::shared_ptr<const VoxelChunk>(new const VoxelChunk(revision, cells));
|
||||
const auto index = static_cast<std::size_t>(old - directory_->begin());
|
||||
(*next)[index].chunk = std::move(chunk);
|
||||
result.changed_chunks.push_back({descriptor_.id, coordinate, VoxelAvailability::Loaded, revision});
|
||||
}
|
||||
first = last;
|
||||
}
|
||||
std::sort(result.changed_cells.begin(), result.changed_cells.end(),
|
||||
[](const auto& a, const auto& b) { return a.position < b.position; });
|
||||
canonicalize(result.dirty_chunks);
|
||||
std::shared_ptr<const VoxelDirectory> publication(std::move(next));
|
||||
directory_.swap(publication);
|
||||
return result;
|
||||
} catch (const std::bad_alloc&) {
|
||||
return std::unexpected(VoxelError::AllocationFailed);
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace settlement
|
||||
+79
-51
@@ -1,4 +1,5 @@
|
||||
#include "settlement/core/world.hpp"
|
||||
#include "settlement/core/inventory_transaction.hpp"
|
||||
|
||||
#include <Void/Core/Scope.hpp>
|
||||
#include <Void/Math/Numeric.hpp>
|
||||
@@ -322,6 +323,29 @@ const ResourceNode* World::find_resource_node(ResourceNodeId id) const noexcept
|
||||
return found == resource_nodes_.end() || found->id != id ? nullptr : &*found;
|
||||
}
|
||||
|
||||
const ProductionOrder* World::find_production(ProductionId id) const noexcept {
|
||||
const auto found = record_position(production_orders_, id);
|
||||
return found == production_orders_.end() || found->id != id ? nullptr : &*found;
|
||||
}
|
||||
|
||||
ProductionOrder& World::production_by_id(ProductionId id) {
|
||||
return require_record(production_orders_, id);
|
||||
}
|
||||
|
||||
// Replace with a restorable checked sequence when Void/Library#7 is available:
|
||||
// https://git.faumaray.com/Void/Library/issues/7
|
||||
bool World::reserve_production(std::size_t count) {
|
||||
if (!Void::Numeric::checked_add(next_production_id_, static_cast<std::uint64_t>(count))) return false;
|
||||
production_orders_.reserve(production_orders_.size() + count);
|
||||
return true;
|
||||
}
|
||||
|
||||
void World::append_production(ProductionOrder order) {
|
||||
order.id = next_production_id_;
|
||||
production_orders_.push_back(std::move(order));
|
||||
++next_production_id_;
|
||||
}
|
||||
|
||||
Storage& World::storage_by_id(StorageId id) {
|
||||
return require_record(storages_, id);
|
||||
}
|
||||
@@ -381,12 +405,12 @@ void World::set_blocked(GridPosition position, bool blocked) {
|
||||
}
|
||||
}
|
||||
for (const Agent& agent : agents_) {
|
||||
if (agent.production_index != no_entity_index &&
|
||||
is_carpentry_recipe(production_orders_[agent.production_index].recipe) &&
|
||||
if (agent.production_id != 0 &&
|
||||
is_carpentry_recipe(production_by_id(agent.production_id).recipe) &&
|
||||
std::find(agent.haul_route.begin(), agent.haul_route.end(), position) != agent.haul_route.end()) {
|
||||
throw std::logic_error("cannot block the carpenter's delivery route");
|
||||
}
|
||||
if (agent.production_index == no_entity_index &&
|
||||
if (agent.production_id == 0 &&
|
||||
agent.state != AgentState::GoingToEat && agent.state != AgentState::GoingToSleep &&
|
||||
!is_carpentry_item(agent.inventory.first_item())) continue;
|
||||
const auto remaining = agent.route.begin() + static_cast<std::ptrdiff_t>(agent.route_cursor);
|
||||
@@ -499,10 +523,11 @@ void World::queue_production(GridPosition position, RecipeId recipe) {
|
||||
throw std::invalid_argument("a building occupies the production site");
|
||||
}
|
||||
}
|
||||
if (!reserve_production(1)) throw ProductionCapacityError{};
|
||||
ProductionOrder order{};
|
||||
order.position = position;
|
||||
order.recipe = recipe;
|
||||
production_orders_.push_back(std::move(order));
|
||||
append_production(std::move(order));
|
||||
}
|
||||
|
||||
bool World::can_place_cabin(GridPosition position) const noexcept {
|
||||
@@ -563,7 +588,8 @@ std::array<ItemStack, 2> World::carpentry_materials(RecipeId recipe) const {
|
||||
return is_carpentry_recipe(recipe) ? recipe_for(recipe).ingredients : std::array<ItemStack, 2>{};
|
||||
}
|
||||
|
||||
std::size_t World::missing_carpentry_orders(ItemType product, std::size_t new_installations) const {
|
||||
std::size_t World::missing_carpentry_orders(ItemType product, std::size_t new_installations,
|
||||
StorageId excluded_storage) const {
|
||||
const auto craft = recipe_for_carpentry_item(product);
|
||||
std::uint64_t waiting_installations = new_installations, supply = 0;
|
||||
for (const auto& order : production_orders_) {
|
||||
@@ -574,11 +600,12 @@ std::size_t World::missing_carpentry_orders(ItemType product, std::size_t new_in
|
||||
}
|
||||
}
|
||||
for (const auto& agent : agents_) {
|
||||
if (agent.state == AgentState::Hauling && agent.production_index == no_entity_index) {
|
||||
if (agent.state == AgentState::Hauling && agent.production_id == 0) {
|
||||
supply += agent.inventory.item_count(product);
|
||||
}
|
||||
}
|
||||
for (const auto& storage : storages_) {
|
||||
if (storage.id == excluded_storage) continue;
|
||||
const auto available = storage.available_item_count(product);
|
||||
if (available != 0 && find_path(scenario_sawmill_, storage.position).reachable) supply += available;
|
||||
}
|
||||
@@ -600,8 +627,9 @@ void World::queue_cabin(GridPosition position, GridPosition sawmill, GridPositio
|
||||
throw std::invalid_argument("the cabin site is disconnected from the workshops");
|
||||
}
|
||||
const Recipe& cabin = recipe_for(RecipeId::BuildCabin);
|
||||
production_orders_.reserve(production_orders_.size() + 1 +
|
||||
cabin.ingredients[0].count + cabin.ingredients[1].count);
|
||||
if (!reserve_production(1 + cabin.ingredients[0].count + cabin.ingredients[1].count)) {
|
||||
throw ProductionCapacityError{};
|
||||
}
|
||||
for (std::uint32_t i = 0; i < cabin.ingredients[0].count; ++i) {
|
||||
queue_production(sawmill, RecipeId::SawPlank);
|
||||
}
|
||||
@@ -691,18 +719,13 @@ CommandStatus World::edit_object(GridPosition position, const GridPosition* dest
|
||||
return CommandStatus::InvalidTarget;
|
||||
}
|
||||
const auto at_position = [position](const auto& item) { return item.position == position; };
|
||||
const auto shift_index = [](std::size_t& index, std::size_t removed) {
|
||||
if (index != no_entity_index && index > removed) --index;
|
||||
};
|
||||
const auto order = std::find_if(production_orders_.begin(), production_orders_.end(), [&](const auto& entry) {
|
||||
return is_production_object(entry.recipe) && !is_finished_floor(entry) && at_position(entry);
|
||||
});
|
||||
if (order != production_orders_.end()) {
|
||||
if (destination) order->position = *destination;
|
||||
else {
|
||||
const auto removed = static_cast<std::size_t>(order - production_orders_.begin());
|
||||
production_orders_.erase(order);
|
||||
for (auto& agent : agents_) shift_index(agent.production_index, removed);
|
||||
}
|
||||
return CommandStatus::Accepted;
|
||||
}
|
||||
@@ -710,19 +733,23 @@ CommandStatus World::edit_object(GridPosition position, const GridPosition* dest
|
||||
if (storage != storages_.end()) {
|
||||
if (destination) storage->position = *destination;
|
||||
else {
|
||||
std::array<std::uint8_t, std::size(carpentry_products)> lost_products{};
|
||||
for (std::size_t i = 0; i < std::size(carpentry_products); ++i) {
|
||||
lost_products[i] = storage->item_count(carpentry_products[i]) != 0;
|
||||
}
|
||||
storages_.erase(storage);
|
||||
std::array<std::size_t, std::size(carpentry_products)> replacements{};
|
||||
std::size_t total = 0;
|
||||
if (scenario_active_) {
|
||||
for (std::size_t i = 0; i < std::size(carpentry_products); ++i) {
|
||||
if (!lost_products[i]) continue;
|
||||
for (std::size_t i = 0; i < replacements.size(); ++i) {
|
||||
const auto product = carpentry_products[i];
|
||||
const auto missing = missing_carpentry_orders(product);
|
||||
for (std::size_t j = 0; j < missing; ++j) {
|
||||
queue_production(scenario_sawmill_, recipe_for_carpentry_item(product));
|
||||
}
|
||||
if (storage->item_count(product) == 0) continue;
|
||||
replacements[i] = missing_carpentry_orders(product, 0, storage->id);
|
||||
total += replacements[i];
|
||||
}
|
||||
}
|
||||
// Demand is evaluated against the post-removal inventory, without
|
||||
// losing stock or issuing any order until the entire batch fits.
|
||||
if (!reserve_production(total)) return CommandStatus::Busy;
|
||||
storages_.erase(storage);
|
||||
for (std::size_t i = 0; i < replacements.size(); ++i) {
|
||||
for (std::size_t j = 0; j < replacements[i]; ++j) {
|
||||
queue_production(scenario_sawmill_, recipe_for_carpentry_item(carpentry_products[i]));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -733,9 +760,7 @@ CommandStatus World::edit_object(GridPosition position, const GridPosition* dest
|
||||
const auto floor = std::find_if(production_orders_.begin(), production_orders_.end(),
|
||||
[&](const auto& entry) { return is_finished_floor(entry) && at_position(entry); });
|
||||
if (floor == production_orders_.end() || destination) return CommandStatus::InvalidTarget;
|
||||
const auto removed = static_cast<std::size_t>(floor - production_orders_.begin());
|
||||
production_orders_.erase(floor);
|
||||
for (auto& agent : agents_) shift_index(agent.production_index, removed);
|
||||
return CommandStatus::Accepted;
|
||||
}
|
||||
if (destination) source->position = *destination;
|
||||
@@ -770,12 +795,12 @@ CommandReceipt World::apply_command(const PlayerCommand& command) {
|
||||
!can_place_bed(command.cell) || !find_path(scenario_sawmill_, command.cell).reachable) {
|
||||
return receipt(CommandStatus::InvalidTarget);
|
||||
}
|
||||
if (!reserve_production(staged_beds_ ? 1 : 2)) return receipt(CommandStatus::Busy);
|
||||
if (staged_beds_) {
|
||||
queue_production(command.cell, RecipeId::BuildBed);
|
||||
production_orders_.back().bed_base = static_cast<BedBase>(command.value);
|
||||
production_orders_.back().bed_stage = BedStage::Foundation;
|
||||
} else {
|
||||
production_orders_.reserve(production_orders_.size() + 2);
|
||||
queue_production(scenario_sawmill_, RecipeId::SawPlank);
|
||||
queue_production(command.cell, RecipeId::BuildBed);
|
||||
}
|
||||
@@ -842,19 +867,22 @@ CommandReceipt World::apply_command(const PlayerCommand& command) {
|
||||
}
|
||||
if (scenario_active_) {
|
||||
const auto missing = missing_carpentry_orders(ItemType::Loom, 1);
|
||||
production_orders_.reserve(production_orders_.size() + 1 + missing);
|
||||
if (!reserve_production(1 + missing)) return receipt(CommandStatus::Busy);
|
||||
queue_production(command.cell, RecipeId::InstallLoom);
|
||||
for (std::size_t i = 0; i < missing; ++i) queue_production(scenario_sawmill_, RecipeId::CraftLoom);
|
||||
} else {
|
||||
if (!reserve_production(1)) return receipt(CommandStatus::Busy);
|
||||
queue_production(command.cell, RecipeId::WeaveCloth);
|
||||
}
|
||||
break;
|
||||
case CommandKind::CraftDoor:
|
||||
if (!reserve_production(1)) return receipt(CommandStatus::Busy);
|
||||
queue_production(scenario_sawmill_, RecipeId::CraftWoodenDoor);
|
||||
break;
|
||||
case CommandKind::CraftFurniture: {
|
||||
const auto product = static_cast<ItemType>(command.value);
|
||||
if (!is_carpentry_item(product) || product == ItemType::WoodenDoor) return receipt(CommandStatus::InvalidTarget);
|
||||
if (!reserve_production(1)) return receipt(CommandStatus::Busy);
|
||||
queue_production(scenario_sawmill_, recipe_for_carpentry_item(product));
|
||||
break;
|
||||
}
|
||||
@@ -871,8 +899,8 @@ CommandReceipt World::apply_command(const PlayerCommand& command) {
|
||||
const auto fixture = furnishings ? room_construction_recipe(furnishings->back().recipe) : RecipeId::BuildFloor;
|
||||
const auto fixture_item = furnishings ? recipe_for(fixture).ingredients.front().type : ItemType::None;
|
||||
const auto fixture_orders = furnishings ? missing_carpentry_orders(fixture_item, 1) : 0;
|
||||
production_orders_.reserve(production_orders_.size() + width * height +
|
||||
(furnishings ? furnishings->size() : 0) + (legacy_bed ? 1U : 0U) + door_orders + fixture_orders);
|
||||
if (!reserve_production(width * height + (furnishings ? furnishings->size() : 0) +
|
||||
(legacy_bed ? 1U : 0U) + door_orders + fixture_orders)) return receipt(CommandStatus::Busy);
|
||||
if (legacy_bed) queue_production(scenario_sawmill_, RecipeId::SawPlank);
|
||||
if (furnishings) {
|
||||
for (const auto& part : *furnishings) {
|
||||
@@ -881,7 +909,7 @@ CommandReceipt World::apply_command(const PlayerCommand& command) {
|
||||
order.recipe = room_construction_recipe(part.recipe);
|
||||
order.bed_base = part.bed_base;
|
||||
if (order.recipe == RecipeId::BuildBed && staged_beds_) order.bed_stage = BedStage::Foundation;
|
||||
production_orders_.push_back(std::move(order));
|
||||
append_production(std::move(order));
|
||||
}
|
||||
}
|
||||
for (int y = plan.first.y; y <= plan.last.y; ++y) {
|
||||
@@ -890,7 +918,7 @@ CommandReceipt World::apply_command(const PlayerCommand& command) {
|
||||
ProductionOrder order{};
|
||||
order.position = cell;
|
||||
order.recipe = room_construction_recipe(plan.recipe_at(cell));
|
||||
production_orders_.push_back(std::move(order));
|
||||
append_production(std::move(order));
|
||||
}
|
||||
}
|
||||
for (std::size_t i = 0; i < door_orders; ++i) queue_production(scenario_sawmill_, RecipeId::CraftWoodenDoor);
|
||||
@@ -1420,7 +1448,7 @@ void World::assign_production_tasks(bool weaving) {
|
||||
order.materials = std::move(materials);
|
||||
order.delivery_stops = std::move(stops);
|
||||
order.state = JobState::InProgress;
|
||||
agent.production_index = index;
|
||||
agent.production_id = order.id;
|
||||
agent.route = std::move(path.positions);
|
||||
agent.route_cursor = 0;
|
||||
agent.work_remaining = recipe.ticks;
|
||||
@@ -1484,8 +1512,10 @@ void World::assign_meals() {
|
||||
void World::finish_meal_step(Agent& agent) {
|
||||
if (agent.state == AgentState::GoingToEat) {
|
||||
if (agent.route_cursor != agent.route.size()) return;
|
||||
take_reserved_material(storage_by_id(agent.storage_id), {agent.storage_id, ItemType::Berries, 1});
|
||||
agent.inventory.add(ItemType::Berries);
|
||||
const std::array meal{MaterialReservation{agent.storage_id, ItemType::Berries, 1}};
|
||||
if (!withdraw_reserved_materials(storage_by_id(agent.storage_id), agent.inventory, meal)) {
|
||||
throw std::logic_error("invalid reserved meal pickup");
|
||||
}
|
||||
agent.storage_id = 0;
|
||||
agent.route.clear();
|
||||
agent.route_cursor = 0;
|
||||
@@ -1553,7 +1583,7 @@ void World::finish_rest_step(Agent& agent) {
|
||||
}
|
||||
|
||||
void World::advance_construction_delivery(Agent& agent) {
|
||||
ProductionOrder& order = production_orders_[agent.production_index];
|
||||
ProductionOrder& order = production_by_id(agent.production_id);
|
||||
if (order.collected_stops == order.delivery_stops.size()) {
|
||||
for (const auto& material : order.materials) {
|
||||
agent.inventory.remove(material.type, material.count);
|
||||
@@ -1566,16 +1596,14 @@ void World::advance_construction_delivery(Agent& agent) {
|
||||
return;
|
||||
}
|
||||
|
||||
auto& stop = order.delivery_stops[order.collected_stops];
|
||||
for (const auto& material : order.materials) {
|
||||
if (material.storage_id == stop.storage_id) {
|
||||
take_reserved_material(storage_by_id(stop.storage_id), material);
|
||||
agent.inventory.add(material.type, material.count);
|
||||
}
|
||||
if (order.collected_stops > order.delivery_stops.size() || order.materials.empty()) {
|
||||
throw std::logic_error("invalid construction pickup stop");
|
||||
}
|
||||
if (is_carpentry_recipe(order.recipe) && stop.storage_id == order.materials.front().storage_id) {
|
||||
// Collecting the first ingredient frees a slot for the finished item.
|
||||
++storage_by_id(stop.storage_id).reserved_slots;
|
||||
auto& stop = order.delivery_stops[order.collected_stops];
|
||||
const bool reserve_output = is_carpentry_recipe(order.recipe) &&
|
||||
stop.storage_id == order.materials.front().storage_id;
|
||||
if (!withdraw_reserved_materials(storage_by_id(stop.storage_id), agent.inventory, order.materials, reserve_output)) {
|
||||
throw std::logic_error("invalid reserved construction pickup");
|
||||
}
|
||||
++order.collected_stops;
|
||||
agent.route = std::move(stop.route_to_next);
|
||||
@@ -1584,7 +1612,7 @@ void World::advance_construction_delivery(Agent& agent) {
|
||||
}
|
||||
|
||||
void World::finish_production(Agent& agent) {
|
||||
ProductionOrder& order = production_orders_[agent.production_index];
|
||||
ProductionOrder& order = production_by_id(agent.production_id);
|
||||
const Recipe recipe = recipe_for(order);
|
||||
assert(!order.materials.empty());
|
||||
if (is_carpentry_recipe(order.recipe)) {
|
||||
@@ -1593,7 +1621,7 @@ void World::finish_production(Agent& agent) {
|
||||
agent.route = std::move(agent.haul_route);
|
||||
agent.haul_route.clear();
|
||||
agent.route_cursor = 0;
|
||||
agent.production_index = no_entity_index;
|
||||
agent.production_id = 0;
|
||||
agent.state = AgentState::Hauling;
|
||||
order.materials.clear();
|
||||
order.state = JobState::Completed;
|
||||
@@ -1619,7 +1647,7 @@ void World::finish_production(Agent& agent) {
|
||||
} else {
|
||||
order.state = JobState::Completed;
|
||||
}
|
||||
agent.production_index = no_entity_index;
|
||||
agent.production_id = 0;
|
||||
agent.state = AgentState::Idle;
|
||||
agent.route.clear();
|
||||
agent.route_cursor = 0;
|
||||
@@ -1695,7 +1723,7 @@ void World::step(TickProfile* profile) {
|
||||
if (agent.state != AgentState::Working) continue;
|
||||
if (agent.work_remaining > 0 && can_work(agent)) --agent.work_remaining;
|
||||
if (agent.work_remaining != 0) continue;
|
||||
if (agent.production_index != no_entity_index) continue;
|
||||
if (agent.production_id != 0) continue;
|
||||
|
||||
const auto job = std::lower_bound(
|
||||
jobs_.begin(), jobs_.end(), agent.current_job,
|
||||
@@ -1742,12 +1770,12 @@ void World::step(TickProfile* profile) {
|
||||
finish_rest_step(agent);
|
||||
continue;
|
||||
}
|
||||
if (agent.production_index != no_entity_index && agent.route_cursor == agent.route.size() &&
|
||||
if (agent.production_id != 0 && agent.route_cursor == agent.route.size() &&
|
||||
(agent.state == AgentState::FetchingMaterials || agent.state == AgentState::Hauling)) {
|
||||
advance_construction_delivery(agent);
|
||||
continue;
|
||||
}
|
||||
if (agent.state == AgentState::Working && agent.production_index != no_entity_index &&
|
||||
if (agent.state == AgentState::Working && agent.production_id != 0 &&
|
||||
agent.work_remaining == 0) {
|
||||
finish_production(agent);
|
||||
}
|
||||
|
||||
+42
-19
@@ -18,7 +18,7 @@ namespace settlement {
|
||||
namespace {
|
||||
|
||||
constexpr std::string_view signature = "SETTLERS";
|
||||
constexpr std::uint32_t save_version = 13;
|
||||
constexpr std::uint32_t save_version = 14;
|
||||
constexpr std::uint32_t last_legacy_footer_version = 8;
|
||||
constexpr std::size_t max_records = 1'000'000;
|
||||
constexpr std::size_t max_save_bytes = 128 * 1024 * 1024;
|
||||
@@ -231,12 +231,13 @@ struct WorldSaveCodec {
|
||||
archive.field(world.next_job_id_);
|
||||
archive.field(world.next_resource_node_id_);
|
||||
archive.field(world.next_storage_id_);
|
||||
if (version >= 14) archive.field(world.next_production_id_);
|
||||
const auto cells = world.blocked_.size();
|
||||
for (auto& cell : world.blocked_) archive.field(cell);
|
||||
|
||||
// Agent links precede their pools in legacy saves. Raw positions stay
|
||||
// loader-owned until the complete, ID-ordered pools are available.
|
||||
std::vector<std::array<std::size_t, 2>> agent_links;
|
||||
std::vector<std::array<std::size_t, 3>> agent_links;
|
||||
sequence(archive, world.agents_, max_records, [&](auto& agent) {
|
||||
archive.field(agent.id);
|
||||
position(archive, agent.position);
|
||||
@@ -245,8 +246,11 @@ struct WorldSaveCodec {
|
||||
route(archive, agent.route, cells);
|
||||
offset(archive, agent.route_cursor);
|
||||
archive.field(agent.work_remaining);
|
||||
if constexpr (Archive::reading) {
|
||||
std::array<std::size_t, 2> links{no_entity_index, no_entity_index};
|
||||
if (version >= 14) {
|
||||
archive.field(agent.resource_node_id);
|
||||
archive.field(agent.storage_id);
|
||||
} else if constexpr (Archive::reading) {
|
||||
std::array<std::size_t, 3> links{no_entity_index, no_entity_index, no_entity_index};
|
||||
index(archive, links[0]);
|
||||
index(archive, links[1]);
|
||||
agent_links.push_back(links);
|
||||
@@ -264,7 +268,9 @@ struct WorldSaveCodec {
|
||||
}
|
||||
}
|
||||
route(archive, agent.haul_route, cells);
|
||||
index(archive, agent.production_index);
|
||||
if (version >= 14) archive.field(agent.production_id);
|
||||
else if constexpr (Archive::reading) index(archive, agent_links.back()[2]);
|
||||
else reference(archive, agent.production_id, world.production_orders_);
|
||||
archive.field(agent.hunger);
|
||||
if (version >= 4) archive.field(agent.fatigue);
|
||||
if (version >= 5) flag(archive, agent.resting_on_ground);
|
||||
@@ -315,6 +321,8 @@ struct WorldSaveCodec {
|
||||
}
|
||||
}
|
||||
sequence(archive, world.production_orders_, max_records, [&](auto& order) {
|
||||
if (version >= 14) archive.field(order.id);
|
||||
else if constexpr (Archive::reading) order.id = world.production_orders_.size();
|
||||
position(archive, order.position);
|
||||
archive.field(order.recipe);
|
||||
require_save(version >= 2 || order.recipe <= RecipeId::BuildCabin, "Unknown recipe for save version.");
|
||||
@@ -325,13 +333,15 @@ struct WorldSaveCodec {
|
||||
require_save(version >= 13 || order.recipe <= RecipeId::CraftWoodenDoor, "Unknown recipe for save version.");
|
||||
archive.field(order.state);
|
||||
sequence(archive, order.materials, item_types, [&](auto& material) {
|
||||
reference(archive, material.storage_id, world.storages_);
|
||||
if (version >= 14) archive.field(material.storage_id);
|
||||
else reference(archive, material.storage_id, world.storages_);
|
||||
archive.field(material.type);
|
||||
require_save(material.type <= max_item, "Unknown material for save version.");
|
||||
archive.field(material.count);
|
||||
});
|
||||
sequence(archive, order.delivery_stops, item_types, [&](auto& stop) {
|
||||
reference(archive, stop.storage_id, world.storages_);
|
||||
if (version >= 14) archive.field(stop.storage_id);
|
||||
else reference(archive, stop.storage_id, world.storages_);
|
||||
route(archive, stop.route_to_next, cells);
|
||||
});
|
||||
offset(archive, order.collected_stops);
|
||||
@@ -341,6 +351,14 @@ struct WorldSaveCodec {
|
||||
archive.field(order.bed_stage);
|
||||
}
|
||||
});
|
||||
if constexpr (Archive::reading) {
|
||||
if (version < 14) {
|
||||
world.next_production_id_ = world.production_orders_.size() + 1;
|
||||
for (std::size_t i = 0; i < agent_links.size(); ++i) {
|
||||
world.agents_[i].production_id = reference_id(world.production_orders_, agent_links[i][2]);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (version >= 2) {
|
||||
flag(archive, world.scenario_active_);
|
||||
flag(archive, world.paused_);
|
||||
@@ -376,6 +394,7 @@ void WorldSaveCodec::validate(const World& world) {
|
||||
check_ids(world.jobs_, world.next_job_id_);
|
||||
check_ids(world.resource_nodes_, world.next_resource_node_id_);
|
||||
check_ids(world.storages_, world.next_storage_id_);
|
||||
check_ids(world.production_orders_, world.next_production_id_);
|
||||
invalid(world.work_priority_ <= WorkPriority::BuildingFirst);
|
||||
std::uint64_t revision = 0;
|
||||
for (const auto sequence : world.player_sequences_) {
|
||||
@@ -540,12 +559,13 @@ void WorldSaveCodec::validate(const World& world) {
|
||||
valid_route(agent.route);
|
||||
valid_route(agent.haul_route);
|
||||
const bool has_job = agent.current_job != 0;
|
||||
const bool has_order = agent.production_index != no_entity_index;
|
||||
const bool has_order = agent.production_id != 0;
|
||||
const auto* production = world.find_production(agent.production_id);
|
||||
invalid(!has_order || production != nullptr);
|
||||
const bool has_source = agent.resource_node_id != 0;
|
||||
const bool has_storage = agent.storage_id != 0;
|
||||
invalid(!has_storage || world.find_storage(agent.storage_id) != nullptr);
|
||||
const bool carpentry = has_order && agent.production_index < world.production_orders_.size() &&
|
||||
is_carpentry_recipe(world.production_orders_[agent.production_index].recipe);
|
||||
const bool carpentry = has_order && is_carpentry_recipe(production->recipe);
|
||||
invalid(agent.haul_route.empty() || has_source || carpentry);
|
||||
if (has_job) {
|
||||
invalid(!has_order && !has_storage && !has_source && agent.inventory.empty() &&
|
||||
@@ -557,11 +577,11 @@ void WorldSaveCodec::validate(const World& world) {
|
||||
invalid(claimed == 0);
|
||||
claimed = 1;
|
||||
} else if (has_order) {
|
||||
invalid(!has_storage && !has_source && agent.production_index < world.production_orders_.size() &&
|
||||
agent.work_remaining > 0);
|
||||
const auto& order = world.production_orders_[agent.production_index];
|
||||
invalid(order.state == JobState::InProgress && order_claims[agent.production_index] == 0);
|
||||
order_claims[agent.production_index] = 1;
|
||||
invalid(!has_storage && !has_source && agent.work_remaining > 0);
|
||||
const auto order_index = static_cast<std::size_t>(production - world.production_orders_.data());
|
||||
const auto& order = *production;
|
||||
invalid(order.state == JobState::InProgress && order_claims[order_index] == 0);
|
||||
order_claims[order_index] = 1;
|
||||
if (!order.delivery_stops.empty()) {
|
||||
invalid(agent.state == (order.collected_stops == 0 ? FetchingMaterials : Hauling));
|
||||
} else {
|
||||
@@ -579,7 +599,7 @@ void WorldSaveCodec::validate(const World& world) {
|
||||
if (collected) ++reserved_slots[storage];
|
||||
}
|
||||
for (std::size_t i = 0; i < item_types; ++i) {
|
||||
invalid(agent.inventory.item_count(static_cast<ItemType>(i + 1)) == expected_cargo[agent.production_index][i]);
|
||||
invalid(agent.inventory.item_count(static_cast<ItemType>(i + 1)) == expected_cargo[order_index][i]);
|
||||
}
|
||||
} else if (has_source) {
|
||||
invalid(world.find_resource_node(agent.resource_node_id) != nullptr &&
|
||||
@@ -654,14 +674,17 @@ void WorldSaveCodec::validate(const World& world) {
|
||||
}
|
||||
}
|
||||
|
||||
void World::write_save(std::ostream& stream) const {
|
||||
void World::write_save(std::ostream& stream, WorldSaveFormat format) const {
|
||||
const auto version = static_cast<std::uint32_t>(format);
|
||||
require_save(format == WorldSaveFormat::Legacy13 || format == WorldSaveFormat::Current14,
|
||||
"Unsupported save output format.");
|
||||
SaveWriter archive(stream);
|
||||
for (char letter : signature) archive.field(letter);
|
||||
archive.field(save_version);
|
||||
archive.field(version);
|
||||
archive.field(seed_);
|
||||
archive.field(width_);
|
||||
archive.field(height_);
|
||||
WorldSaveCodec::body(archive, *this, save_version);
|
||||
WorldSaveCodec::body(archive, *this, version);
|
||||
}
|
||||
|
||||
std::unique_ptr<World> World::read_save(std::istream& stream, std::size_t workers, ExecutionMode mode,
|
||||
|
||||
@@ -205,7 +205,7 @@ Test CheckpointFileTests::modern_failures_retain_exact_diagnostics() {
|
||||
"modern failure lost its codec diagnostic");
|
||||
}
|
||||
auto unsupported = current;
|
||||
unsupported[8] = 2;
|
||||
unsupported[8] = static_cast<char>(checkpoint_version + 1);
|
||||
write(path, unsupported);
|
||||
const auto version = load(files, path);
|
||||
require(!version && version.error().checkpoint &&
|
||||
|
||||
@@ -112,7 +112,51 @@ std::string package_json(std::string_view id, std::string_view version = "1.0.0"
|
||||
|
||||
RulePackage load(std::string_view json) { return checked(load_rule_package("checkpoint-fixture.json", json)); }
|
||||
|
||||
// Captured before S04 with the baseline 4ba64f7 library, using seed 43,
|
||||
// a 3x3 world, one SawPlank order, default rules, world_id and city 7.
|
||||
// The v13 frame is byte-for-byte original (SHA256
|
||||
// 28043dcc2a9faa6e1b217eb19df5807e159a0ac4bfdcd65de464034527557847).
|
||||
// v1/v8 bodies apply their historical field/footer layout to that fixed fixture.
|
||||
std::string old_checkpoint(std::size_t variant) {
|
||||
constexpr std::array<std::string_view, 3> hex{
|
||||
"53544843484b505401000000b6000000cb000000000000009102030405064708890a0b0c0d0e0f1007000000000000000000"
|
||||
"00000000000006d39e42fa79f06859b9bee1dcb08088142cb83e8cdcf72dc0984cfc62cd83d1020000001100736574746c65"
|
||||
"6d656e742e636f6c6f6e790500312e302e3008e18a58989430c5435a2de6fb8f6a27a912b4d2970c1b965282408880d2c089"
|
||||
"0f00736574746c656d656e742e636f72650500312e302e3061b36b8a230eebbe862e696603e021ace7151a9faf0ab3c069ab"
|
||||
"7124188d337f534554544c4552530d0000002b00000000000000030000000300000000000000000000000000000000000000"
|
||||
"0000000000000000000000000000000000000000000000000001000000000000000100000000000000010000000000000001"
|
||||
"0000000000000000000000000000000000000000000000000000000000000000010000000100000001000000000000000000"
|
||||
"0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
|
||||
"000000000000000000bd7066618db314e2ca874c7eae12d9f8cc45a222c446e23906dbd6645710cd62",
|
||||
"53544843484b505401000000b6000000a4000000000000009102030405064708890a0b0c0d0e0f1007000000000000000000"
|
||||
"00000000000006d39e42fa79f06859b9bee1dcb08088142cb83e8cdcf72dc0984cfc62cd83d1020000001100736574746c65"
|
||||
"6d656e742e636f6c6f6e790500312e302e3008e18a58989430c5435a2de6fb8f6a27a912b4d2970c1b965282408880d2c089"
|
||||
"0f00736574746c656d656e742e636f72650500312e302e3061b36b8a230eebbe862e696603e021ace7151a9faf0ab3c069ab"
|
||||
"7124188d337f534554544c455253010000002b00000000000000030000000300000000000000000000000000000000000000"
|
||||
"0000000000000000000000000000000000000000000000000001000000000000000100000000000000010000000000000001"
|
||||
"0000000000000000000000000000000000000000000000000000000000000000010000000100000001000000000000000000"
|
||||
"000000000000000000000000224ae83870bea33ac3afafcd0190d032cb7b517123fb4ac93479daa4cc71cc74ed17ba385446"
|
||||
"aa69",
|
||||
"53544843484b505401000000b6000000d3000000000000009102030405064708890a0b0c0d0e0f1007000000000000000000"
|
||||
"00000000000006d39e42fa79f06859b9bee1dcb08088142cb83e8cdcf72dc0984cfc62cd83d1020000001100736574746c65"
|
||||
"6d656e742e636f6c6f6e790500312e302e3008e18a58989430c5435a2de6fb8f6a27a912b4d2970c1b965282408880d2c089"
|
||||
"0f00736574746c656d656e742e636f72650500312e302e3061b36b8a230eebbe862e696603e021ace7151a9faf0ab3c069ab"
|
||||
"7124188d337f534554544c455253080000002b00000000000000030000000300000000000000000000000000000000000000"
|
||||
"0000000000000000000000000000000000000000000000000001000000000000000100000000000000010000000000000001"
|
||||
"0000000000000000000000000000000000000000000000000000000000000000010000000100000001000000000000000000"
|
||||
"0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
|
||||
"000000000000000000f92cb77443aeca815745b0132cc684f43738865a4034d4474a373902a294e9c31801c47cf80037e4",
|
||||
};
|
||||
std::string result;
|
||||
const auto value = [](char c) { return c <= '9' ? c - '0' : c - 'a' + 10; };
|
||||
for (std::size_t i = 0; i < hex[variant].size(); i += 2) {
|
||||
result.push_back(static_cast<char>(value(hex[variant][i]) * 16 + value(hex[variant][i + 1])));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
struct [[= Void::Testing::name("CheckpointTests")]] CheckpointTests : Void::Testing::Suite<CheckpointTests> {
|
||||
[[= Void::Testing::tag("production-id")]] Test test_authentic_v1_import_and_authenticated_schema_body_pairing();
|
||||
[[= Void::Testing::tag("checkpoint")]] Test test_round_trip_preserves_identity_and_legacy_world_bytes();
|
||||
[[= Void::Testing::tag("checkpoint")]] Test test_mid_carry_round_trip_continues_the_same_world();
|
||||
[[= Void::Testing::tag("checkpoint")]] Test test_selected_rules_survive_catalog_reordering();
|
||||
@@ -123,6 +167,35 @@ struct [[= Void::Testing::name("CheckpointTests")]] CheckpointTests : Void::Test
|
||||
[[= Void::Testing::tag("checkpoint")]] Test test_world_body_larger_than_one_shot_hash_limit();
|
||||
};
|
||||
|
||||
Test CheckpointTests::test_authentic_v1_import_and_authenticated_schema_body_pairing() {
|
||||
const auto catalog = checked(builtin_rule_packages());
|
||||
const auto rules = checked(default_rules_manifest());
|
||||
for (std::size_t variant = 0; variant < 3; ++variant) {
|
||||
auto imported = decoded(old_checkpoint(variant), catalog);
|
||||
require(imported.world_id == world_id && imported.city == 7 && imported.rules == rules &&
|
||||
imported.world->production_orders().size() == 1 && imported.world->production_orders().front().id == 1,
|
||||
"authentic schema-1 checkpoint did not import its legacy body");
|
||||
imported.world->queue_production({2, 2}, RecipeId::SawPlank);
|
||||
require(imported.world->production_orders().back().id == 2, "legacy import did not set its next production ID");
|
||||
}
|
||||
auto imported = decoded(old_checkpoint(0), catalog);
|
||||
auto current = encoded(*imported.world, rules);
|
||||
require(static_cast<unsigned char>(current[8]) == 2 &&
|
||||
static_cast<unsigned char>(current[layout(current).body_begin + 8]) == 14,
|
||||
"new checkpoint lacks the current schema/body pair");
|
||||
auto false_legacy = current;
|
||||
change(false_legacy, 8, std::uint32_t{1}); rehash(false_legacy);
|
||||
rejected(false_legacy, catalog, CheckpointError::InvalidWorld, "world.version");
|
||||
auto false_current = old_checkpoint(0);
|
||||
change(false_current, 8, std::uint32_t{2}); rehash(false_current);
|
||||
rejected(false_current, catalog, CheckpointError::InvalidWorld, "world.version");
|
||||
for (std::size_t variant : {1U, 2U}) {
|
||||
auto wrong = old_checkpoint(variant); // Inner FNV and outer SHA are both valid.
|
||||
change(wrong, 8, std::uint32_t{2}); rehash(wrong);
|
||||
rejected(wrong, catalog, CheckpointError::InvalidWorld, "world.version");
|
||||
}
|
||||
}
|
||||
|
||||
Test CheckpointTests::test_round_trip_preserves_identity_and_legacy_world_bytes() {
|
||||
const auto catalog = checked(builtin_rule_packages());
|
||||
const auto rules = checked(default_rules_manifest());
|
||||
@@ -137,8 +210,10 @@ Test CheckpointTests::test_round_trip_preserves_identity_and_legacy_world_bytes(
|
||||
"checkpoint lost stable world identity, city or rules");
|
||||
require(saved_state(*restored.world) == before && saved_state(world) == before,
|
||||
"checkpoint changed the original or restored canonical state");
|
||||
require(bytes.substr(layout(bytes).body_begin, before.size()) == before,
|
||||
"checkpoint did not use the existing world serialization");
|
||||
std::ostringstream modern(std::ios::binary);
|
||||
world.write_save(modern, WorldSaveFormat::Current14);
|
||||
require(bytes.substr(layout(bytes).body_begin, modern.str().size()) == modern.str(),
|
||||
"checkpoint did not use the current world serialization");
|
||||
require(before.substr(0, 8) == "SETTLERS" && static_cast<unsigned char>(before[8]) == 13,
|
||||
"canonical serialization version changed");
|
||||
require(encoded(*restored.world, restored.rules) == bytes, "re-encoding changed the checkpoint frame");
|
||||
|
||||
+14
-13
@@ -242,7 +242,7 @@ Test CoreTests::test_production_reservations_and_construction() {
|
||||
world.storages()[1].item_count(ItemType::StoneBlock) == 2,
|
||||
"materials left a store before the builder reached it");
|
||||
for (const auto& agent : world.agents()) {
|
||||
if (agent.production_index != 0) continue;
|
||||
if (agent.production_id != orders[0].id) continue;
|
||||
require(agent.inventory.item_count(ItemType::Plank) == 3 &&
|
||||
agent.inventory.item_count(ItemType::StoneBlock) == 0,
|
||||
"the builder's bag does not match the first pickup");
|
||||
@@ -253,14 +253,14 @@ Test CoreTests::test_production_reservations_and_construction() {
|
||||
require(world.storages()[1].item_count(ItemType::StoneBlock) == 0,
|
||||
"the builder did not pick up the second shipment");
|
||||
for (const auto& agent : world.agents()) {
|
||||
if (agent.production_index != 0) continue;
|
||||
if (agent.production_id != orders[0].id) continue;
|
||||
require(agent.inventory.item_count(ItemType::Plank) == 3 &&
|
||||
agent.inventory.item_count(ItemType::StoneBlock) == 2,
|
||||
"the builder's bag does not match the complete haul");
|
||||
}
|
||||
}
|
||||
for (const auto& agent : world.agents()) {
|
||||
if (agent.production_index != 0 || agent.state != settlement::AgentState::Working) continue;
|
||||
if (agent.production_id != orders[0].id || agent.state != settlement::AgentState::Working) continue;
|
||||
require(agent.position == orders[0].position && orders[0].delivery_stops.empty(),
|
||||
"construction started before the builder reached the site with its materials");
|
||||
require(agent.inventory.empty(), "the builder retained the cargo after unloading");
|
||||
@@ -483,15 +483,16 @@ Test CoreTests::test_bed_parts_are_delivered_separately() {
|
||||
for (int tick = 0; tick < 250 && world->scenario_progress().assigned_beds < 2; ++tick) {
|
||||
world->step();
|
||||
for (const auto& agent : world->agents()) {
|
||||
if (agent.production_index == no_entity_index || agent.state != AgentState::Hauling) continue;
|
||||
const auto& order = world->production_orders()[agent.production_index];
|
||||
if (agent.production_id == 0 || agent.state != AgentState::Hauling) continue;
|
||||
const auto& order = *world->find_production(agent.production_id);
|
||||
const auto order_index = static_cast<std::size_t>(&order - world->production_orders().data());
|
||||
const auto expected = order.bed_stage == BedStage::Foundation
|
||||
? (order.position == wood_bed ? ItemType::Wood : ItemType::Stone) : ItemType::Cloth;
|
||||
require(agent.inventory.item_count(expected) == 1,
|
||||
"the resident did not carry the raw material required by this stage");
|
||||
const auto bit = 1U << static_cast<unsigned>(order.bed_stage);
|
||||
if ((seen[agent.production_index] & bit) == 0) {
|
||||
seen[agent.production_index] |= bit;
|
||||
if ((seen[order_index] & bit) == 0) {
|
||||
seen[order_index] |= bit;
|
||||
auto copy = save_roundtrip(*world);
|
||||
copy->step();
|
||||
}
|
||||
@@ -696,7 +697,7 @@ Test CoreTests::test_specialists_take_their_own_jobs_and_finish_prior_assignment
|
||||
for (std::size_t index = 0; index < 3; ++index) {
|
||||
require(world.agents()[index].resource_node_id == world.resource_nodes()[index].id, "a specialist chose the wrong resource");
|
||||
}
|
||||
require(world.agents()[3].production_index == 0 && world.agents()[3].resource_node_id == 0,
|
||||
require(world.agents()[3].production_id == world.production_orders().front().id && world.agents()[3].resource_node_id == 0,
|
||||
"the builder did not take the construction job");
|
||||
require(assign(miner, Profession::Woodcutter) == CommandStatus::Accepted &&
|
||||
world.agents()[2].resource_node_id == world.resource_nodes()[2].id,
|
||||
@@ -774,7 +775,7 @@ Test CoreTests::test_flax_and_loom_supply_a_bed_without_starting_cloth() {
|
||||
saved_flax_in_transit = true;
|
||||
}
|
||||
if (!saved_active_weaving && loom_order.recipe == RecipeId::WeaveCloth && loom_order.state == JobState::InProgress) {
|
||||
require(world.agents()[1].production_index == 0 &&
|
||||
require(world.agents()[1].production_id == world.production_orders().front().id &&
|
||||
world.object_status(moved_loom, true) == CommandStatus::Busy,
|
||||
"the loom was assigned to the wrong worker or could move while active");
|
||||
restored = save_roundtrip(world);
|
||||
@@ -1126,8 +1127,8 @@ Test CoreTests::test_carpenter_makes_furnishings_for_rooms() {
|
||||
world->step();
|
||||
const auto& maker = world->agents()[1];
|
||||
if (variant.item == ItemType::MiningRack && !saved_stone_stop &&
|
||||
maker.production_index != no_entity_index &&
|
||||
world->production_orders()[maker.production_index].recipe == variant.craft &&
|
||||
maker.production_id != 0 &&
|
||||
world->find_production(maker.production_id)->recipe == variant.craft &&
|
||||
maker.inventory.item_count(ItemType::Stone) != 0 && maker.inventory.item_count(ItemType::Wood) == 0) {
|
||||
require(world->storages()[1].reserved_slots == 0, "output space was reserved before collecting wood");
|
||||
saved_stone_stop = true;
|
||||
@@ -1135,8 +1136,8 @@ Test CoreTests::test_carpenter_makes_furnishings_for_rooms() {
|
||||
continue;
|
||||
}
|
||||
if (!saved_workshop && maker.state == AgentState::Working && maker.position == workshop &&
|
||||
maker.production_index != no_entity_index &&
|
||||
world->production_orders()[maker.production_index].recipe == variant.craft) {
|
||||
maker.production_id != 0 &&
|
||||
world->find_production(maker.production_id)->recipe == variant.craft) {
|
||||
require(world->storages()[1].reserved_slots == 1, "output space was not reserved while crafting");
|
||||
saved_workshop = true;
|
||||
world = save_roundtrip(*world);
|
||||
|
||||
+102
-1
@@ -6,6 +6,9 @@
|
||||
|
||||
#include <atomic>
|
||||
#include <chrono>
|
||||
#include <array>
|
||||
#include <condition_variable>
|
||||
#include <mutex>
|
||||
#include <future>
|
||||
#include <memory>
|
||||
#include <sstream>
|
||||
@@ -82,6 +85,8 @@ void check_world_unwind(std::size_t phase, bool submit_failure) {
|
||||
}
|
||||
|
||||
struct [[= Void::Testing::name("ExecutorTests")]] ExecutorTests : Void::Testing::Suite<ExecutorTests> {
|
||||
[[= Void::Testing::tag("executor")]] Test test_completion_observer_results_and_failures();
|
||||
[[= Void::Testing::tag("executor")]] Test test_completion_observer_precedes_future_readiness();
|
||||
[[= Void::Testing::tag("executor")]] Test test_limits_and_nested_submission();
|
||||
[[= Void::Testing::tag("executor")]] Test test_capacity_retains_move_only_work_and_exceptions();
|
||||
[[= Void::Testing::tag("executor")]] Test test_failed_callable_transfer_releases_capacity();
|
||||
@@ -92,6 +97,102 @@ struct [[= Void::Testing::name("ExecutorTests")]] ExecutorTests : Void::Testing:
|
||||
[[= Void::Testing::tag("executor")]] Test test_world_capacity_one_matches_reference();
|
||||
};
|
||||
|
||||
// Exercise the same wrapper on a worker and on the submitting thread. Keeping
|
||||
// index zero admitted forces every other submission through inline overload.
|
||||
Test ExecutorTests::test_completion_observer_results_and_failures() {
|
||||
for (bool inline_work : {false, true}) {
|
||||
std::promise<void> release;
|
||||
auto permit = release.get_future().share();
|
||||
std::promise<void> entered;
|
||||
auto running = entered.get_future();
|
||||
std::array<std::atomic<int>, 8> observed{};
|
||||
std::array<std::atomic<bool>, 8> returned{};
|
||||
std::atomic<bool> observed_too_early{false};
|
||||
WorkerPoolOptions options{.max_admitted = inline_work ? 1U : 4096U};
|
||||
options.before_submit = [](std::size_t index) {
|
||||
if (index == 8) throw std::bad_alloc();
|
||||
};
|
||||
options.before_execute = [](std::size_t index) {
|
||||
if (index == 6) throw std::runtime_error("before invocation");
|
||||
};
|
||||
options.after_execute = [&](std::size_t index) {
|
||||
if (index >= observed.size()) throw std::logic_error("observer on failed submission");
|
||||
if (!returned[index].load()) observed_too_early.store(true);
|
||||
++observed[index];
|
||||
if (index == 7) throw std::runtime_error("after invocation");
|
||||
};
|
||||
WorkerPool pool(2, std::move(options));
|
||||
auto release_task = Void::Scope::on_exit([&] { release.set_value(); });
|
||||
auto held = pool.submit([&] {
|
||||
entered.set_value();
|
||||
if (permit.wait_for(5s) != std::future_status::ready) throw std::runtime_error("release timeout");
|
||||
returned[0] = true;
|
||||
});
|
||||
require(running.wait_for(5s) == std::future_status::ready);
|
||||
const auto caller = std::this_thread::get_id();
|
||||
auto value = pool.submit([&] {
|
||||
returned[1] = true;
|
||||
return std::pair{17, std::this_thread::get_id() == caller};
|
||||
});
|
||||
require(value.get() == std::pair{17, inline_work});
|
||||
int referent = 23;
|
||||
auto reference = pool.submit([&]() -> int& { returned[2] = true; return referent; });
|
||||
require(&reference.get() == &referent);
|
||||
auto nothing = pool.submit([&] { returned[3] = true; });
|
||||
nothing.get();
|
||||
auto owned = pool.submit([&, value = std::make_unique<int>(31)]() mutable {
|
||||
returned[4] = true;
|
||||
return std::move(value);
|
||||
});
|
||||
require(*owned.get() == 31);
|
||||
auto failure = pool.submit([]() -> int { throw std::runtime_error("invocation failed"); });
|
||||
expect_throw<std::runtime_error>([&] { static_cast<void>(failure.get()); });
|
||||
auto before = pool.submit([&] { returned[6] = true; });
|
||||
expect_throw<std::runtime_error>([&] { before.get(); });
|
||||
auto after = pool.submit([&] { returned[7] = true; });
|
||||
expect_throw<std::runtime_error>([&] { after.get(); });
|
||||
bool submitted_failure_ran = false;
|
||||
expect_throw<std::bad_alloc>([&] {
|
||||
static_cast<void>(pool.submit([&] { submitted_failure_ran = true; }));
|
||||
});
|
||||
require(!submitted_failure_ran);
|
||||
release_task.release();
|
||||
release.set_value();
|
||||
held.get();
|
||||
for (std::size_t i = 0; i < observed.size(); ++i) {
|
||||
require(observed[i] == ((i == 5 || i == 6) ? 0 : 1));
|
||||
}
|
||||
require(!returned[6] && !observed_too_early);
|
||||
}
|
||||
}
|
||||
|
||||
Test ExecutorTests::test_completion_observer_precedes_future_readiness() {
|
||||
std::promise<void> observed;
|
||||
auto entered = observed.get_future();
|
||||
std::promise<void> release;
|
||||
auto permit = release.get_future().share();
|
||||
std::atomic<int> calls{0};
|
||||
WorkerPoolOptions options;
|
||||
// Observer alone must enable monotonically increasing submission indices.
|
||||
options.after_execute = [&](std::size_t index) {
|
||||
if (index != static_cast<std::size_t>(calls.fetch_add(1))) throw std::runtime_error("bad index");
|
||||
if (index == 0) {
|
||||
observed.set_value();
|
||||
if (permit.wait_for(5s) != std::future_status::ready) throw std::runtime_error("release timeout");
|
||||
}
|
||||
};
|
||||
WorkerPool pool(2, std::move(options));
|
||||
auto release_task = Void::Scope::on_exit([&] { release.set_value(); });
|
||||
auto result = pool.submit([] { return 11; });
|
||||
require(entered.wait_for(5s) == std::future_status::ready);
|
||||
require(result.wait_for(0s) == std::future_status::timeout);
|
||||
release_task.release();
|
||||
release.set_value();
|
||||
require(result.get() == 11);
|
||||
pool.submit([] {}).get();
|
||||
require(calls == 2);
|
||||
}
|
||||
|
||||
Test ExecutorTests::test_limits_and_nested_submission() {
|
||||
expect_throw<std::invalid_argument>([] { WorkerPool pool(1); });
|
||||
expect_throw<std::invalid_argument>([] { WorkerPool pool(2, {.max_admitted = 0}); });
|
||||
@@ -118,7 +219,7 @@ Test ExecutorTests::test_capacity_retains_move_only_work_and_exceptions() {
|
||||
const auto coordinator = std::this_thread::get_id();
|
||||
std::atomic<int> executions{0};
|
||||
auto answer = pool.submit([value = std::make_unique<int>(17), coordinator, &executions] {
|
||||
require(std::this_thread::get_id() == coordinator);
|
||||
if (std::this_thread::get_id() != coordinator) throw std::runtime_error("expected inline work");
|
||||
++executions;
|
||||
return *value;
|
||||
});
|
||||
|
||||
@@ -1,14 +1,26 @@
|
||||
#define NOMINMAX
|
||||
#include <winsock2.h>
|
||||
#include <ws2tcpip.h>
|
||||
|
||||
#include "lan_session.hpp"
|
||||
#include "lan_wire.hpp"
|
||||
#include "settlement/core/simulation_runtime.hpp"
|
||||
|
||||
#include <Void/Core/Scope.hpp>
|
||||
#include <Void/Testing/Assert.hpp>
|
||||
#include <Void/Testing/Suite.hpp>
|
||||
|
||||
#include <chrono>
|
||||
#include <condition_variable>
|
||||
#include <future>
|
||||
#include <mutex>
|
||||
#include <spanstream>
|
||||
#include <sstream>
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <thread>
|
||||
#include <vector>
|
||||
|
||||
namespace {
|
||||
|
||||
@@ -29,11 +41,128 @@ constexpr auto command_bytes = "\x23\x00\x00\x00\x03"
|
||||
constexpr auto receipt_bytes = "\x0a\x00\x00\x00\x04\x04\x10\x32\x54\x76\x98\xba\xdc\xfe"sv;
|
||||
constexpr auto ping_bytes = "\x01\x00\x00\x00\x06"sv;
|
||||
|
||||
WorldCheckpoint colony_checkpoint() {
|
||||
auto identity = Void::Uuid::try_v4();
|
||||
auto rules = default_rules_manifest();
|
||||
require(identity.has_value() && rules.has_value());
|
||||
return {make_first_colony(2), *identity, 1, std::move(*rules)};
|
||||
}
|
||||
|
||||
template<class Pump, class Condition>
|
||||
void pump_until(Pump pump, Condition condition, const char* message) {
|
||||
const auto deadline = std::chrono::steady_clock::now() + 3s;
|
||||
do {
|
||||
pump();
|
||||
if (condition()) return;
|
||||
std::this_thread::sleep_for(1ms);
|
||||
} while (std::chrono::steady_clock::now() < deadline);
|
||||
throw std::runtime_error(message);
|
||||
}
|
||||
|
||||
struct CaptureGate {
|
||||
std::mutex mutex;
|
||||
std::condition_variable changed;
|
||||
bool armed = false;
|
||||
bool entered = false;
|
||||
bool released = false;
|
||||
|
||||
void capture(RuntimePhase phase) {
|
||||
if (phase != RuntimePhase::BeforeCapture) return;
|
||||
std::unique_lock lock(mutex);
|
||||
if (!armed) return;
|
||||
entered = true;
|
||||
changed.notify_all();
|
||||
if (!changed.wait_for(lock, 5s, [&] { return released; })) {
|
||||
throw std::runtime_error("LAN test capture gate timed out.");
|
||||
}
|
||||
}
|
||||
|
||||
void arm() { std::lock_guard lock(mutex); armed = true; }
|
||||
bool waiting() { std::lock_guard lock(mutex); return entered; }
|
||||
void release() {
|
||||
std::lock_guard lock(mutex);
|
||||
released = true;
|
||||
changed.notify_all();
|
||||
}
|
||||
};
|
||||
|
||||
struct RawGuest {
|
||||
SOCKET socket = INVALID_SOCKET;
|
||||
std::string input;
|
||||
std::string output;
|
||||
bool closed = false;
|
||||
std::vector<lan_wire::Receipt> receipts;
|
||||
std::unique_ptr<World> snapshot;
|
||||
|
||||
RawGuest(std::uint16_t port, std::uint64_t key) {
|
||||
socket = ::socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
|
||||
if (socket == INVALID_SOCKET) throw std::runtime_error("Raw guest socket failed.");
|
||||
auto close_on_error = Void::Scope::on_exit([&] { closesocket(socket); });
|
||||
sockaddr_in remote{};
|
||||
remote.sin_family = AF_INET;
|
||||
remote.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
|
||||
remote.sin_port = htons(port);
|
||||
if (connect(socket, reinterpret_cast<const sockaddr*>(&remote), sizeof(remote)) != 0) {
|
||||
throw std::runtime_error("Raw guest connect failed.");
|
||||
}
|
||||
u_long enabled = 1;
|
||||
require(ioctlsocket(socket, static_cast<long>(FIONBIO), &enabled) == 0);
|
||||
const auto hello = lan_wire::encode_hello({lan_wire::protocol_version, key});
|
||||
lan_wire::append_frame(output, lan_wire::Message::Hello, std::string_view(hello));
|
||||
close_on_error.release();
|
||||
}
|
||||
~RawGuest() { closesocket(socket); }
|
||||
RawGuest(const RawGuest&) = delete;
|
||||
RawGuest& operator=(const RawGuest&) = delete;
|
||||
|
||||
void command(std::uint64_t sequence, CommandKind kind, GridPosition cell = {}, std::uint8_t value = 0) {
|
||||
const auto bytes = lan_wire::encode_command({2, sequence, kind, cell, value});
|
||||
lan_wire::append_frame(output, lan_wire::Message::Command, std::string_view(bytes));
|
||||
}
|
||||
|
||||
void poll() {
|
||||
if (closed) return;
|
||||
if (!output.empty()) {
|
||||
const auto sent = send(socket, output.data(), static_cast<int>(output.size()), 0);
|
||||
if (sent > 0) output.erase(0, static_cast<std::size_t>(sent));
|
||||
else if (sent == SOCKET_ERROR && WSAGetLastError() != WSAEWOULDBLOCK) closed = true;
|
||||
}
|
||||
std::array<char, 8192> bytes{};
|
||||
for (int attempt = 0; attempt < 16 && !closed; ++attempt) {
|
||||
const auto count = recv(socket, bytes.data(), static_cast<int>(bytes.size()), 0);
|
||||
if (count == SOCKET_ERROR) {
|
||||
if (WSAGetLastError() != WSAEWOULDBLOCK) closed = true;
|
||||
break;
|
||||
}
|
||||
if (count == 0) { closed = true; break; }
|
||||
input.append(bytes.data(), static_cast<std::size_t>(count));
|
||||
std::size_t consumed = 0;
|
||||
while (const auto frame = lan_wire::next_frame(std::string_view(input).substr(consumed))) {
|
||||
if (frame->message == lan_wire::Message::Receipt) {
|
||||
auto receipt = lan_wire::decode_receipt(frame->payload);
|
||||
require(receipt.has_value());
|
||||
receipts.push_back(*receipt);
|
||||
} else if (frame->message == lan_wire::Message::Snapshot) {
|
||||
std::ispanstream stream(frame->payload);
|
||||
snapshot = World::read_save(stream);
|
||||
}
|
||||
consumed += frame->size;
|
||||
}
|
||||
input.erase(0, consumed);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
struct LanTests : Void::Testing::Suite<LanTests> {
|
||||
[[= Void::Testing::tag("wire")]] Test test_protocol_11_fixed_messages();
|
||||
[[= Void::Testing::tag("wire")]] Test test_fragmented_and_coalesced_frames();
|
||||
[[= Void::Testing::tag("wire")]] Test test_frame_size_limits();
|
||||
[[= Void::Testing::tag("lan")]] Test test_shared_colony_over_loopback();
|
||||
[[= Void::Testing::tag("lan-owner")]] Test test_runtime_host_receipts_and_corrected_legacy_sequence();
|
||||
[[= Void::Testing::tag("lan-owner")]] Test test_runtime_host_wrong_sequence_busy_and_pipelining();
|
||||
[[= Void::Testing::tag("lan-owner")]] Test test_runtime_host_retains_slot_work_across_reconnect();
|
||||
[[= Void::Testing::tag("lan-owner")]] Test test_runtime_host_reauthenticates_after_pending_rollback();
|
||||
[[= Void::Testing::tag("lan-owner")]] Test test_runtime_host_rejects_nondefault_rules_and_faults();
|
||||
};
|
||||
|
||||
Test LanTests::test_protocol_11_fixed_messages() {
|
||||
@@ -295,4 +424,197 @@ Test LanTests::test_shared_colony_over_loopback() {
|
||||
require(authoritative->production_orders().size() == previous_size + 10);
|
||||
}
|
||||
|
||||
Test LanTests::test_runtime_host_receipts_and_corrected_legacy_sequence() {
|
||||
SimulationRuntime runtime(colony_checkpoint(), {.ticking = false});
|
||||
LanSession host, guest;
|
||||
host.host(0, true);
|
||||
guest.join("127.0.0.1", host.join_code(), host.port());
|
||||
std::unique_ptr<World> view;
|
||||
const auto pump = [&] {
|
||||
host.poll_host(runtime);
|
||||
if (auto latest = guest.poll_guest()) view = std::move(latest);
|
||||
};
|
||||
pump_until(pump, [&] { return guest.state() == LanState::GuestConnected; }, "Runtime guest did not join.");
|
||||
require(view && view->tick() == 0);
|
||||
const auto resident = view->agents().back().id;
|
||||
require(guest.submit(CommandKind::AssignProfession, {}, static_cast<std::uint8_t>(Profession::Miner), {}, resident));
|
||||
std::optional<LanCommandResult> result;
|
||||
pump_until(pump, [&] { result = guest.take_result(); return result.has_value(); }, "Profession receipt missing.");
|
||||
require(result->status == CommandStatus::Accepted && result->kind == CommandKind::AssignProfession &&
|
||||
result->resident == resident && result->value == static_cast<std::uint8_t>(Profession::Miner));
|
||||
require(runtime.latest()->world->agents().back().profession == Profession::Miner);
|
||||
|
||||
require(guest.submit(CommandKind::PlaceBed, {16, 18}, static_cast<std::uint8_t>(BedBase::Stone)));
|
||||
pump_until(pump, [&] { result = guest.take_result(); return result.has_value(); }, "Bed receipt missing.");
|
||||
require(result->status == CommandStatus::Accepted && result->cell == GridPosition{16, 18});
|
||||
require(guest.submit(CommandKind::PlaceBed, {16, 18}, 0));
|
||||
require(guest.submit(CommandKind::SetForaging, {14, 12}, 1));
|
||||
pump_until(pump, [&] { return guest.take_rejection().has_value(); }, "Bed rejection missing.");
|
||||
// The failed result remains undrained. The queued correction cannot execute.
|
||||
for (int attempt = 0; attempt < 20; ++attempt) pump();
|
||||
require(runtime.latest()->next_requests[1] == 4);
|
||||
result = guest.take_result();
|
||||
require(result && result->status == CommandStatus::InvalidTarget && result->kind == CommandKind::PlaceBed &&
|
||||
result->cell == GridPosition{16, 18} && result->destination == GridPosition{} && result->value == 0);
|
||||
pump_until(pump, [&] { result = guest.take_result(); return result.has_value(); }, "Corrected command receipt missing.");
|
||||
require(result->status == CommandStatus::Accepted && result->kind == CommandKind::SetForaging);
|
||||
require(runtime.latest()->next_requests[1] == 5 && runtime.latest()->world->next_command_sequence(2) == 4);
|
||||
require(runtime.latest()->world->production_orders().size() == 1);
|
||||
pump_until(pump, [&] { return view->next_command_sequence(2) == 4; }, "Same-tick snapshot missing.");
|
||||
require(view->tick() == 0);
|
||||
guest.leave();
|
||||
require(!guest.take_result());
|
||||
}
|
||||
|
||||
Test LanTests::test_runtime_host_wrong_sequence_busy_and_pipelining() {
|
||||
CaptureGate gate;
|
||||
RuntimeOptions options{.capacity = 1, .ticking = false};
|
||||
options.observer = [&](RuntimePhase phase) { gate.capture(phase); };
|
||||
SimulationRuntime runtime(colony_checkpoint(), options);
|
||||
auto release = Void::Scope::on_exit([&] { gate.release(); });
|
||||
LanSession host;
|
||||
host.host(0, true);
|
||||
RawGuest guest(host.port(), std::stoull(host.join_code(), nullptr, 16));
|
||||
const auto pump = [&] { host.poll_host(runtime); guest.poll(); };
|
||||
pump_until(pump, [&] { return guest.snapshot != nullptr; }, "Raw runtime guest did not join.");
|
||||
guest.command(99, CommandKind::SetForaging, {14, 12}, 1);
|
||||
pump_until(pump, [&] { return guest.receipts.size() == 1; }, "Wrong-sequence receipt missing.");
|
||||
require(guest.receipts[0].status == CommandStatus::WrongSequence && guest.receipts[0].next_sequence == 1);
|
||||
const auto snapshot = runtime.latest();
|
||||
gate.arm();
|
||||
const auto& id = snapshot->identity;
|
||||
auto local = runtime.try_submit({1}, {command_envelope_version, id.world, id.session, id.city, 1,
|
||||
CommandPayload{CommandKind::SetForaging, {13, 14}, 1}});
|
||||
require(local.admission == RuntimeAdmission::Accepted);
|
||||
pump_until(pump, [&] { return gate.waiting(); }, "Owner did not reach blocked capture.");
|
||||
guest.command(1, CommandKind::SetForaging, {14, 12}, 1);
|
||||
pump_until(pump, [&] { return guest.receipts.size() == 2; }, "Busy receipt missing.");
|
||||
require(guest.receipts[1].status == CommandStatus::Busy && guest.receipts[1].next_sequence == 1);
|
||||
require(runtime.latest()->next_requests[1] == 1);
|
||||
gate.release();
|
||||
require(local.completion.wait_for(3s) == std::future_status::ready);
|
||||
require(local.completion.get().receipt->command_status == CommandStatus::Accepted);
|
||||
|
||||
// Two coalesced commands cannot turn one guest slot into multiple in-flight operations.
|
||||
guest.command(1, CommandKind::SetForaging, {14, 12}, 1);
|
||||
guest.command(2, CommandKind::SetForaging, {18, 12}, 1);
|
||||
pump_until(pump, [&] { return guest.closed; }, "Pipelined guest was not bounded.");
|
||||
RuntimeSubmission fence{RuntimeAdmission::Busy, {}};
|
||||
pump_until(pump, [&] {
|
||||
fence = runtime.synchronize();
|
||||
return fence.admission == RuntimeAdmission::Accepted;
|
||||
}, "Owner did not release its admission slot.");
|
||||
require(fence.completion.wait_for(3s) == std::future_status::ready);
|
||||
require(fence.completion.get().outcome == RuntimeOutcome::Completed);
|
||||
require(runtime.latest()->next_requests[1] == 2 && runtime.latest()->world->next_command_sequence(2) == 2);
|
||||
}
|
||||
|
||||
Test LanTests::test_runtime_host_retains_slot_work_across_reconnect() {
|
||||
CaptureGate gate;
|
||||
RuntimeOptions options{.ticking = false};
|
||||
options.observer = [&](RuntimePhase phase) { gate.capture(phase); };
|
||||
SimulationRuntime runtime(colony_checkpoint(), options);
|
||||
auto release = Void::Scope::on_exit([&] { gate.release(); });
|
||||
LanSession host, first, next;
|
||||
host.host(0, true);
|
||||
const auto code = host.join_code();
|
||||
const auto pump = [&] {
|
||||
host.poll_host(runtime);
|
||||
static_cast<void>(first.poll_guest());
|
||||
static_cast<void>(next.poll_guest());
|
||||
};
|
||||
first.join("127.0.0.1", code, host.port());
|
||||
pump_until(pump, [&] { return first.state() == LanState::GuestConnected; }, "First guest did not join.");
|
||||
gate.arm();
|
||||
require(first.submit(CommandKind::PlaceBed, {16, 18}, 1));
|
||||
pump_until(pump, [&] { return gate.waiting(); }, "Guest command did not reach blocked owner.");
|
||||
require(runtime.latest()->world->production_orders().empty());
|
||||
first.leave();
|
||||
pump_until(pump, [&] { return host.state() == LanState::Hosting; }, "Old socket did not close.");
|
||||
next.join("127.0.0.1", code, host.port());
|
||||
for (int attempt = 0; attempt < 20; ++attempt) pump();
|
||||
require(next.state() == LanState::Connecting && !next.take_result());
|
||||
gate.release();
|
||||
pump_until(pump, [&] { return next.state() == LanState::GuestConnected; }, "Reconnected guest did not join.");
|
||||
require(!next.take_result());
|
||||
require(runtime.latest()->world->production_orders().size() == 1);
|
||||
require(runtime.latest()->next_requests[1] == 2);
|
||||
require(next.submit(CommandKind::SetForaging, {14, 12}, 1));
|
||||
std::optional<LanCommandResult> result;
|
||||
pump_until(pump, [&] { result = next.take_result(); return result.has_value(); }, "New guest receipt missing.");
|
||||
require(result->status == CommandStatus::Accepted && result->kind == CommandKind::SetForaging);
|
||||
require(runtime.latest()->next_requests[1] == 3 && runtime.latest()->world->next_command_sequence(2) == 3);
|
||||
}
|
||||
|
||||
Test LanTests::test_runtime_host_reauthenticates_after_pending_rollback() {
|
||||
CaptureGate gate;
|
||||
RuntimeOptions options{.ticking = false};
|
||||
options.observer = [&](RuntimePhase phase) { gate.capture(phase); };
|
||||
auto initial = colony_checkpoint();
|
||||
const auto world_id = initial.world_id;
|
||||
SimulationRuntime runtime(std::move(initial), options);
|
||||
auto release = Void::Scope::on_exit([&] { gate.release(); });
|
||||
LanSession host, guest;
|
||||
host.host(0, true);
|
||||
guest.join("127.0.0.1", host.join_code(), host.port());
|
||||
const auto pump = [&] { host.poll_host(runtime); static_cast<void>(guest.poll_guest()); };
|
||||
pump_until(pump, [&] { return guest.state() == LanState::GuestConnected; }, "Rollback guest did not join.");
|
||||
const auto old_session = runtime.latest()->identity.session;
|
||||
gate.arm();
|
||||
require(guest.submit(CommandKind::PlaceBed, {16, 18}, 1));
|
||||
pump_until(pump, [&] { return gate.waiting(); }, "Rollback guest command did not block.");
|
||||
auto ticket = runtime.begin_load();
|
||||
require(ticket.has_value());
|
||||
auto rollback = colony_checkpoint();
|
||||
rollback.world_id = world_id;
|
||||
auto installed = runtime.try_install(*ticket, rollback);
|
||||
require(installed.admission == RuntimeAdmission::Accepted);
|
||||
gate.release();
|
||||
require(installed.completion.wait_for(3s) == std::future_status::ready);
|
||||
require(installed.completion.get().outcome == RuntimeOutcome::Completed);
|
||||
pump_until(pump, [&] { return guest.state() == LanState::GuestDisconnected; }, "Old epoch peer stayed connected.");
|
||||
require(runtime.latest()->identity.session != old_session && runtime.latest()->identity.world == world_id);
|
||||
require(runtime.latest()->world->production_orders().empty() && !guest.take_result());
|
||||
guest.reconnect();
|
||||
pump_until(pump, [&] { return guest.state() == LanState::GuestConnected; }, "Guest could not reauthenticate.");
|
||||
require(guest.submit(CommandKind::PlaceBed, {16, 18}, 1));
|
||||
std::optional<LanCommandResult> result;
|
||||
pump_until(pump, [&] { result = guest.take_result(); return result.has_value(); }, "New epoch receipt missing.");
|
||||
require(result->status == CommandStatus::Accepted && runtime.latest()->next_requests[1] == 2);
|
||||
}
|
||||
|
||||
Test LanTests::test_runtime_host_rejects_nondefault_rules_and_faults() {
|
||||
auto initial = colony_checkpoint();
|
||||
auto packages = builtin_rule_packages();
|
||||
require(packages.has_value());
|
||||
const std::array selected{std::string{"settlement.core"}};
|
||||
auto rules = resolve_rules(*packages, selected);
|
||||
require(rules.has_value());
|
||||
initial.rules = std::move(*rules);
|
||||
SimulationRuntime incompatible(std::move(initial), {.ticking = false});
|
||||
LanSession host, guest;
|
||||
host.host(0, true);
|
||||
guest.join("127.0.0.1", host.join_code(), host.port());
|
||||
host.poll_host(incompatible);
|
||||
require(host.state() == LanState::Hosting && host.detail().find("default rules") != std::string::npos);
|
||||
for (int attempt = 0; attempt < 20; ++attempt) {
|
||||
host.poll_host(incompatible);
|
||||
require(!guest.poll_guest());
|
||||
}
|
||||
require(guest.state() != LanState::GuestConnected);
|
||||
guest.leave();
|
||||
RuntimeOptions options{.ticking = false};
|
||||
options.observer = [](RuntimePhase phase) {
|
||||
if (phase == RuntimePhase::BeforeCapture) throw std::runtime_error("Injected capture failure.");
|
||||
};
|
||||
SimulationRuntime faulting(colony_checkpoint(), options);
|
||||
guest.join("127.0.0.1", host.join_code(), host.port());
|
||||
const auto pump = [&] { host.poll_host(faulting); static_cast<void>(guest.poll_guest()); };
|
||||
pump_until(pump, [&] { return guest.state() == LanState::GuestConnected; }, "Fault guest did not join.");
|
||||
require(guest.submit(CommandKind::PlaceBed, {16, 18}, 1));
|
||||
pump_until(pump, [&] { return guest.state() == LanState::GuestDisconnected; }, "Faulted peer stayed connected.");
|
||||
require(faulting.view().state == RuntimeState::Faulted && faulting.latest()->world->production_orders().empty());
|
||||
require(!guest.take_result());
|
||||
}
|
||||
|
||||
} // namespace
|
||||
@@ -0,0 +1,352 @@
|
||||
#include "settlement/core/checkpoint.hpp"
|
||||
#include "settlement/core/simulation_runtime.hpp"
|
||||
|
||||
#include <Void/Binary/Reader.hpp>
|
||||
#include <Void/Binary/Writer.hpp>
|
||||
#include <Void/Testing/Suite.hpp>
|
||||
|
||||
#include <algorithm>
|
||||
#include <array>
|
||||
#include <limits>
|
||||
#include <sstream>
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace {
|
||||
using namespace settlement;
|
||||
using Void::Testing::Test;
|
||||
constexpr auto terminal = std::numeric_limits<ProductionId>::max();
|
||||
constexpr std::size_t next_production_offset = 101;
|
||||
constexpr Void::Uuid::Uuid world_id{{0x91, 2, 3, 4, 5, 6, 0x47, 8, 0x89, 10, 11, 12, 13, 14, 15, 16}};
|
||||
|
||||
void require(bool condition, const char* message = "production identity invariant failed") {
|
||||
if (!condition) throw std::runtime_error(message);
|
||||
}
|
||||
std::string bytes(const World& world, WorldSaveFormat format = WorldSaveFormat::Current14) {
|
||||
std::ostringstream stream(std::ios::binary);
|
||||
world.write_save(stream, format);
|
||||
return stream.str();
|
||||
}
|
||||
std::unique_ptr<World> restore(const std::string& data, std::size_t workers = 1) {
|
||||
std::istringstream input(data, std::ios::binary);
|
||||
return World::read_save(input, workers, workers == 1 ? ExecutionMode::SerialReference : ExecutionMode::Parallel);
|
||||
}
|
||||
template<class T>
|
||||
void put(std::string& data, std::size_t offset, T value) {
|
||||
Void::Binary::Writer writer(std::as_writable_bytes(std::span{data.data(), data.size()}).subspan(offset));
|
||||
require(writer.writeLittle(value).has_value(), "fixture write failed");
|
||||
}
|
||||
std::unique_ptr<World> with_next(const World& world, ProductionId next) {
|
||||
auto data = bytes(world);
|
||||
put(data, next_production_offset, next);
|
||||
return restore(data);
|
||||
}
|
||||
std::unique_ptr<World> checkpoint(const World& world, std::size_t workers = 1) {
|
||||
const auto rules = default_rules_manifest();
|
||||
const auto catalog = builtin_rule_packages();
|
||||
require(rules.has_value() && catalog.has_value());
|
||||
const auto encoded = encode_checkpoint(world, world_id, 7, *rules);
|
||||
require(encoded.has_value());
|
||||
auto decoded = decode_checkpoint(*encoded, *catalog, workers,
|
||||
workers == 1 ? ExecutionMode::SerialReference : ExecutionMode::Parallel);
|
||||
require(decoded.has_value() && decoded->world_id == world_id && bytes(*decoded->world) == bytes(world),
|
||||
"modern checkpoint changed stable identity or high-water state");
|
||||
return std::move(decoded->world);
|
||||
}
|
||||
CommandStatus command(World& world, CommandKind kind, GridPosition cell = {}, std::uint8_t value = 0,
|
||||
GridPosition destination = {}) {
|
||||
return world.apply_command({1, world.next_command_sequence(1), kind, cell, value, destination}).status;
|
||||
}
|
||||
std::unique_ptr<World> scenario(bool legacy_beds = false) {
|
||||
auto world = std::make_unique<World>(43, 24, 24, 1, ExecutionMode::SerialReference);
|
||||
world->start_scenario({2, 2});
|
||||
if (legacy_beds) {
|
||||
auto data = bytes(*world);
|
||||
data.back() = 0; // Historical scenario without staged beds.
|
||||
world = restore(data);
|
||||
}
|
||||
return world;
|
||||
}
|
||||
|
||||
// Parse only field boundaries, using the public version-14 wire layout. This
|
||||
// avoids relying on C++ object layout when attacking references/counters.
|
||||
struct Locations { std::vector<std::size_t> orders; std::vector<std::size_t> links; };
|
||||
Locations locations(const std::string& data) {
|
||||
Void::Binary::Reader reader(std::as_bytes(std::span{data.data(), data.size()}));
|
||||
const auto skip = [&](std::size_t n) { require(reader.skip(n).has_value()); };
|
||||
const auto count = [&] { return reader.readLittle<std::uint32_t>().value(); };
|
||||
const auto route = [&] { const auto n = count(); skip(static_cast<std::size_t>(n) * 8); };
|
||||
skip(20);
|
||||
const auto width = count(), height = count();
|
||||
skip(81 + static_cast<std::size_t>(width) * height);
|
||||
Locations found;
|
||||
const auto agents = count();
|
||||
for (std::uint32_t i = 0; i < agents; ++i) {
|
||||
skip(25); route(); skip(28 + item_type_count * 4); route();
|
||||
found.links.push_back(reader.position()); skip(14);
|
||||
}
|
||||
const auto jobs = count(); skip(static_cast<std::size_t>(jobs) * 25);
|
||||
const auto nodes = count(); skip(static_cast<std::size_t>(nodes) * 39);
|
||||
const auto stores = count();
|
||||
for (std::uint32_t i = 0; i < stores; ++i) { skip(25); const auto stacks = count(); skip(stacks * 9U); }
|
||||
const auto orders = count();
|
||||
for (std::uint32_t i = 0; i < orders; ++i) {
|
||||
found.orders.push_back(reader.position()); skip(18);
|
||||
const auto materials = count(); skip(materials * 13U);
|
||||
const auto stops = count();
|
||||
for (std::uint32_t j = 0; j < stops; ++j) { skip(8); route(); }
|
||||
skip(18);
|
||||
}
|
||||
return found;
|
||||
}
|
||||
void rejected(const std::string& data) {
|
||||
bool failed = false;
|
||||
try { static_cast<void>(restore(data)); } catch (const std::runtime_error&) { failed = true; }
|
||||
require(failed, "corrupt stable production state was accepted");
|
||||
}
|
||||
|
||||
struct [[= Void::Testing::name("ProductionIdentityTests")]] ProductionIdentityTests
|
||||
: Void::Testing::Suite<ProductionIdentityTests> {
|
||||
[[= Void::Testing::tag("production-id")]] Test active_delivery_survives_lower_deletion_and_modern_replay();
|
||||
[[= Void::Testing::tag("production-id")]] Test highest_and_all_deletions_preserve_high_water();
|
||||
[[= Void::Testing::tag("production-id")]] Test last_single_id_and_complete_command_batches();
|
||||
[[= Void::Testing::tag("production-id")]] Test demolition_preflights_every_product_before_losing_stock();
|
||||
[[= Void::Testing::tag("production-id")]] Test demolition_counts_existing_supply_and_pending_crafts_exactly();
|
||||
[[= Void::Testing::tag("production-id")]] Test legacy_cabin_exhaustion_is_a_repeatable_healthy_runtime_result();
|
||||
[[= Void::Testing::tag("production-id")]] Test malformed_ids_and_references_fail_before_dereference();
|
||||
[[= Void::Testing::tag("production-id")]] Test legacy_projection_imports_deterministic_dense_ids();
|
||||
};
|
||||
|
||||
Test ProductionIdentityTests::active_delivery_survives_lower_deletion_and_modern_replay() {
|
||||
World world(42, 32, 32, 1, ExecutionMode::SerialReference);
|
||||
const auto store = world.add_storage({3, 3}, 20);
|
||||
world.stock_storage(store, ItemType::Plank, 3);
|
||||
world.stock_storage(store, ItemType::StoneBlock, 2);
|
||||
static_cast<void>(world.spawn_agent({2, 3}));
|
||||
world.queue_production({20, 20}, RecipeId::BuildMedicineCabinet); // No wood: remains available.
|
||||
world.queue_production({14, 3}, RecipeId::BuildCabin);
|
||||
const auto lower = world.production_orders().front().id;
|
||||
const auto active = world.production_orders().back().id;
|
||||
for (int tick = 0; tick < 30 && world.agents().front().inventory.empty(); ++tick) world.step();
|
||||
require(world.agents().front().production_id == active && !world.agents().front().inventory.empty(),
|
||||
"fixture must exercise actual mid-delivery cargo");
|
||||
require(command(world, CommandKind::DemolishObject, {20, 20}) == CommandStatus::Accepted);
|
||||
require(world.find_production(lower) == nullptr && world.find_production(0) == nullptr &&
|
||||
world.find_production(terminal) == nullptr && world.agents().front().production_id == active);
|
||||
const auto legacy_bytes = bytes(world, WorldSaveFormat::Legacy13);
|
||||
const auto legacy = restore(legacy_bytes);
|
||||
require(legacy->agents().front().production_id == legacy->production_orders().front().id &&
|
||||
bytes(*legacy, WorldSaveFormat::Legacy13) == legacy_bytes,
|
||||
"legacy positional projection changed a live delivery after lower deletion");
|
||||
const auto held = world.capture();
|
||||
const auto frozen = bytes(*held);
|
||||
std::vector<std::unique_ptr<World>> copies;
|
||||
for (auto workers : {1U, 2U, 6U, 12U}) copies.push_back(checkpoint(world, workers));
|
||||
for (int tick = 0; tick < 70; ++tick) {
|
||||
world.step();
|
||||
for (auto& copy : copies) {
|
||||
copy->step();
|
||||
require(bytes(*copy) == bytes(world), "modern canonical tick replay diverged across worker counts");
|
||||
}
|
||||
require(bytes(*held) == frozen, "capture did not retain production state independently");
|
||||
}
|
||||
require(world.find_production(active)->state == JobState::Completed);
|
||||
require(command(world, CommandKind::DemolishObject, {14, 3}) == CommandStatus::Accepted);
|
||||
auto empty = checkpoint(world);
|
||||
empty->queue_production({15, 3}, RecipeId::BuildCabin);
|
||||
require(empty->production_orders().front().id > active, "deleting all orders reissued an identity");
|
||||
}
|
||||
|
||||
Test ProductionIdentityTests::highest_and_all_deletions_preserve_high_water() {
|
||||
auto world = scenario();
|
||||
world->queue_production({6, 6}, RecipeId::BuildMedicineCabinet);
|
||||
world->queue_production({7, 6}, RecipeId::BuildMedicineCabinet);
|
||||
const auto highest = world->production_orders().back().id;
|
||||
require(command(*world, CommandKind::DemolishObject, {7, 6}) == CommandStatus::Accepted);
|
||||
world = checkpoint(*world);
|
||||
world->queue_production({8, 6}, RecipeId::BuildMedicineCabinet);
|
||||
require(world->production_orders().back().id == highest + 1);
|
||||
require(command(*world, CommandKind::DemolishObject, {6, 6}) == CommandStatus::Accepted);
|
||||
require(command(*world, CommandKind::DemolishObject, {8, 6}) == CommandStatus::Accepted);
|
||||
world = checkpoint(*world);
|
||||
world->queue_production({9, 6}, RecipeId::BuildMedicineCabinet);
|
||||
require(world->production_orders().front().id == highest + 2);
|
||||
}
|
||||
|
||||
Test ProductionIdentityTests::last_single_id_and_complete_command_batches() {
|
||||
World basic(42, 24, 24, 1, ExecutionMode::SerialReference);
|
||||
auto single = with_next(basic, terminal - 1);
|
||||
single->queue_production({6, 6}, RecipeId::BuildCabin);
|
||||
require(single->production_orders().back().id == terminal - 1);
|
||||
single = checkpoint(*single);
|
||||
const auto before = bytes(*single);
|
||||
bool exhausted = false;
|
||||
try { single->queue_production({7, 6}, RecipeId::BuildCabin); }
|
||||
catch (const ProductionCapacityError&) { exhausted = true; }
|
||||
require(exhausted && bytes(*single) == before);
|
||||
|
||||
struct Batch { CommandKind kind; std::uint8_t value; std::size_t count; bool legacy; GridPosition last; };
|
||||
const RoomPlan furnished{{6, 6}, {9, 9}, RoomSide::South, RoomTemplate::Doctor};
|
||||
const RoomPlan empty{{6, 6}, {9, 9}, RoomSide::South, RoomTemplate::Empty};
|
||||
const std::array batches{
|
||||
Batch{CommandKind::PlaceBed, 0, 1, false, {}},
|
||||
Batch{CommandKind::PlaceBed, 0, 2, true, {}},
|
||||
Batch{CommandKind::PlaceLoom, 0, 2, false, {}},
|
||||
Batch{CommandKind::CraftDoor, 0, 1, false, {}},
|
||||
Batch{CommandKind::CraftFurniture, static_cast<std::uint8_t>(ItemType::MiningRack), 1, false, {}},
|
||||
Batch{CommandKind::PlaceRoom, furnished.placement_value(), 20, false, furnished.last},
|
||||
Batch{CommandKind::PlaceRoom, furnished.placement_value(), 21, true, furnished.last},
|
||||
Batch{CommandKind::PlaceRoom, empty.placement_value(), 17, false, empty.last}};
|
||||
for (const auto& batch : batches) {
|
||||
const auto initial = scenario(batch.legacy);
|
||||
auto refused = with_next(*initial, terminal - batch.count + 1);
|
||||
const auto original = bytes(*refused);
|
||||
require(command(*refused, batch.kind, {6, 6}, batch.value, batch.last) == CommandStatus::Busy,
|
||||
"insufficient complete command batch was not Busy");
|
||||
require(bytes(*refused) == original && refused->next_command_sequence(1) == 1,
|
||||
"batch refusal changed orders, counter, stock, terrain or command sequence");
|
||||
auto accepted = with_next(*initial, terminal - batch.count);
|
||||
require(command(*accepted, batch.kind, {6, 6}, batch.value, batch.last) == CommandStatus::Accepted);
|
||||
require(accepted->production_orders().size() == batch.count &&
|
||||
accepted->production_orders().back().id == terminal - 1, "batch allocation count or last ID differs");
|
||||
accepted = checkpoint(*accepted);
|
||||
const auto full = bytes(*accepted);
|
||||
require(command(*accepted, CommandKind::CraftDoor) == CommandStatus::Busy && bytes(*accepted) == full);
|
||||
}
|
||||
static_cast<void>(basic.spawn_agent({2, 2}));
|
||||
auto loom = with_next(basic, terminal - 1);
|
||||
require(command(*loom, CommandKind::PlaceLoom, {6, 6}) == CommandStatus::Accepted &&
|
||||
loom->production_orders().size() == 1 && loom->production_orders().front().id == terminal - 1);
|
||||
for (auto count : {5U, 6U}) {
|
||||
auto cabin = with_next(basic, terminal - count);
|
||||
const auto original = bytes(*cabin);
|
||||
bool failed = false;
|
||||
try { cabin->queue_cabin({10, 10}, {3, 3}, {4, 3}); }
|
||||
catch (const ProductionCapacityError&) { failed = true; }
|
||||
require(count == 5 ? failed && bytes(*cabin) == original :
|
||||
!failed && cabin->production_orders().size() == 6 && cabin->production_orders().back().id == terminal - 1);
|
||||
}
|
||||
}
|
||||
|
||||
Test ProductionIdentityTests::demolition_preflights_every_product_before_losing_stock() {
|
||||
auto initial = scenario();
|
||||
const auto store = initial->add_storage({3, 3}, 20);
|
||||
initial->stock_storage(store, ItemType::WoodenDoor, 1);
|
||||
initial->stock_storage(store, ItemType::Loom, 1);
|
||||
initial->stock_storage(store, ItemType::MedicineCabinet, 1);
|
||||
initial->queue_production({6, 6}, RecipeId::InstallDoorAlongX);
|
||||
initial->queue_production({7, 6}, RecipeId::InstallLoom);
|
||||
initial->queue_production({8, 6}, RecipeId::InstallMedicineCabinet);
|
||||
for (auto available : {0U, 1U, 2U}) {
|
||||
auto world = with_next(*initial, terminal - available);
|
||||
const auto before = bytes(*world);
|
||||
require(command(*world, CommandKind::DemolishObject, {3, 3}) == CommandStatus::Busy && bytes(*world) == before,
|
||||
"multi-product demolition lost stock or allocated a partial replacement batch");
|
||||
require(world->find_storage(store) != nullptr && world->next_command_sequence(1) == 1);
|
||||
}
|
||||
auto world = with_next(*initial, terminal - 3);
|
||||
require(command(*world, CommandKind::DemolishObject, {3, 3}) == CommandStatus::Accepted);
|
||||
require(world->find_storage(store) == nullptr && world->production_orders().size() == 6);
|
||||
for (auto recipe : {RecipeId::CraftWoodenDoor, RecipeId::CraftLoom, RecipeId::CraftMedicineCabinet}) {
|
||||
require(std::count_if(world->production_orders().begin(), world->production_orders().end(),
|
||||
[&](const auto& order) { return order.recipe == recipe; }) == 1);
|
||||
}
|
||||
static_cast<void>(checkpoint(*world));
|
||||
}
|
||||
|
||||
Test ProductionIdentityTests::demolition_counts_existing_supply_and_pending_crafts_exactly() {
|
||||
auto world = scenario();
|
||||
const auto lost = world->add_storage({3, 3}, 20);
|
||||
const auto retained = world->add_storage({4, 3}, 20);
|
||||
world->stock_storage(lost, ItemType::WoodenDoor, 1);
|
||||
world->stock_storage(lost, ItemType::Loom, 1);
|
||||
world->stock_storage(lost, ItemType::MedicineCabinet, 1);
|
||||
world->stock_storage(retained, ItemType::WoodenDoor, 1);
|
||||
world->queue_production({6, 6}, RecipeId::InstallDoorAlongX);
|
||||
world->queue_production({7, 6}, RecipeId::InstallLoom);
|
||||
world->queue_production({8, 6}, RecipeId::InstallMedicineCabinet);
|
||||
world->queue_production({2, 2}, RecipeId::CraftLoom);
|
||||
world = with_next(*world, terminal - 1);
|
||||
require(command(*world, CommandKind::DemolishObject, {3, 3}) == CommandStatus::Accepted,
|
||||
"demolition overcounted replacement orders already covered by stock or pending craft");
|
||||
require(world->production_orders().size() == 5 && world->production_orders().back().recipe == RecipeId::CraftMedicineCabinet &&
|
||||
world->production_orders().back().id == terminal - 1 && world->find_storage(retained)->item_count(ItemType::WoodenDoor) == 1);
|
||||
}
|
||||
|
||||
Test ProductionIdentityTests::legacy_cabin_exhaustion_is_a_repeatable_healthy_runtime_result() {
|
||||
World initial(42, 24, 24, 1, ExecutionMode::SerialReference);
|
||||
static_cast<void>(initial.spawn_agent({2, 2}));
|
||||
auto world = with_next(initial, terminal - 5);
|
||||
const auto before = bytes(*world);
|
||||
auto rules = default_rules_manifest(); require(rules.has_value());
|
||||
SimulationRuntime runtime(WorldCheckpoint{std::move(world), world_id, 7, *rules}, {.ticking = false});
|
||||
const auto identity = runtime.latest()->identity;
|
||||
const CommandEnvelope cabin{command_envelope_version, identity.world, identity.session, identity.city, 1,
|
||||
LegacyCabinPayload{{10, 10}, {3, 3}, {4, 3}}};
|
||||
auto result = runtime.try_submit({1}, cabin);
|
||||
require(result.admission == RuntimeAdmission::Accepted);
|
||||
auto completed = result.completion.get();
|
||||
require(completed.outcome == RuntimeOutcome::Completed && completed.receipt ==
|
||||
DispatchReceipt{DispatchStatus::Completed, CommandStatus::Busy, 0, 0});
|
||||
auto repeat = runtime.try_submit({1}, cabin);
|
||||
require(repeat.admission == RuntimeAdmission::Accepted && repeat.completion.get().receipt == completed.receipt);
|
||||
require(runtime.lookup({1}, cabin) == completed.receipt && runtime.latest()->next_requests[0] == 2 &&
|
||||
runtime.view().state == RuntimeState::Running && bytes(*runtime.latest()->world) == before,
|
||||
"pre-mutation cabin refusal faulted the session, changed state or lost its retained receipt");
|
||||
const CommandEnvelope storage{command_envelope_version, identity.world, identity.session, identity.city, 2,
|
||||
CommandPayload{CommandKind::PlaceStorage, {6, 6}}};
|
||||
auto continued = runtime.try_submit({1}, storage);
|
||||
require(continued.admission == RuntimeAdmission::Accepted);
|
||||
const auto next = continued.completion.get();
|
||||
require(next.outcome == RuntimeOutcome::Completed && next.receipt->command_status == CommandStatus::Accepted &&
|
||||
runtime.view().state == RuntimeState::Running && runtime.latest()->world->storages().size() == 1);
|
||||
}
|
||||
|
||||
Test ProductionIdentityTests::malformed_ids_and_references_fail_before_dereference() {
|
||||
auto world = scenario();
|
||||
static_cast<void>(world->spawn_agent({4, 4}));
|
||||
world->queue_production({6, 6}, RecipeId::BuildMedicineCabinet);
|
||||
world->queue_production({7, 6}, RecipeId::BuildMedicineCabinet);
|
||||
const auto valid = bytes(*world);
|
||||
const auto offsets = locations(valid);
|
||||
require(offsets.orders.size() == 2 && offsets.links.size() == 1);
|
||||
for (const auto value : {ProductionId{0}, ProductionId{2}, terminal}) {
|
||||
auto data = valid; put(data, offsets.orders.front(), value); rejected(data);
|
||||
}
|
||||
auto duplicate = valid; put(duplicate, offsets.orders.back(), ProductionId{1}); rejected(duplicate);
|
||||
auto unsorted = valid; put(unsorted, offsets.orders.front(), ProductionId{2});
|
||||
put(unsorted, offsets.orders.back(), ProductionId{1}); rejected(unsorted);
|
||||
for (const auto value : {ProductionId{0}, ProductionId{2}}) {
|
||||
auto data = valid; put(data, next_production_offset, value); rejected(data);
|
||||
}
|
||||
for (const auto value : {ProductionId{1}, ProductionId{3}, terminal}) {
|
||||
auto data = valid; put(data, offsets.links.front(), value); rejected(data);
|
||||
}
|
||||
const auto store = world->add_storage({3, 3}, 20);
|
||||
world->stock_storage(store, ItemType::Wood, 4);
|
||||
world->step();
|
||||
require(world->agents().front().production_id != 0);
|
||||
const auto active = bytes(*world);
|
||||
auto none = active; put(none, locations(active).links.front(), ProductionId{0}); rejected(none);
|
||||
auto wrong = active; put(wrong, locations(active).links.front(), world->production_orders().back().id); rejected(wrong);
|
||||
}
|
||||
|
||||
Test ProductionIdentityTests::legacy_projection_imports_deterministic_dense_ids() {
|
||||
auto world = scenario();
|
||||
world->queue_production({6, 6}, RecipeId::BuildMedicineCabinet);
|
||||
world->queue_production({7, 6}, RecipeId::BuildMedicineCabinet);
|
||||
require(command(*world, CommandKind::DemolishObject, {6, 6}) == CommandStatus::Accepted);
|
||||
world = with_next(*world, 123);
|
||||
world->queue_production({8, 6}, RecipeId::BuildMedicineCabinet);
|
||||
const auto old_bytes = bytes(*world, WorldSaveFormat::Legacy13);
|
||||
auto legacy = restore(old_bytes);
|
||||
require(legacy->production_orders()[0].id == 1 && legacy->production_orders()[1].id == 2 &&
|
||||
bytes(*legacy, WorldSaveFormat::Legacy13) == old_bytes, "legacy positional projection or deterministic import changed");
|
||||
legacy->queue_production({9, 6}, RecipeId::BuildMedicineCabinet);
|
||||
require(legacy->production_orders().back().id == 3);
|
||||
auto modern = checkpoint(*world);
|
||||
modern->queue_production({9, 6}, RecipeId::BuildMedicineCabinet);
|
||||
require(modern->production_orders().back().id == 124);
|
||||
}
|
||||
} // namespace
|
||||
@@ -0,0 +1,407 @@
|
||||
#include "settlement/core/inventory_transaction.hpp"
|
||||
#include "settlement/core/simulation_runtime.hpp"
|
||||
|
||||
#include <Void/Testing/Suite.hpp>
|
||||
|
||||
#include <array>
|
||||
#include <chrono>
|
||||
#include <limits>
|
||||
#include <sstream>
|
||||
#include <stdexcept>
|
||||
#include <thread>
|
||||
|
||||
namespace {
|
||||
using namespace settlement;
|
||||
using Void::Testing::Test;
|
||||
constexpr auto maximum = std::numeric_limits<std::uint32_t>::max();
|
||||
|
||||
void require(bool condition, const char* message = "quantity transfer invariant failed") {
|
||||
if (!condition) throw std::runtime_error(message);
|
||||
}
|
||||
|
||||
Storage source() {
|
||||
return {7, {3, 3}, 20, 0, {{ItemType::Wood, 4, 3}, {ItemType::Stone, 3, 2}}};
|
||||
}
|
||||
|
||||
void same_inventory(const Inventory& actual, const Inventory& expected) {
|
||||
for (std::size_t i = 1; i <= item_type_count; ++i) {
|
||||
require(actual.item_count(static_cast<ItemType>(i)) == expected.item_count(static_cast<ItemType>(i)),
|
||||
"failed pickup changed destination");
|
||||
}
|
||||
}
|
||||
|
||||
void same_storage(const Storage& actual, const Storage& expected) {
|
||||
require(actual.id == expected.id && actual.position == expected.position && actual.capacity == expected.capacity &&
|
||||
actual.reserved_slots == expected.reserved_slots && actual.kind == expected.kind &&
|
||||
actual.items.size() == expected.items.size(), "failed pickup changed storage metadata");
|
||||
for (std::size_t i = 0; i < actual.items.size(); ++i) {
|
||||
require(actual.items[i].type == expected.items[i].type && actual.items[i].count == expected.items[i].count &&
|
||||
actual.items[i].reserved == expected.items[i].reserved, "failed pickup changed source quantities/order");
|
||||
}
|
||||
}
|
||||
|
||||
void rejected(Storage& storage, Inventory& inventory, std::span<const MaterialReservation> materials,
|
||||
QuantityTransferError error, bool slot = false) {
|
||||
const auto before = storage;
|
||||
const auto cargo = inventory;
|
||||
const auto result = withdraw_reserved_materials(storage, inventory, materials, slot);
|
||||
require(!result && result.error() == error, "pickup accepted bad input or returned the wrong diagnostic");
|
||||
same_storage(storage, before);
|
||||
same_inventory(inventory, cargo);
|
||||
}
|
||||
|
||||
std::string bytes(const World& world) {
|
||||
std::ostringstream stream(std::ios::binary);
|
||||
world.write_save(stream, WorldSaveFormat::Current14);
|
||||
return stream.str();
|
||||
}
|
||||
|
||||
void same_pickup_actor(const Agent& actual, const Agent& expected) {
|
||||
same_inventory(actual.inventory, expected.inventory);
|
||||
require(actual.position == expected.position && actual.route == expected.route &&
|
||||
actual.route_cursor == expected.route_cursor && actual.haul_route == expected.haul_route &&
|
||||
actual.state == expected.state && actual.storage_id == expected.storage_id &&
|
||||
actual.production_id == expected.production_id && actual.work_remaining == expected.work_remaining,
|
||||
"rejected pickup changed actor/route state");
|
||||
}
|
||||
|
||||
std::unique_ptr<World> cabin() {
|
||||
auto world = std::make_unique<World>(43, 32, 32, 1, ExecutionMode::SerialReference);
|
||||
const auto store = world->add_storage({3, 3}, 20);
|
||||
world->stock_storage(store, ItemType::Plank, 3);
|
||||
world->stock_storage(store, ItemType::StoneBlock, 2);
|
||||
static_cast<void>(world->spawn_agent({1, 3}));
|
||||
world->queue_production({14, 3}, RecipeId::BuildCabin);
|
||||
world->step();
|
||||
require(world->agents().front().state == AgentState::FetchingMaterials, "fixture already picked up materials");
|
||||
return world;
|
||||
}
|
||||
|
||||
// Test-only corruption uses public read views of a nonconst fixture. Production
|
||||
// code cannot create these malformed sources through the checked save loader.
|
||||
void at_pickup(World& world) {
|
||||
auto& agent = const_cast<Agent&>(world.agents().front());
|
||||
agent.position = world.storages().front().position;
|
||||
agent.route.clear();
|
||||
agent.route_cursor = 0;
|
||||
}
|
||||
|
||||
struct [[= Void::Testing::name("QuantityTransactionTests")]] QuantityTransactionTests
|
||||
: Void::Testing::Suite<QuantityTransactionTests> {
|
||||
[[= Void::Testing::tag("quantity-transfer")]] Test late_failure_is_atomic();
|
||||
[[= Void::Testing::tag("quantity-transfer")]] Test nonadjacent_duplicates_and_foreign_stops();
|
||||
[[= Void::Testing::tag("quantity-transfer")]] Test invalid_selection_and_item_bounds();
|
||||
[[= Void::Testing::tag("quantity-transfer")]] Test source_invariants_and_underflow();
|
||||
[[= Void::Testing::tag("quantity-transfer")]] Test cumulative_and_destination_boundaries();
|
||||
[[= Void::Testing::tag("quantity-transfer")]] Test stable_multiple_erasure_and_output_capacity();
|
||||
[[= Void::Testing::tag("quantity-transfer")]] Test invalid_capacity_and_slot_overflow_are_atomic();
|
||||
[[= Void::Testing::tag("quantity-transfer")]] Test real_construction_rejection_keeps_stop_actor_and_routes();
|
||||
[[= Void::Testing::tag("quantity-transfer")]] Test real_split_lines_and_invalid_storage_selection();
|
||||
[[= Void::Testing::tag("quantity-transfer")]] Test real_carpentry_invalid_capacity_keeps_pickup_untouched();
|
||||
[[= Void::Testing::tag("quantity-transfer")]] Test real_meal_pickup_and_overflow_rejection();
|
||||
[[= Void::Testing::tag("quantity-transfer")]] Test real_multistop_carpentry_reserves_first_ingredient_store();
|
||||
[[= Void::Testing::tag("quantity-transfer")]] Test direct_crafting_stays_in_storage();
|
||||
[[= Void::Testing::tag("quantity-transfer")]] Test owner_fault_preserves_last_healthy_publication();
|
||||
};
|
||||
|
||||
Test QuantityTransactionTests::late_failure_is_atomic() {
|
||||
auto storage = source();
|
||||
Inventory inventory;
|
||||
inventory.add(ItemType::Wood, 9);
|
||||
const std::array materials{MaterialReservation{7, ItemType::Wood, 2}, MaterialReservation{7, ItemType::Stone, 3}};
|
||||
rejected(storage, inventory, materials, QuantityTransferError::InsufficientStock);
|
||||
inventory.add(ItemType::Stone, maximum);
|
||||
auto valid = materials;
|
||||
valid[1].count = 1;
|
||||
rejected(storage, inventory, valid, QuantityTransferError::Overflow, true);
|
||||
}
|
||||
|
||||
Test QuantityTransactionTests::nonadjacent_duplicates_and_foreign_stops() {
|
||||
auto storage = source();
|
||||
Inventory inventory;
|
||||
const std::array materials{MaterialReservation{7, ItemType::Wood, 1}, MaterialReservation{9, ItemType::Wood, 5},
|
||||
MaterialReservation{7, ItemType::Stone, 2}, MaterialReservation{7, ItemType::Wood, 2}};
|
||||
require(withdraw_reserved_materials(storage, inventory, materials).has_value());
|
||||
require(inventory.item_count(ItemType::Wood) == 3 && inventory.item_count(ItemType::Stone) == 2);
|
||||
require(storage.items[0].count == 1 && storage.items[0].reserved == 0 && storage.items[1].count == 1 &&
|
||||
storage.items[1].reserved == 0);
|
||||
auto insufficient = source();
|
||||
const std::array duplicates{MaterialReservation{7, ItemType::Wood, 2}, MaterialReservation{7, ItemType::Stone, 1},
|
||||
MaterialReservation{7, ItemType::Wood, 2}};
|
||||
rejected(insufficient, inventory, duplicates, QuantityTransferError::InsufficientStock);
|
||||
}
|
||||
|
||||
Test QuantityTransactionTests::invalid_selection_and_item_bounds() {
|
||||
auto storage = source();
|
||||
Inventory inventory;
|
||||
const std::array valid{MaterialReservation{7, ItemType::Wood, 1}};
|
||||
rejected(storage, inventory, {}, QuantityTransferError::MissingSelection);
|
||||
const std::array foreign{MaterialReservation{8, ItemType::Wood, 1}};
|
||||
rejected(storage, inventory, foreign, QuantityTransferError::MissingSelection);
|
||||
const std::array zero_id{MaterialReservation{0, ItemType::Wood, 1}};
|
||||
rejected(storage, inventory, zero_id, QuantityTransferError::MissingSelection);
|
||||
for (const auto type : {ItemType::None, static_cast<ItemType>(item_type_count + 1), static_cast<ItemType>(255)}) {
|
||||
const std::array bad{MaterialReservation{7, type, 1}};
|
||||
rejected(storage, inventory, bad, QuantityTransferError::InvalidMaterial);
|
||||
}
|
||||
const std::array zero{MaterialReservation{7, ItemType::Wood, 0}};
|
||||
rejected(storage, inventory, zero, QuantityTransferError::InvalidMaterial);
|
||||
storage.id = 0;
|
||||
rejected(storage, inventory, zero_id, QuantityTransferError::InvalidStorage);
|
||||
storage = source();
|
||||
storage.kind = static_cast<StorageKind>(255);
|
||||
rejected(storage, inventory, valid, QuantityTransferError::InvalidStorage);
|
||||
}
|
||||
|
||||
Test QuantityTransactionTests::source_invariants_and_underflow() {
|
||||
Inventory inventory;
|
||||
const std::array materials{MaterialReservation{7, ItemType::Wood, 1}};
|
||||
const std::array missing{MaterialReservation{7, ItemType::Plank, 1}};
|
||||
auto storage = source();
|
||||
rejected(storage, inventory, missing, QuantityTransferError::InsufficientStock);
|
||||
for (int fault = 0; fault < 8; ++fault) {
|
||||
storage = source();
|
||||
switch (fault) {
|
||||
case 0: storage.items[0].reserved = 5; break;
|
||||
case 1: storage.items[0].count = 0; break;
|
||||
case 2: storage.items[0].type = ItemType::None; break;
|
||||
case 3: storage.items[0].type = static_cast<ItemType>(item_type_count + 1); break;
|
||||
case 4: storage.items[1].type = ItemType::Wood; break;
|
||||
case 5: std::swap(storage.items[0], storage.items[1]); break;
|
||||
case 6: storage.kind = StorageKind::Pantry; break;
|
||||
case 7: storage.items[1].reserved = 4; break;
|
||||
}
|
||||
rejected(storage, inventory, materials, QuantityTransferError::InvalidStock);
|
||||
}
|
||||
storage = source();
|
||||
storage.items[0].reserved = 0;
|
||||
rejected(storage, inventory, materials, QuantityTransferError::InsufficientStock);
|
||||
storage.items[0].reserved = storage.items[0].count = 1;
|
||||
const std::array too_many{MaterialReservation{7, ItemType::Wood, 2}};
|
||||
rejected(storage, inventory, too_many, QuantityTransferError::InsufficientStock);
|
||||
}
|
||||
|
||||
Test QuantityTransactionTests::cumulative_and_destination_boundaries() {
|
||||
Storage storage{7, {}, maximum, 0, {{ItemType::Wood, maximum, maximum}}};
|
||||
Inventory inventory;
|
||||
const std::array overflow{MaterialReservation{7, ItemType::Wood, maximum},
|
||||
MaterialReservation{8, ItemType::Stone, 1}, MaterialReservation{7, ItemType::Wood, 1}};
|
||||
rejected(storage, inventory, overflow, QuantityTransferError::Overflow);
|
||||
const std::array exact{MaterialReservation{7, ItemType::Wood, maximum - 1}, MaterialReservation{7, ItemType::Wood, 1}};
|
||||
require(withdraw_reserved_materials(storage, inventory, exact).has_value());
|
||||
require(storage.items.empty() && inventory.item_count(ItemType::Wood) == maximum);
|
||||
storage = source();
|
||||
const std::array one{MaterialReservation{7, ItemType::Wood, 1}};
|
||||
rejected(storage, inventory, one, QuantityTransferError::Overflow);
|
||||
Inventory boundary;
|
||||
boundary.add(ItemType::Wood, maximum - 1);
|
||||
require(withdraw_reserved_materials(storage, boundary, one).has_value());
|
||||
require(boundary.item_count(ItemType::Wood) == maximum);
|
||||
}
|
||||
|
||||
Test QuantityTransactionTests::stable_multiple_erasure_and_output_capacity() {
|
||||
Storage storage{7, {}, 10, 0, {{ItemType::Wood, 2, 2}, {ItemType::Stone, 3, 1},
|
||||
{ItemType::Plank, 1, 1}, {ItemType::StoneBlock, 4, 0}}};
|
||||
Inventory inventory;
|
||||
const std::array materials{MaterialReservation{7, ItemType::Plank, 1}, MaterialReservation{7, ItemType::Wood, 2}};
|
||||
require(withdraw_reserved_materials(storage, inventory, materials, true).has_value());
|
||||
require(storage.reserved_slots == 1 && storage.items.size() == 2 &&
|
||||
storage.items[0].type == ItemType::Stone && storage.items[0].count == 3 && storage.items[0].reserved == 1 &&
|
||||
storage.items[1].type == ItemType::StoneBlock && storage.items[1].count == 4 && storage.items[1].reserved == 0);
|
||||
Storage full{7, {}, 1, 0, {{ItemType::Wood, 1, 1}}};
|
||||
const std::array one{MaterialReservation{7, ItemType::Wood, 1}};
|
||||
require(withdraw_reserved_materials(full, inventory, one, true).has_value());
|
||||
require(full.items.empty() && full.reserved_slots == 1 && full.total_items() + full.reserved_slots == full.capacity);
|
||||
}
|
||||
|
||||
Test QuantityTransactionTests::invalid_capacity_and_slot_overflow_are_atomic() {
|
||||
Inventory inventory;
|
||||
const std::array materials{MaterialReservation{7, ItemType::Wood, 1}};
|
||||
for (int fault = 0; fault < 4; ++fault) {
|
||||
auto storage = source();
|
||||
switch (fault) {
|
||||
case 0: storage.capacity = 0; break;
|
||||
case 1: storage.capacity = 6; break;
|
||||
case 2: storage.reserved_slots = maximum; break;
|
||||
case 3: storage.capacity = 7; storage.reserved_slots = 1; break;
|
||||
}
|
||||
rejected(storage, inventory, materials, QuantityTransferError::Capacity, true);
|
||||
}
|
||||
}
|
||||
|
||||
Test QuantityTransactionTests::real_construction_rejection_keeps_stop_actor_and_routes() {
|
||||
auto world = cabin();
|
||||
at_pickup(*world);
|
||||
auto& storage = const_cast<Storage&>(world->storages().front());
|
||||
storage.items.back().reserved = 1; // The first item is valid; the second fails.
|
||||
const auto before = storage;
|
||||
const auto actor = world->agents().front();
|
||||
const auto order = world->production_orders().front();
|
||||
bool failed = false;
|
||||
try { world->step(); } catch (const std::logic_error&) { failed = true; }
|
||||
require(failed);
|
||||
same_storage(storage, before);
|
||||
same_pickup_actor(world->agents().front(), actor);
|
||||
const auto& after = world->production_orders().front();
|
||||
require(after.collected_stops == order.collected_stops && after.delivery_stops.size() == order.delivery_stops.size());
|
||||
require(after.delivery_stops.front().route_to_next == order.delivery_stops.front().route_to_next);
|
||||
}
|
||||
|
||||
Test QuantityTransactionTests::real_split_lines_and_invalid_storage_selection() {
|
||||
auto world = cabin();
|
||||
at_pickup(*world);
|
||||
auto& order = const_cast<ProductionOrder&>(world->production_orders().front());
|
||||
const auto id = world->storages().front().id;
|
||||
order.materials = {{id, ItemType::Plank, 1}, {id, ItemType::StoneBlock, 2}, {id, ItemType::Plank, 2}};
|
||||
for (const auto invalid : {StorageId{0}, StorageId{123}, id}) {
|
||||
order.delivery_stops.front().storage_id = invalid;
|
||||
if (invalid == id) { // A real storage, but no selected reservation.
|
||||
for (auto& material : order.materials) material.storage_id = 123;
|
||||
}
|
||||
const auto before = world->storages().front();
|
||||
const auto actor = world->agents().front();
|
||||
const auto route = order.delivery_stops.front().route_to_next;
|
||||
bool failed = false;
|
||||
try { world->step(); } catch (const std::logic_error&) { failed = true; }
|
||||
require(failed && order.collected_stops == 0 && order.delivery_stops.front().route_to_next == route);
|
||||
same_pickup_actor(world->agents().front(), actor);
|
||||
same_storage(world->storages().front(), before);
|
||||
}
|
||||
for (auto& material : order.materials) material.storage_id = id;
|
||||
world->step();
|
||||
require(order.collected_stops == 1 && world->storages().front().items.empty());
|
||||
require(world->agents().front().inventory.item_count(ItemType::Plank) == 3 &&
|
||||
world->agents().front().inventory.item_count(ItemType::StoneBlock) == 2);
|
||||
for (int i = 0; i < 80 && order.state != JobState::Completed; ++i) world->step();
|
||||
require(order.state == JobState::Completed && world->agents().front().inventory.empty());
|
||||
}
|
||||
|
||||
Test QuantityTransactionTests::real_carpentry_invalid_capacity_keeps_pickup_untouched() {
|
||||
World world(49, 32, 32, 1, ExecutionMode::SerialReference);
|
||||
const auto store = world.add_storage({3, 3}, 1);
|
||||
world.stock_storage(store, ItemType::Wood, 1);
|
||||
const auto carpenter = world.spawn_agent({1, 3});
|
||||
world.start_scenario({8, 3});
|
||||
require(world.apply_command({1, 1, CommandKind::AssignProfession, {},
|
||||
static_cast<std::uint8_t>(Profession::Carpenter), {}, carpenter}).status == CommandStatus::Accepted);
|
||||
world.queue_production({8, 3}, RecipeId::CraftMedicineCabinet);
|
||||
world.step();
|
||||
require(world.agents().front().state == AgentState::FetchingMaterials);
|
||||
at_pickup(world);
|
||||
auto& storage = const_cast<Storage&>(world.storages().front());
|
||||
storage.reserved_slots = 1; // Already over capacity before this pickup.
|
||||
const auto before = storage;
|
||||
const auto actor = world.agents().front();
|
||||
const auto order = world.production_orders().front();
|
||||
bool failed = false;
|
||||
try { world.step(); } catch (const std::logic_error&) { failed = true; }
|
||||
require(failed && world.production_orders().front().collected_stops == 0);
|
||||
same_storage(storage, before);
|
||||
same_pickup_actor(world.agents().front(), actor);
|
||||
require(world.production_orders().front().delivery_stops.front().route_to_next == order.delivery_stops.front().route_to_next);
|
||||
}
|
||||
|
||||
Test QuantityTransactionTests::real_meal_pickup_and_overflow_rejection() {
|
||||
World world(44, 32, 32, 1, ExecutionMode::SerialReference);
|
||||
const auto pantry = world.add_storage({28, 4}, 50, StorageKind::Pantry);
|
||||
world.stock_storage(pantry, ItemType::Berries, 40);
|
||||
static_cast<void>(world.spawn_agent({4, 4}));
|
||||
world.enable_hunger();
|
||||
for (int i = 0; i < 500 && world.agents().front().state != AgentState::GoingToEat; ++i) world.step();
|
||||
require(world.agents().front().state == AgentState::GoingToEat);
|
||||
auto& actor = const_cast<Agent&>(world.agents().front());
|
||||
at_pickup(world);
|
||||
actor.inventory.add(ItemType::Berries, maximum);
|
||||
const auto agent_before = actor;
|
||||
const auto storage_before = world.storages().front();
|
||||
bool failed = false;
|
||||
try { world.step(); } catch (const std::logic_error&) { failed = true; }
|
||||
require(failed);
|
||||
same_pickup_actor(actor, agent_before);
|
||||
same_storage(world.storages().front(), storage_before);
|
||||
actor.inventory.remove(ItemType::Berries, maximum);
|
||||
world.step();
|
||||
require(actor.state == AgentState::Eating && actor.inventory.item_count(ItemType::Berries) == 1 && actor.storage_id == 0);
|
||||
require(world.storages().front().item_count(ItemType::Berries) == 39);
|
||||
for (int i = 0; i < 5; ++i) world.step();
|
||||
require(world.meals_eaten() == 1 && actor.inventory.empty() && actor.hunger == 0);
|
||||
}
|
||||
|
||||
Test QuantityTransactionTests::real_multistop_carpentry_reserves_first_ingredient_store() {
|
||||
World world(49, 32, 32, 1, ExecutionMode::SerialReference);
|
||||
const auto stone = world.add_storage({3, 3}, 1);
|
||||
const auto wood = world.add_storage({6, 3}, 1);
|
||||
world.stock_storage(stone, ItemType::Stone, 1);
|
||||
world.stock_storage(wood, ItemType::Wood, 1);
|
||||
const auto carpenter = world.spawn_agent({2, 3});
|
||||
world.start_scenario({8, 3});
|
||||
require(world.apply_command({1, 1, CommandKind::AssignProfession, {},
|
||||
static_cast<std::uint8_t>(Profession::Carpenter), {}, carpenter}).status == CommandStatus::Accepted);
|
||||
world.queue_production({8, 3}, RecipeId::CraftMiningRack);
|
||||
world.step();
|
||||
const auto& order = world.production_orders().front();
|
||||
require(order.materials.front().storage_id == wood && order.delivery_stops.front().storage_id == stone);
|
||||
for (int i = 0; i < 20 && order.collected_stops == 0; ++i) world.step();
|
||||
require(order.collected_stops == 1 && world.find_storage(stone)->reserved_slots == 0 &&
|
||||
world.find_storage(wood)->reserved_slots == 0);
|
||||
for (int i = 0; i < 20 && order.collected_stops == 1; ++i) world.step();
|
||||
require(order.collected_stops == 2 && world.find_storage(wood)->items.empty() &&
|
||||
world.find_storage(wood)->reserved_slots == 1);
|
||||
for (int i = 0; i < 80 && world.find_storage(wood)->item_count(ItemType::MiningRack) == 0; ++i) world.step();
|
||||
require(world.find_storage(wood)->item_count(ItemType::MiningRack) == 1 &&
|
||||
world.find_storage(wood)->reserved_slots == 0 && world.find_storage(stone)->items.empty());
|
||||
}
|
||||
|
||||
Test QuantityTransactionTests::direct_crafting_stays_in_storage() {
|
||||
World world(51, 24, 24, 1, ExecutionMode::SerialReference);
|
||||
const auto store = world.add_storage({3, 3}, 2);
|
||||
world.stock_storage(store, ItemType::Wood, 1);
|
||||
world.stock_storage(store, ItemType::Stone, 1);
|
||||
static_cast<void>(world.spawn_agent({2, 3}));
|
||||
world.queue_production({5, 3}, RecipeId::SawPlank);
|
||||
world.queue_production({7, 3}, RecipeId::CutStoneBlock);
|
||||
for (int i = 0; i < 80; ++i) {
|
||||
world.step();
|
||||
require(world.agents().front().inventory.empty(), "direct recipe created physical carrier cargo");
|
||||
}
|
||||
const auto* storage = world.find_storage(store);
|
||||
require(storage->item_count(ItemType::Wood) == 0 && storage->item_count(ItemType::Stone) == 0 &&
|
||||
storage->item_count(ItemType::Plank) == 1 && storage->item_count(ItemType::StoneBlock) == 1 &&
|
||||
storage->reserved_slots == 0);
|
||||
}
|
||||
|
||||
Test QuantityTransactionTests::owner_fault_preserves_last_healthy_publication() {
|
||||
using namespace std::chrono_literals;
|
||||
auto world = cabin();
|
||||
at_pickup(*world);
|
||||
auto* fixture = world.get();
|
||||
auto clock = std::make_shared<Void::Time::ManualClock>();
|
||||
RuntimeOptions options{.clock = clock};
|
||||
options.observer = [fixture](RuntimePhase phase) {
|
||||
if (phase == RuntimePhase::BeforeTick) {
|
||||
const_cast<Storage&>(fixture->storages().front()).items.back().reserved = 1;
|
||||
}
|
||||
};
|
||||
auto rules = default_rules_manifest();
|
||||
require(rules.has_value());
|
||||
Void::Uuid::Uuid id;
|
||||
id.bytes.back() = 71;
|
||||
SimulationRuntime runtime({std::move(world), id, 1, std::move(*rules)}, std::move(options));
|
||||
const auto previous = runtime.latest();
|
||||
const auto healthy = bytes(*previous->world);
|
||||
require(clock->advance(50ms).has_value());
|
||||
RuntimeSubmission fence;
|
||||
const auto limit = std::chrono::steady_clock::now() + 5s;
|
||||
do {
|
||||
fence = runtime.synchronize();
|
||||
if (fence.admission != RuntimeAdmission::Busy) break;
|
||||
require(std::chrono::steady_clock::now() < limit, "runtime fence admission timed out");
|
||||
std::this_thread::yield();
|
||||
} while (true);
|
||||
require(fence.admission == RuntimeAdmission::Accepted && fence.completion.wait_for(5s) == std::future_status::ready);
|
||||
require(fence.completion.get().outcome == RuntimeOutcome::Faulted && runtime.view().state == RuntimeState::Faulted &&
|
||||
runtime.view().failure && !runtime.snapshot_for_save());
|
||||
require(runtime.latest() == previous && bytes(*runtime.latest()->world) == healthy,
|
||||
"owner published the rejected pickup candidate");
|
||||
}
|
||||
} // namespace
|
||||
@@ -0,0 +1,135 @@
|
||||
#pragma once
|
||||
|
||||
#include "settlement/core/world.hpp"
|
||||
#include <algorithm>
|
||||
#include <map>
|
||||
#include <sstream>
|
||||
#include <string>
|
||||
#include <type_traits>
|
||||
|
||||
namespace replay_diagnostics {
|
||||
using namespace settlement;
|
||||
|
||||
struct Context {
|
||||
std::uint64_t attempt = 0;
|
||||
std::size_t workers = 1;
|
||||
std::string schedule = "uncontrolled";
|
||||
std::string load = "uninterrupted";
|
||||
std::size_t capacity = 4096;
|
||||
};
|
||||
|
||||
inline std::string canonical(const World& world) {
|
||||
std::ostringstream stream(std::ios::binary);
|
||||
world.write_save(stream, WorldSaveFormat::Current14);
|
||||
return stream.str();
|
||||
}
|
||||
|
||||
template<class T> std::string value(T item) {
|
||||
if constexpr (std::is_enum_v<T>) return std::to_string(static_cast<unsigned>(item));
|
||||
else return std::to_string(item);
|
||||
}
|
||||
inline std::string value(GridPosition p) { return "(" + value(p.x) + "," + value(p.y) + ")"; }
|
||||
inline std::string value(const std::vector<GridPosition>& route) {
|
||||
std::string text = "[";
|
||||
for (auto p : route) text += value(p) + ",";
|
||||
return text + "]";
|
||||
}
|
||||
|
||||
// Diagnostic projection of public domain objects, never a save parser or an
|
||||
// alternate equality oracle. Unknown/private fields retain the byte fallback.
|
||||
using Facts = std::map<std::string, std::string>;
|
||||
inline Facts facts(const World& world) {
|
||||
Facts out;
|
||||
const auto put = [&](const std::string& owner, const char* field, const auto& item) {
|
||||
out[owner + " field=" + field] = value(item);
|
||||
};
|
||||
for (const auto& a : world.agents()) {
|
||||
const auto key = "agent id=" + value(a.id);
|
||||
#define AGENT_FIELD(field) put(key, #field, a.field)
|
||||
AGENT_FIELD(position); AGENT_FIELD(state); AGENT_FIELD(current_job);
|
||||
AGENT_FIELD(route); AGENT_FIELD(route_cursor); AGENT_FIELD(work_remaining);
|
||||
AGENT_FIELD(resource_node_id); AGENT_FIELD(storage_id); AGENT_FIELD(haul_route);
|
||||
AGENT_FIELD(production_id); AGENT_FIELD(hunger); AGENT_FIELD(fatigue);
|
||||
AGENT_FIELD(resting_on_ground); AGENT_FIELD(profession);
|
||||
#undef AGENT_FIELD
|
||||
for (std::size_t item = 1; item <= item_type_count; ++item) {
|
||||
put("stock owner=agent:" + value(a.id) + " item=" + value(item), "count",
|
||||
a.inventory.item_count(static_cast<ItemType>(item)));
|
||||
}
|
||||
}
|
||||
for (const auto& j : world.jobs()) {
|
||||
const auto key = "job id=" + value(j.id);
|
||||
put(key, "position", j.position); put(key, "state", j.state);
|
||||
put(key, "work_required", j.work_required); put(key, "work_remaining", j.work_remaining);
|
||||
}
|
||||
for (const auto& p : world.production_orders()) {
|
||||
const auto key = "production id=" + value(p.id);
|
||||
put(key, "position", p.position); put(key, "recipe", p.recipe); put(key, "state", p.state);
|
||||
put(key, "collected_stops", p.collected_stops); put(key, "bed_owner", p.bed_owner);
|
||||
put(key, "bed_base", p.bed_base); put(key, "bed_stage", p.bed_stage);
|
||||
for (const auto& m : p.materials) {
|
||||
put(key + " material owner=storage:" + value(m.storage_id) + " item=" + value(m.type),
|
||||
"count", m.count);
|
||||
}
|
||||
for (std::size_t i = 0; i < p.delivery_stops.size(); ++i) {
|
||||
const auto stop = key + " stop=" + value(i);
|
||||
put(stop, "storage_id", p.delivery_stops[i].storage_id);
|
||||
put(stop, "route_to_next", p.delivery_stops[i].route_to_next);
|
||||
}
|
||||
}
|
||||
for (const auto& s : world.storages()) {
|
||||
const auto key = "storage id=" + value(s.id);
|
||||
put(key, "position", s.position); put(key, "capacity", s.capacity);
|
||||
put(key, "reserved_slots", s.reserved_slots); put(key, "kind", s.kind);
|
||||
for (const auto& stack : s.items) {
|
||||
const auto stock = "stock owner=storage:" + value(s.id) + " item=" + value(stack.type);
|
||||
put(stock, "count", stack.count); put(stock, "reserved", stack.reserved);
|
||||
}
|
||||
}
|
||||
for (std::uint8_t player = 1; player <= colony_player_slots; ++player) {
|
||||
put("command player=" + value(player), "next_sequence", world.next_command_sequence(player));
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
inline std::string context(const World& world, const Context& c) {
|
||||
return "replay divergence tick=" + value(world.tick()) + " attempt=" + value(c.attempt) +
|
||||
" seed=" + value(world.seed()) + " workers=" + value(c.workers) + " schedule=" + c.schedule +
|
||||
" load=" + c.load + " capacity=" + value(c.capacity) + " ";
|
||||
}
|
||||
|
||||
inline std::string difference(const World& expected, const World& actual, const Context& c = {}) {
|
||||
const auto left = canonical(expected), right = canonical(actual);
|
||||
if (left == right) return {};
|
||||
const auto a = facts(expected), b = facts(actual);
|
||||
auto ai = a.begin(), bi = b.begin();
|
||||
while (ai != a.end() || bi != b.end()) {
|
||||
if (bi == b.end() || (ai != a.end() && ai->first < bi->first)) {
|
||||
return context(expected, c) + ai->first + " expected=" + ai->second + " actual=<absent>";
|
||||
}
|
||||
if (ai == a.end() || bi->first < ai->first) {
|
||||
return context(expected, c) + bi->first + " expected=<absent> actual=" + bi->second;
|
||||
}
|
||||
if (ai->second != bi->second) {
|
||||
return context(expected, c) + ai->first + " expected=" + ai->second + " actual=" + bi->second;
|
||||
}
|
||||
++ai; ++bi;
|
||||
}
|
||||
const auto mismatch = std::mismatch(left.begin(), left.end(), right.begin(), right.end());
|
||||
const auto offset = static_cast<std::size_t>(mismatch.first - left.begin());
|
||||
const auto byte = [offset](const std::string& bytes) {
|
||||
return offset < bytes.size() ? value(static_cast<unsigned char>(bytes[offset])) : "<end>";
|
||||
};
|
||||
return context(expected, c) + "byte=" + value(offset) + " expected=" + byte(left) + " actual=" + byte(right);
|
||||
}
|
||||
|
||||
inline std::string receipt_difference(const World& world, const PlayerCommand& command,
|
||||
CommandReceipt expected, CommandReceipt actual, const Context& c) {
|
||||
if (expected.status == actual.status && expected.tick == actual.tick && expected.revision == actual.revision) return {};
|
||||
const auto receipt = [](CommandReceipt r) {
|
||||
return "{status=" + value(r.status) + ",tick=" + value(r.tick) + ",revision=" + value(r.revision) + "}";
|
||||
};
|
||||
return context(world, c) + "command player=" + value(command.player) + " sequence=" + value(command.sequence) +
|
||||
" field=receipt expected=" + receipt(expected) + " actual=" + receipt(actual);
|
||||
}
|
||||
} // namespace replay_diagnostics
|
||||
+179
-17
@@ -1,10 +1,17 @@
|
||||
#include "settlement/core/world.hpp"
|
||||
#include "replay_diagnostics.hpp"
|
||||
#include <Void/Core/Scope.hpp>
|
||||
|
||||
#include <Void/Testing/Assert.hpp>
|
||||
#include <Void/Testing/Suite.hpp>
|
||||
|
||||
#include <algorithm>
|
||||
#include <array>
|
||||
#include <chrono>
|
||||
#include <condition_variable>
|
||||
#include <future>
|
||||
#include <iostream>
|
||||
#include <mutex>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <memory>
|
||||
@@ -38,7 +45,7 @@ void require(bool condition, std::string_view message) {
|
||||
|
||||
std::string saved_state(const World& world) {
|
||||
std::ostringstream stream(std::ios::binary);
|
||||
world.write_save(stream);
|
||||
world.write_save(stream, WorldSaveFormat::Current14);
|
||||
return stream.str();
|
||||
}
|
||||
|
||||
@@ -66,6 +73,7 @@ public:
|
||||
}
|
||||
|
||||
void step() {
|
||||
++attempt_;
|
||||
reference->step();
|
||||
for (auto& run : runs_) run.world->step();
|
||||
compare();
|
||||
@@ -75,9 +83,10 @@ public:
|
||||
std::uint64_t expected_tick, std::uint64_t expected_revision) {
|
||||
const auto check = [&](World& world) {
|
||||
const auto result = world.apply_command(command);
|
||||
require(result.status == expected_status && result.tick == expected_tick &&
|
||||
result.revision == expected_revision,
|
||||
"command receipt differs from the recorded status, tick or revision");
|
||||
const auto diagnostic = replay_diagnostics::receipt_difference(world, command,
|
||||
{expected_status, expected_tick, expected_revision}, result,
|
||||
{attempt_, world.worker_count(), "journal", "command", options_.max_admitted});
|
||||
require(diagnostic.empty(), diagnostic);
|
||||
};
|
||||
check(*reference);
|
||||
for (auto& run : runs_) check(*run.world);
|
||||
@@ -102,28 +111,23 @@ private:
|
||||
};
|
||||
|
||||
void compare() const {
|
||||
const auto expected = saved_state(*reference);
|
||||
for (const auto& run : runs_) {
|
||||
const auto actual = saved_state(*run.world);
|
||||
if (actual == expected) continue;
|
||||
const auto mismatch = std::mismatch(expected.begin(), expected.end(), actual.begin(), actual.end());
|
||||
const auto offset = static_cast<std::size_t>(mismatch.first - expected.begin());
|
||||
throw std::runtime_error("replay diverged at tick " + std::to_string(reference->tick()) +
|
||||
", workers " + std::to_string(run.config.workers) +
|
||||
(run.reloaded ? ", reloaded" : ", uninterrupted") +
|
||||
", byte " + std::to_string(offset) +
|
||||
", path searches " + std::to_string(reference->path_searches()) + "/" +
|
||||
std::to_string(run.world->path_searches()) + ", path nodes " +
|
||||
std::to_string(reference->path_nodes_visited()) + "/" +
|
||||
std::to_string(run.world->path_nodes_visited()));
|
||||
const auto diagnostic = replay_diagnostics::difference(*reference, *run.world,
|
||||
{attempt_, run.config.workers, "uncontrolled", run.reloaded ? "reloaded" : "uninterrupted",
|
||||
options_.max_admitted});
|
||||
require(diagnostic.empty(), diagnostic);
|
||||
}
|
||||
}
|
||||
|
||||
std::uint64_t attempt_ = 0;
|
||||
|
||||
WorkerPoolOptions options_;
|
||||
std::vector<Run> runs_;
|
||||
};
|
||||
|
||||
struct [[= Void::Testing::name("ReplayTests")]] ReplayTests : Void::Testing::Suite<ReplayTests> {
|
||||
[[= Void::Testing::tag("replay")]] Test test_opposite_real_completion_orders();
|
||||
[[= Void::Testing::tag("replay")]] Test test_semantic_divergence_diagnostics();
|
||||
[[= Void::Testing::tag("replay")]] Test test_execution_configuration_and_empty_world();
|
||||
[[= Void::Testing::tag("replay")]] Test test_one_resident_completes_work();
|
||||
[[= Void::Testing::tag("replay")]] Test test_competing_jobs_retry_unreachable_routes();
|
||||
@@ -132,6 +136,164 @@ struct [[= Void::Testing::name("ReplayTests")]] ReplayTests : Void::Testing::Sui
|
||||
[[= Void::Testing::tag("replay")]] Test test_last_meal_has_one_winner_and_one_consumer();
|
||||
};
|
||||
|
||||
// The driver is the test thread, separate from World::step's coordinator:
|
||||
// capacity one can run submission 1 inline while submission 0 is held.
|
||||
struct CompletionGate {
|
||||
std::mutex mutex;
|
||||
std::condition_variable changed;
|
||||
std::array<bool, 2> entered{}, permitted{};
|
||||
std::vector<std::size_t> completed;
|
||||
bool released = false;
|
||||
|
||||
void before(std::size_t index) {
|
||||
if (index > 1) return;
|
||||
std::unique_lock lock(mutex);
|
||||
entered[index] = true;
|
||||
changed.notify_all();
|
||||
if (!changed.wait_for(lock, std::chrono::seconds(5), [&] { return released || permitted[index]; })) {
|
||||
throw std::runtime_error("completion gate release timeout");
|
||||
}
|
||||
}
|
||||
void after(std::size_t index) {
|
||||
if (index > 1) return;
|
||||
std::lock_guard lock(mutex);
|
||||
completed.push_back(index);
|
||||
changed.notify_all();
|
||||
}
|
||||
void drive(std::size_t first) {
|
||||
std::unique_lock lock(mutex);
|
||||
require(changed.wait_for(lock, std::chrono::seconds(5), [&] { return entered[0] && entered[1]; }),
|
||||
"both real calculations did not enter");
|
||||
require(completed.empty(), "a calculation completed before its gate was released");
|
||||
permitted[first] = true;
|
||||
changed.notify_all();
|
||||
require(changed.wait_for(lock, std::chrono::seconds(5), [&] { return !completed.empty(); }),
|
||||
"first real calculation did not return");
|
||||
require(completed == std::vector<std::size_t>{first}, "completion order was not forced");
|
||||
permitted[1 - first] = true;
|
||||
changed.notify_all();
|
||||
}
|
||||
void release() {
|
||||
std::lock_guard lock(mutex);
|
||||
released = true;
|
||||
changed.notify_all();
|
||||
}
|
||||
};
|
||||
|
||||
Test ReplayTests::test_opposite_real_completion_orders() {
|
||||
for (bool meal : {false, true}) {
|
||||
World initial(meal ? 97 : 101, 8, 8, 1, ExecutionMode::SerialReference);
|
||||
const auto winner = initial.spawn_agent({5, 1});
|
||||
static_cast<void>(initial.spawn_agent({5, 1}));
|
||||
JobId job = 0;
|
||||
if (meal) {
|
||||
const auto pantry = initial.add_storage({1, 1}, 1, StorageKind::Pantry);
|
||||
initial.enable_hunger();
|
||||
for (std::uint16_t tick = 0; tick < hunger_threshold; ++tick) initial.step();
|
||||
initial.stock_storage(pantry, ItemType::Berries, 1);
|
||||
} else {
|
||||
job = initial.add_job({1, 1}, 3);
|
||||
}
|
||||
const auto fixture = saved_state(initial);
|
||||
for (auto workers : {2U, 6U, 12U}) for (auto capacity : {4096U, 1U}) for (auto first : {0U, 1U}) {
|
||||
CompletionGate gate;
|
||||
WorkerPoolOptions options{.max_admitted = capacity};
|
||||
options.before_execute = [&](std::size_t index) { gate.before(index); };
|
||||
options.after_execute = [&](std::size_t index) { gate.after(index); };
|
||||
auto reference = load_state(fixture, execution_configs.front());
|
||||
auto candidate = load_state(fixture, {workers, ExecutionMode::Parallel}, std::move(options));
|
||||
auto step = std::async(std::launch::async, [&] { candidate->step(); });
|
||||
// Always release before joining the coordinator, including assertion failure.
|
||||
auto release = Void::Scope::on_exit([&] { gate.release(); });
|
||||
gate.drive(first);
|
||||
gate.release();
|
||||
require(step.wait_for(std::chrono::seconds(5)) == std::future_status::ready, "world step did not drain");
|
||||
step.get();
|
||||
require(gate.completed == std::vector<std::size_t>{first, 1 - first}, "wrong actual return trace");
|
||||
const std::string schedule = first == 0 ? "A->B" : "B->A";
|
||||
std::cout << "actual " << (meal ? "meal movement" : "job choices") << " workers=" << workers
|
||||
<< " capacity=" << capacity << " completions=" << schedule << '\n';
|
||||
for (std::uint64_t attempt = 1; attempt <= 40; ++attempt) {
|
||||
reference->step();
|
||||
const auto diagnostic = replay_diagnostics::difference(*reference, *candidate,
|
||||
{attempt, workers, schedule, "fixture", capacity});
|
||||
require(diagnostic.empty(), diagnostic);
|
||||
if (attempt == 1) {
|
||||
require(candidate->agents()[0].id == winner, "fixture IDs changed");
|
||||
if (meal) {
|
||||
require(candidate->agents()[0].state == AgentState::GoingToEat &&
|
||||
candidate->agents()[1].state == AgentState::Idle,
|
||||
"serial meal claim lost its stable winner");
|
||||
} else {
|
||||
require(candidate->agents()[0].current_job == job && candidate->agents()[1].current_job == 0,
|
||||
"competing real calculations changed the lower-ID winner");
|
||||
}
|
||||
}
|
||||
if (meal) {
|
||||
const auto& agents = candidate->agents();
|
||||
require(candidate->storages()[0].item_count(ItemType::Berries) +
|
||||
agents[0].inventory.item_count(ItemType::Berries) + agents[1].inventory.item_count(ItemType::Berries) +
|
||||
candidate->meals_eaten() == 1, "meal duplicated or lost");
|
||||
require(agents[1].inventory.empty() && agents[1].state != AgentState::GoingToEat &&
|
||||
agents[1].state != AgentState::Eating, "second resident consumed reserved meal");
|
||||
}
|
||||
if (attempt != 40) candidate->step();
|
||||
}
|
||||
require(meal ? candidate->meals_eaten() == 1 : candidate->jobs_completed() == 1,
|
||||
"the sole job or meal did not finish exactly once");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Test ReplayTests::test_semantic_divergence_diagnostics() {
|
||||
const replay_diagnostics::Context context{7, 6, "B->A", "checkpoint", 1};
|
||||
World expected(103, 8, 8, 1, ExecutionMode::SerialReference);
|
||||
const auto storage = expected.add_storage({1, 1}, 20);
|
||||
expected.stock_storage(storage, ItemType::Wood, 2);
|
||||
const auto job = expected.add_job({4, 4}, 2);
|
||||
const auto fixture = saved_state(expected);
|
||||
auto actual = load_state(fixture, execution_configs.front());
|
||||
require(replay_diagnostics::difference(expected, *actual, context).empty(), "equal worlds reported divergence");
|
||||
actual->stock_storage(storage, ItemType::Wood, 1);
|
||||
auto report = replay_diagnostics::difference(expected, *actual, context);
|
||||
require(report.find("stock owner=storage:" + std::to_string(storage)) != std::string::npos &&
|
||||
report.find("item=1 field=count expected=2 actual=3") != std::string::npos &&
|
||||
report.find("attempt=7 seed=103 workers=6 schedule=B->A load=checkpoint capacity=1") != std::string::npos,
|
||||
"stock diagnostic omitted context or identity: " + report);
|
||||
actual = load_state(fixture, execution_configs.front());
|
||||
// These are deliberate diagnostic inputs built by public domain operations.
|
||||
World changed_job(103, 8, 8, 1, ExecutionMode::SerialReference);
|
||||
const auto matching = changed_job.add_storage({1, 1}, 20);
|
||||
changed_job.stock_storage(matching, ItemType::Wood, 2);
|
||||
static_cast<void>(changed_job.add_job({4, 4}, 3));
|
||||
report = replay_diagnostics::difference(expected, changed_job, context);
|
||||
require(report.find("job id=" + std::to_string(job)) != std::string::npos &&
|
||||
report.find("field=work_remaining expected=2 actual=3") != std::string::npos,
|
||||
"job diagnostic omitted identity: " + report);
|
||||
auto command_world = make_first_colony(2);
|
||||
auto command_copy = load_state(saved_state(*command_world), execution_configs.front());
|
||||
const PlayerCommand command{1, 1, CommandKind::SetPaused, {}, 1};
|
||||
const auto receipt = command_copy->apply_command(command);
|
||||
report = replay_diagnostics::difference(*command_world, *command_copy, context);
|
||||
require(report.find("command player=1 field=next_sequence expected=1 actual=2") != std::string::npos,
|
||||
"command diagnostic omitted player and sequence: " + report);
|
||||
report = replay_diagnostics::receipt_difference(*command_copy, command,
|
||||
{CommandStatus::Accepted, 0, 0}, receipt, context);
|
||||
require(report.find("command player=1 sequence=1 field=receipt") != std::string::npos &&
|
||||
report.find("revision=0") != std::string::npos && report.find("revision=1") != std::string::npos,
|
||||
"receipt diagnostic omitted revision: " + report);
|
||||
require(replay_diagnostics::receipt_difference(*command_copy, command, receipt, receipt, context).empty(),
|
||||
"equal receipts reported divergence");
|
||||
// An absent entity and a private field exercise identity and byte fallbacks.
|
||||
static_cast<void>(actual->add_job({6, 6}, 1));
|
||||
require(replay_diagnostics::difference(expected, *actual).find("job id=2") != std::string::npos,
|
||||
"extra entity lost stable identity");
|
||||
actual = load_state(fixture, execution_configs.front());
|
||||
actual->set_blocked({7, 7});
|
||||
require(replay_diagnostics::difference(expected, *actual).find("byte=") != std::string::npos,
|
||||
"unprojected canonical field lost byte fallback");
|
||||
}
|
||||
|
||||
Test ReplayTests::test_execution_configuration_and_empty_world() {
|
||||
World initial(20261202, 5, 5);
|
||||
const auto bytes = saved_state(initial);
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
#include "settlement/core/simulation_runtime.hpp"
|
||||
#include "replay_diagnostics.hpp"
|
||||
#include <Void/Core/Scope.hpp>
|
||||
#include <Void/Testing/Assert.hpp>
|
||||
#include <Void/Testing/Suite.hpp>
|
||||
@@ -98,6 +99,7 @@ void command_observer(CommandMutationPhase phase) {
|
||||
}
|
||||
|
||||
struct [[= Void::Testing::name("RuntimeTests")]] RuntimeTests : Void::Testing::Suite<RuntimeTests> {
|
||||
[[= Void::Testing::tag("runtime")]] Test test_queued_same_save_install_drains_old_world();
|
||||
[[= Void::Testing::tag("runtime")]] Test test_fixed_clock_matches_reference_and_suspend_discards_idle_time();
|
||||
[[= Void::Testing::tag("runtime")]] Test test_paused_commands_publish_and_two_clients_replay_exact_results();
|
||||
[[= Void::Testing::tag("runtime")]] Test test_readers_and_save_capture_progress_during_real_worker_tick();
|
||||
@@ -110,6 +112,69 @@ struct [[= Void::Testing::name("RuntimeTests")]] RuntimeTests : Void::Testing::S
|
||||
[[= Void::Testing::tag("runtime")]] Test test_exhausted_clock_faults_without_spinning();
|
||||
};
|
||||
|
||||
Test RuntimeTests::test_queued_same_save_install_drains_old_world() {
|
||||
auto gate = std::make_shared<Gate>();
|
||||
auto clock = std::make_shared<Void::Time::ManualClock>();
|
||||
std::atomic<std::size_t> started{0}, completed{0};
|
||||
std::atomic<bool> install_saw_drained{false};
|
||||
WorkerPoolOptions workers;
|
||||
workers.before_execute = [&](std::size_t index) {
|
||||
++started;
|
||||
if (index == 0) gate->block();
|
||||
};
|
||||
workers.after_execute = [&](std::size_t) { ++completed; };
|
||||
RuntimeOptions options{.clock = clock};
|
||||
options.observer = [&](RuntimePhase phase) {
|
||||
if (phase == RuntimePhase::BeforeInstallCapture) {
|
||||
install_saw_drained = started.load() >= 2 && started.load() == completed.load();
|
||||
}
|
||||
};
|
||||
auto replacement = colony();
|
||||
const auto replacement_bytes = replay_diagnostics::canonical(*replacement.world);
|
||||
SimulationRuntime runtime(colony(2, std::move(workers)), std::move(options));
|
||||
auto release = Void::Scope::on_exit([&] { gate->release(); });
|
||||
const auto old_view = runtime.latest();
|
||||
const auto old_bytes = replay_diagnostics::canonical(*old_view->world);
|
||||
const auto stale_command = envelope(*old_view, 1, CommandKind::SetPaused, 1);
|
||||
require(clock->advance(50ms).has_value());
|
||||
runtime.notify_clock();
|
||||
gate->wait();
|
||||
const auto ticket = runtime.begin_load();
|
||||
require(ticket.has_value());
|
||||
auto installing = admitted([&] { return runtime.try_install(*ticket, replacement); });
|
||||
require(installing.admission == RuntimeAdmission::Accepted && !replacement.world);
|
||||
auto stale = admitted([&] { return runtime.try_submit(host, stale_command); });
|
||||
require(stale.admission == RuntimeAdmission::Accepted);
|
||||
require(installing.completion.wait_for(0s) == std::future_status::timeout);
|
||||
require(stale.completion.wait_for(0s) == std::future_status::timeout);
|
||||
require(!install_saw_drained && started.load() > completed.load());
|
||||
require(runtime.latest() == old_view);
|
||||
require(runtime.snapshot_for_save().value() == old_view);
|
||||
require(replay_diagnostics::canonical(*old_view->world) == old_bytes);
|
||||
gate->release();
|
||||
const auto installed = finished(std::move(installing));
|
||||
require(installed.outcome == RuntimeOutcome::Completed && install_saw_drained);
|
||||
require(installed.snapshot->identity.world == old_view->identity.world);
|
||||
require(installed.snapshot->identity.session != old_view->identity.session);
|
||||
require(installed.snapshot->world->tick() == 0);
|
||||
const auto rejected = finished(std::move(stale));
|
||||
require(rejected.receipt && rejected.receipt->status == DispatchStatus::StaleSession);
|
||||
const auto drained_count = completed.load();
|
||||
require(fence(runtime).outcome == RuntimeOutcome::Completed);
|
||||
require(runtime.latest() == installed.snapshot);
|
||||
require(replay_diagnostics::canonical(*runtime.latest()->world) == replacement_bytes);
|
||||
require(replay_diagnostics::canonical(*old_view->world) == old_bytes);
|
||||
require(completed.load() == drained_count && started.load() == completed.load());
|
||||
auto serial = colony(1);
|
||||
serial.world->step();
|
||||
require(clock->advance(50ms).has_value());
|
||||
require(fence(runtime).outcome == RuntimeOutcome::Completed);
|
||||
const auto diagnostic = replay_diagnostics::difference(*serial.world, *runtime.latest()->world,
|
||||
{1, 2, "old-worker-held", "same-save-replacement", 4096});
|
||||
if (!diagnostic.empty()) throw std::runtime_error(diagnostic);
|
||||
require(completed.load() == drained_count);
|
||||
}
|
||||
|
||||
Test RuntimeTests::test_fixed_clock_matches_reference_and_suspend_discards_idle_time() {
|
||||
for (const auto workers : {1U, 2U, 6U, 12U}) {
|
||||
auto clock = std::make_shared<Void::Time::ManualClock>();
|
||||
|
||||
@@ -113,7 +113,7 @@ Test SnapshotTests::test_mid_delivery_and_paused_command_state_survives_owner()
|
||||
source->step();
|
||||
carrying = source->assignment_path_cache_hits() > 0 &&
|
||||
std::any_of(source->agents().begin(), source->agents().end(), [](const Agent& agent) {
|
||||
return !agent.inventory.empty() && agent.production_index != no_entity_index;
|
||||
return !agent.inventory.empty() && agent.production_id != 0;
|
||||
});
|
||||
}
|
||||
require(carrying);
|
||||
|
||||
@@ -0,0 +1,325 @@
|
||||
// Exercise the real two-window handlers without an alternate rendering path.
|
||||
#define SETTLEMENT_FRAME_TEST
|
||||
#include "../app/viewer_win32.cpp"
|
||||
#include <d3d11.h>
|
||||
#include <atomic>
|
||||
#include <condition_variable>
|
||||
#include <cstdio>
|
||||
#include <mutex>
|
||||
#include <sstream>
|
||||
|
||||
using namespace std::chrono_literals;
|
||||
namespace {
|
||||
bool probe_device(D3D_DRIVER_TYPE driver) {
|
||||
ID3D11Device* device = nullptr;
|
||||
if (FAILED(D3D11CreateDevice(nullptr, driver, nullptr, 0, nullptr, 0,
|
||||
D3D11_SDK_VERSION, &device, nullptr, nullptr))) return false;
|
||||
IDXGIDevice* dxgi = nullptr;
|
||||
if (SUCCEEDED(device->QueryInterface(__uuidof(IDXGIDevice), reinterpret_cast<void**>(&dxgi)))) {
|
||||
IDXGIAdapter* adapter = nullptr;
|
||||
if (SUCCEEDED(dxgi->GetAdapter(&adapter))) {
|
||||
DXGI_ADAPTER_DESC desc{};
|
||||
if (SUCCEEDED(adapter->GetDesc(&desc))) std::printf("DEVICE %s: %ls\n",
|
||||
driver == D3D_DRIVER_TYPE_WARP ? "WARP" : "hardware", desc.Description);
|
||||
adapter->Release();
|
||||
}
|
||||
dxgi->Release();
|
||||
}
|
||||
device->Release(); return true;
|
||||
}
|
||||
void require_frame(bool value, const char* message) {
|
||||
if (!value) throw std::runtime_error(message);
|
||||
}
|
||||
struct Gate {
|
||||
std::mutex mutex;
|
||||
std::condition_variable changed;
|
||||
bool entered = false, released = false;
|
||||
void block() {
|
||||
std::unique_lock lock(mutex);
|
||||
entered = true; changed.notify_all();
|
||||
if (!changed.wait_for(lock, 30s, [&] { return released; })) throw std::runtime_error("gate deadline");
|
||||
}
|
||||
void wait() {
|
||||
std::unique_lock lock(mutex);
|
||||
require_frame(changed.wait_for(lock, 10s, [&] { return entered; }), "gate did not enter");
|
||||
}
|
||||
void release() { std::lock_guard lock(mutex); released = true; changed.notify_all(); }
|
||||
};
|
||||
template<class Predicate> void wait_for_frame(Predicate done) {
|
||||
const auto deadline = std::chrono::steady_clock::now() + 10s;
|
||||
while (!done()) {
|
||||
require_frame(std::chrono::steady_clock::now() < deadline, "frame wait deadline");
|
||||
std::this_thread::yield();
|
||||
}
|
||||
}
|
||||
std::string canonical(const settlement::World& value) {
|
||||
std::ostringstream stream(std::ios::binary);
|
||||
value.write_save(stream, settlement::WorldSaveFormat::Current14);
|
||||
return stream.str();
|
||||
}
|
||||
void frame_only(HWND window) {
|
||||
SendMessageW(window, WM_TIMER, frame_timer_id, 0);
|
||||
UpdateWindow(window);
|
||||
if (scene_window) UpdateWindow(scene_window);
|
||||
}
|
||||
void event_and_frame(HWND window) {
|
||||
SendMessageW(window, WM_TIMER, timer_id, 0);
|
||||
frame_only(window);
|
||||
}
|
||||
std::vector<std::uint32_t> capture_frame(settlement::viewer::D3DScene& renderer,
|
||||
const std::shared_ptr<const PreparedFrame>& frame) {
|
||||
std::vector<std::uint32_t> pixels;
|
||||
require_frame(frame && frame->content && renderer.render(frame->content->geometry, frame->view, &pixels), "capture frame");
|
||||
return pixels;
|
||||
}
|
||||
void drag(HWND window, bool left, int dx, int dy) {
|
||||
const auto start = MAKELPARAM(420, 220), finish = MAKELPARAM(420 + dx, 220 + dy);
|
||||
SendMessageW(window, left ? WM_LBUTTONDOWN : WM_MBUTTONDOWN, 0, start);
|
||||
SendMessageW(window, WM_MOUSEMOVE, left ? MK_LBUTTON : MK_MBUTTON, finish);
|
||||
SendMessageW(window, left ? WM_LBUTTONUP : WM_MBUTTONUP, 0, finish);
|
||||
}
|
||||
}
|
||||
|
||||
int main() {
|
||||
auto clock = std::make_shared<Void::Time::ManualClock>();
|
||||
auto worker = std::make_shared<Gate>(), writer = std::make_shared<Gate>(), installer = std::make_shared<Gate>();
|
||||
auto reader = std::make_shared<Gate>();
|
||||
std::atomic<bool> block_worker{false}, block_install{false}, block_reader{false};
|
||||
std::atomic<DWORD> worker_thread{0};
|
||||
HWND window = nullptr;
|
||||
std::unique_ptr<settlement::SaveService> saves;
|
||||
wchar_t temporary[MAX_PATH]{}; GetTempPathW(MAX_PATH, temporary);
|
||||
const auto folder = std::filesystem::path(temporary) / (L"settlement-frames-" + std::to_wstring(GetCurrentProcessId()));
|
||||
std::filesystem::create_directories(folder);
|
||||
SetEnvironmentVariableW(L"LOCALAPPDATA", folder.c_str());
|
||||
try {
|
||||
auto colony = settlement::make_first_colony(2);
|
||||
std::istringstream input(canonical(*colony), std::ios::binary);
|
||||
settlement::WorkerPoolOptions workers;
|
||||
workers.before_execute = [&](std::size_t) {
|
||||
if (block_worker.exchange(false)) { worker_thread = GetCurrentThreadId(); worker->block(); }
|
||||
};
|
||||
auto owned = settlement::World::read_save(input, 2, settlement::ExecutionMode::Parallel, std::move(workers));
|
||||
auto id = Void::Uuid::try_v4(); auto rules = settlement::default_rules_manifest();
|
||||
require_frame(id.has_value() && rules.has_value(), "fixture identity/rules");
|
||||
settlement::viewer::ViewerSessionOptions options;
|
||||
options.runtime.clock = clock;
|
||||
options.runtime.observer = [&](settlement::RuntimePhase phase) {
|
||||
if (phase == settlement::RuntimePhase::BeforeInstallCapture && block_install.exchange(false)) installer->block();
|
||||
};
|
||||
options.files.read_observer = [&](settlement::CheckpointReadPhase phase) {
|
||||
if (phase == settlement::CheckpointReadPhase::BeforeRead && block_reader.exchange(false)) reader->block();
|
||||
};
|
||||
session = std::make_unique<settlement::viewer::ViewerSession>(
|
||||
settlement::WorldCheckpoint{std::move(owned), *id, 1, *rules}, 2, std::move(options));
|
||||
INITCOMMONCONTROLSEX controls{sizeof(controls), ICC_LISTVIEW_CLASSES | ICC_BAR_CLASSES}; InitCommonControlsEx(&controls);
|
||||
WNDCLASSEXW klass{}; klass.cbSize = sizeof(klass); klass.hInstance = GetModuleHandleW(nullptr);
|
||||
klass.lpfnWndProc = window_proc; klass.lpszClassName = window_class;
|
||||
require_frame(RegisterClassExW(&klass) != 0, "register viewer");
|
||||
window = CreateWindowExW(0, window_class, L"Prepared frame regression", WS_OVERLAPPEDWINDOW | WS_CLIPCHILDREN,
|
||||
0, 0, 1120, 752, nullptr, nullptr, klass.hInstance, nullptr);
|
||||
require_frame(window != nullptr && scene_window != nullptr, "real main and scene windows");
|
||||
ShowWindow(window, SW_SHOW);
|
||||
KillTimer(window, timer_id); KillTimer(window, frame_timer_id); // Test drives each timer explicitly.
|
||||
world = session->world(); has_session = true; show_title_screen(window, false);
|
||||
const bool warp_device = probe_device(D3D_DRIVER_TYPE_WARP);
|
||||
const bool hardware_device = probe_device(D3D_DRIVER_TYPE_HARDWARE);
|
||||
if (!graphics.ready()) {
|
||||
require_frame(!warp_device && !hardware_device, "renderer failed despite available D3D device");
|
||||
std::puts("SKIP D3D11 hardware and WARP unavailable; real frame assertions require a backend");
|
||||
DestroyWindow(window); session.reset(); std::filesystem::remove_all(folder); return 77;
|
||||
}
|
||||
event_and_frame(window);
|
||||
require_frame(prepared_frame && prepared_frame->content && graphics.frames() > 0, "first real child render");
|
||||
settlement::viewer::D3DScene offscreen;
|
||||
const bool warp = offscreen.initialize(nullptr, true);
|
||||
if (!warp) {
|
||||
require_frame(!warp_device, "WARP renderer failed despite available device");
|
||||
require_frame(offscreen.initialize(nullptr), "offscreen hardware fallback");
|
||||
}
|
||||
std::printf("BACKEND offscreen %s; visible D3D11 swap chain\n", warp ? "WARP" : "hardware");
|
||||
// Ensure ticking has been admitted before holding an actual World worker.
|
||||
event_and_frame(window);
|
||||
auto sync = session->runtime().synchronize();
|
||||
require_frame(sync.admission == settlement::RuntimeAdmission::Accepted && sync.completion.wait_for(10s) == std::future_status::ready, "owner synchronized");
|
||||
event_and_frame(window);
|
||||
block_worker = true; require_frame(clock->advance(50ms).has_value(), "clock advance");
|
||||
session->runtime().notify_clock(); worker->wait();
|
||||
require_frame(worker_thread != GetCurrentThreadId(), "worker is not UI thread");
|
||||
const auto original = session->runtime().latest();
|
||||
const auto original_bytes = canonical(*original->world);
|
||||
auto encoded = settlement::encode_checkpoint(*original->world, original->identity.world, original->identity.city, *original->rules);
|
||||
require_frame(encoded.has_value(), "encode full snapshot");
|
||||
settlement::SaveServiceOptions save_options;
|
||||
save_options.fault_hook = [&](settlement::SavePhase phase) -> std::uint32_t {
|
||||
if (phase == settlement::SavePhase::WriteStage) writer->block();
|
||||
return 0;
|
||||
};
|
||||
saves = std::make_unique<settlement::SaveService>(std::move(save_options));
|
||||
const auto path = folder / L"held.settlement";
|
||||
auto saved = saves->try_submit({path, original->world->tick(), original->identity.session, [original] {
|
||||
auto bytes = settlement::encode_checkpoint(*original->world, original->identity.world, original->identity.city, *original->rules);
|
||||
if (!bytes) throw std::runtime_error("encode save");
|
||||
return *bytes;
|
||||
}});
|
||||
require_frame(saved.admission == settlement::SaveAdmission::Accepted, "writer admitted"); writer->wait();
|
||||
const auto initial = prepared_frame;
|
||||
const auto pixels = capture_frame(offscreen, initial);
|
||||
const auto uploads = graphics.uploads(), frames = graphics.frames();
|
||||
POINT anchor{420, 220}; ClientToScreen(window, &anchor);
|
||||
SendMessageW(window, WM_MOUSEWHEEL, MAKEWPARAM(0, WHEEL_DELTA), MAKELPARAM(anchor.x, anchor.y));
|
||||
frame_only(window);
|
||||
require_frame(prepared_frame->view.scale != initial->view.scale && graphics.frames() > frames, "frame timer alone presents wheel");
|
||||
require_frame(prepared_frame->content->geometry == initial->content->geometry && graphics.uploads() == uploads, "zoom reuses CPU/GPU geometry");
|
||||
require_frame(capture_frame(offscreen, prepared_frame) != pixels, "zoom changes rendered pixels");
|
||||
const auto before_drag = prepared_frame;
|
||||
drag(window, false, 35, 18); frame_only(window);
|
||||
require_frame(prepared_frame->view.origin_x != before_drag->view.origin_x, "middle drag changes frame");
|
||||
const auto before_left = prepared_frame;
|
||||
drag(window, true, -24, 16); frame_only(window);
|
||||
require_frame(prepared_frame->view.origin_y != before_left->view.origin_y, "left drag changes frame");
|
||||
require_frame(graphics.uploads() == uploads && prepared_frame->content->geometry == initial->content->geometry, "both drags reuse upload");
|
||||
const auto prior_building_view = prepared_frame->content->geometry;
|
||||
SendMessageW(window, WM_COMMAND, building_view_id, 0); frame_only(window);
|
||||
require_frame(prepared_frame->content->geometry != prior_building_view, "building visibility invalidates geometry");
|
||||
const auto stable_frames = graphics.frames();
|
||||
frame_only(window); frame_only(window);
|
||||
require_frame(graphics.frames() == stable_frames, "unchanged frame timer does no rendering");
|
||||
require_frame(session->runtime().latest() == original && canonical(*original->world) == original_bytes, "blocked world snapshot/tick unchanged");
|
||||
std::puts("PASS wheel and both real drags/rendered pixels while World worker and WriteStage held; frame timer independent; geometry/upload reused");
|
||||
|
||||
// Dirty work arriving inside a nested paint must survive the outer paint.
|
||||
bool nested = false;
|
||||
frame_test_during_paint = [&] {
|
||||
if (nested) return; nested = true;
|
||||
camera.pan(9, 0); invalidate_scene(window);
|
||||
SendMessageW(scene_window, WM_PAINT, 0, 0);
|
||||
};
|
||||
InvalidateRect(scene_window, nullptr, FALSE); UpdateWindow(scene_window);
|
||||
frame_test_during_paint = {};
|
||||
require_frame(frame_requests != sampled_request, "nested paint leaves dirty request pending");
|
||||
frame_only(window); require_frame(frame_requests == sampled_request, "next frame consumes nested dirty request");
|
||||
// An exposure paint can nest without changing camera or world content.
|
||||
frame_test_during_paint = [&] { SendMessageW(scene_window, WM_PAINT, 0, 0); };
|
||||
InvalidateRect(scene_window, nullptr, FALSE); UpdateWindow(scene_window);
|
||||
frame_test_during_paint = {};
|
||||
const auto exposed_frames = graphics.frames();
|
||||
frame_only(window);
|
||||
require_frame(graphics.frames() > exposed_frames, "nested unchanged exposure is repainted");
|
||||
// Owned overlay data and old geometry survive later edits/publications.
|
||||
blueprint.push_back({{6, 10}, settlement::RecipeId::BuildBed});
|
||||
room_blueprints.push_back({{20, 20}, {23, 23}, settlement::RoomSide::North});
|
||||
selected_resident = world->agents().front().id;
|
||||
invalidate_scene(window); frame_only(window);
|
||||
const auto overlay = prepared_frame;
|
||||
const auto old_pixels = capture_frame(offscreen, overlay);
|
||||
blueprint.clear(); room_blueprints.clear(); selected_resident.reset();
|
||||
invalidate_scene(window); frame_only(window);
|
||||
require_frame(prepared_frame->content->geometry != overlay->content->geometry, "overlay invalidates geometry");
|
||||
capture_frame(offscreen, prepared_frame);
|
||||
require_frame(capture_frame(offscreen, overlay) == old_pixels && overlay->view.blueprint.size() == 1 && overlay->view.room_blueprints.size() == 1,
|
||||
"retained old packet owns overlays and reuploads correct mesh");
|
||||
worker->release(); writer->release();
|
||||
require_frame(saved.completion.wait_for(10s) == std::future_status::ready && saved.completion.get().succeeded(), "held save completes");
|
||||
saves.reset();
|
||||
std::ifstream saved_file(path, std::ios::binary);
|
||||
const std::string saved_bytes{std::istreambuf_iterator<char>(saved_file), {}}; saved_file.close();
|
||||
require_frame(saved_bytes == *encoded, "saved bytes match full captured World and metadata");
|
||||
std::puts("PASS nested paints retain pending dirt; retained packet/overlays; saved full canonical World and checkpoint metadata");
|
||||
|
||||
// A real file reader can remain blocked while the old presentation moves.
|
||||
block_reader = true; handle_save_menu(window, false, path); reader->wait();
|
||||
const auto before_read = prepared_frame;
|
||||
drag(window, false, 12, 8); frame_only(window);
|
||||
require_frame(session->changing_world() && prepared_frame->content == before_read->content &&
|
||||
prepared_frame->view.origin_x != before_read->view.origin_x, "camera while file reader held");
|
||||
reader->release();
|
||||
std::puts("PASS real asynchronous file reader held while camera presents the prior packet");
|
||||
wait_for_frame([&] { event_and_frame(window); return !session->changing_world(); });
|
||||
|
||||
// Deterministically publish between poll_changes' not-ready check and
|
||||
// pump_session's world fetch, including nested paints in that interval.
|
||||
auto install_race = [&](bool absent) {
|
||||
installer = std::make_shared<Gate>(); block_install = true;
|
||||
if (absent) { world.reset(); prepared_frame.reset(); }
|
||||
const auto prior_world = world;
|
||||
const auto prior_frame = prepared_frame;
|
||||
session->new_colony();
|
||||
event_and_frame(window); installer->wait();
|
||||
const auto prior_session = session->runtime().latest()->identity.session;
|
||||
bool injected = false;
|
||||
frame_test_after_poll = [&] {
|
||||
if (injected) return; injected = true;
|
||||
require_frame(session->changing_world(), "poll still changing before install completion");
|
||||
installer->release();
|
||||
wait_for_frame([&] { return session->runtime().latest()->identity.session != prior_session; });
|
||||
SendMessageW(window, WM_PAINT, 0, 0);
|
||||
SendMessageW(scene_window, WM_PAINT, 0, 0);
|
||||
};
|
||||
SendMessageW(window, WM_TIMER, timer_id, 0);
|
||||
frame_test_after_poll = {};
|
||||
frame_only(window);
|
||||
require_frame(world == prior_world, "pre-Replaced published candidate must not escape, including null");
|
||||
require_frame(!prepared_frame->content || (prior_frame && prepared_frame->content == prior_frame->content), "old presentation content remains pinned");
|
||||
wait_for_frame([&] { event_and_frame(window); return !session->changing_world(); });
|
||||
require_frame(world == session->world() && prepared_frame->content->world == world &&
|
||||
blueprint.empty() && room_blueprints.empty() && !selected_resident && camera.scale() == 1.0, "Replaced clears overlays/selection/camera before release");
|
||||
};
|
||||
install_race(false); install_race(true);
|
||||
std::puts("PASS real publication race after poll/not-ready, nested main/child paints, old/null fence and Replaced reset");
|
||||
|
||||
const auto visible = prepared_frame;
|
||||
const auto visible_frames = graphics.frames();
|
||||
ShowWindow(window, SW_HIDE); drag(window, false, 10, 10); frame_only(window);
|
||||
require_frame(prepared_frame == visible && graphics.frames() == visible_frames, "hidden suppresses preparation/render");
|
||||
const auto hidden_command = session->submit(settlement::CommandPayload{settlement::CommandKind::SetPriority, {}, 2});
|
||||
require_frame(hidden_command.has_value(), "hidden command admitted");
|
||||
wait_for_frame([&] { event_and_frame(window); return !session->pending(*hidden_command); });
|
||||
require_frame(prepared_frame == visible && world != visible->content->world, "hidden retains packet while world publishes");
|
||||
ShowWindow(window, SW_SHOW); frame_only(window);
|
||||
require_frame(prepared_frame->content->world == world, "restore presents latest accepted snapshot");
|
||||
ShowWindow(window, SW_MINIMIZE); const auto minimized = prepared_frame;
|
||||
invalidate_scene(window); frame_only(window);
|
||||
require_frame(prepared_frame == minimized, "minimized suppresses preparation");
|
||||
ShowWindow(window, SW_RESTORE); frame_only(window);
|
||||
show_title_screen(window, true); const auto title_frame = prepared_frame;
|
||||
invalidate_scene(window); frame_only(window); require_frame(prepared_frame == title_frame, "title suppresses preparation");
|
||||
show_title_screen(window, false); frame_only(window);
|
||||
const auto restore = prepared_frame;
|
||||
const auto size_uploads = graphics.uploads();
|
||||
SetWindowPos(window, nullptr, 0, 0, 1200, 800, SWP_NOMOVE | SWP_NOZORDER); frame_only(window);
|
||||
require_frame(prepared_frame->content->geometry == restore->content->geometry && graphics.uploads() > size_uploads, "resize reuses CPU mesh and invalidates upload");
|
||||
const auto zero_frames = graphics.frames();
|
||||
SetWindowPos(scene_window, nullptr, 0, map_top, 0, 0, SWP_NOZORDER);
|
||||
InvalidateRect(scene_window, nullptr, FALSE); SendMessageW(scene_window, WM_PAINT, 0, 0);
|
||||
require_frame(graphics.frames() == zero_frames, "zero-sized real viewport suppresses render");
|
||||
layout_scene(window); frame_only(window);
|
||||
auto zero_view = prepared_frame->view; zero_view.height = 0;
|
||||
require_frame(!offscreen.render(prepared_frame->content->geometry, zero_view), "zero viewport rejected");
|
||||
auto bad_frame = std::make_shared<PreparedFrame>(*prepared_frame); bad_frame->view.height = 0;
|
||||
prepared_frame = bad_frame;
|
||||
InvalidateRect(scene_window, nullptr, FALSE); UpdateWindow(scene_window);
|
||||
frame_only(window);
|
||||
require_frame(!graphics.ready() && !prepared_frame->backend_ready, "render failure reaches current error HUD");
|
||||
show_title_screen(window, true); show_title_screen(window, false); frame_only(window);
|
||||
require_frame(graphics.ready() && prepared_frame->backend_ready, "menu retry recovers backend");
|
||||
const auto reset_uploads = offscreen.uploads();
|
||||
offscreen.reset(); require_frame(offscreen.initialize(nullptr, warp), "recreate offscreen backend");
|
||||
require_frame(capture_frame(offscreen, overlay) == old_pixels && offscreen.uploads() > reset_uploads, "backend reset reuploads retained packet");
|
||||
std::puts("PASS hidden/minimized/title/restore, resize, zero viewport, error HUD/recovery and backend reset");
|
||||
const auto final_frames = graphics.frames();
|
||||
frame_test_during_paint = [&] { DestroyWindow(window); };
|
||||
InvalidateRect(scene_window, nullptr, FALSE); UpdateWindow(scene_window);
|
||||
frame_test_during_paint = {};
|
||||
window_proc(window, WM_TIMER, frame_timer_id, 0); window_proc(window, WM_TIMER, timer_id, 0);
|
||||
require_frame(viewer_destroyed && !prepared_frame && !graphics.ready() && graphics.frames() == final_frames, "queued timers after destruction ignored");
|
||||
window = nullptr; session.reset(); std::filesystem::remove_all(folder);
|
||||
std::puts("PASS destruction and queued timers; no physical refresh-rate claim");
|
||||
return 0;
|
||||
} catch (const std::exception& error) {
|
||||
frame_test_after_poll = {}; frame_test_during_paint = {};
|
||||
worker->release(); writer->release(); installer->release(); reader->release();
|
||||
saves.reset(); if (window) DestroyWindow(window); session.reset();
|
||||
std::fprintf(stderr, "FAIL %s\n", error.what()); return 1;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,547 @@
|
||||
#include "viewer_session.hpp"
|
||||
|
||||
#include <Void/Core/Scope.hpp>
|
||||
#include <Void/Testing/Assert.hpp>
|
||||
#include <Void/Testing/Suite.hpp>
|
||||
|
||||
#include <atomic>
|
||||
#include <algorithm>
|
||||
#include <chrono>
|
||||
#include <condition_variable>
|
||||
#include <fstream>
|
||||
#include <mutex>
|
||||
#include <sstream>
|
||||
#include <thread>
|
||||
|
||||
namespace {
|
||||
using namespace settlement;
|
||||
using namespace settlement::viewer;
|
||||
using namespace std::chrono_literals;
|
||||
using Void::Testing::require;
|
||||
using Void::Testing::Test;
|
||||
|
||||
struct TempFiles {
|
||||
std::filesystem::path root;
|
||||
TempFiles() {
|
||||
const auto id = Void::Uuid::try_v4();
|
||||
require(id.has_value());
|
||||
root = std::filesystem::temp_directory_path() /
|
||||
("settlement-client-" + id->to_string());
|
||||
require(std::filesystem::create_directory(root));
|
||||
}
|
||||
~TempFiles() {
|
||||
std::error_code error;
|
||||
std::filesystem::remove_all(root, error);
|
||||
}
|
||||
};
|
||||
|
||||
struct Gate {
|
||||
std::mutex mutex;
|
||||
std::condition_variable changed;
|
||||
bool entered = false;
|
||||
bool released = false;
|
||||
void hold() {
|
||||
std::unique_lock lock(mutex);
|
||||
entered = true;
|
||||
changed.notify_all();
|
||||
if (!changed.wait_for(lock, 5s, [&] { return released; })) throw std::runtime_error("gate timeout");
|
||||
}
|
||||
void wait() {
|
||||
std::unique_lock lock(mutex);
|
||||
require(changed.wait_for(lock, 5s, [&] { return entered; }));
|
||||
}
|
||||
void release() {
|
||||
std::lock_guard lock(mutex);
|
||||
released = true;
|
||||
changed.notify_all();
|
||||
}
|
||||
};
|
||||
|
||||
std::string bytes(const World& world) {
|
||||
std::ostringstream stream(std::ios::binary);
|
||||
world.write_save(stream);
|
||||
return stream.str();
|
||||
}
|
||||
|
||||
void write(const std::filesystem::path& path, std::string_view contents) {
|
||||
std::ofstream file(path, std::ios::binary);
|
||||
file.write(contents.data(), static_cast<std::streamsize>(contents.size()));
|
||||
file.close();
|
||||
require(file.good());
|
||||
}
|
||||
|
||||
template<class Predicate>
|
||||
std::vector<ViewerEvent> pump_until(ViewerSession& session, Predicate done) {
|
||||
const auto deadline = std::chrono::steady_clock::now() + 5s;
|
||||
std::vector<ViewerEvent> events;
|
||||
while (!done(events)) {
|
||||
auto current = session.poll();
|
||||
for (auto& event : current) events.push_back(std::move(event));
|
||||
require(std::chrono::steady_clock::now() < deadline);
|
||||
std::this_thread::yield();
|
||||
}
|
||||
return events;
|
||||
}
|
||||
|
||||
bool has(const std::vector<ViewerEvent>& events, ViewerEventKind kind) {
|
||||
return std::any_of(events.begin(), events.end(), [kind](const auto& event) { return event.kind == kind; });
|
||||
}
|
||||
|
||||
void flush_owner(ViewerSession& session) {
|
||||
for (;;) {
|
||||
auto sync = session.runtime().synchronize();
|
||||
if (sync.admission == RuntimeAdmission::Busy) {
|
||||
std::this_thread::yield();
|
||||
continue;
|
||||
}
|
||||
require(sync.admission == RuntimeAdmission::Accepted);
|
||||
require(sync.completion.wait_for(5s) == std::future_status::ready);
|
||||
require(sync.completion.get().outcome == RuntimeOutcome::Completed);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
struct [[= Void::Testing::name("ViewerSessionTests")]] ViewerSessionTests : Void::Testing::Suite<ViewerSessionTests> {
|
||||
[[= Void::Testing::tag("viewer-session")]] Test test_commands_wait_for_commit_and_keep_rejected_drafts_retryable();
|
||||
[[= Void::Testing::tag("viewer-session")]] Test test_long_tick_allows_reset_without_joining_and_fences_old_intents();
|
||||
[[= Void::Testing::tag("viewer-session")]] Test test_title_load_and_later_failed_load_supersede_old_preparation();
|
||||
[[= Void::Testing::tag("viewer-session")]] Test test_unsupported_profile_and_dimensions_keep_current_world();
|
||||
[[= Void::Testing::tag("viewer-session")]] Test test_save_keeps_captured_session_across_reset();
|
||||
[[= Void::Testing::tag("viewer-session")]] Test test_guest_view_is_read_only_and_leave_installs_received_world();
|
||||
[[= Void::Testing::tag("viewer-session")]] Test test_runtime_busy_keeps_the_same_intent_until_commit();
|
||||
[[= Void::Testing::tag("viewer-session")]] Test test_initial_candidate_requires_supported_rules_and_dimensions();
|
||||
[[= Void::Testing::tag("viewer-session")]] Test test_fault_retains_view_and_explicit_load_recovers();
|
||||
[[= Void::Testing::tag("viewer-session")]] Test test_failed_guest_transitions_retain_received_replica();
|
||||
[[= Void::Testing::tag("viewer-session")]] Test test_profiles_new_save_load_and_legacy_host_admission();
|
||||
[[= Void::Testing::tag("viewer-session")]] Test test_profile_validation_rejects_initial_and_loaded_mismatches();
|
||||
[[= Void::Testing::tag("viewer-session")]] Test test_pending_optional_load_blocks_host_and_newest_invalid_load_wins();
|
||||
[[= Void::Testing::tag("viewer-session")]] Test test_historical_default_modes_and_guest_leave_keep_default_rules();
|
||||
};
|
||||
|
||||
Test ViewerSessionTests::test_commands_wait_for_commit_and_keep_rejected_drafts_retryable() {
|
||||
ViewerSession session(2, {.command_capacity = 1});
|
||||
const auto before = session.world();
|
||||
const SessionPayload payload = CommandPayload{CommandKind::SetPriority, {}, 1};
|
||||
const auto first = session.submit(payload);
|
||||
require(first.has_value());
|
||||
require(session.submit(payload) == first);
|
||||
require(!session.submit(CommandPayload{CommandKind::SetPaused, {}, 1}));
|
||||
require(session.world()->work_priority() == before->work_priority());
|
||||
const auto changed = pump_until(session, [](const auto& events) { return has(events, ViewerEventKind::Command); });
|
||||
require(changed.front().command == *first);
|
||||
require(changed.front().status == CommandStatus::Accepted);
|
||||
require(!session.pending(*first));
|
||||
require(session.world()->work_priority() == WorkPriority::FoodFirst);
|
||||
require(session.world()->tick() == before->tick());
|
||||
require(before->work_priority() == WorkPriority::Balanced);
|
||||
|
||||
require(session.submit(CommandPayload{CommandKind::PlaceBed, {15, 16}, 0}).has_value());
|
||||
const auto rejected = pump_until(session, [](const auto& events) { return has(events, ViewerEventKind::Command); });
|
||||
require(rejected.front().status == CommandStatus::InvalidTarget);
|
||||
require(session.submit(CommandPayload{CommandKind::SetPaused, {}, 1}).has_value());
|
||||
const auto paused = pump_until(session, [](const auto& events) { return has(events, ViewerEventKind::Command); });
|
||||
require(paused.front().status == CommandStatus::Accepted);
|
||||
require(session.world()->paused());
|
||||
}
|
||||
|
||||
Test ViewerSessionTests::test_long_tick_allows_reset_without_joining_and_fences_old_intents() {
|
||||
const auto clock = std::make_shared<Void::Time::ManualClock>();
|
||||
auto gate = std::make_shared<Gate>();
|
||||
std::atomic<bool> block{true};
|
||||
ViewerSessionOptions options;
|
||||
options.runtime.clock = clock;
|
||||
options.runtime.observer = [gate, &block](RuntimePhase phase) {
|
||||
if (phase == RuntimePhase::BeforeTick && block.exchange(false)) gate->hold();
|
||||
};
|
||||
ViewerSession session(2, std::move(options));
|
||||
auto release = Void::Scope::on_exit([&] { gate->release(); });
|
||||
session.set_ticking(true);
|
||||
static_cast<void>(session.poll());
|
||||
flush_owner(session);
|
||||
require(clock->advance(50ms).has_value());
|
||||
session.runtime().notify_clock();
|
||||
gate->wait();
|
||||
const auto old = session.runtime().latest();
|
||||
require(session.submit(CommandPayload{CommandKind::SetPriority, {}, 1}).has_value());
|
||||
static_cast<void>(session.poll());
|
||||
session.new_colony();
|
||||
const auto pending = session.poll();
|
||||
require(pending.empty());
|
||||
require(session.changing_world());
|
||||
require(session.world() == old->world);
|
||||
gate->release();
|
||||
const auto events = pump_until(session, [](const auto& values) { return has(values, ViewerEventKind::Replaced); });
|
||||
require(!has(events, ViewerEventKind::Command));
|
||||
require(session.runtime().latest()->identity.session != old->identity.session);
|
||||
require(session.world()->work_priority() == WorkPriority::Balanced);
|
||||
}
|
||||
|
||||
Test ViewerSessionTests::test_title_load_and_later_failed_load_supersede_old_preparation() {
|
||||
TempFiles files;
|
||||
const auto original = make_first_colony(2);
|
||||
write(files.root / "old.settlement", bytes(*original));
|
||||
auto gate = std::make_shared<Gate>();
|
||||
std::atomic<bool> block{true};
|
||||
ViewerSessionOptions options;
|
||||
options.files.read_observer = [gate, &block](CheckpointReadPhase phase) {
|
||||
if (phase == CheckpointReadPhase::Opened && block.exchange(false)) gate->hold();
|
||||
};
|
||||
ViewerSession session(2, std::move(options));
|
||||
auto release = Void::Scope::on_exit([&] { gate->release(); });
|
||||
const auto before = session.runtime().latest();
|
||||
session.load(files.root / "old.settlement");
|
||||
gate->wait();
|
||||
session.load(files.root / "missing.settlement");
|
||||
require(session.poll().empty());
|
||||
gate->release();
|
||||
const auto failed = pump_until(session, [](const auto& events) { return has(events, ViewerEventKind::Error); });
|
||||
require(!has(failed, ViewerEventKind::Replaced));
|
||||
require(session.runtime().latest()->identity == before->identity);
|
||||
require(!session.changing_world());
|
||||
session.load(files.root / "old.settlement");
|
||||
pump_until(session, [](const auto& events) { return has(events, ViewerEventKind::Replaced); });
|
||||
require(session.runtime().latest()->identity.world != before->identity.world);
|
||||
require(session.world()->tick() == 0);
|
||||
require(bytes(*session.world()) == bytes(*original));
|
||||
}
|
||||
|
||||
Test ViewerSessionTests::test_unsupported_profile_and_dimensions_keep_current_world() {
|
||||
TempFiles files;
|
||||
ViewerSession session(2);
|
||||
const auto initial = session.runtime().latest();
|
||||
auto catalog = builtin_rule_packages();
|
||||
require(catalog.has_value());
|
||||
const std::array selected{std::string{"settlement.core"}};
|
||||
const auto rules = resolve_rules(*catalog, selected);
|
||||
require(rules.has_value());
|
||||
const auto custom = encode_checkpoint(*initial->world, initial->identity.world, 1, *rules);
|
||||
require(custom.has_value());
|
||||
write(files.root / "custom.settlement", *custom);
|
||||
session.load(files.root / "custom.settlement");
|
||||
pump_until(session, [](const auto& events) { return has(events, ViewerEventKind::Error); });
|
||||
require(session.runtime().latest() == initial);
|
||||
|
||||
World small(1, 16, 16);
|
||||
write(files.root / "small.settlement", bytes(small));
|
||||
session.load(files.root / "small.settlement");
|
||||
pump_until(session, [](const auto& events) { return has(events, ViewerEventKind::Error); });
|
||||
require(session.runtime().latest() == initial);
|
||||
|
||||
write(files.root / "broken.settlement", "STHCHKPTmalformed");
|
||||
session.load(files.root / "broken.settlement");
|
||||
pump_until(session, [](const auto& events) { return has(events, ViewerEventKind::Error); });
|
||||
require(session.runtime().latest() == initial);
|
||||
}
|
||||
|
||||
Test ViewerSessionTests::test_save_keeps_captured_session_across_reset() {
|
||||
TempFiles files;
|
||||
ViewerSession session(2);
|
||||
const auto before = session.runtime().latest();
|
||||
session.save(files.root / "captured.settlement");
|
||||
session.new_colony();
|
||||
const auto events = pump_until(session, [](const auto& values) { return has(values, ViewerEventKind::Replaced); });
|
||||
require(!has(events, ViewerEventKind::Saved));
|
||||
require(session.runtime().latest()->identity.world != before->identity.world);
|
||||
CheckpointFiles reader;
|
||||
CheckpointLoadResult loaded = std::unexpected{CheckpointFileDiagnostic{CheckpointFileError::Io, "waiting"}};
|
||||
const auto limit = std::chrono::steady_clock::now() + 5s;
|
||||
while (!loaded) {
|
||||
auto operation = reader.try_load(files.root / "captured.settlement");
|
||||
require(operation.admission == CheckpointLoadAdmission::Accepted);
|
||||
require(operation.completion.wait_for(5s) == std::future_status::ready);
|
||||
loaded = operation.completion.get();
|
||||
require(std::chrono::steady_clock::now() < limit);
|
||||
}
|
||||
require(loaded->world_id == before->identity.world);
|
||||
require(bytes(*loaded->world) == bytes(*before->world));
|
||||
}
|
||||
|
||||
Test ViewerSessionTests::test_guest_view_is_read_only_and_leave_installs_received_world() {
|
||||
ViewerSession session(2);
|
||||
auto* owner = &session.runtime();
|
||||
const auto before = session.runtime().latest();
|
||||
session.enter_guest();
|
||||
require(!session.world());
|
||||
require(!session.submit(CommandPayload{CommandKind::SetPaused, {}, 1}));
|
||||
auto incoming = make_first_colony(2);
|
||||
const auto receipt = incoming->apply_command({1, 1, CommandKind::SetPriority, {}, 2});
|
||||
require(receipt.status == CommandStatus::Accepted);
|
||||
const auto expected = bytes(*incoming);
|
||||
session.receive_guest(std::move(incoming));
|
||||
const auto held = session.world();
|
||||
require(bytes(*held) == expected);
|
||||
session.leave_guest();
|
||||
require(session.world() == held);
|
||||
pump_until(session, [](const auto& events) { return has(events, ViewerEventKind::Replaced); });
|
||||
require(&session.runtime() == owner);
|
||||
require(session.runtime().latest()->identity.session != before->identity.session);
|
||||
require(bytes(*session.world()) == expected);
|
||||
require(bytes(*held) == expected);
|
||||
require(!session.guest());
|
||||
}
|
||||
|
||||
Test ViewerSessionTests::test_runtime_busy_keeps_the_same_intent_until_commit() {
|
||||
const auto clock = std::make_shared<Void::Time::ManualClock>();
|
||||
auto gate = std::make_shared<Gate>();
|
||||
std::atomic<bool> block{true};
|
||||
ViewerSessionOptions options;
|
||||
options.runtime.capacity = 1;
|
||||
options.runtime.clock = clock;
|
||||
options.runtime.observer = [gate, &block](RuntimePhase phase) {
|
||||
if (phase == RuntimePhase::BeforeTick && block.exchange(false)) gate->hold();
|
||||
};
|
||||
ViewerSession session(2, std::move(options));
|
||||
auto release = Void::Scope::on_exit([&] { gate->release(); });
|
||||
session.set_ticking(true);
|
||||
static_cast<void>(session.poll());
|
||||
flush_owner(session);
|
||||
require(clock->advance(50ms).has_value());
|
||||
session.runtime().notify_clock();
|
||||
gate->wait();
|
||||
auto occupying = session.runtime().synchronize();
|
||||
require(occupying.admission == RuntimeAdmission::Accepted);
|
||||
require(session.runtime().synchronize().admission == RuntimeAdmission::Busy);
|
||||
const auto command = session.submit(CommandPayload{CommandKind::SetPriority, {}, 1});
|
||||
require(command.has_value());
|
||||
require(session.poll().empty());
|
||||
require(session.pending(*command));
|
||||
require(session.world()->work_priority() == WorkPriority::Balanced);
|
||||
gate->release();
|
||||
const auto result = pump_until(session, [](const auto& events) { return has(events, ViewerEventKind::Command); });
|
||||
require(result.front().command == *command && result.front().status == CommandStatus::Accepted);
|
||||
require(session.world()->next_command_sequence(colony_host) == 2);
|
||||
}
|
||||
|
||||
Test ViewerSessionTests::test_initial_candidate_requires_supported_rules_and_dimensions() {
|
||||
const auto id = Void::Uuid::try_v4();
|
||||
require(id.has_value());
|
||||
const auto catalog = builtin_rule_packages();
|
||||
require(catalog.has_value());
|
||||
const std::array selected{std::string{"settlement.core"}};
|
||||
const auto custom = resolve_rules(*catalog, selected);
|
||||
require(custom.has_value());
|
||||
bool rejected = false;
|
||||
try { ViewerSession session({make_first_colony(2), *id, 1, *custom}, 2); }
|
||||
catch (const std::runtime_error&) { rejected = true; }
|
||||
require(rejected);
|
||||
const auto defaults = default_rules_manifest();
|
||||
require(defaults.has_value());
|
||||
rejected = false;
|
||||
try { ViewerSession session({std::make_unique<World>(1, 16, 16), *id, 1, *defaults}, 2); }
|
||||
catch (const std::runtime_error&) { rejected = true; }
|
||||
require(rejected);
|
||||
}
|
||||
|
||||
Test ViewerSessionTests::test_fault_retains_view_and_explicit_load_recovers() {
|
||||
TempFiles files;
|
||||
const auto clock = std::make_shared<Void::Time::ManualClock>();
|
||||
std::atomic<bool> fail{true};
|
||||
ViewerSessionOptions options;
|
||||
options.runtime.clock = clock;
|
||||
options.runtime.observer = [&fail](RuntimePhase phase) {
|
||||
if (phase == RuntimePhase::BeforeTick && fail.exchange(false)) throw std::runtime_error("injected tick fault");
|
||||
};
|
||||
ViewerSession session(2, std::move(options));
|
||||
const auto before = session.world();
|
||||
write(files.root / "recover.settlement", bytes(*before));
|
||||
session.set_ticking(true);
|
||||
static_cast<void>(session.poll());
|
||||
flush_owner(session);
|
||||
require(clock->advance(50ms).has_value());
|
||||
session.runtime().notify_clock();
|
||||
pump_until(session, [](const auto& events) { return has(events, ViewerEventKind::Fault); });
|
||||
require(session.world() == before);
|
||||
require(!session.can_submit());
|
||||
require(!has(session.poll(), ViewerEventKind::Fault));
|
||||
bool rejected_save = false;
|
||||
try { session.save(files.root / "fault.settlement"); }
|
||||
catch (const std::runtime_error&) { rejected_save = true; }
|
||||
require(rejected_save);
|
||||
session.set_ticking(false);
|
||||
static_cast<void>(session.poll());
|
||||
auto suspended = session.runtime().synchronize();
|
||||
require(suspended.admission == RuntimeAdmission::Accepted);
|
||||
require(suspended.completion.wait_for(5s) == std::future_status::ready);
|
||||
require(suspended.completion.get().outcome == RuntimeOutcome::Faulted);
|
||||
static_cast<void>(session.poll());
|
||||
session.load(files.root / "recover.settlement");
|
||||
pump_until(session, [](const auto& events) { return has(events, ViewerEventKind::Replaced); });
|
||||
require(session.can_submit());
|
||||
require(bytes(*session.world()) == bytes(*before));
|
||||
require(clock->advance(50ms).has_value());
|
||||
session.runtime().notify_clock();
|
||||
flush_owner(session);
|
||||
require(session.world()->tick() == before->tick());
|
||||
session.set_ticking(true);
|
||||
static_cast<void>(session.poll());
|
||||
flush_owner(session);
|
||||
require(clock->advance(50ms).has_value());
|
||||
session.runtime().notify_clock();
|
||||
pump_until(session, [&](const auto&) { return session.world()->tick() > before->tick(); });
|
||||
}
|
||||
|
||||
Test ViewerSessionTests::test_failed_guest_transitions_retain_received_replica() {
|
||||
ViewerSession session(2);
|
||||
session.enter_guest();
|
||||
session.receive_guest(make_first_colony(2));
|
||||
const auto received = session.world();
|
||||
session.runtime().shutdown();
|
||||
bool rejected_join = false;
|
||||
try { session.enter_guest(); }
|
||||
catch (const std::runtime_error&) { rejected_join = true; }
|
||||
require(rejected_join && session.guest() && session.world() == received);
|
||||
bool rejected_leave = false;
|
||||
try { session.leave_guest(); }
|
||||
catch (const std::runtime_error&) { rejected_leave = true; }
|
||||
require(rejected_leave && session.guest() && session.world() == received);
|
||||
}
|
||||
|
||||
template<class T, class E>
|
||||
T checked(std::expected<T, E> result) {
|
||||
if (!result) throw std::runtime_error(result.error().message);
|
||||
return std::move(*result);
|
||||
}
|
||||
|
||||
std::string checkpoint_bytes(const WorldCheckpoint& candidate) {
|
||||
return checked(encode_checkpoint(*candidate.world, candidate.world_id, candidate.city, candidate.rules));
|
||||
}
|
||||
|
||||
Test ViewerSessionTests::test_profiles_new_save_load_and_legacy_host_admission() {
|
||||
TempFiles files;
|
||||
ViewerSession session(2);
|
||||
for (const auto profile : {ColonyProfile::PlankBeds, ColonyProfile::Default}) {
|
||||
const auto before = session.runtime().latest();
|
||||
session.new_colony(profile);
|
||||
require(session.changing_world() && !session.can_host_legacy());
|
||||
pump_until(session, [](const auto& events) { return has(events, ViewerEventKind::Replaced); });
|
||||
const auto created = session.runtime().latest();
|
||||
const auto expected = checked(colony_rules(profile));
|
||||
require(created->identity.world != before->identity.world && created->identity.session != before->identity.session);
|
||||
require(*created->rules == expected.manifest());
|
||||
require(created->world->staged_beds() == (profile == ColonyProfile::Default));
|
||||
require(session.can_host_legacy() == (profile == ColonyProfile::Default));
|
||||
const auto path = files.root / "profile.settlement";
|
||||
session.save(path);
|
||||
pump_until(session, [](const auto& events) { return has(events, ViewerEventKind::Saved); });
|
||||
CheckpointFiles reader;
|
||||
auto read = reader.try_load(path, 2);
|
||||
require(read.admission == CheckpointLoadAdmission::Accepted);
|
||||
require(read.completion.wait_for(5s) == std::future_status::ready);
|
||||
const auto saved = checked(read.completion.get());
|
||||
require(saved.rules == expected.manifest() && saved.world_id == created->identity.world);
|
||||
require(bytes(*saved.world) == bytes(*created->world));
|
||||
session.new_colony(profile == ColonyProfile::Default ? ColonyProfile::PlankBeds : ColonyProfile::Default);
|
||||
pump_until(session, [](const auto& events) { return has(events, ViewerEventKind::Replaced); });
|
||||
session.load(path);
|
||||
pump_until(session, [](const auto& events) { return has(events, ViewerEventKind::Replaced); });
|
||||
require(*session.runtime().latest()->rules == saved.rules);
|
||||
require(session.runtime().latest()->identity.world == saved.world_id);
|
||||
require(bytes(*session.world()) == bytes(*saved.world));
|
||||
}
|
||||
}
|
||||
|
||||
Test ViewerSessionTests::test_profile_validation_rejects_initial_and_loaded_mismatches() {
|
||||
TempFiles files;
|
||||
auto catalog = checked(builtin_rule_packages());
|
||||
const auto optional_rules = checked(colony_rules(ColonyProfile::PlankBeds)).manifest();
|
||||
const auto core_rules = checked(resolve_rules(catalog, std::array{std::string{"settlement.core"}}));
|
||||
catalog.push_back(checked(load_rule_package("extra",
|
||||
R"({"schema":1,"id":"game.extra","version":"1.0.0","dependencies":[],"exclusive_capabilities":[],"definitions":[]})")));
|
||||
const auto extra_rules = checked(resolve_rules(catalog,
|
||||
std::array{std::string{"settlement.colony"}, std::string{"game.extra"}}));
|
||||
auto altered = std::string(catalog[1].canonical_json());
|
||||
const auto recipe = altered.find("\"output_count\":1");
|
||||
require(recipe != std::string::npos);
|
||||
altered.replace(recipe, std::string_view{"\"output_count\":1"}.size(), "\"output_count\":2");
|
||||
catalog[1] = checked(load_rule_package("forged", altered));
|
||||
const auto forged_rules = checked(resolve_rules(catalog, std::array{std::string{"settlement.colony"}}));
|
||||
ViewerSession session(2);
|
||||
const auto before = session.runtime().latest();
|
||||
for (const auto& rules : {core_rules, extra_rules, forged_rules, optional_rules}) {
|
||||
auto candidate = checked(make_colony_checkpoint(ColonyProfile::Default, 2));
|
||||
candidate.rules = rules;
|
||||
write(files.root / "invalid.settlement", checkpoint_bytes(candidate));
|
||||
bool rejected = false;
|
||||
try { ViewerSession invalid(std::move(candidate), 2); }
|
||||
catch (const std::runtime_error&) { rejected = true; }
|
||||
require(rejected);
|
||||
session.load(files.root / "invalid.settlement");
|
||||
const auto events = pump_until(session, [](const auto& values) { return has(values, ViewerEventKind::Error); });
|
||||
require(!has(events, ViewerEventKind::Replaced));
|
||||
require(session.runtime().latest() == before && !session.changing_world());
|
||||
}
|
||||
for (int problem = 0; problem < 3; ++problem) {
|
||||
auto candidate = checked(make_colony_checkpoint(ColonyProfile::Default, 2));
|
||||
if (problem == 0) candidate.world.reset();
|
||||
if (problem == 1) candidate.world_id = {};
|
||||
if (problem == 2) candidate.city = 0;
|
||||
bool rejected = false;
|
||||
try { ViewerSession invalid(std::move(candidate), 2); }
|
||||
catch (const std::runtime_error&) { rejected = true; }
|
||||
require(rejected);
|
||||
}
|
||||
bool rejected = false;
|
||||
try { session.new_colony(static_cast<ColonyProfile>(255)); }
|
||||
catch (const std::runtime_error&) { rejected = true; }
|
||||
require(rejected && session.runtime().latest() == before && session.can_host_legacy());
|
||||
auto supported = checked(make_colony_checkpoint(ColonyProfile::PlankBeds, 2));
|
||||
ViewerSession optional(std::move(supported), 2);
|
||||
require(!optional.world()->staged_beds() && !optional.can_host_legacy());
|
||||
}
|
||||
|
||||
Test ViewerSessionTests::test_pending_optional_load_blocks_host_and_newest_invalid_load_wins() {
|
||||
TempFiles files;
|
||||
auto valid = checked(make_colony_checkpoint(ColonyProfile::PlankBeds, 2));
|
||||
write(files.root / "optional.settlement", checkpoint_bytes(valid));
|
||||
valid.world = make_first_colony(2);
|
||||
write(files.root / "invalid.settlement", checkpoint_bytes(valid));
|
||||
auto gate = std::make_shared<Gate>();
|
||||
std::atomic<bool> block{true};
|
||||
ViewerSessionOptions options;
|
||||
options.files.read_observer = [gate, &block](CheckpointReadPhase phase) {
|
||||
if (phase == CheckpointReadPhase::Opened && block.exchange(false)) gate->hold();
|
||||
};
|
||||
ViewerSession session(2, std::move(options));
|
||||
auto release = Void::Scope::on_exit([&] { gate->release(); });
|
||||
const auto before = session.runtime().latest();
|
||||
require(session.can_host_legacy());
|
||||
session.load(files.root / "optional.settlement");
|
||||
gate->wait();
|
||||
require(session.changing_world() && !session.can_host_legacy() && session.runtime().latest() == before);
|
||||
// Invalid direct New preparation must retain the pending load and its ticket.
|
||||
const auto generation = session.generation();
|
||||
try { session.new_colony(static_cast<ColonyProfile>(255)); }
|
||||
catch (const std::runtime_error&) {}
|
||||
require(session.changing_world() && session.generation() == generation);
|
||||
session.load(files.root / "invalid.settlement");
|
||||
gate->release();
|
||||
const auto events = pump_until(session, [](const auto& values) { return has(values, ViewerEventKind::Error); });
|
||||
require(!has(events, ViewerEventKind::Replaced) && session.runtime().latest() == before);
|
||||
flush_owner(session);
|
||||
require(session.poll().empty() && session.runtime().latest() == before && session.can_host_legacy());
|
||||
}
|
||||
|
||||
Test ViewerSessionTests::test_historical_default_modes_and_guest_leave_keep_default_rules() {
|
||||
TempFiles files;
|
||||
const auto defaults = checked(default_rules_manifest());
|
||||
for (int mode = 0; mode < 3; ++mode) {
|
||||
auto candidate = checked(make_colony_checkpoint(ColonyProfile::Default, 2));
|
||||
if (mode == 1) candidate.world = make_first_colony(2, BedConstructionMode::Plank);
|
||||
if (mode == 2) candidate.world = std::make_unique<World>(17, 32, 32, 2);
|
||||
const auto expected = bytes(*candidate.world);
|
||||
ViewerSession session(std::move(candidate), 2);
|
||||
require(bytes(*session.world()) == expected && session.can_host_legacy());
|
||||
write(files.root / "legacy.settlement", expected);
|
||||
session.load(files.root / "legacy.settlement");
|
||||
pump_until(session, [](const auto& events) { return has(events, ViewerEventKind::Replaced); });
|
||||
require(bytes(*session.world()) == expected && *session.runtime().latest()->rules == defaults);
|
||||
}
|
||||
ViewerSession session(checked(make_colony_checkpoint(ColonyProfile::PlankBeds, 2)), 2);
|
||||
session.enter_guest();
|
||||
session.receive_guest(make_first_colony(2, BedConstructionMode::Plank));
|
||||
session.leave_guest();
|
||||
pump_until(session, [](const auto& events) { return has(events, ViewerEventKind::Replaced); });
|
||||
require(!session.world()->staged_beds() && *session.runtime().latest()->rules == defaults && session.can_host_legacy());
|
||||
}
|
||||
|
||||
} // namespace
|
||||
@@ -0,0 +1,392 @@
|
||||
#include "settlement/core/voxel_navigation.hpp"
|
||||
#include "settlement/core/worker_pool.hpp"
|
||||
#include <Void/Testing/Suite.hpp>
|
||||
#include <algorithm>
|
||||
#include <array>
|
||||
#include <cstdint>
|
||||
#include <future>
|
||||
#include <limits>
|
||||
#include <queue>
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace {
|
||||
using namespace settlement;
|
||||
using Status = VoxelNavigationStatus;
|
||||
using Void::Testing::Test;
|
||||
void require(bool condition, const char* message) {
|
||||
if (!condition) throw std::runtime_error(message);
|
||||
}
|
||||
Void::Uuid::Uuid epoch(std::uint8_t value = 1) {
|
||||
Void::Uuid::Uuid result;
|
||||
result.bytes.back() = value;
|
||||
return result;
|
||||
}
|
||||
template<class Material>
|
||||
void install(VoxelRegion& world, ChunkCoordinate chunk, Material material) {
|
||||
std::array<MaterialId, voxel_chunk_cells> cells{};
|
||||
for (std::uint8_t z = 0; z < 32; ++z) for (std::uint8_t y = 0; y < 32; ++y) for (std::uint8_t x = 0; x < 32; ++x) {
|
||||
const auto p = join_voxel(chunk, {x, y, z});
|
||||
if (p && world.descriptor().bounds.contains(*p)) cells[*voxel_index({x, y, z})] = material(*p);
|
||||
}
|
||||
auto candidate = world.prepare_restored(chunk, 1, cells);
|
||||
require(candidate.has_value(), "valid fixture page refused");
|
||||
require(world.activate(std::span(&*candidate, 1)).has_value(), "valid fixture activation refused");
|
||||
}
|
||||
void edit(VoxelRegion& world, VoxelPosition p, MaterialId material) {
|
||||
const VoxelEdit change{p, material, world.sample(p).stamp.revision};
|
||||
require(world.edit(std::span(&change, 1)).has_value(), "fixture edit refused");
|
||||
}
|
||||
VoxelRegion flat(VoxelBounds bounds = {{0, 0, 0}, {8, 8, 4}}) {
|
||||
VoxelRegion world({1, 42, 1, bounds});
|
||||
const auto low = split_voxel({static_cast<std::int32_t>(bounds.lower.x), static_cast<std::int32_t>(bounds.lower.y), static_cast<std::int32_t>(bounds.lower.z)}).chunk;
|
||||
const auto high = split_voxel({static_cast<std::int32_t>(bounds.upper.x - 1), static_cast<std::int32_t>(bounds.upper.y - 1), static_cast<std::int32_t>(bounds.upper.z - 1)}).chunk;
|
||||
for (auto z = low.z; z <= high.z; ++z) for (auto y = low.y; y <= high.y; ++y) for (auto x = low.x; x <= high.x; ++x) {
|
||||
install(world, {x, y, z}, [](auto p) { return p.z == 0 ? MaterialId::Stone : MaterialId::Air; });
|
||||
}
|
||||
return world;
|
||||
}
|
||||
VoxelPathRequest request(const VoxelRegion& world, VoxelPosition start, std::vector<VoxelPosition> goals) {
|
||||
return {world.descriptor().id, epoch(), start, world.descriptor().bounds, std::move(goals), {}};
|
||||
}
|
||||
VoxelRegion stairs(bool closed) {
|
||||
VoxelRegion world({7, 42, 1, {{28, 0, 0}, {38, 3, 8}}});
|
||||
for (int x : {0, 1}) install(world, {x, 0, 0}, [closed](auto p) {
|
||||
const auto height = std::clamp(p.x - 31, 0, 3);
|
||||
if (p.z <= height) return MaterialId::Stone;
|
||||
if ((p.y == 0 || p.y == 2) && p.z <= height + 2) return MaterialId::Stone;
|
||||
if (p.x == 30 && p.y == 1 && (p.z == 1 || p.z == 2)) return closed ? MaterialId::DoorClosed : MaterialId::DoorOpen;
|
||||
return MaterialId::Air;
|
||||
});
|
||||
return world;
|
||||
}
|
||||
void require_route(const VoxelRegion& world, const VoxelPathRequest& query, const VoxelPathResult& result) {
|
||||
require(result.status == Status::Reachable && result.goal.has_value(), "expected a reachable goal");
|
||||
require(result.cost == result.route.size(), "cost differs from actual route");
|
||||
auto from = query.start;
|
||||
for (auto to : result.route) {
|
||||
require(voxel_transition(world, query.session, from, to).status == Status::Reachable, "returned route crosses invalid transition");
|
||||
from = to;
|
||||
}
|
||||
require(from == *result.goal && result.consulted.current(world, query.session), "route target or read stamps invalid");
|
||||
require(std::is_sorted(result.consulted.chunks.begin(), result.consulted.chunks.end(),
|
||||
[](const auto& a, const auto& b) { return a.coordinate < b.coordinate; }), "read stamps not canonical");
|
||||
}
|
||||
|
||||
struct [[= Void::Testing::name("VoxelNavigationTests")]] VoxelNavigationTests : Void::Testing::Suite<VoxelNavigationTests> {
|
||||
[[= Void::Testing::tag("voxel-navigation")]] Test doorway_stairs_and_upper_work_contact();
|
||||
[[= Void::Testing::tag("voxel-navigation")]] Test support_edit_invalidates_route_before_next_step();
|
||||
[[= Void::Testing::tag("voxel-navigation")]] Test body_headroom_and_step_sweep_are_required();
|
||||
[[= Void::Testing::tag("voxel-navigation")]] Test missing_support_page_and_negative_answer_are_dependencies();
|
||||
[[= Void::Testing::tag("voxel-navigation")]] Test known_blockers_do_not_require_unrelated_missing_data();
|
||||
[[= Void::Testing::tag("voxel-navigation")]] Test reachable_missing_frontier_waits_for_actual_gateway();
|
||||
[[= Void::Testing::tag("voxel-navigation")]] Test unrepresentable_vector_capacity_is_a_bounded_refusal();
|
||||
[[= Void::Testing::tag("voxel-navigation")]] Test interaction_contacts_outside_window_need_frontier_evidence();
|
||||
[[= Void::Testing::tag("voxel-navigation")]] Test unchanged_chunks_and_old_snapshots_remain_usable();
|
||||
[[= Void::Testing::tag("voxel-navigation")]] Test bounded_search_has_distinct_incomplete_and_error_results();
|
||||
[[= Void::Testing::tag("voxel-navigation")]] Test invalid_same_goal_and_extreme_coordinate_windows();
|
||||
[[= Void::Testing::tag("voxel-navigation")]] Test goals_and_neighbors_have_stable_shortest_ties();
|
||||
[[= Void::Testing::tag("voxel-navigation")]] Test shortest_costs_match_exhaustive_small_grid();
|
||||
[[= Void::Testing::tag("voxel-navigation")]] Test real_parallel_queries_preserve_route_and_readsets();
|
||||
};
|
||||
|
||||
Test VoxelNavigationTests::doorway_stairs_and_upper_work_contact() {
|
||||
auto world = stairs(true);
|
||||
auto query = request(world, {29, 1, 1}, {{36, 1, 4}});
|
||||
auto blocked = find_voxel_path(world, query);
|
||||
require(blocked.status == Status::Unreachable, "closed two-cell door was passable");
|
||||
const std::array changes{VoxelEdit{{30, 1, 1}, MaterialId::DoorOpen, 1}, VoxelEdit{{30, 1, 2}, MaterialId::DoorOpen, 1}};
|
||||
require(world.edit(changes).has_value(), "door opening failed");
|
||||
require(!blocked.consulted.current(world, epoch()), "door change retained negative result");
|
||||
auto found = find_voxel_path(world, query);
|
||||
require_route(world, query, found);
|
||||
require(found.cost == 7 && std::any_of(found.route.begin(), found.route.end(), [](auto p) { return p.x == 32 && p.z == 2; }), "path failed actual border stair");
|
||||
edit(world, {37, 1, 4}, MaterialId::Stone);
|
||||
auto work = find_voxel_interaction_path(world, query, {37, 1, 4});
|
||||
require_route(world, query, work);
|
||||
require(work.goal == VoxelPosition{36, 1, 4}, "upper work position lacks direct face contact");
|
||||
}
|
||||
Test VoxelNavigationTests::support_edit_invalidates_route_before_next_step() {
|
||||
auto world = stairs(false);
|
||||
const auto query = request(world, {32, 1, 2}, {{36, 1, 4}});
|
||||
auto found = find_voxel_path(world, query);
|
||||
require_route(world, query, found);
|
||||
const auto held = world;
|
||||
edit(world, {33, 1, 2}, MaterialId::Air);
|
||||
require(!found.consulted.current(world, epoch()), "support change did not expire route");
|
||||
require(voxel_standing(world, epoch(), query.start).status == Status::Reachable, "future support edit invalidated current foot");
|
||||
require(voxel_transition(world, epoch(), query.start, found.route.front()).status == Status::Unreachable, "unsafe stored next step still allowed");
|
||||
require(find_voxel_path(world, query).status == Status::Unreachable, "missing stair allowed a two-cell rise");
|
||||
require(found.consulted.current(held, epoch()), "retained immutable geometry changed");
|
||||
edit(world, {33, 1, 2}, MaterialId::Stone);
|
||||
require_route(world, query, find_voxel_path(world, query));
|
||||
}
|
||||
Test VoxelNavigationTests::body_headroom_and_step_sweep_are_required() {
|
||||
auto world = flat();
|
||||
require(voxel_standing(world, epoch(), {2, 2, 1}).status == Status::Reachable, "ordinary stance refused");
|
||||
edit(world, {3, 2, 1}, MaterialId::Stone);
|
||||
require(voxel_transition(world, epoch(), {2, 2, 1}, {3, 2, 2}).status == Status::Reachable, "single stair refused");
|
||||
edit(world, {2, 2, 3}, MaterialId::Stone);
|
||||
require(voxel_transition(world, epoch(), {2, 2, 1}, {3, 2, 2}).status == Status::Unreachable, "step rose through source ceiling");
|
||||
require(voxel_transition(world, epoch(), {3, 2, 2}, {2, 2, 1}).status == Status::Unreachable, "step descended through swept ceiling");
|
||||
edit(world, {2, 2, 3}, MaterialId::Air);
|
||||
edit(world, {3, 2, 3}, MaterialId::DoorClosed);
|
||||
require(voxel_standing(world, epoch(), {3, 2, 2}).status == Status::Unreachable, "head entered closed upper door");
|
||||
edit(world, {3, 2, 3}, MaterialId::DoorOpen);
|
||||
require(voxel_transition(world, epoch(), {2, 2, 1}, {3, 2, 2}).status == Status::Reachable, "open door blocked head");
|
||||
require(voxel_transition(world, epoch(), {2, 2, 1}, {3, 3, 1}).status == Status::Unreachable, "diagonal corner cutting accepted");
|
||||
require(voxel_transition(world, epoch(), {2, 2, 1}, {2, 2, 2}).status == Status::Unreachable, "unsupported vertical movement accepted");
|
||||
}
|
||||
Test VoxelNavigationTests::missing_support_page_and_negative_answer_are_dependencies() {
|
||||
VoxelRegion world({1, 42, 1, {{-3, 0, -1}, {3, 3, 4}}});
|
||||
install(world, {-1, 0, 0}, [](auto) { return MaterialId::Air; });
|
||||
install(world, {0, 0, 0}, [](auto) { return MaterialId::Air; });
|
||||
auto check = voxel_standing(world, epoch(), {-1, 1, 0});
|
||||
require(check.status == Status::Unavailable, "unloaded support treated as empty or solid");
|
||||
require(std::any_of(check.consulted.chunks.begin(), check.consulted.chunks.end(), [](const auto& s) { return s.coordinate == ChunkCoordinate{-1, 0, -1} && s.availability == VoxelAvailability::Unavailable; }), "missing support page omitted from reads");
|
||||
install(world, {-1, 0, -1}, [](auto) { return MaterialId::Stone; });
|
||||
require(!check.consulted.current(world, epoch()), "missing-to-loaded support kept stale result");
|
||||
require(voxel_standing(world, epoch(), {-1, 1, 0}).status == Status::Reachable, "new support still unavailable");
|
||||
auto query = request(world, {-1, 1, 0}, {{1, 1, 0}});
|
||||
auto negative = find_voxel_path(world, query);
|
||||
require(negative.status == Status::Unavailable, "missing route support was proven unreachable");
|
||||
install(world, {0, 0, -1}, [](auto) { return MaterialId::Stone; });
|
||||
require(!negative.consulted.current(world, epoch()), "negative path omitted queried missing chunk");
|
||||
require_route(world, query, find_voxel_path(world, query));
|
||||
}
|
||||
Test VoxelNavigationTests::known_blockers_do_not_require_unrelated_missing_data() {
|
||||
VoxelRegion world({1, 42, 1, {{0, 0, -1}, {64, 8, 4}}});
|
||||
install(world, {0, 0, 0}, [](auto p) {
|
||||
return p.z == 0 || (p.x == 2 && p.z <= 2) ? MaterialId::Stone : MaterialId::Air;
|
||||
});
|
||||
auto query = request(world, {1, 1, 1}, {{5, 5, 1}});
|
||||
auto result = find_voxel_path(world, query);
|
||||
require(result.status == Status::Unreachable, "solid floor and closed wall unnecessarily wait for missing lower page");
|
||||
require(find_voxel_interaction_path(world, query, {5, 5, 1}).status == Status::Unreachable,
|
||||
"loaded interaction behind known wall unnecessarily waits for missing lower page");
|
||||
require(std::any_of(result.consulted.chunks.begin(), result.consulted.chunks.end(), [](const auto& s) {
|
||||
return s.coordinate == ChunkCoordinate{0, 0, -1} && s.availability == VoxelAvailability::Unavailable;
|
||||
}), "conclusively blocked reads lost their actual dependency stamps");
|
||||
query.goals = {{35, 5, 1}};
|
||||
result = find_voxel_path(world, query);
|
||||
require(result.status == Status::Unreachable, "disconnected unknown goal manufactured reachable frontier");
|
||||
require(std::any_of(result.consulted.chunks.begin(), result.consulted.chunks.end(), [](const auto& s) {
|
||||
return s.coordinate == ChunkCoordinate{1, 0, 0} && s.availability == VoxelAvailability::Unavailable;
|
||||
}), "unknown goal reads were not retained");
|
||||
query.goals = {{5, 5, 1}};
|
||||
query.search_bounds.upper = {8, 6, 4};
|
||||
require(find_voxel_path(world, query).status == Status::SearchBoundary,
|
||||
"actual reachable window exit was replaced by irrelevant missing data");
|
||||
install(world, {0, 0, -1}, [](auto) { return MaterialId::Stone; });
|
||||
query.search_bounds = world.descriptor().bounds;
|
||||
require(find_voxel_path(world, query).status == Status::Unreachable,
|
||||
"lower-page activation changed proven blocked reachability");
|
||||
for (int x : {0, 1}) for (int z : {1, 2}) edit(world, {x, 3, z}, MaterialId::Stone);
|
||||
query.goals = {{1, 5, 1}};
|
||||
query.search_bounds.upper.x = 2;
|
||||
require(find_voxel_path(world, query).status == Status::Unreachable,
|
||||
"known blocked transitions beyond search window manufactured an exit");
|
||||
}
|
||||
Test VoxelNavigationTests::reachable_missing_frontier_waits_for_actual_gateway() {
|
||||
VoxelRegion world({1, 42, 1, {{0, 0, -1}, {64, 8, 4}}});
|
||||
const auto floor = [](auto p) { return p.z == 0 ? MaterialId::Stone : MaterialId::Air; };
|
||||
install(world, {0, 0, 0}, floor);
|
||||
auto blocked_goal = request(world, {1, 1, 1}, {{5, 5, 1}});
|
||||
edit(world, {5, 5, 2}, MaterialId::Stone);
|
||||
require(find_voxel_path(world, blocked_goal).status == Status::Unreachable,
|
||||
"missing branch elsewhere manufactured access to conclusively blocked goal");
|
||||
edit(world, {5, 5, 2}, MaterialId::Air);
|
||||
auto query = request(world, {1, 1, 1}, {{35, 5, 1}});
|
||||
auto pending = find_voxel_path(world, query);
|
||||
require(pending.status == Status::Unavailable, "reachable missing gateway was proven unreachable");
|
||||
install(world, {1, 0, 0}, floor);
|
||||
require(!pending.consulted.current(world, epoch()), "gateway activation did not invalidate pending answer");
|
||||
auto result = find_voxel_path(world, query);
|
||||
require_route(world, query, result);
|
||||
require(result.cost == 38, "loaded gateway changed shortest path cost");
|
||||
}
|
||||
Test VoxelNavigationTests::unrepresentable_vector_capacity_is_a_bounded_refusal() {
|
||||
auto world = flat();
|
||||
auto query = request(world, {1, 1, 1}, {{5, 5, 1}});
|
||||
query.limits.max_dependencies = std::vector<ChunkStamp>{}.max_size() + 1;
|
||||
query.limits.max_scratch_bytes = std::numeric_limits<std::size_t>::max();
|
||||
require(find_voxel_path(world, query).status == Status::LimitExceeded, "unrepresentable read reserve escaped path API");
|
||||
require(find_voxel_interaction_path(world, query, {5, 5, 1}).status == Status::LimitExceeded,
|
||||
"unrepresentable read reserve escaped interaction API");
|
||||
require(voxel_standing(world, epoch(), query.start, query.limits).status == Status::LimitExceeded,
|
||||
"unrepresentable read reserve escaped stance API");
|
||||
require(voxel_transition(world, epoch(), query.start, {2, 1, 1}, query.limits).status == Status::LimitExceeded,
|
||||
"unrepresentable read reserve escaped transition API");
|
||||
}
|
||||
Test VoxelNavigationTests::interaction_contacts_outside_window_need_frontier_evidence() {
|
||||
auto world = flat();
|
||||
edit(world, {3, 3, 1}, MaterialId::Stone);
|
||||
for (auto blocker : {VoxelPosition{2, 3, 2}, VoxelPosition{3, 2, 2}, VoxelPosition{3, 4, 2}, VoxelPosition{3, 3, 3}}) {
|
||||
edit(world, blocker, MaterialId::Stone);
|
||||
}
|
||||
auto query = request(world, {1, 1, 1}, {});
|
||||
query.search_bounds.upper.x = 6;
|
||||
auto complete = find_voxel_interaction_path(world, query, {3, 3, 1});
|
||||
require_route(world, query, complete);
|
||||
require(complete.goal == VoxelPosition{4, 3, 1}, "expanded window did not reach sole valid contact");
|
||||
query.search_bounds.upper.x = 4;
|
||||
require(find_voxel_interaction_path(world, query, {3, 3, 1}).status == Status::SearchBoundary,
|
||||
"clipped valid interaction contact was classified globally unreachable");
|
||||
|
||||
// A valid omitted goal cannot manufacture an exit from an enclosed start.
|
||||
for (auto p : {VoxelPosition{0, 1, 1}, VoxelPosition{1, 0, 1}, VoxelPosition{1, 2, 1}, VoxelPosition{2, 1, 1}}) {
|
||||
edit(world, p, MaterialId::Stone);
|
||||
edit(world, {p.x, p.y, 2}, MaterialId::Stone);
|
||||
}
|
||||
require(find_voxel_interaction_path(world, query, {3, 3, 1}).status == Status::Unreachable,
|
||||
"omitted contact manufactured an escape from a known enclosed start");
|
||||
|
||||
// The only useful contact is beyond x=31, in an unavailable page.
|
||||
VoxelRegion pending({1, 42, 1, {{0, 0, 0}, {40, 8, 4}}});
|
||||
install(pending, {0, 0, 0}, [](auto p) {
|
||||
if (p.z == 0 || p == VoxelPosition{31, 3, 1}) return MaterialId::Stone;
|
||||
if (p == VoxelPosition{30, 3, 2} || p == VoxelPosition{31, 2, 2} ||
|
||||
p == VoxelPosition{31, 4, 2} || p == VoxelPosition{31, 3, 3}) return MaterialId::Stone;
|
||||
return MaterialId::Air;
|
||||
});
|
||||
auto partial = request(pending, {29, 1, 1}, {});
|
||||
partial.search_bounds.upper.x = 32;
|
||||
const auto waiting = find_voxel_interaction_path(pending, partial, {31, 3, 1});
|
||||
require(waiting.status == Status::Unavailable, "unresolved interaction exit was proven unreachable");
|
||||
install(pending, {1, 0, 0}, [](auto p) { return p.z == 0 ? MaterialId::Stone : MaterialId::Air; });
|
||||
require(!waiting.consulted.current(pending, epoch()), "missing omitted contact was absent from dependencies");
|
||||
require(find_voxel_interaction_path(pending, partial, {31, 3, 1}).status == Status::SearchBoundary,
|
||||
"loaded omitted contact failed to expose reachable window exit");
|
||||
partial.search_bounds.upper.x = 36;
|
||||
auto reached = find_voxel_interaction_path(pending, partial, {31, 3, 1});
|
||||
require_route(pending, partial, reached);
|
||||
require(reached.goal == VoxelPosition{32, 3, 1}, "expanded gateway did not expose actual contact");
|
||||
}
|
||||
Test VoxelNavigationTests::unchanged_chunks_and_old_snapshots_remain_usable() {
|
||||
auto world = flat({{0, 0, 0}, {100, 8, 4}});
|
||||
auto query = request(world, {1, 1, 1}, {{5, 5, 1}});
|
||||
query.search_bounds.upper.x = 8;
|
||||
auto route = find_voxel_path(world, query);
|
||||
require_route(world, query, route);
|
||||
edit(world, {97, 2, 1}, MaterialId::Stone);
|
||||
require(route.consulted.current(world, epoch()), "unconsulted page invalidated a path");
|
||||
require(!route.consulted.current(world, epoch(2)), "old session accepted same numeric revisions");
|
||||
VoxelRegion other({2, 42, 1, world.descriptor().bounds});
|
||||
require(!route.consulted.current(other, epoch()), "another region accepted old route");
|
||||
}
|
||||
Test VoxelNavigationTests::bounded_search_has_distinct_incomplete_and_error_results() {
|
||||
auto world = flat();
|
||||
auto query = request(world, {1, 1, 1}, {{5, 5, 1}});
|
||||
query.limits.max_vertices = 1;
|
||||
require(find_voxel_path(world, query).status == Status::LimitExceeded, "vertex budget fabricated unreachable");
|
||||
query.limits = {}; query.limits.max_scratch_bytes = 8;
|
||||
require(find_voxel_path(world, query).status == Status::LimitExceeded, "scratch budget ignored");
|
||||
query.limits = {}; query.limits.max_steps = 1;
|
||||
require(find_voxel_path(world, query).status == Status::LimitExceeded, "traversal budget fabricated unreachable");
|
||||
query.limits = {}; query.limits.max_samples = 2;
|
||||
require(find_voxel_path(world, query).status == Status::LimitExceeded, "material query budget ignored");
|
||||
query.limits = {}; query.limits.max_dependencies = 0;
|
||||
require(find_voxel_path(world, query).status == Status::LimitExceeded, "read-set bound ignored");
|
||||
query.limits = {}; query.limits.max_goals = 0;
|
||||
require(find_voxel_path(world, query).status == Status::LimitExceeded, "goal bound ignored");
|
||||
query.limits = {};
|
||||
std::stop_source cancelled; cancelled.request_stop();
|
||||
require(find_voxel_path(world, query, cancelled.get_token()).status == Status::Cancelled, "cancellation fabricated unreachable");
|
||||
auto clipped_interaction = query;
|
||||
clipped_interaction.search_bounds.upper = {2, 2, 4};
|
||||
require(find_voxel_interaction_path(world, clipped_interaction, {6, 6, 1}).status == Status::SearchBoundary,
|
||||
"interaction with all feet clipped fabricated invalid input");
|
||||
clipped_interaction.region = 2;
|
||||
require(find_voxel_interaction_path(world, clipped_interaction, {6, 6, 1}).status == Status::InvalidInput,
|
||||
"clipped interaction bypassed region identity");
|
||||
query.search_bounds.upper.x = 4; query.goals = {{3, 5, 1}};
|
||||
for (int y = 0; y < 8; ++y) { edit(world, {2, y, 1}, MaterialId::Stone); edit(world, {2, y, 2}, MaterialId::Stone); }
|
||||
// The accessible edge at x=0 has no escape (region bound), but y edges do
|
||||
// not either. Make a window smaller than the region along y as well.
|
||||
query.search_bounds.upper.y = 6;
|
||||
require(find_voxel_path(world, query).status == Status::SearchBoundary, "clipped search claimed global unreachability");
|
||||
VoxelRegion sparse({1, 42, 1, {{std::numeric_limits<std::int32_t>::min(), 0, 0}, {std::int64_t{std::numeric_limits<std::int32_t>::max()} + 1, 8, 4}}});
|
||||
auto huge = request(sparse, {0, 1, 1}, {{1, 1, 1}});
|
||||
require(find_voxel_path(sparse, huge).status == Status::LimitExceeded, "sparse huge extent allocated densely");
|
||||
}
|
||||
Test VoxelNavigationTests::invalid_same_goal_and_extreme_coordinate_windows() {
|
||||
auto world = flat();
|
||||
auto query = request(world, {1, 1, 1}, {{1, 1, 1}});
|
||||
auto same = find_voxel_path(world, query);
|
||||
require_route(world, query, same);
|
||||
require(same.route.empty() && same.cost == 0, "already-at-goal result wrong");
|
||||
edit(world, {1, 1, 2}, MaterialId::Stone);
|
||||
require(find_voxel_path(world, query).status == Status::Unreachable, "blocked start==goal bypassed geometry");
|
||||
query.session = {};
|
||||
require(find_voxel_path(world, query).status == Status::InvalidInput, "nil session accepted");
|
||||
for (auto x : {std::numeric_limits<std::int32_t>::min(), std::numeric_limits<std::int32_t>::max() - 3}) {
|
||||
const VoxelBounds b{{x, 0, 0}, {std::int64_t{x} + 4, 3, 4}};
|
||||
auto edge = flat(b);
|
||||
auto edge_query = request(edge, {x, 1, 1}, {{static_cast<std::int32_t>(std::int64_t{x} + 3), 1, 1}});
|
||||
const auto route = find_voxel_path(edge, edge_query);
|
||||
require_route(edge, edge_query, route);
|
||||
require(route.cost == 3, "extreme coordinate route wrapped");
|
||||
}
|
||||
}
|
||||
Test VoxelNavigationTests::goals_and_neighbors_have_stable_shortest_ties() {
|
||||
auto world = flat();
|
||||
auto query = request(world, {3, 3, 1}, {{4, 3, 1}, {2, 3, 1}, {3, 4, 1}});
|
||||
auto result = find_voxel_path(world, query);
|
||||
require(result.goal == VoxelPosition{2, 3, 1} && result.cost == 1, "equal goals depend on request order");
|
||||
std::reverse(query.goals.begin(), query.goals.end());
|
||||
require(find_voxel_path(world, query).route == result.route, "goal order changed route");
|
||||
query.goals = {{4, 4, 1}};
|
||||
result = find_voxel_path(world, query);
|
||||
require(result.route == std::vector<VoxelPosition>{{3, 4, 1}, {4, 4, 1}}, "equal paths violated coordinate neighbor order");
|
||||
}
|
||||
Test VoxelNavigationTests::shortest_costs_match_exhaustive_small_grid() {
|
||||
for (std::uint32_t pattern = 0; pattern < 16; ++pattern) {
|
||||
std::array<bool, 49> walls{};
|
||||
for (std::size_t i = 0; i < walls.size(); ++i) walls[i] = ((i * 13 + pattern * 7) % 17) < 4;
|
||||
walls[8] = false; walls[40] = false;
|
||||
auto world = flat({{0, 0, 0}, {7, 7, 4}});
|
||||
std::vector<VoxelEdit> changes;
|
||||
for (int y = 0; y < 7; ++y) for (int x = 0; x < 7; ++x) if (walls[static_cast<std::size_t>(x + 7 * y)]) {
|
||||
changes.push_back({{x, y, 1}, MaterialId::Stone, 1}); changes.push_back({{x, y, 2}, MaterialId::Stone, 1});
|
||||
}
|
||||
require(world.edit(changes).has_value(), "small oracle fixture failed");
|
||||
std::array<int, 49> distance; distance.fill(-1); distance[8] = 0;
|
||||
std::queue<int> queue; queue.push(8);
|
||||
while (!queue.empty()) {
|
||||
const auto v = queue.front(); queue.pop();
|
||||
for (auto d : std::array<std::array<int, 2>, 4>{{{-1, 0}, {0, -1}, {0, 1}, {1, 0}}}) {
|
||||
const int x = v % 7 + d[0], y = v / 7 + d[1];
|
||||
if (x < 0 || x >= 7 || y < 0 || y >= 7) continue;
|
||||
const auto n = static_cast<std::size_t>(x + 7 * y);
|
||||
if (walls[n] || distance[n] >= 0) continue;
|
||||
distance[n] = distance[static_cast<std::size_t>(v)] + 1; queue.push(static_cast<int>(n));
|
||||
}
|
||||
}
|
||||
auto query = request(world, {1, 1, 1}, {{5, 5, 1}});
|
||||
auto result = find_voxel_path(world, query);
|
||||
if (distance[40] < 0) require(result.status == Status::Unreachable, "oracle blocked path found");
|
||||
else {
|
||||
require_route(world, query, result);
|
||||
require(result.cost == static_cast<std::size_t>(distance[40]), "Void graph route differs from exhaustive grid cost");
|
||||
}
|
||||
}
|
||||
}
|
||||
Test VoxelNavigationTests::real_parallel_queries_preserve_route_and_readsets() {
|
||||
const auto world = stairs(false);
|
||||
const auto query = request(world, {29, 1, 1}, {{36, 1, 4}});
|
||||
const auto expected = find_voxel_path(world, query);
|
||||
require_route(world, query, expected);
|
||||
for (std::size_t workers : {2U, 6U, 12U}) {
|
||||
WorkerPool pool(workers);
|
||||
std::vector<std::future<VoxelPathResult>> futures;
|
||||
for (int i = 0; i < 12; ++i) futures.push_back(pool.submit([&] { return find_voxel_path(world, query); }));
|
||||
std::reverse(futures.begin(), futures.end());
|
||||
for (auto& future : futures) {
|
||||
auto result = future.get();
|
||||
require(result.status == expected.status && result.route == expected.route && result.goal == expected.goal &&
|
||||
result.consulted.chunks == expected.consulted.chunks, "worker completion order altered navigation");
|
||||
}
|
||||
}
|
||||
}
|
||||
} // namespace
|
||||
@@ -0,0 +1,479 @@
|
||||
#include "settlement/core/voxel_region.hpp"
|
||||
#include "settlement/core/worker_pool.hpp"
|
||||
|
||||
#include <Void/Core/Hash.hpp>
|
||||
#include <Void/Core/Scope.hpp>
|
||||
#include <Void/Testing/Suite.hpp>
|
||||
|
||||
#include <algorithm>
|
||||
#include <array>
|
||||
#include <chrono>
|
||||
#include <condition_variable>
|
||||
#include <future>
|
||||
#include <iostream>
|
||||
#include <limits>
|
||||
#include <mutex>
|
||||
#include <span>
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace {
|
||||
using namespace settlement;
|
||||
using Void::Testing::Test;
|
||||
constexpr auto smallest = std::numeric_limits<std::int32_t>::min();
|
||||
constexpr auto largest = std::numeric_limits<std::int32_t>::max();
|
||||
constexpr auto exhausted = std::numeric_limits<std::uint64_t>::max();
|
||||
|
||||
void require(bool condition, const char* message = "voxel region invariant failed") {
|
||||
if (!condition) throw std::runtime_error(message);
|
||||
}
|
||||
VoxelRegionDescriptor descriptor(VoxelBounds bounds = {{-64, -64, -32}, {64, 64, 32}}) {
|
||||
return {7, 42, voxel_generator_version, bounds};
|
||||
}
|
||||
PreparedVoxelChunk generated(const VoxelRegion& region, ChunkCoordinate coordinate) {
|
||||
auto candidate = region.prepare_generated(coordinate);
|
||||
require(candidate.has_value(), "valid chunk generation refused");
|
||||
return std::move(*candidate);
|
||||
}
|
||||
void activate(VoxelRegion& region, std::span<const ChunkCoordinate> coordinates) {
|
||||
std::vector<PreparedVoxelChunk> candidates;
|
||||
for (auto coordinate : coordinates) candidates.push_back(generated(region, coordinate));
|
||||
require(region.activate(candidates).has_value(), "valid chunk activation refused");
|
||||
}
|
||||
VoxelEdit change(const VoxelRegion& region, VoxelPosition position) {
|
||||
const auto sample = region.sample(position);
|
||||
require(sample.availability == VoxelAvailability::Loaded);
|
||||
return {position, sample.material == MaterialId::Air ? MaterialId::Stone : MaterialId::Air, sample.stamp.revision};
|
||||
}
|
||||
void equivalent(const VoxelRegion& left, const VoxelRegion& right) {
|
||||
require(left.descriptor() == right.descriptor());
|
||||
const auto a = left.directory(), b = right.directory();
|
||||
require(a->size() == b->size());
|
||||
for (std::size_t i = 0; i < a->size(); ++i) {
|
||||
require((*a)[i].coordinate == (*b)[i].coordinate &&
|
||||
(*a)[i].chunk->revision() == (*b)[i].chunk->revision());
|
||||
require(std::equal((*a)[i].chunk->cells().begin(), (*a)[i].chunk->cells().end(), (*b)[i].chunk->cells().begin()),
|
||||
"complete material pages differ");
|
||||
}
|
||||
}
|
||||
template<class T> void error(const std::expected<T, VoxelError>& result, VoxelError expected) {
|
||||
require(!result && result.error() == expected, "unexpected operation result");
|
||||
}
|
||||
bool contains(const std::vector<ChunkCoordinate>& coordinates, ChunkCoordinate coordinate) {
|
||||
return std::binary_search(coordinates.begin(), coordinates.end(), coordinate);
|
||||
}
|
||||
|
||||
struct [[= Void::Testing::name("VoxelRegionTests")]] VoxelRegionTests : Void::Testing::Suite<VoxelRegionTests> {
|
||||
[[= Void::Testing::tag("voxel-region")]] Test signed_coordinates_and_x_fast_layout();
|
||||
[[= Void::Testing::tag("voxel-region")]] Test descriptor_validation_and_sparse_extreme_bounds();
|
||||
[[= Void::Testing::tag("voxel-region")]] Test generated_pages_have_fixed_materials_and_continuous_surface();
|
||||
[[= Void::Testing::tag("voxel-region")]] Test preparation_order_and_worker_order_preserve_complete_pages();
|
||||
[[= Void::Testing::tag("voxel-region")]] Test partial_pages_mask_outside_and_validate_import();
|
||||
[[= Void::Testing::tag("voxel-region")]] Test availability_and_snapshot_lifetimes();
|
||||
[[= Void::Testing::tag("voxel-region")]] Test atomic_multichunk_edit_reuses_unchanged_pages();
|
||||
[[= Void::Testing::tag("voxel-region")]] Test refused_batches_and_identical_writes_preserve_publication();
|
||||
[[= Void::Testing::tag("voxel-region")]] Test face_neighbors_and_unavailable_boundaries();
|
||||
[[= Void::Testing::tag("voxel-region")]] Test activation_checks_source_duplicates_and_prior_publication();
|
||||
[[= Void::Testing::tag("voxel-region")]] Test imported_revision_exhaustion_preserves_all_pages();
|
||||
[[= Void::Testing::tag("voxel-region")]] Test page_edit_and_staging_budgets_are_atomic();
|
||||
[[= Void::Testing::tag("voxel-region")]] Test doorway_crossing_two_chunks_opens_atomically();
|
||||
[[= Void::Testing::tag("voxel-region")]] Test full_resident_directory_copies_one_changed_page();
|
||||
};
|
||||
|
||||
Test VoxelRegionTests::signed_coordinates_and_x_fast_layout() {
|
||||
constexpr std::array values{smallest, -33, -32, -1, 0, 31, 32, largest};
|
||||
constexpr std::array chunks{-67108864, -2, -1, -1, 0, 0, 1, 67108863};
|
||||
constexpr std::array locals{0, 31, 0, 31, 0, 31, 0, 31};
|
||||
for (std::size_t i = 0; i < values.size(); ++i) {
|
||||
for (auto y : values) for (auto z : values) {
|
||||
const VoxelPosition position{values[i], y, z};
|
||||
const auto address = split_voxel(position);
|
||||
require(address.chunk.x == chunks[i] && address.local.x == locals[i]);
|
||||
require(join_voxel(address.chunk, address.local) == position);
|
||||
}
|
||||
}
|
||||
require(voxel_index({1, 0, 0}) == 1 && voxel_index({0, 1, 0}) == 32 &&
|
||||
voxel_index({0, 0, 1}) == 1024 && voxel_index({31, 31, 31}) == voxel_chunk_cells - 1);
|
||||
require(!voxel_index({32, 0, 0}) && !voxel_index({0, 255, 0}));
|
||||
require(!join_voxel({67108864, 0, 0}, {}) && !join_voxel({-67108865, 0, 0}, {31, 0, 0}));
|
||||
require(!join_voxel({}, {0, 0, 32}));
|
||||
}
|
||||
|
||||
Test VoxelRegionTests::descriptor_validation_and_sparse_extreme_bounds() {
|
||||
const auto rejected = [](VoxelRegionDescriptor definition) {
|
||||
try { const VoxelRegion region(definition); }
|
||||
catch (const std::invalid_argument&) { return true; }
|
||||
return false;
|
||||
};
|
||||
auto definition = descriptor(); definition.id = 0; require(rejected(definition));
|
||||
definition = descriptor(); definition.generator_version = 0; require(rejected(definition));
|
||||
definition.generator_version = 2; require(rejected(definition));
|
||||
definition = descriptor(); definition.bounds.upper.x = definition.bounds.lower.x; require(rejected(definition));
|
||||
definition = descriptor(); definition.bounds.lower.z = std::int64_t{smallest} - 1; require(rejected(definition));
|
||||
definition = descriptor(); definition.bounds.upper.y = std::int64_t{largest} + 2; require(rejected(definition));
|
||||
VoxelRegion sparse(descriptor({{smallest, smallest, smallest},
|
||||
{std::int64_t{largest} + 1, std::int64_t{largest} + 1, std::int64_t{largest} + 1}}));
|
||||
require(sparse.directory()->empty() && sparse.resident_bytes() == sizeof(VoxelDirectory));
|
||||
const std::array coordinates{ChunkCoordinate{-67108864, -67108864, -67108864},
|
||||
ChunkCoordinate{67108863, 67108863, 67108863}};
|
||||
activate(sparse, coordinates);
|
||||
require(sparse.sample({smallest, smallest, smallest}).material == MaterialId::Stone);
|
||||
require(sparse.sample({largest, largest, largest}).availability == VoxelAvailability::Loaded &&
|
||||
sparse.sample({largest, largest, largest}).material == MaterialId::Air);
|
||||
error(sparse.prepare_generated({largest, 0, 0}), VoxelError::InvalidCoordinate);
|
||||
}
|
||||
|
||||
Test VoxelRegionTests::generated_pages_have_fixed_materials_and_continuous_surface() {
|
||||
VoxelRegion region(descriptor());
|
||||
std::vector<ChunkCoordinate> coordinates;
|
||||
for (int x = -1; x <= 0; ++x) for (int y = -1; y <= 0; ++y) for (int z = -1; z <= 0; ++z) {
|
||||
coordinates.push_back({x, y, z});
|
||||
}
|
||||
activate(region, coordinates);
|
||||
const auto height = [&](int x, int y) {
|
||||
int top = -20;
|
||||
for (int z = -16; z < 16; ++z) if (region.sample({x, y, z}).material != MaterialId::Air) top = z;
|
||||
require(top >= -8 && top <= 8);
|
||||
require(region.sample({x, y, top}).material == MaterialId::Soil &&
|
||||
region.sample({x, y, top - 2}).material == MaterialId::Soil &&
|
||||
region.sample({x, y, top - 3}).material == MaterialId::Stone &&
|
||||
region.sample({x, y, top + 1}).material == MaterialId::Air);
|
||||
return top;
|
||||
};
|
||||
for (int x = -31; x < 31; ++x) for (int y = -31; y < 31; ++y) {
|
||||
const auto top = height(x, y);
|
||||
require(std::abs(top - height(x + 1, y)) <= 1 && std::abs(top - height(x, y + 1)) <= 1,
|
||||
"generator has a discontinuous chunk/lattice surface");
|
||||
}
|
||||
const auto page = region.directory()->front().chunk;
|
||||
const auto hash = Void::Hash::fnv1a64(std::as_bytes(page->cells()));
|
||||
std::cout << "generator1 seed42 chunk(-1,-1,-1) fnv1a64=" << hash << '\n';
|
||||
// Recorded against the canonical little-endian generator, independently
|
||||
// reproduced by the fixture calculation before accepting this revision.
|
||||
require(hash == 13302332479434111011ULL, "canonical generator fixture changed");
|
||||
}
|
||||
|
||||
Test VoxelRegionTests::preparation_order_and_worker_order_preserve_complete_pages() {
|
||||
const std::array coordinates{ChunkCoordinate{0, 0, 0}, ChunkCoordinate{-1, 0, 0},
|
||||
ChunkCoordinate{0, -1, -1}, ChunkCoordinate{1, 1, 0}};
|
||||
VoxelRegion forward(descriptor());
|
||||
activate(forward, coordinates);
|
||||
VoxelRegion reverse(descriptor());
|
||||
auto reversed = coordinates; std::reverse(reversed.begin(), reversed.end());
|
||||
activate(reverse, reversed);
|
||||
equivalent(forward, reverse);
|
||||
for (std::size_t workers : {2, 6, 12}) for (bool reverse_completion : {false, true}) {
|
||||
VoxelRegion parallel(descriptor());
|
||||
WorkerPool pool(workers);
|
||||
std::vector<PreparedVoxelChunk> candidates;
|
||||
for (std::size_t pair = 0; pair < coordinates.size(); pair += 2) {
|
||||
std::mutex mutex;
|
||||
std::condition_variable changed;
|
||||
int ready = 0;
|
||||
std::array<bool, 2> permitted{};
|
||||
bool released = false;
|
||||
std::array<std::future<std::expected<PreparedVoxelChunk, VoxelError>>, 2> futures;
|
||||
// Release and drain every accepted task before its captured gate
|
||||
// dies, including a failed submission or assertion.
|
||||
auto release = Void::Scope::on_exit([&] {
|
||||
{
|
||||
std::lock_guard lock(mutex);
|
||||
released = true;
|
||||
changed.notify_all();
|
||||
}
|
||||
for (auto& future : futures) if (future.valid()) future.wait();
|
||||
});
|
||||
for (std::size_t index = 0; index < 2; ++index) {
|
||||
futures[index] = pool.submit([&, parallel, coordinate = coordinates[pair + index], index] {
|
||||
auto result = parallel.prepare_generated(coordinate);
|
||||
std::unique_lock lock(mutex);
|
||||
++ready;
|
||||
changed.notify_all();
|
||||
changed.wait(lock, [&] { return released || permitted[index]; });
|
||||
return result;
|
||||
});
|
||||
}
|
||||
{
|
||||
std::unique_lock lock(mutex);
|
||||
require(changed.wait_for(lock, std::chrono::seconds(5), [&] { return ready == 2; }),
|
||||
"two real generator tasks did not reach completion gates");
|
||||
}
|
||||
const std::array<std::size_t, 2> order = reverse_completion ?
|
||||
std::array<std::size_t, 2>{1, 0} : std::array<std::size_t, 2>{0, 1};
|
||||
for (auto index : order) {
|
||||
{
|
||||
std::lock_guard lock(mutex);
|
||||
permitted[index] = true;
|
||||
changed.notify_all();
|
||||
}
|
||||
require(futures[index].wait_for(std::chrono::seconds(5)) == std::future_status::ready);
|
||||
auto result = futures[index].get();
|
||||
require(result.has_value());
|
||||
candidates.push_back(std::move(*result));
|
||||
}
|
||||
}
|
||||
require(parallel.activate(candidates).has_value());
|
||||
equivalent(forward, parallel);
|
||||
}
|
||||
auto other_definition = descriptor(); ++other_definition.seed;
|
||||
VoxelRegion other(other_definition); activate(other, coordinates);
|
||||
require(!std::equal(forward.directory()->front().chunk->cells().begin(),
|
||||
forward.directory()->front().chunk->cells().end(), other.directory()->front().chunk->cells().begin()));
|
||||
}
|
||||
|
||||
Test VoxelRegionTests::partial_pages_mask_outside_and_validate_import() {
|
||||
const std::array bounds{VoxelBounds{{-1, -1, -1}, {1, 1, 1}},
|
||||
VoxelBounds{{largest, largest, largest}, {std::int64_t{largest} + 1,
|
||||
std::int64_t{largest} + 1, std::int64_t{largest} + 1}},
|
||||
VoxelBounds{{smallest, smallest, smallest}, {std::int64_t{smallest} + 1,
|
||||
std::int64_t{smallest} + 1, std::int64_t{smallest} + 1}}};
|
||||
for (const auto& bound : bounds) {
|
||||
VoxelRegion region(descriptor(bound));
|
||||
const VoxelPosition position{static_cast<std::int32_t>(bound.lower.x),
|
||||
static_cast<std::int32_t>(bound.lower.y), static_cast<std::int32_t>(bound.lower.z)};
|
||||
const auto coordinate = split_voxel(position).chunk;
|
||||
auto candidate = generated(region, coordinate);
|
||||
const auto cells = candidate.chunk()->cells();
|
||||
for (std::size_t i = 0; i < cells.size(); ++i) {
|
||||
const auto p = join_voxel(coordinate, {static_cast<std::uint8_t>(i % 32),
|
||||
static_cast<std::uint8_t>((i / 32) % 32), static_cast<std::uint8_t>(i / 1024)});
|
||||
require(p.has_value());
|
||||
if (!bound.contains(*p)) require(cells[i] == MaterialId::Air);
|
||||
}
|
||||
auto restored = region.prepare_restored(coordinate, 72, cells);
|
||||
require(restored.has_value() && restored->chunk()->revision() == 72);
|
||||
std::array<MaterialId, voxel_chunk_cells> owned;
|
||||
std::copy(cells.begin(), cells.end(), owned.begin());
|
||||
auto independent = region.prepare_restored(coordinate, 1, owned);
|
||||
require(independent.has_value());
|
||||
const auto index = *voxel_index(split_voxel(position).local);
|
||||
owned[index] = static_cast<MaterialId>(200);
|
||||
error(region.prepare_restored(coordinate, 1, owned), VoxelError::InvalidMaterial);
|
||||
require(independent->chunk()->cells()[index] == cells[index], "import retained caller's mutable cells");
|
||||
owned[index] = cells[index];
|
||||
const auto outside_index = (index + 1234) % voxel_chunk_cells;
|
||||
owned[outside_index] = MaterialId::Stone;
|
||||
error(region.prepare_restored(coordinate, 1, owned), VoxelError::InvalidCoordinate);
|
||||
error(region.prepare_restored(coordinate, 0, cells), VoxelError::InvalidRevision);
|
||||
error(region.prepare_restored(coordinate, 1, cells.first(100)), VoxelError::InvalidSource);
|
||||
}
|
||||
}
|
||||
|
||||
Test VoxelRegionTests::availability_and_snapshot_lifetimes() {
|
||||
VoxelRegion region(descriptor());
|
||||
const auto absent = region.sample({0, 0, 20});
|
||||
require(absent.availability == VoxelAvailability::Unavailable);
|
||||
const auto outside = region.sample({64, 0, 20});
|
||||
require(outside.availability == VoxelAvailability::Outside);
|
||||
auto held = region;
|
||||
const std::array coordinates{ChunkCoordinate{0, 0, 0}};
|
||||
activate(region, coordinates);
|
||||
require(!region.matches(absent.stamp) && held.matches(absent.stamp));
|
||||
const auto loaded = region.sample({0, 0, 20});
|
||||
require(loaded.availability == VoxelAvailability::Loaded && loaded.material == MaterialId::Air);
|
||||
require(held.sample({0, 0, 20}).availability == VoxelAvailability::Unavailable);
|
||||
auto owned_directory = region.directory();
|
||||
auto retained = region;
|
||||
const std::array changes{change(region, {0, 0, 20})};
|
||||
require(region.edit(changes).has_value());
|
||||
require(retained.matches(loaded.stamp) && !region.matches(loaded.stamp));
|
||||
require(owned_directory->front().chunk->cells()[20 * 1024] == MaterialId::Air);
|
||||
auto other_stamp = loaded.stamp; ++other_stamp.region; require(!retained.matches(other_stamp));
|
||||
}
|
||||
|
||||
Test VoxelRegionTests::atomic_multichunk_edit_reuses_unchanged_pages() {
|
||||
VoxelRegion region(descriptor());
|
||||
const std::array coordinates{ChunkCoordinate{-1, 0, 0}, ChunkCoordinate{0, 0, 0}, ChunkCoordinate{1, 0, 0}};
|
||||
activate(region, coordinates);
|
||||
const auto held = region;
|
||||
const std::array changes{change(region, {0, 2, 20}), change(region, {-1, 2, 20}), change(region, {4, 4, 20})};
|
||||
const auto result = region.edit(changes);
|
||||
require(result.has_value() && result->changed_chunks.size() == 2 && result->changed_cells.size() == 3);
|
||||
require(result->changed_cells[0].position == VoxelPosition{-1, 2, 20} &&
|
||||
result->changed_cells[1].position == VoxelPosition{0, 2, 20});
|
||||
require(result->changed_chunks[0].coordinate == ChunkCoordinate{-1, 0, 0} &&
|
||||
result->changed_chunks[1].coordinate == ChunkCoordinate{0, 0, 0});
|
||||
for (const auto& change : changes) {
|
||||
require(region.sample(change.position).material == change.material);
|
||||
require(held.sample(change.position).material != change.material);
|
||||
require(region.sample(change.position).stamp.revision == 2);
|
||||
}
|
||||
require(region.directory()->back().chunk == held.directory()->back().chunk,
|
||||
"untouched geometry was copied");
|
||||
VoxelRegion other = held;
|
||||
auto reversed = changes; std::reverse(reversed.begin(), reversed.end());
|
||||
require(other.edit(reversed).has_value()); equivalent(region, other);
|
||||
}
|
||||
|
||||
Test VoxelRegionTests::refused_batches_and_identical_writes_preserve_publication() {
|
||||
VoxelRegion region(descriptor());
|
||||
const std::array coordinates{ChunkCoordinate{-1, 0, 0}, ChunkCoordinate{0, 0, 0}};
|
||||
activate(region, coordinates);
|
||||
const auto held = region;
|
||||
auto changes = std::array{change(region, {-1, 1, 20}), change(region, {0, 1, 20})};
|
||||
++changes[1].expected_revision;
|
||||
error(region.edit(changes), VoxelError::Stale);
|
||||
--changes[1].expected_revision; changes[1].material = static_cast<MaterialId>(255);
|
||||
error(region.edit(changes), VoxelError::InvalidMaterial);
|
||||
changes[1] = changes[0]; error(region.edit(changes), VoxelError::Duplicate);
|
||||
changes[1] = {{32, 1, 20}, MaterialId::Stone, 1}; error(region.edit(changes), VoxelError::Unavailable);
|
||||
changes[1].position.x = 64; error(region.edit(changes), VoxelError::InvalidCoordinate);
|
||||
require(region.directory() == held.directory()); equivalent(region, held);
|
||||
require(region.edit({}).has_value() && region.directory() == held.directory());
|
||||
const auto current = region.sample({0, 1, 20});
|
||||
std::array identical{VoxelEdit{{0, 1, 20}, current.material, current.stamp.revision}};
|
||||
const auto result = region.edit(identical);
|
||||
require(result && result->changed_chunks.empty() && result->changed_cells.empty() && result->dirty_chunks.empty());
|
||||
require(region.directory() == held.directory());
|
||||
--identical[0].expected_revision; error(region.edit(identical), VoxelError::Stale);
|
||||
require(region.directory() == held.directory());
|
||||
}
|
||||
|
||||
Test VoxelRegionTests::face_neighbors_and_unavailable_boundaries() {
|
||||
VoxelRegion region(descriptor({{-64, -64, -64}, {64, 64, 64}}));
|
||||
const std::array coordinates{ChunkCoordinate{-1, -1, -1}, ChunkCoordinate{0, -1, -1}};
|
||||
activate(region, coordinates);
|
||||
const auto neighbor = region.chunk_stamp({0, -1, -1});
|
||||
const auto absent = region.chunk_stamp({-1, 0, -1});
|
||||
const std::array changes{change(region, {-1, -1, -1})};
|
||||
const auto result = region.edit(changes);
|
||||
require(result && result->dirty_chunks.size() == 4);
|
||||
require(contains(result->dirty_chunks, {-1, -1, -1}) && contains(result->dirty_chunks, {0, -1, -1}) &&
|
||||
contains(result->dirty_chunks, {-1, 0, -1}) && contains(result->dirty_chunks, {-1, -1, 0}));
|
||||
require(!contains(result->dirty_chunks, {0, 0, -1}) && !contains(result->dirty_chunks, {0, 0, 0}));
|
||||
require(region.matches(neighbor) && region.matches(absent));
|
||||
const std::array interior{change(region, {-2, -2, -2})};
|
||||
const auto result2 = region.edit(interior);
|
||||
require(result2 && result2->dirty_chunks == std::vector<ChunkCoordinate>{{-1, -1, -1}});
|
||||
VoxelRegion edge(descriptor({{largest, 0, 0}, {std::int64_t{largest} + 1, 1, 1}}));
|
||||
const std::array last_chunk{split_voxel({largest, 0, 0}).chunk}; activate(edge, last_chunk);
|
||||
const std::array last_change{change(edge, {largest, 0, 0})};
|
||||
const auto last_result = edge.edit(last_change);
|
||||
require(last_result && last_result->dirty_chunks == std::vector<ChunkCoordinate>{last_chunk[0]});
|
||||
}
|
||||
|
||||
Test VoxelRegionTests::activation_checks_source_duplicates_and_prior_publication() {
|
||||
VoxelRegion region(descriptor());
|
||||
auto candidate = generated(region, {});
|
||||
const auto empty = region.directory();
|
||||
const std::array duplicate{candidate, candidate}; error(region.activate(duplicate), VoxelError::Duplicate);
|
||||
require(region.directory() == empty);
|
||||
for (int field = 0; field < 3; ++field) {
|
||||
auto wrong = descriptor();
|
||||
if (field == 0) ++wrong.id;
|
||||
if (field == 1) ++wrong.seed;
|
||||
if (field == 2) --wrong.bounds.lower.x;
|
||||
VoxelRegion other(wrong);
|
||||
const std::array mixed{candidate, generated(other, {-1, 0, 0})};
|
||||
error(region.activate(mixed), VoxelError::InvalidSource);
|
||||
require(region.directory() == empty);
|
||||
}
|
||||
const std::array first{candidate}; require(region.activate(first).has_value());
|
||||
const auto held = region.directory();
|
||||
const std::array late{generated(region, {-1, 0, 0}), candidate};
|
||||
error(region.activate(late), VoxelError::Stale); require(region.directory() == held);
|
||||
}
|
||||
|
||||
Test VoxelRegionTests::imported_revision_exhaustion_preserves_all_pages() {
|
||||
VoxelRegion region(descriptor());
|
||||
const auto source = generated(region, {});
|
||||
auto maximum = region.prepare_restored({}, exhausted, source.chunk()->cells());
|
||||
require(maximum.has_value());
|
||||
const std::array pages{generated(region, {-1, 0, 0}), *maximum};
|
||||
require(region.activate(pages).has_value());
|
||||
const auto held = region;
|
||||
const std::array changes{change(region, {-1, 1, 20}), change(region, {0, 1, 20})};
|
||||
error(region.edit(changes), VoxelError::RevisionExhausted);
|
||||
require(region.directory() == held.directory()); equivalent(region, held);
|
||||
const auto current = region.sample({0, 1, 20});
|
||||
const std::array identical{VoxelEdit{{0, 1, 20}, current.material, exhausted}};
|
||||
require(region.edit(identical).has_value() && region.directory() == held.directory());
|
||||
}
|
||||
|
||||
Test VoxelRegionTests::page_edit_and_staging_budgets_are_atomic() {
|
||||
VoxelRegion source(descriptor());
|
||||
const std::array pages{generated(source, {}), generated(source, {-1, 0, 0})};
|
||||
VoxelLimits one; one.max_resident_chunks = 1;
|
||||
VoxelRegion bounded(descriptor(), one);
|
||||
const auto empty = bounded.directory();
|
||||
error(bounded.activate(pages), VoxelError::LimitExceeded); require(bounded.directory() == empty);
|
||||
require(bounded.activate(std::span(pages).first(1)).has_value());
|
||||
error(bounded.activate(std::span(pages).last(1)), VoxelError::LimitExceeded);
|
||||
VoxelLimits bytes; bytes.max_resident_bytes = sizeof(VoxelDirectory) + sizeof(VoxelChunkEntry) + sizeof(VoxelChunk) - 1;
|
||||
VoxelRegion small(descriptor(), bytes);
|
||||
error(small.activate(std::span(pages).first(1)), VoxelError::LimitExceeded);
|
||||
VoxelLimits transactions; transactions.max_transaction_bytes = sizeof(VoxelChunk) + 1024;
|
||||
VoxelRegion limited(descriptor(), transactions);
|
||||
error(limited.prepare_generated({}), VoxelError::LimitExceeded);
|
||||
require(limited.activate(std::span(pages).first(1)).has_value());
|
||||
const auto held = limited.directory();
|
||||
const std::array edits{change(limited, {1, 1, 20})};
|
||||
error(limited.edit(edits), VoxelError::LimitExceeded); require(limited.directory() == held);
|
||||
VoxelLimits edit_limit; edit_limit.max_edit_cells = 1;
|
||||
VoxelRegion two(descriptor(), edit_limit); require(two.activate(pages).has_value());
|
||||
const std::array too_many{change(two, {1, 1, 20}), change(two, {-1, 1, 20})};
|
||||
error(two.edit(too_many), VoxelError::LimitExceeded);
|
||||
require(two.resident_bytes() == sizeof(VoxelDirectory) + 2 * (sizeof(VoxelChunkEntry) + sizeof(VoxelChunk)));
|
||||
VoxelLimits hostile; hostile.max_resident_chunks = std::numeric_limits<std::size_t>::max();
|
||||
VoxelRegion sparse(descriptor(), hostile); require(sparse.directory()->empty());
|
||||
std::cout << "voxel payload: page=" << sizeof(VoxelChunk) << " directory entry=" << sizeof(VoxelChunkEntry)
|
||||
<< " active256=" << sizeof(VoxelDirectory) + 256 * (sizeof(VoxelChunkEntry) + sizeof(VoxelChunk)) << '\n';
|
||||
}
|
||||
|
||||
Test VoxelRegionTests::doorway_crossing_two_chunks_opens_atomically() {
|
||||
require(voxel_blocks_passage(MaterialId::DoorClosed) && !voxel_blocks_passage(MaterialId::DoorOpen));
|
||||
require(!voxel_provides_support(MaterialId::DoorClosed) && !voxel_provides_support(MaterialId::DoorOpen));
|
||||
require(!voxel_blocks_passage(MaterialId::Air) && !voxel_provides_support(MaterialId::Air));
|
||||
for (auto material : {MaterialId::Soil, MaterialId::Stone}) {
|
||||
require(voxel_blocks_passage(material) && voxel_provides_support(material));
|
||||
}
|
||||
VoxelRegion region(descriptor({{0, 0, 0}, {32, 32, 64}}));
|
||||
const std::array coordinates{ChunkCoordinate{0, 0, 0}, ChunkCoordinate{0, 0, 1}};
|
||||
activate(region, coordinates);
|
||||
const std::array closed{VoxelEdit{{2, 2, 31}, MaterialId::DoorClosed, 1},
|
||||
VoxelEdit{{2, 2, 32}, MaterialId::DoorClosed, 1}};
|
||||
require(region.edit(closed).has_value());
|
||||
const auto held = region;
|
||||
std::array opened{VoxelEdit{{2, 2, 31}, MaterialId::DoorOpen, 2},
|
||||
VoxelEdit{{2, 2, 32}, MaterialId::DoorOpen, 1}};
|
||||
error(region.edit(opened), VoxelError::Stale);
|
||||
require(region.directory() == held.directory());
|
||||
opened[1].expected_revision = 2;
|
||||
const auto result = region.edit(opened);
|
||||
require(result && result->changed_chunks.size() == 2 && result->changed_cells.size() == 2);
|
||||
for (auto edit : opened) {
|
||||
require(region.sample(edit.position).material == MaterialId::DoorOpen);
|
||||
require(held.sample(edit.position).material == MaterialId::DoorClosed);
|
||||
}
|
||||
auto imported = region.prepare_restored(coordinates[0], 3, region.directory()->front().chunk->cells());
|
||||
require(imported.has_value());
|
||||
}
|
||||
|
||||
Test VoxelRegionTests::full_resident_directory_copies_one_changed_page() {
|
||||
using Clock = std::chrono::steady_clock;
|
||||
VoxelRegion region(descriptor({{-256, -256, 0}, {256, 256, 32}}));
|
||||
std::vector<ChunkCoordinate> coordinates;
|
||||
for (int x = -8; x < 8; ++x) for (int y = -8; y < 8; ++y) coordinates.push_back({x, y, 0});
|
||||
const auto preparation_started = Clock::now();
|
||||
activate(region, coordinates);
|
||||
const auto preparation_done = Clock::now();
|
||||
const auto held = region;
|
||||
require(held.directory() == region.directory() && held.directory()->size() == 256);
|
||||
const std::array edits{change(region, {1, 1, 20})};
|
||||
const auto edit_started = Clock::now();
|
||||
const auto result = region.edit(edits);
|
||||
const auto edit_done = Clock::now();
|
||||
require(result && result->changed_chunks.size() == 1);
|
||||
std::size_t shared = 0;
|
||||
for (std::size_t i = 0; i < region.directory()->size(); ++i) {
|
||||
if ((*held.directory())[i].chunk == (*region.directory())[i].chunk) ++shared;
|
||||
}
|
||||
require(shared == 255 && region.directory() != held.directory());
|
||||
require(held.sample(edits[0].position).material != region.sample(edits[0].position).material);
|
||||
std::cout << "full256 pages: prepare+activate_us="
|
||||
<< std::chrono::duration_cast<std::chrono::microseconds>(preparation_done - preparation_started).count()
|
||||
<< " edit_us=" << std::chrono::duration_cast<std::chrono::microseconds>(edit_done - edit_started).count()
|
||||
<< " shared_pages=" << shared << " resident_payload=" << region.resident_bytes() << '\n';
|
||||
}
|
||||
} // namespace
|
||||
Reference in new issue
Block a user