Integrate durable production orders and checkpoint schema 2 into M01
# Conflicts: # CMakeLists.txt
This commit is contained in:
commit
a8cd7bb415
16 files changed
+661
-88
No files matched your search
@@ -118,6 +118,7 @@ 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/replay_tests.cpp
|
||||
tests/rules_tests.cpp
|
||||
|
||||
@@ -1879,8 +1879,8 @@ std::wstring resident_details() {
|
||||
profession_name(resident->profession) + L" Голод " + std::to_wstring(hunger) + L"%";
|
||||
if (resident->state == settlement::AgentState::GoingToEat) text += L" Идёт к кладовой";
|
||||
else if (resident->state == settlement::AgentState::Eating) text += L" Ест";
|
||||
else if (resident->production_index != settlement::no_entity_index &&
|
||||
settlement::is_carpentry_recipe(world->production_orders()[resident->production_index].recipe)) {
|
||||
else if (world->find_production(resident->production_id) != nullptr &&
|
||||
settlement::is_carpentry_recipe(world->find_production(resident->production_id)->recipe)) {
|
||||
text += resident->state == settlement::AgentState::Working ? L" Работает за верстаком" :
|
||||
L" Везёт материалы в мастерскую";
|
||||
}
|
||||
|
||||
@@ -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.
|
||||
@@ -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.
|
||||
|
||||
## Данные и владение
|
||||
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
+67
-40
@@ -322,6 +322,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 +404,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 +522,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 +587,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 +599,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 +626,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 +718,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 +732,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 +759,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 +794,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 +866,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 +898,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 +908,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 +917,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 +1447,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;
|
||||
@@ -1553,7 +1580,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);
|
||||
@@ -1584,7 +1611,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 +1620,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 +1646,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 +1722,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 +1769,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);
|
||||
|
||||
@@ -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
|
||||
@@ -38,7 +38,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();
|
||||
}
|
||||
|
||||
|
||||
@@ -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);
|
||||
|
||||
Reference in new issue
Block a user