Integrate persistent logistics references with the simulation owner

This commit is contained in:
faumaray committed 2026-12-02 22:02:47 +03:00
commit c2d9d8d51a
9 files changed
+494 -87

No files matched your search

+3 -2
View File
@@ -23,7 +23,7 @@ function(add_void_library)
set(BUILD_SHARED_LIBS OFF)
set(VOID_ENABLE_TESTING OFF)
set(VOID_ENABLE_BENCHMARKS OFF)
set(VOID_ENABLED_MODULES Algorithms Async Binary Core Crypto Data Text Time)
set(VOID_ENABLED_MODULES Algorithms Async Binary Core Crypto Data Math Text Time)
set(CMAKE_DISABLE_FIND_PACKAGE_OpenSSL ON)
if(BUILD_TESTING)
list(APPEND VOID_ENABLED_MODULES Testing)
@@ -58,7 +58,7 @@ target_include_directories(settlement_core
target_compile_features(settlement_core PUBLIC cxx_std_23)
target_link_libraries(settlement_core
PUBLIC Threads::Threads Void::Async Void::Core Void::Time
PRIVATE Void::Algorithms Void::Binary Void::Crypto Void::Data Void::Text
PRIVATE Void::Algorithms Void::Binary Void::Crypto Void::Data Void::Math Void::Text
)
if(MSVC)
@@ -114,6 +114,7 @@ if(BUILD_TESTING)
tests/checkpoint_tests.cpp
tests/core_tests.cpp
tests/executor_tests.cpp
tests/identity_tests.cpp
tests/replay_tests.cpp
tests/rules_tests.cpp
tests/runtime_tests.cpp
+2 -3
View File
@@ -1884,9 +1884,8 @@ std::wstring resident_details() {
text += resident->state == settlement::AgentState::Working ? L" Работает за верстаком" :
L" Везёт материалы в мастерскую";
}
else if (resident->resource_node_index != settlement::no_entity_index &&
resident->storage_index == settlement::no_entity_index) {
const auto& site = world->resource_nodes()[resident->resource_node_index];
else if (resident->resource_node_id != 0 && resident->storage_id == 0) {
const auto& site = *world->find_resource_node(resident->resource_node_id);
const bool trees = site.site == settlement::ResourceSite::TreePlot;
if (resident->state == settlement::AgentState::Travelling) {
text += trees ? L" Идёт на посадку деревьев" : L" Идёт засевать поле";
+48
View File
@@ -0,0 +1,48 @@
# Resolve stored logistics references by stable storage and resource IDs
Task ID: S06-01
Role: sol_implementer
Status: READY
## 1. Context and baseline
Isolated checkout /home/faumaray/Projects/stoneheart_at_home-worktrees/s06, system/s06-logistics begins a4cf99c. M01-P3 mapped World+codec+UI references, M01-V6 requires checked exhaustion for all storage/node allocation paths. Actual WorldState groups the complete capture; modern v1 checkpoint embeds format13; legacy tests 1–13/LAN11.
## 2. Objective and deliverables
Migrate live Agent::resource_node_index and storage_index, MaterialReservation::storage_index and ConstructionStop::storage_index to the selected objects' existing nonzero IDs. Deleting an earlier unrelated element must preserve all targets and quantities. Cover restoration and ID exhaustion.
## 3. Scope and non-goals
Only S06-01 storage/resource references and checked allocation at all existing sites. Production index and next agent/job/production counters have their own later contract, stack/reservation/transfer identity comes later. Preserve deliberately confirmed stock demolition behavior. No public new network protocol, geometry, checkpoint schema or UI feature.
## 4. Files to inspect
Inspect world.hpp, world.cpp, world_save.cpp, first_colony.cpp, viewer_win32.cpp resident detail, graphics/callers including benchmarks, core/replay/snapshot/checkpoint tests. Read S06/S04, M01-P3/V6, pin Math/Numeric.hpp checked_add and Core/Counted.hpp. Use stable-vector ordering validated by WorldSaveCodec. Verify existing API users by rg.
## 5. Write ownership and coordination
Write scope: engine/include/settlement/core/world.hpp; engine/src/world.cpp; engine/src/world_save.cpp; app/viewer_win32.cpp (existing resident-detail reference access only); tests/core_tests.cpp; tests/snapshot_tests.cpp; tests/replay_tests.cpp; tests/checkpoint_tests.cpp; tests/identity_tests.cpp (NEW); CMakeLists.txt; docs/plan/systems/S06.md
Other code owners operate in isolated branches. You are not alone; do not revert others or change Git/shared Serena. Modify existing tests only for changed ref semantics, not to weaken checks.
## 6. Implementation or investigation approach
Use zero as missing typed ResourceNodeId/StorageId, remove positional fixups for these members everywhere. Expose read-only bounded ID lookup and reuse ID-ordered lower_bound or equivalent. Keep indices ephemeral inside assignment and validation count arrays. Encode ID→old positional one-based/sentinel fields exactly; decode raw positions in explicitly bounded loader temporaries then convert to IDs after referenced arrays are populated and order validated, before world domain validation/use. Reject out-of-range/missing ID before indexing. Keep production_index/no_entity_index independent. Preserve ordering, deterministic routes and complete old wire bytes. Write source comments with linked replacement test for Void/Library #7.
## 7. Interfaces and data contracts
ID exhaustion: UINT64_MAX in next_* is a legitimate terminal high-water mark, last allocatable ID is MAX-1. Precompute checked successor with pinned Void::Numeric::checked_add before world/vector/terrain effects in World::add_resource_node, World::add_storage AND direct Place{BerryField,TreePlot,FlaxField,Mine} and PlaceStorage command paths. Only commit counter after successful construction/insertion. No returning zero, wraparound or duplicate IDs. Direct factory exhaustion raises std::overflow_error, commands return non-mutating Busy without consuming legacy sequence. For MAX-1 exactly one insertion then a stable serialized exhausted world. Validate invalid refs and preserve existing stronger invariants/canonical old bytes.
## 8. Dependencies and integration
Root owns CMake merge, dependent runtime/GUI packages, Git and upstream. Void/Library #7 covers restorable checked sequences; #8 is later custody, pinned Void Numeric handles arithmetic now. Preserve current std::unique_ptr<World> factories/mode, Render const path, standalone tests. No compatibility alias which silently restores use of vector indices.
## 9. Edge cases security and performance
Mid-carry before/after erasing earlier store/node, pantry meal, site tending with no storage, construction multi-stop delivery, carpenter output reservation, active targets remain protected by existing rules. Guard lookup for none/dangling, sorted IDs and caches. Ensure fast logarithmic lookups; avoid O(N²) scans or per-agent linear scans during codec, no duplicate durable map to synchronize. Check max vs max-1 inputs, failed insertions and byte-level determinism. Use pre-migration external baseline or saved corpus to verify exact bytes when gameplay equivalent.
## 10. Acceptance criteria
1. Live references preserve meaning after erasing an earlier unrelated store/node; no shifted refs remain in runtime. 2. Capture, legacy save13, checkpoint roundtrip and serial/2/6/12 trajectories agree mid-haul. 3. MAX/MAX-1 at every allocation path, including mine blocked-cell/cache on rejection. 4. Damaged legacy indices reject candidate, no partial live mutation. 5. All tests/cross build pass incl baseline, focused identity tests and project docs.
## 11. Verification commands and evidence
Source /tmp/stoneheart-verify.KoZwE4o8/env.sh. From YOUR worktree configure cmake -S . -B /tmp/stoneheart-milestones.xprJ2SVp/identity-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 identity, verbose CTest, git diff --check. Cross-baseline compare relevant old outputs; root shares /tmp/stoneheart-milestones.xprJ2SVp/trajectory.cpp & old-trajectory.bin. Report actual bytes/scenarios and time if performance measured.
## 12. Constraints and stop conditions
No side effects outside checkout/build/log temp. Stop if current wire cannot represent migrating these existing IDs without loss, or a supported caller needs out-of-scope change, or after two failed repairs of the same issue. Do not silently drop malformed/legacy data.
## 13. Authorization and decisions
User authorizes all milestone/system implementation, upstream issues, commits and PRs. M01-P3 proposed slice and M01-V6 preflight correction is incorporated here; root confirms narrow corrective re-review before dispatch.
## 14. Return format
Return S06-01 status, actual files/lookup and legacy conversion boundaries, overflow/Busy semantics, commands/counts, cross-baseline byte evidence, remaining limitations. No children/commits/push.
+6
View File
@@ -60,6 +60,12 @@ S06 владеет фактическими количествами, содер
## VoidLibrary и приёмка
Первый срез 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)
Применять существующие подходящие средства контейнеров, проверяемой арифметики, сериализации и результатов из [VoidLibrary](../void-library.md). Для отсутствующей возможности перед локальной реализацией найти либо создать issue в `Void/Library` и указать ссылку в задаче и коде.
- Два заказа запрашивают последнюю единицу ресурса. Только один получает резерв, свободный запас остаётся неотрицательным.
+12 -6
View File
@@ -17,6 +17,8 @@ namespace settlement {
using AgentId = std::uint64_t;
using JobId = std::uint64_t;
using ResourceNodeId = std::uint64_t;
using StorageId = std::uint64_t;
struct GridPosition {
std::int32_t x = 0;
@@ -237,8 +239,8 @@ struct Agent {
std::vector<GridPosition> route;
std::size_t route_cursor = 0;
std::uint32_t work_remaining = 0;
std::size_t resource_node_index = no_entity_index;
std::size_t storage_index = no_entity_index;
ResourceNodeId resource_node_id = 0;
StorageId storage_id = 0;
Inventory inventory;
std::vector<GridPosition> haul_route;
std::size_t production_index = no_entity_index;
@@ -260,7 +262,7 @@ struct WorkJob {
};
struct ResourceNode {
std::uint64_t id = 0;
ResourceNodeId id = 0;
GridPosition position;
ItemType type = ItemType::None;
std::uint32_t quantity = 0;
@@ -282,7 +284,7 @@ struct ItemStack {
};
struct Storage {
std::uint64_t id = 0;
StorageId id = 0;
GridPosition position;
std::uint32_t capacity = 0;
std::uint32_t reserved_slots = 0;
@@ -317,13 +319,13 @@ struct Storage {
};
struct MaterialReservation {
std::size_t storage_index;
StorageId storage_id;
ItemType type;
std::uint32_t count;
};
struct ConstructionStop {
std::size_t storage_index;
StorageId storage_id;
std::vector<GridPosition> route_to_next;
};
@@ -443,6 +445,8 @@ public:
[[nodiscard]] const std::vector<WorkJob>& jobs() const noexcept;
[[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 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;
[[nodiscard]] bool is_bed_cell(GridPosition position) const noexcept;
@@ -463,6 +467,8 @@ private:
bool reachable = false;
};
[[nodiscard]] Storage& storage_by_id(StorageId id);
[[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;
[[nodiscard]] PathResult assignment_path(GridPosition start, GridPosition goal);
+75 -41
View File
@@ -1,6 +1,7 @@
#include "settlement/core/world.hpp"
#include <Void/Core/Scope.hpp>
#include <Void/Math/Numeric.hpp>
#include <algorithm>
#include <array>
@@ -134,6 +135,19 @@ auto stack_position(Storage& storage, ItemType type) {
[](const ItemStack& stack, ItemType target) { return stack.type < target; });
}
template<class Records>
auto record_position(Records& records, std::uint64_t id) {
return std::lower_bound(records.begin(), records.end(), id,
[](const auto& record, std::uint64_t target) { return record.id < target; });
}
template<class Records>
auto& require_record(Records& records, std::uint64_t id) {
const auto found = record_position(records, id);
if (found == records.end() || found->id != id) throw std::logic_error("Missing simulation object ID.");
return *found;
}
std::size_t checked_cell_count(std::int32_t width, std::int32_t height) {
if (width <= 0 || height <= 0 || width > max_map_dimension || height > max_map_dimension) {
throw std::invalid_argument("map dimensions must be in the range 1..512");
@@ -298,6 +312,24 @@ std::shared_ptr<const World> World::capture() const {
return std::shared_ptr<const World>(new const World(CaptureTag{}, *this));
}
const Storage* World::find_storage(StorageId id) const noexcept {
const auto found = record_position(storages_, id);
return found == storages_.end() || found->id != id ? nullptr : &*found;
}
const ResourceNode* World::find_resource_node(ResourceNodeId id) const noexcept {
const auto found = record_position(resource_nodes_, id);
return found == resource_nodes_.end() || found->id != id ? nullptr : &*found;
}
Storage& World::storage_by_id(StorageId id) {
return require_record(storages_, id);
}
ResourceNode& World::resource_node_by_id(ResourceNodeId id) {
return require_record(resource_nodes_, id);
}
std::size_t World::cell_index(GridPosition position) const noexcept {
return static_cast<std::size_t>(position.y) * static_cast<std::size_t>(width_) +
static_cast<std::size_t>(position.x);
@@ -401,9 +433,14 @@ std::uint64_t World::add_resource_node(GridPosition position, ItemType type,
if ((type != ItemType::Wood && type != ItemType::Stone && type != ItemType::Berries) || quantity == 0) {
throw std::invalid_argument("resource node needs wood, stone, or berries and a positive quantity");
}
const std::uint64_t id = next_resource_node_id_++;
// Restorable counters stay with each World. Replacement contract and limits
// are tracked at https://git.faumaray.com/Void/Library/issues/7.
const std::uint64_t id = next_resource_node_id_;
const auto successor = Void::Numeric::checked_add(id, std::uint64_t{1});
if (!successor) throw std::overflow_error("resource node IDs exhausted");
const bool foraging = type != ItemType::Berries || !scenario_active_;
resource_nodes_.push_back(ResourceNode{id, position, type, quantity, quantity, 0, foraging});
next_resource_node_id_ = *successor;
return id;
}
@@ -418,10 +455,12 @@ std::uint64_t World::add_storage(GridPosition position, std::uint32_t capacity,
throw std::invalid_argument("unknown storage kind");
}
const std::uint64_t id = next_storage_id_;
const auto successor = Void::Numeric::checked_add(id, std::uint64_t{1});
if (!successor) throw std::overflow_error("storage IDs exhausted");
Storage storage{id, position, capacity, 0, {}, kind};
storage.items.reserve(kind == StorageKind::Pantry ? 1 : item_type_count - 1);
storages_.push_back(std::move(storage));
++next_storage_id_;
next_storage_id_ = *successor;
return id;
}
@@ -628,7 +667,7 @@ CommandStatus World::object_status(GridPosition position, bool moving) const noe
[](const auto& item) { return item.reserved != 0; })) return busy;
for (const auto& order : production_orders_) {
if (std::any_of(order.materials.begin(), order.materials.end(),
[i](const auto& material) { return material.storage_index == i; })) return busy;
[&storage](const auto& material) { return material.storage_id == storage.id; })) return busy;
}
return ready;
}
@@ -674,13 +713,7 @@ CommandStatus World::edit_object(GridPosition position, const GridPosition* dest
for (std::size_t i = 0; i < std::size(carpentry_products); ++i) {
lost_products[i] = storage->item_count(carpentry_products[i]) != 0;
}
const auto removed = static_cast<std::size_t>(storage - storages_.begin());
storages_.erase(storage);
for (auto& agent : agents_) shift_index(agent.storage_index, removed);
for (auto& entry : production_orders_) {
for (auto& material : entry.materials) shift_index(material.storage_index, removed);
for (auto& stop : entry.delivery_stops) shift_index(stop.storage_index, removed);
}
if (scenario_active_) {
for (std::size_t i = 0; i < std::size(carpentry_products); ++i) {
if (!lost_products[i]) continue;
@@ -706,9 +739,7 @@ CommandStatus World::edit_object(GridPosition position, const GridPosition* dest
}
if (destination) source->position = *destination;
else {
const auto removed = static_cast<std::size_t>(source - resource_nodes_.begin());
resource_nodes_.erase(source);
for (auto& agent : agents_) shift_index(agent.resource_node_index, removed);
}
return CommandStatus::Accepted;
}
@@ -793,9 +824,11 @@ CommandReceipt World::apply_command(const PlayerCommand& command) {
} else if (!can_reach_object_cell(command.cell)) {
return receipt(CommandStatus::InvalidTarget);
}
const auto successor = Void::Numeric::checked_add(next_resource_node_id_, std::uint64_t{1});
if (!successor) return receipt(CommandStatus::Busy);
resource_nodes_.push_back({next_resource_node_id_, command.cell, site_resource(site), mine ? yield : 0,
yield, 0, true, site});
++next_resource_node_id_;
next_resource_node_id_ = *successor;
if (mine) {
blocked_[cell_index(command.cell)] = 0;
assignment_path_cache_.clear();
@@ -870,6 +903,7 @@ CommandReceipt World::apply_command(const PlayerCommand& command) {
!can_place_storage(command.cell) || !can_reach_object_cell(command.cell)) {
return receipt(CommandStatus::InvalidTarget);
}
if (!Void::Numeric::checked_add(next_storage_id_, std::uint64_t{1})) return receipt(CommandStatus::Busy);
static_cast<void>(add_storage(command.cell, 18, static_cast<StorageKind>(command.value)));
break;
case CommandKind::MoveObject:
@@ -1244,7 +1278,7 @@ void World::assign_resource_tasks(ResourceFocus focus) {
if (node.needs_tending()) {
++resource_nodes_[node_index].reserved_workers;
--untended_sites;
agent.resource_node_index = node_index;
agent.resource_node_id = node.id;
agent.route = std::move(path_to_node.positions);
agent.route_cursor = 0;
agent.work_remaining = tending_ticks;
@@ -1285,8 +1319,8 @@ void World::assign_resource_tasks(ResourceFocus focus) {
if (storage.kind == StorageKind::Pantry) --open_pantry_count;
else --open_material_store_count;
}
agent.resource_node_index = node_index;
agent.storage_index = storage_index;
agent.resource_node_id = node.id;
agent.storage_id = storage.id;
agent.haul_route = std::move(path_to_storage.positions);
agent.route = std::move(path_to_node.positions);
agent.route_cursor = 0;
@@ -1341,7 +1375,7 @@ void World::assign_production_tasks(bool weaving) {
}
if (access == Access::Unreachable) continue;
}
materials.push_back({storage_index, ingredient.type, count});
materials.push_back({storage.id, ingredient.type, count});
remaining -= count;
}
if (remaining != 0) {
@@ -1354,12 +1388,12 @@ void World::assign_production_tasks(bool weaving) {
std::vector<ConstructionStop> stops;
if (deliver_ingredients) {
for (std::size_t s = 0; s < storage_access.size(); ++s) {
if (storage_access[s] == Access::Reachable) stops.push_back({s, {}});
if (storage_access[s] == Access::Reachable) stops.push_back({storages_[s].id, {}});
}
for (std::size_t i = 0; i < stops.size(); ++i) {
const auto from = storages_[stops[i].storage_index].position;
const auto from = storage_by_id(stops[i].storage_id).position;
const auto to = i + 1 == stops.size()
? order.position : storages_[stops[i + 1].storage_index].position;
? order.position : storage_by_id(stops[i + 1].storage_id).position;
auto path = assignment_path(from, to);
// Each stop can reach the site on the same undirected map.
assert(path.reachable);
@@ -1367,7 +1401,7 @@ void World::assign_production_tasks(bool weaving) {
}
}
const GridPosition destination = deliver_ingredients
? storages_[stops.front().storage_index].position : order.position;
? storage_by_id(stops.front().storage_id).position : order.position;
for (Agent& agent : agents_) {
const bool can_craft = agent.profession == Profession::Carpenter;
const bool eligible = carpentry ? can_craft :
@@ -1376,11 +1410,11 @@ void World::assign_production_tasks(bool weaving) {
auto path = assignment_path(agent.position, destination);
if (!path.reachable) continue;
if (carpentry) {
agent.haul_route = assignment_path(order.position, storages_[materials.front().storage_index].position).positions;
agent.haul_route = assignment_path(order.position, storage_by_id(materials.front().storage_id).position).positions;
}
for (const auto& material : materials) {
stack_position(storages_[material.storage_index], material.type)->reserved += material.count;
stack_position(storage_by_id(material.storage_id), material.type)->reserved += material.count;
}
order.materials = std::move(materials);
order.delivery_stops = std::move(stops);
@@ -1436,7 +1470,7 @@ void World::assign_meals() {
auto stack = stack_position(storage, ItemType::Berries);
++stack->reserved;
agent.storage_index = *pantry;
agent.storage_id = storage.id;
agent.state = AgentState::GoingToEat;
agent.route = std::move(path.positions);
agent.route_cursor = 0;
@@ -1449,9 +1483,9 @@ 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(storages_[agent.storage_index], {agent.storage_index, ItemType::Berries, 1});
take_reserved_material(storage_by_id(agent.storage_id), {agent.storage_id, ItemType::Berries, 1});
agent.inventory.add(ItemType::Berries);
agent.storage_index = no_entity_index;
agent.storage_id = 0;
agent.route.clear();
agent.route_cursor = 0;
agent.work_remaining = meal_ticks;
@@ -1533,14 +1567,14 @@ void World::advance_construction_delivery(Agent& agent) {
auto& stop = order.delivery_stops[order.collected_stops];
for (const auto& material : order.materials) {
if (material.storage_index == stop.storage_index) {
take_reserved_material(storages_[stop.storage_index], material);
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 (is_carpentry_recipe(order.recipe) && stop.storage_index == order.materials.front().storage_index) {
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.
++storages_[stop.storage_index].reserved_slots;
++storage_by_id(stop.storage_id).reserved_slots;
}
++order.collected_stops;
agent.route = std::move(stop.route_to_next);
@@ -1554,7 +1588,7 @@ void World::finish_production(Agent& agent) {
assert(!order.materials.empty());
if (is_carpentry_recipe(order.recipe)) {
agent.inventory.add(recipe.output);
agent.storage_index = order.materials.front().storage_index;
agent.storage_id = order.materials.front().storage_id;
agent.route = std::move(agent.haul_route);
agent.haul_route.clear();
agent.route_cursor = 0;
@@ -1566,10 +1600,10 @@ void World::finish_production(Agent& agent) {
}
if (recipe.output != ItemType::None) {
for (const auto& material : order.materials) {
take_reserved_material(storages_[material.storage_index], material);
take_reserved_material(storage_by_id(material.storage_id), material);
}
// Crafting replaces one raw item with one finished item in the same store.
storages_[order.materials.front().storage_index].add_item(recipe.output);
storage_by_id(order.materials.front().storage_id).add_item(recipe.output);
}
order.materials.clear();
if (order.recipe == RecipeId::BuildBed &&
@@ -1648,7 +1682,7 @@ void World::step(TickProfile* profile) {
agent.route_cursor < agent.route.size()) {
agent.position = agent.route[agent.route_cursor++];
if (agent.state == AgentState::Travelling && agent.route_cursor == agent.route.size()) {
agent.state = agent.resource_node_index == no_entity_index
agent.state = agent.resource_node_id == 0
? AgentState::Working : AgentState::Gathering;
}
}
@@ -1717,12 +1751,12 @@ void World::step(TickProfile* profile) {
finish_production(agent);
}
if (agent.state == AgentState::Gathering) {
if (agent.work_remaining == 0 && agent.resource_node_index < resource_nodes_.size()) {
ResourceNode& node = resource_nodes_[agent.resource_node_index];
if (agent.storage_index == no_entity_index) {
if (agent.work_remaining == 0 && agent.resource_node_id != 0) {
ResourceNode& node = resource_node_by_id(agent.resource_node_id);
if (agent.storage_id == 0) {
node.growth_at = tick_ + growing_time(node.site);
--node.reserved_workers;
agent.resource_node_index = no_entity_index;
agent.resource_node_id = 0;
agent.state = AgentState::Idle;
agent.route.clear();
agent.route_cursor = 0;
@@ -1731,7 +1765,7 @@ void World::step(TickProfile* profile) {
if (node.quantity > 0) --node.quantity;
if (node.reserved_workers > 0) --node.reserved_workers;
agent.inventory.add(node.type);
agent.resource_node_index = no_entity_index;
agent.resource_node_id = 0;
agent.route = std::move(agent.haul_route);
agent.haul_route.clear();
agent.route_cursor = 0;
@@ -1740,13 +1774,13 @@ void World::step(TickProfile* profile) {
}
if (agent.state == AgentState::Hauling && agent.route_cursor == agent.route.size() &&
agent.storage_index < storages_.size()) {
Storage& storage = storages_[agent.storage_index];
agent.storage_id != 0) {
Storage& storage = storage_by_id(agent.storage_id);
const ItemType cargo = agent.inventory.first_item();
if (storage.reserved_slots > 0) --storage.reserved_slots;
storage.add_item(cargo);
agent.inventory.remove(cargo);
agent.storage_index = no_entity_index;
agent.storage_id = 0;
agent.state = AgentState::Idle;
agent.route.clear();
agent.route_cursor = 0;
+82 -27
View File
@@ -146,6 +146,41 @@ void index(Archive& archive, Index& value) {
}
}
template<class Records>
std::size_t record_index(const Records& records, std::uint64_t id) {
const auto found = std::lower_bound(records.begin(), records.end(), id,
[](const auto& record, std::uint64_t target) { return record.id < target; });
require_save(found != records.end() && found->id == id, "Save contains an invalid object reference.");
return static_cast<std::size_t>(found - records.begin());
}
template<class Records>
std::uint64_t reference_id(const Records& records, std::size_t position) {
if (position == no_entity_index) return 0;
require_save(position < records.size(), "Save contains an invalid object index.");
return records[position].id;
}
template<class Records>
void validate_reference_pool(const Records& records, std::uint64_t next_id) {
std::uint64_t previous = 0;
for (const auto& record : records) {
require_save(record.id > previous, "Save contains unordered object IDs.");
previous = record.id;
}
require_save(next_id > previous, "Save contains an invalid next object ID.");
}
template<class Archive, class Id, class Records>
void reference(Archive& archive, Id& id, const Records& records) {
std::size_t position = no_entity_index;
if constexpr (!Archive::reading) {
if (id != 0) position = record_index(records, id);
}
index(archive, position);
if constexpr (Archive::reading) id = reference_id(records, position);
}
template<class Archive, class Size>
void offset(Archive& archive, Size& value) {
auto wire = static_cast<std::uint64_t>(value);
@@ -199,6 +234,9 @@ struct WorldSaveCodec {
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;
sequence(archive, world.agents_, max_records, [&](auto& agent) {
archive.field(agent.id);
position(archive, agent.position);
@@ -207,8 +245,15 @@ struct WorldSaveCodec {
route(archive, agent.route, cells);
offset(archive, agent.route_cursor);
archive.field(agent.work_remaining);
index(archive, agent.resource_node_index);
index(archive, agent.storage_index);
if constexpr (Archive::reading) {
std::array<std::size_t, 2> links{no_entity_index, no_entity_index};
index(archive, links[0]);
index(archive, links[1]);
agent_links.push_back(links);
} else {
reference(archive, agent.resource_node_id, world.resource_nodes_);
reference(archive, agent.storage_id, world.storages_);
}
const auto inventory_types = version >= 3 ? max_item_count : static_cast<std::size_t>(ItemType::Berries);
for (std::size_t i = 1; i <= inventory_types; ++i) {
const auto type = static_cast<ItemType>(i);
@@ -261,6 +306,14 @@ struct WorldSaveCodec {
storage.items.reserve(storage.kind == StorageKind::Pantry ? 1 : item_types - 1);
}
});
if constexpr (Archive::reading) {
validate_reference_pool(world.resource_nodes_, world.next_resource_node_id_);
validate_reference_pool(world.storages_, world.next_storage_id_);
for (std::size_t i = 0; i < agent_links.size(); ++i) {
world.agents_[i].resource_node_id = reference_id(world.resource_nodes_, agent_links[i][0]);
world.agents_[i].storage_id = reference_id(world.storages_, agent_links[i][1]);
}
}
sequence(archive, world.production_orders_, max_records, [&](auto& order) {
position(archive, order.position);
archive.field(order.recipe);
@@ -272,13 +325,13 @@ 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) {
index(archive, material.storage_index);
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) {
index(archive, stop.storage_index);
reference(archive, stop.storage_id, world.storages_);
route(archive, stop.route_to_next, cells);
});
offset(archive, order.collected_stops);
@@ -371,6 +424,8 @@ void WorldSaveCodec::validate(const World& world) {
}
}
const auto storage_index = [&](StorageId id) { return record_index(world.storages_, id); };
const auto node_index = [&](ResourceNodeId id) { return record_index(world.resource_nodes_, id); };
std::vector<ItemCounts> reserved_items(world.storages_.size());
std::vector<ItemCounts> expected_cargo(world.production_orders_.size());
std::vector<AgentId> bed_owners;
@@ -399,33 +454,33 @@ void WorldSaveCodec::validate(const World& world) {
const bool delivery = delivers_materials(order.recipe);
invalid(order.collected_stops <= order.delivery_stops.size() && (delivery || order.delivery_stops.empty()));
std::size_t last_storage = 0;
StorageId last_storage = 0;
bool first_stop = true;
for (const auto& stop : order.delivery_stops) {
invalid(stop.storage_index < world.storages_.size() && (first_stop || last_storage < stop.storage_index));
invalid(world.find_storage(stop.storage_id) != nullptr && (first_stop || last_storage < stop.storage_id));
invalid(std::any_of(order.materials.begin(), order.materials.end(),
[&](const auto& material) { return material.storage_index == stop.storage_index; }));
[&](const auto& material) { return material.storage_id == stop.storage_id; }));
valid_route(stop.route_to_next);
first_stop = false;
last_storage = stop.storage_index;
last_storage = stop.storage_id;
}
ItemCounts ingredients{};
for (const auto& material : order.materials) {
const auto type = item_index(material.type);
invalid(material.storage_index < world.storages_.size() && material.count > 0 &&
world.storages_[material.storage_index].kind == StorageKind::Materials);
invalid(world.find_storage(material.storage_id) != nullptr && material.count > 0 &&
world.storages_[storage_index(material.storage_id)].kind == StorageKind::Materials);
ingredients[type] += material.count;
if (!delivery) {
reserved_items[material.storage_index][type] += material.count;
reserved_items[storage_index(material.storage_id)][type] += material.count;
} else if (!order.delivery_stops.empty()) {
const auto stop = std::find_if(order.delivery_stops.begin(), order.delivery_stops.end(),
[&](const auto& entry) { return entry.storage_index == material.storage_index; });
[&](const auto& entry) { return entry.storage_id == material.storage_id; });
invalid(stop != order.delivery_stops.end());
if (static_cast<std::size_t>(stop - order.delivery_stops.begin()) < order.collected_stops) {
expected_cargo[i][type] += material.count;
} else {
reserved_items[material.storage_index][type] += material.count;
reserved_items[storage_index(material.storage_id)][type] += material.count;
}
}
}
@@ -486,9 +541,9 @@ void WorldSaveCodec::validate(const World& world) {
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_source = agent.resource_node_index != no_entity_index;
const bool has_storage = agent.storage_index != no_entity_index;
invalid(!has_storage || agent.storage_index < world.storages_.size());
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);
invalid(agent.haul_route.empty() || has_source || carpentry);
@@ -513,12 +568,12 @@ void WorldSaveCodec::validate(const World& world) {
invalid(agent.state == Working || (agent.state == Travelling && !delivers_materials(order.recipe)));
}
if (carpentry) {
const auto storage = order.materials.front().storage_index;
const auto storage = storage_index(order.materials.front().storage_id);
const auto destination = world.storages_[storage].position;
invalid(agent.haul_route.empty() ? destination == order.position : agent.haul_route.back() == destination);
const auto& stops = order.delivery_stops;
const auto output_stop = std::find_if(stops.begin(), stops.end(),
[storage](const auto& stop) { return stop.storage_index == storage; });
[&order](const auto& stop) { return stop.storage_id == order.materials.front().storage_id; });
const bool collected = stops.empty() ||
static_cast<std::size_t>(output_stop - stops.begin()) < order.collected_stops;
if (collected) ++reserved_slots[storage];
@@ -527,32 +582,32 @@ void WorldSaveCodec::validate(const World& world) {
invalid(agent.inventory.item_count(static_cast<ItemType>(i + 1)) == expected_cargo[agent.production_index][i]);
}
} else if (has_source) {
invalid(agent.resource_node_index < world.resource_nodes_.size() &&
invalid(world.find_resource_node(agent.resource_node_id) != nullptr &&
(agent.state == Travelling || agent.state == Gathering) && agent.inventory.empty() &&
agent.work_remaining > 0);
const auto& source = world.resource_nodes_[agent.resource_node_index];
const auto& source = world.resource_nodes_[node_index(agent.resource_node_id)];
if (has_storage) {
invalid(source.quantity > 0 && world.storages_[agent.storage_index].accepts(source.type));
++reserved_slots[agent.storage_index];
invalid(source.quantity > 0 && world.storages_[storage_index(agent.storage_id)].accepts(source.type));
++reserved_slots[storage_index(agent.storage_id)];
} else {
invalid(source.needs_tending() && agent.haul_route.empty());
}
++reserved_nodes[agent.resource_node_index];
++reserved_nodes[node_index(agent.resource_node_id)];
} else if (agent.state == Hauling) {
const auto cargo = agent.inventory.first_item();
invalid(has_storage && (cargo == ItemType::Wood || cargo == ItemType::Stone ||
cargo == ItemType::Berries || cargo == ItemType::Flax || is_carpentry_item(cargo)) &&
agent.inventory.item_count(cargo) == 1 && agent.work_remaining == 0 &&
world.storages_[agent.storage_index].accepts(cargo));
world.storages_[storage_index(agent.storage_id)].accepts(cargo));
for (std::size_t i = 1; i <= item_types; ++i) {
const auto type = static_cast<ItemType>(i);
invalid(type == cargo || agent.inventory.item_count(type) == 0);
}
++reserved_slots[agent.storage_index];
++reserved_slots[storage_index(agent.storage_id)];
} else if (agent.state == GoingToEat) {
invalid(world.hunger_enabled_ && has_storage && agent.inventory.empty() &&
world.storages_[agent.storage_index].kind == StorageKind::Pantry);
++reserved_items[agent.storage_index][item_index(ItemType::Berries)];
world.storages_[storage_index(agent.storage_id)].kind == StorageKind::Pantry);
++reserved_items[storage_index(agent.storage_id)][item_index(ItemType::Berries)];
} else if (agent.state == Eating) {
invalid(world.hunger_enabled_ && !has_storage && agent.work_remaining > 0 &&
agent.inventory.item_count(ItemType::Berries) == 1 &&
+8 -8
View File
@@ -694,12 +694,12 @@ Test CoreTests::test_specialists_take_their_own_jobs_and_finish_prior_assignment
CommandStatus::Accepted, "could not schedule the specialist jobs");
world.step();
for (std::size_t index = 0; index < 3; ++index) {
require(world.agents()[index].resource_node_index == index, "a specialist chose the wrong resource");
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_index == no_entity_index,
require(world.agents()[3].production_index == 0 && 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_index == 2,
world.agents()[2].resource_node_id == world.resource_nodes()[2].id,
"changing professions interrupted a reserved mining job");
auto copy = save_roundtrip(world);
@@ -711,8 +711,8 @@ Test CoreTests::test_specialists_take_their_own_jobs_and_finish_prior_assignment
require(save_contents(world) == save_contents(*copy), "specialist jobs diverged after loading");
const auto& resident = world.agents()[2];
if (resident.inventory.item_count(ItemType::Stone) > 0) delivered_stone = true;
if (resident.resource_node_index == 1) later_cut_wood = true;
if (later_cut_wood) require(resident.resource_node_index != 2, "a woodcutter kept selecting mining jobs");
if (resident.resource_node_id == world.resource_nodes()[1].id) later_cut_wood = true;
if (later_cut_wood) require(resident.resource_node_id != world.resource_nodes()[2].id, "a woodcutter kept selecting mining jobs");
}
require(delivered_stone && later_cut_wood, "the reassigned miner did not finish mining and then cut wood");
require(world.scenario_progress().assigned_beds == 1, "the builder did not complete the bed");
@@ -812,7 +812,7 @@ Test CoreTests::test_field_growth_requires_a_worker() {
"could not assign the farmer");
world.step();
require(world.agents().front().state == AgentState::Travelling &&
world.agents().front().storage_index == no_entity_index &&
world.agents().front().storage_id == 0 &&
world.object_status(field, true) == CommandStatus::Busy, "the farmer did not reserve and walk to the field");
auto restored = save_roundtrip(world);
for (int i = 0; i < 100; ++i) {
@@ -840,7 +840,7 @@ Test CoreTests::test_opening_a_mine_invalidates_unreachable_routes() {
require(world.apply_command({1, 2, CommandKind::PlaceMine, {3, 4}}).status == CommandStatus::Accepted,
"failed to open a passage");
world.step();
require(world.agents().front().resource_node_index == 0 &&
require(world.agents().front().resource_node_id == world.resource_nodes()[0].id &&
world.agents().front().state == AgentState::Travelling, "terrain edit left a stale route in the cache");
}
@@ -1041,7 +1041,7 @@ Test CoreTests::test_carpenter_delivers_the_door_before_installation() {
}
if (!delivered_door && resident.inventory.item_count(ItemType::WoodenDoor) == 1) {
delivered_door = true;
require(resident.state == AgentState::Hauling && resident.storage_index == 0 &&
require(resident.state == AgentState::Hauling && resident.storage_id == world->storages()[0].id &&
world->storages()[0].item_count(ItemType::WoodenDoor) == 0,
"the finished door appeared on the store before being delivered");
world = save_roundtrip(*world);
+258
View File
@@ -0,0 +1,258 @@
#include "settlement/core/checkpoint.hpp"
#include "settlement/core/world.hpp"
#include <Void/Testing/Assert.hpp>
#include <Void/Testing/Suite.hpp>
#include <array>
#include <limits>
#include <sstream>
#include <stdexcept>
#include <string>
namespace {
using namespace settlement;
using Void::Testing::Test;
void require(bool condition, const char* message = "identity invariant failed") {
if (!condition) throw std::runtime_error(message);
}
constexpr auto last_counter = std::numeric_limits<std::uint64_t>::max();
// Format 13 header, five tick/stat counters, hunger and four next-ID counters.
constexpr std::size_t next_node_offset = 85;
constexpr std::size_t next_storage_offset = 93;
std::string bytes(const World& world) {
std::ostringstream stream(std::ios::binary);
world.write_save(stream);
return stream.str();
}
void put_u64(std::string& data, std::size_t at, std::uint64_t value) {
require(at + 8 <= data.size(), "fixture offset outside save");
for (unsigned i = 0; i < 8; ++i) data[at + i] = static_cast<char>((value >> (i * 8)) & 255);
}
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);
}
CommandStatus command(World& world, CommandKind kind, GridPosition cell = {}, std::uint8_t value = 0) {
return world.apply_command({1, world.next_command_sequence(1), kind, cell, value}).status;
}
void compare_continuation(World& original, int ticks) {
const auto initial = bytes(original);
std::array copies{restore(initial, 1), restore(initial, 2), restore(initial, 6), restore(initial, 12)};
const auto catalog = builtin_rule_packages();
const auto rules = default_rules_manifest();
require(catalog.has_value() && rules.has_value(), "built-in rule fixture failed");
const auto id = Void::Uuid::try_v4();
require(id.has_value(), "UUID fixture failed");
const auto checkpoint = encode_checkpoint(original, *id, 1, *rules);
require(checkpoint.has_value(), "checkpoint encode failed");
auto candidate = decode_checkpoint(*checkpoint, *catalog, 1, ExecutionMode::SerialReference);
require(candidate.has_value(), "checkpoint decode failed");
const auto held = original.capture();
for (int tick = 0; tick < ticks; ++tick) {
original.step();
const auto expected = bytes(original);
for (auto& copy : copies) {
copy->step();
require(bytes(*copy) == expected, "ID-linked continuation differs across execution modes");
}
candidate->world->step();
require(bytes(*candidate->world) == expected, "checkpoint continuation changed ID links");
require(bytes(*held) == initial, "held snapshot changed after ID-linked world advanced");
}
}
template<class Work>
void require_exhausted(World& world, Work work) {
const auto before = bytes(world);
bool overflow = false;
try { work(); } catch (const std::overflow_error&) { overflow = true; }
require(overflow && bytes(world) == before, "exhausted factory mutated state or failed to report overflow");
}
struct [[= Void::Testing::name("IdentityTests")]] IdentityTests : Void::Testing::Suite<IdentityTests> {
[[= Void::Testing::tag("identity")]] Test test_active_haul_survives_earlier_storage_and_node_deletion();
[[= Void::Testing::tag("identity")]] Test test_construction_stops_retain_ids_after_earlier_storage_deletion();
[[= Void::Testing::tag("identity")]] Test test_pantry_and_unstored_tending_restore_stable_ids();
[[= Void::Testing::tag("identity")]] Test test_carpenter_output_retains_its_storage_id();
[[= Void::Testing::tag("identity")]] Test test_factory_counters_stop_before_max_without_mutation();
[[= Void::Testing::tag("identity")]] Test test_command_counters_stop_before_max_without_terrain_changes();
[[= Void::Testing::tag("identity")]] Test test_invalid_legacy_positions_fail_before_candidate_publication();
};
Test IdentityTests::test_active_haul_survives_earlier_storage_and_node_deletion() {
World world(42, 32, 32, 1, ExecutionMode::SerialReference);
const auto unused_store = world.add_storage({1, 1}, 10, StorageKind::Pantry);
const auto destination = world.add_storage({28, 4}, 30);
const auto unused_node = world.add_resource_node({30, 25}, ItemType::Stone, 3);
const auto source = world.add_resource_node({6, 4}, ItemType::Wood, 5);
const auto resident = world.spawn_agent({4, 4});
require(world.apply_command({1, 1, CommandKind::AssignProfession, {},
static_cast<std::uint8_t>(Profession::Woodcutter), {}, resident}).status == CommandStatus::Accepted);
world.step();
require(world.agents().front().resource_node_id == source &&
world.agents().front().storage_id == destination, "fixture did not reserve the later node and store");
require(command(world, CommandKind::DemolishObject, {1, 1}) == CommandStatus::Accepted &&
command(world, CommandKind::DemolishObject, {30, 25}) == CommandStatus::Accepted);
require(world.find_storage(unused_store) == nullptr && world.find_resource_node(unused_node) == nullptr);
require(world.agents().front().resource_node_id == source &&
world.agents().front().storage_id == destination, "deleting earlier records changed durable links");
require(world.find_storage(0) == nullptr && world.find_resource_node(last_counter) == nullptr);
for (int tick = 0; tick < 40 && world.agents().front().state != AgentState::Hauling; ++tick) world.step();
require(world.agents().front().state == AgentState::Hauling &&
world.agents().front().inventory.item_count(ItemType::Wood) == 1);
compare_continuation(world, 80);
require(world.find_storage(destination)->item_count(ItemType::Wood) > 0, "cargo missed its stable destination");
}
Test IdentityTests::test_construction_stops_retain_ids_after_earlier_storage_deletion() {
World world(43, 32, 32, 1, ExecutionMode::SerialReference);
static_cast<void>(world.add_storage({1, 1}, 10, StorageKind::Pantry));
const auto planks = world.add_storage({3, 3}, 20);
const auto blocks = world.add_storage({8, 3}, 20);
world.stock_storage(planks, ItemType::Plank, 3);
world.stock_storage(blocks, ItemType::StoneBlock, 2);
static_cast<void>(world.spawn_agent({2, 3}));
world.queue_production({14, 3}, RecipeId::BuildCabin);
world.step();
const auto& order = world.production_orders().front();
require(order.delivery_stops.size() == 2 && order.delivery_stops[0].storage_id == planks &&
order.delivery_stops[1].storage_id == blocks, "construction did not retain both actual store IDs");
require(command(world, CommandKind::DemolishObject, {1, 1}) == CommandStatus::Accepted);
require(order.materials[0].storage_id == planks && order.materials[1].storage_id == blocks);
for (int tick = 0; tick < 20 && order.collected_stops == 0; ++tick) world.step();
require(order.collected_stops == 1 && !world.agents().front().inventory.empty());
compare_continuation(world, 65);
require(order.state == JobState::Completed, "multi-store construction did not finish");
}
Test IdentityTests::test_pantry_and_unstored_tending_restore_stable_ids() {
World meal(44, 32, 32, 1, ExecutionMode::SerialReference);
static_cast<void>(meal.add_storage({1, 1}, 5));
const auto pantry = meal.add_storage({28, 4}, 50, StorageKind::Pantry);
meal.stock_storage(pantry, ItemType::Berries, 40);
static_cast<void>(meal.spawn_agent({4, 4}));
meal.enable_hunger();
for (int tick = 0; tick < 500 && meal.agents().front().state != AgentState::GoingToEat; ++tick) meal.step();
require(meal.agents().front().storage_id == pantry);
require(command(meal, CommandKind::DemolishObject, {1, 1}) == CommandStatus::Accepted);
compare_continuation(meal, 50);
require(meal.meals_eaten() > 0);
World tending(45, 32, 32, 1, ExecutionMode::SerialReference);
static_cast<void>(tending.spawn_agent({2, 3}));
static_cast<void>(tending.add_resource_node({30, 30}, ItemType::Stone, 1));
require(command(tending, CommandKind::PlaceBerryField, {9, 3}) == CommandStatus::Accepted);
tending.step();
require(tending.agents().front().resource_node_id == tending.resource_nodes().back().id &&
tending.agents().front().storage_id == 0, "tending acquired an unrelated storage");
require(command(tending, CommandKind::DemolishObject, {30, 30}) == CommandStatus::Accepted);
compare_continuation(tending, 100);
require(tending.resource_nodes().front().quantity > 0);
}
Test IdentityTests::test_carpenter_output_retains_its_storage_id() {
World world(49, 32, 32, 1, ExecutionMode::SerialReference);
static_cast<void>(world.add_storage({1, 1}, 10, StorageKind::Pantry));
const auto materials = world.add_storage({2, 3}, 10);
world.stock_storage(materials, ItemType::Wood, 2);
const auto carpenter = world.spawn_agent({2, 2});
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::CraftWoodenDoor);
world.step();
require(command(world, CommandKind::DemolishObject, {1, 1}) == CommandStatus::Accepted);
for (int tick = 0; tick < 100 &&
world.agents().front().inventory.item_count(ItemType::WoodenDoor) == 0; ++tick) world.step();
require(world.agents().front().inventory.item_count(ItemType::WoodenDoor) == 1 &&
world.agents().front().storage_id == materials && world.find_storage(materials)->reserved_slots == 1,
"carpenter output lost its persistent reserved destination");
compare_continuation(world, 30);
require(world.find_storage(materials)->item_count(ItemType::WoodenDoor) == 1 &&
world.find_storage(materials)->reserved_slots == 0, "carpenter delivered into the wrong storage");
}
Test IdentityTests::test_factory_counters_stop_before_max_without_mutation() {
World empty(46, 8, 8, 1, ExecutionMode::SerialReference);
for (const auto offset : {next_node_offset, next_storage_offset}) {
auto data = bytes(empty);
put_u64(data, offset, last_counter - 1);
auto world = restore(data);
if (offset == next_node_offset) {
require(world->add_resource_node({2, 2}, ItemType::Wood, 1) == last_counter - 1);
world = restore(bytes(*world));
require_exhausted(*world, [&] { static_cast<void>(world->add_resource_node({3, 3}, ItemType::Stone, 1)); });
} else {
require(world->add_storage({2, 2}, 10) == last_counter - 1);
world = restore(bytes(*world));
require_exhausted(*world, [&] { static_cast<void>(world->add_storage({3, 3}, 10)); });
}
put_u64(data, offset, last_counter);
world = restore(data);
if (offset == next_node_offset) {
require_exhausted(*world, [&] { static_cast<void>(world->add_resource_node({2, 2}, ItemType::Wood, 1)); });
} else {
require_exhausted(*world, [&] { static_cast<void>(world->add_storage({2, 2}, 10)); });
}
}
}
Test IdentityTests::test_command_counters_stop_before_max_without_terrain_changes() {
constexpr std::array kinds{CommandKind::PlaceBerryField, CommandKind::PlaceTreePlot,
CommandKind::PlaceFlaxField, CommandKind::PlaceMine, CommandKind::PlaceStorage};
for (const auto kind : kinds) {
World initial(47, 8, 8, 1, ExecutionMode::SerialReference);
static_cast<void>(initial.spawn_agent({2, 2}));
const bool mine = kind == CommandKind::PlaceMine;
if (mine) {
initial.set_blocked({4, 4});
initial.set_blocked({5, 4});
}
const auto offset = kind == CommandKind::PlaceStorage ? next_storage_offset : next_node_offset;
auto data = bytes(initial);
put_u64(data, offset, last_counter);
auto world = restore(data);
const auto before = bytes(*world);
require(command(*world, kind, {4, 4}) == CommandStatus::Busy && bytes(*world) == before &&
world->next_command_sequence(1) == 1, "exhausted command changed world or consumed sequence");
if (mine) require(!world->is_walkable({4, 4}));
put_u64(data, offset, last_counter - 1);
world = restore(data);
require(command(*world, kind, {4, 4}) == CommandStatus::Accepted);
require(kind == CommandKind::PlaceStorage ? world->storages().back().id == last_counter - 1 :
world->resource_nodes().back().id == last_counter - 1);
world = restore(bytes(*world));
const auto exhausted = bytes(*world);
require(command(*world, kind, {5, 4}) == CommandStatus::Busy && bytes(*world) == exhausted &&
world->next_command_sequence(1) == 2, "second exhausted command changed state");
if (mine) require(!world->is_walkable({5, 4}));
}
}
Test IdentityTests::test_invalid_legacy_positions_fail_before_candidate_publication() {
World world(48, 8, 8, 1, ExecutionMode::SerialReference);
static_cast<void>(world.spawn_agent({2, 2}));
static_cast<void>(world.add_resource_node({3, 3}, ItemType::Wood, 2));
static_cast<void>(world.add_storage({4, 4}, 10));
const auto original = bytes(world);
// The first resident has an empty route. Its two legacy links follow the
// 101-byte prefix, cell mask, resident count and 41 bytes of resident fields.
constexpr std::size_t node_link = 101 + 8 * 8 + 4 + 41;
for (const auto at : {node_link, node_link + 8}) {
auto invalid = original;
put_u64(invalid, at, 2); // One-based position two, with a single record.
bool rejected = false;
try { static_cast<void>(restore(invalid)); } catch (const std::runtime_error&) { rejected = true; }
require(rejected && bytes(world) == original, "dangling legacy link escaped candidate validation");
}
}
} // namespace