#include "settlement/core/world.hpp" #include #include #include #include #include #include #include #include #include #include #include #include namespace settlement { namespace { constexpr std::string_view signature = "SETTLERS"; constexpr std::uint32_t save_version = 15; 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; // The wire limit is independent of decoded C++ layout: an old byte-light agent // now includes an execution/claim array. Cover every bounded top-level pool, // nested vectors (maximum element expansion <4x wire), and the receipt ring. // This is an accounting ceiling, never a reserve() request from untrusted input. constexpr std::size_t record_pool_bytes = sizeof(Agent) + sizeof(WorkJob) + sizeof(ResourceNode) + sizeof(Storage) + sizeof(ProductionOrder); static_assert(record_pool_bytes <= (std::numeric_limits::max() - 4 * max_save_bytes - custody_receipt_limit * (sizeof(CustodyReceipt) + 32)) / max_records); constexpr std::size_t max_decode_allocation_bytes = max_records * record_pool_bytes + 4 * max_save_bytes + custody_receipt_limit * (sizeof(CustodyReceipt) + 32); void require_save(bool condition, const char* error) { if (!condition) throw std::runtime_error(error); } class SaveWriter { public: static constexpr bool reading = false; explicit SaveWriter(std::ostream& stream) : stream_(stream) {} template void field(T value) { if constexpr (std::is_enum_v) { field(static_cast>(value)); } else { std::array bytes; Void::Binary::Writer writer(std::as_writable_bytes(std::span{bytes})); require_save(writer.writeLittle(value).has_value(), "Could not encode a save field."); // Preserve the stream prefix if writing stops partway through a field. for (char byte : bytes) { require_save(bytes_ < max_save_bytes, "Save exceeds the 128 MiB limit."); ++bytes_; stream_.put(byte); require_save(static_cast(stream_), "Could not write the save."); } } } private: std::ostream& stream_; std::size_t bytes_ = 0; }; class SaveReader { public: static constexpr bool reading = true; explicit SaveReader(std::istream& stream) : stream_(stream) {} template void field(T& value, bool payload = true) { if constexpr (std::is_enum_v) { std::underlying_type_t bits = 0; field(bits, payload); value = static_cast(bits); } else { std::array bytes; for (char& byte : bytes) { const int next = stream_.get(); require_save(next != std::char_traits::eof(), "Save is incomplete or unreadable."); byte = std::char_traits::to_char_type(next); if (payload) { require_save(bytes_ < max_save_bytes, "Save exceeds the 128 MiB limit."); ++bytes_; } } const auto wire = std::as_bytes(std::span{bytes}); if (payload && legacy_footer_) legacy_digest_ = Void::Hash::fnv1a64_update(legacy_digest_, wire); Void::Binary::Reader reader(wire); const auto decoded = reader.readLittle(); require_save(decoded.has_value(), "Could not decode a save field."); value = *decoded; } } void allocate(std::size_t count, std::size_t size) { require_save(count <= max_decode_allocation_bytes / size && allocations_.consume_field(count * size).has_value(), "Save allocation budget exceeded."); } void set_version(std::uint32_t version) { legacy_footer_ = version <= last_legacy_footer_version; } void finish() { if (legacy_footer_) { std::uint64_t expected = 0; field(expected, false); require_save(legacy_digest_ == expected, "Legacy save integrity footer does not match."); } require_save(stream_.peek() == std::char_traits::eof() && !stream_.bad(), "Save contains unexpected trailing data."); } private: std::istream& stream_; std::size_t bytes_ = 0; // Legacy footers cover the signature and version, which are read first. Void::Binary::DecodeBudget allocations_{{max_decode_allocation_bytes, max_decode_allocation_bytes, 64}}; bool legacy_footer_ = true; std::uint64_t legacy_digest_ = Void::Hash::fnv1a64_offset_basis; }; template void sequence(Archive& archive, Vector& values, std::size_t limit, Visit visit) { require_save(values.size() <= limit, "Save contains too many records."); auto length = static_cast(values.size()); archive.field(length); require_save(length <= limit, "Save contains too many records."); if constexpr (Archive::reading) { archive.allocate(length, sizeof(typename Vector::value_type)); for (std::uint32_t i = 0; i < length; ++i) { values.emplace_back(); visit(values.back()); } } else { for (const auto& value : values) visit(value); } } template void position(Archive& archive, Position& value) { archive.field(value.x); archive.field(value.y); } template void route(Archive& archive, Route& points, std::size_t cells) { sequence(archive, points, cells, [&](auto& point) { position(archive, point); }); } template void index(Archive& archive, Index& value) { // Store zero for missing links and one-based indices for present links on all platforms. std::uint64_t wire = value == no_entity_index ? 0 : static_cast(value) + 1; archive.field(wire); if constexpr (Archive::reading) { require_save(wire <= max_records, "Save contains an invalid index."); value = wire == 0 ? no_entity_index : static_cast(wire - 1); } } template 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(found - records.begin()); } template 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 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 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 void offset(Archive& archive, Size& value) { auto wire = static_cast(value); archive.field(wire); require_save(wire <= max_records, "Save contains an invalid offset."); if constexpr (Archive::reading) value = static_cast(wire); } constexpr std::size_t item_types = item_type_count; using ItemCounts = std::array; std::size_t item_index(ItemType type) { const auto raw = static_cast(type); require_save(raw > 0 && raw <= item_types, "Save contains an unknown item."); return raw - 1; } template void stack_fields(auto& archive, Stack& stack) { archive.field(stack.type); archive.field(stack.count); archive.field(stack.reserved); } template void flag(Archive& archive, Flag& value) { auto wire = static_cast(value); archive.field(wire); require_save(wire <= 1, "Save contains an invalid flag."); if constexpr (Archive::reading) value = wire != 0; } } // namespace struct WorldSaveCodec { template static void body(Archive& archive, State& world, std::uint32_t version) { const auto max_item = version >= 13 ? ItemType::Loom : version >= 12 ? ItemType::WoodenDoor : (version >= 7 ? ItemType::Flax : ItemType::Cloth); const auto max_item_count = static_cast(max_item); archive.field(world.tick_); archive.field(world.path_searches_); archive.field(world.path_nodes_visited_); archive.field(world.jobs_completed_); archive.field(world.meals_eaten_); flag(archive, world.hunger_enabled_); archive.field(world.next_agent_id_); 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> agent_links; sequence(archive, world.agents_, max_records, [&](auto& agent) { archive.field(agent.id); position(archive, agent.position); archive.field(agent.state); archive.field(agent.current_job); route(archive, agent.route, cells); offset(archive, agent.route_cursor); archive.field(agent.work_remaining); if (version >= 14) { archive.field(agent.resource_node_id); archive.field(agent.storage_id); } else if constexpr (Archive::reading) { std::array links{no_entity_index, 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(ItemType::Berries); for (std::size_t i = 1; i <= inventory_types; ++i) { const auto type = static_cast(i); auto count = agent.inventory.item_count(type); archive.field(count); if constexpr (Archive::reading) { if (count != 0) agent.inventory.add(type, count); } } route(archive, agent.haul_route, cells); 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); if (version >= 6) archive.field(agent.profession); require_save(version >= 12 || agent.profession <= Profession::Builder, "Unknown profession for save version."); }); sequence(archive, world.jobs_, max_records, [&](auto& job) { archive.field(job.id); position(archive, job.position); archive.field(job.work_required); archive.field(job.work_remaining); archive.field(job.state); }); sequence(archive, world.resource_nodes_, max_records, [&](auto& node) { archive.field(node.id); position(archive, node.position); archive.field(node.type); archive.field(node.quantity); archive.field(node.initial_quantity); archive.field(node.reserved_workers); if (version >= 2) flag(archive, node.foraging_enabled); if (version >= 5) { archive.field(node.site); require_save(version >= 7 || node.site <= ResourceSite::Mine, "Unknown site for save version."); archive.field(node.growth_at); } }); sequence(archive, world.storages_, max_records, [&](auto& storage) { archive.field(storage.id); position(archive, storage.position); archive.field(storage.capacity); archive.field(storage.reserved_slots); archive.field(storage.kind); sequence(archive, storage.items, max_item_count, [&](auto& stack) { stack_fields(archive, stack); require_save(stack.type <= max_item, "Unknown item for save version."); }); if constexpr (Archive::reading) { 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) { 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."); require_save(version >= 7 || order.recipe <= RecipeId::BuildBed, "Unknown recipe for save version."); require_save(version >= 10 || order.recipe <= RecipeId::WeaveCloth, "Unknown recipe for save version."); require_save(version >= 11 || order.recipe <= RecipeId::BuildDoorAlongY, "Unknown recipe for save version."); require_save(version >= 12 || order.recipe <= RecipeId::BuildLoom, "Unknown recipe for save version."); 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) { 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) { 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); if (version >= 2) archive.field(order.bed_owner); if (version >= 3) { archive.field(order.bed_base); 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_); flag(archive, world.scenario_completed_); archive.field(world.work_priority_); position(archive, world.scenario_sawmill_); for (auto& sequence : world.player_sequences_) archive.field(sequence); archive.field(world.command_revision_); if (version >= 3) flag(archive, world.staged_beds_); } } template static void custody(Archive& archive, State& world); static void validate(const World& world, bool modern = false); }; namespace { template void owner_fields(Archive& archive, Owner& owner) { archive.field(owner.kind); archive.field(owner.id); require_save(owner.kind <= OwnerKind::Production, "Unknown custody owner."); require_save((owner.kind == OwnerKind::None) == (owner.id == 0), "Invalid custody owner identity."); } template void claim_fields(Archive& archive, Claim& claim) { archive.field(claim.id); archive.field(claim.kind); owner_fields(archive, claim.owner); archive.field(claim.stack); archive.field(claim.item); archive.field(claim.count); archive.field(claim.backing); archive.field(claim.origin_storage); require_save(claim.kind <= ReservationKind::Tending && claim.item <= ItemType::Loom, "Unknown reservation kind or item."); require_save(claim.id != 0 || claim == Reservation{}, "Noncanonical released reservation."); } template void request_fields(Archive& archive, Request& request) { // These are exact tagged little-endian fields, never an object image or hash. std::uint16_t size = static_cast(44 + 13 * request.line_count); archive.field(size); require_save(size <= 1024, "Custody request exceeds 1024 bytes."); archive.field(request.key.kind); archive.field(request.key.id); archive.field(request.key.ordinal); archive.field(request.operation); archive.field(request.kind); archive.field(request.production); archive.field(request.source); archive.field(request.destination); archive.field(request.line_count); require_save(request.line_count <= custody_material_limit && size == 44 + 13 * request.line_count, "Noncanonical custody request length."); require_save(request.key.kind <= CustodyKeyKind::Operation && request.operation <= CustodyOperation::Tend && request.kind <= TransferKind::Return && request.key.id != 0 && request.key.ordinal != 0 && ((request.key.kind == CustodyKeyKind::Admission) == (request.operation == CustodyOperation::Admit)), "Invalid custody request tag or key."); for (std::size_t i = 0; i < request.line_count; ++i) { auto& line = request.lines[i]; archive.field(line.storage); archive.field(line.item); archive.field(line.count); require_save(line.storage != 0 && line.item > ItemType::None && line.item <= ItemType::Loom && line.count != 0, "Invalid custody request line."); } for (std::size_t i = request.line_count; i < request.lines.size(); ++i) { require_save(request.lines[i] == CustodyLine{}, "Noncanonical unused request line."); } } template void result_fields(Archive& archive, Result& result) { std::uint16_t size = static_cast(12 + 8 * result.reservation_count + 22 * result.effect_count); archive.field(size); require_save(size <= 1024, "Custody result exceeds 1024 bytes."); archive.field(result.status); archive.field(result.transfer); archive.field(result.reservation_count); archive.field(result.effect_count); flag(archive, result.terminal); require_save(result.status <= CustodyStatus::NoDestination && result.reservation_count <= custody_reservation_limit && result.effect_count <= item_type_count && size == 12 + 8 * result.reservation_count + 22 * result.effect_count, "Noncanonical custody result length or tag."); for (std::size_t i = 0; i < result.reservation_count; ++i) archive.field(result.reservations[i]); for (std::size_t i = result.reservation_count; i < result.reservations.size(); ++i) { require_save(result.reservations[i] == 0, "Noncanonical unused result reservation."); } for (std::size_t i = 0; i < result.effect_count; ++i) { auto& effect = result.effects[i]; owner_fields(archive, effect.owner); archive.field(effect.stack); archive.field(effect.item); archive.field(effect.count); require_save(effect.owner.kind != OwnerKind::None && effect.stack != 0 && effect.item > ItemType::None && effect.item <= ItemType::Loom, "Invalid custody result effect."); } for (std::size_t i = result.effect_count; i < result.effects.size(); ++i) { require_save(result.effects[i] == CustodyEffect{}, "Noncanonical unused result effect."); } } } // namespace template void WorldSaveCodec::custody(Archive& archive, State& world) { archive.field(world.next_stack_id_); archive.field(world.next_reservation_id_); archive.field(world.next_transfer_id_); const auto inventory = [&](auto& value, bool quantities) { for (std::size_t i = 1; i <= item_type_count; ++i) { const auto type = static_cast(i); auto count = value.item_count(type); if (quantities) archive.field(count); auto id = value.stack_id(type); archive.field(id); require_save((id == 0) == (count == 0), "Noncanonical custody stack identity."); if constexpr (Archive::reading) { if (quantities && count != 0) value.add(type, count); value.set_stack_id(type, id); } } }; for (auto& storage : world.storages_) { for (auto& stack : storage.items) archive.field(stack.id); } for (auto& agent : world.agents_) { inventory(agent.inventory, false); archive.field(agent.next_admission); bool present = agent.execution.has_value(); flag(archive, present); if constexpr (Archive::reading) { if (present) agent.execution.emplace(); } if (!present) continue; auto& execution = *agent.execution; archive.field(execution.id); archive.field(execution.kind); archive.field(execution.production); archive.field(execution.source); archive.field(execution.destination); archive.field(execution.next_operation); archive.field(execution.blocked); archive.field(execution.reservation_count); require_save(execution.kind <= TransferKind::Return && execution.blocked <= CustodyStatus::NoDestination && execution.reservation_count <= custody_reservation_limit, "Invalid custody execution fields."); for (std::size_t i = 0; i < execution.reservation_count; ++i) claim_fields(archive, execution.reservations[i]); for (std::size_t i = execution.reservation_count; i < execution.reservations.size(); ++i) { require_save(execution.reservations[i] == Reservation{}, "Noncanonical unused reservation."); } } for (auto& order : world.production_orders_) { inventory(order.input, true); flag(archive, order.suspended); } for (auto& balance : world.item_balances_) { archive.field(balance.opening); archive.field(balance.grant); archive.field(balance.harvest); archive.field(balance.recipe_output); archive.field(balance.recipe_input); archive.field(balance.meal); archive.field(balance.installation); archive.field(balance.demolition); } auto count = static_cast(world.custody_receipts_.size()); require_save(world.custody_receipts_.size() <= custody_receipt_limit, "Too many custody receipts."); archive.field(count); require_save(count <= custody_receipt_limit, "Too many custody receipts."); if constexpr (Archive::reading) { archive.allocate(count, sizeof(CustodyReceipt) + sizeof(std::shared_ptr)); world.custody_receipts_.reserve(count); for (std::uint32_t i = 0; i < count; ++i) { auto receipt = std::make_shared(); request_fields(archive, receipt->request); result_fields(archive, receipt->result); world.custody_receipts_.push_back(std::move(receipt)); } world.custody_receipt_cursor_ = 0; } else { require_save(count == custody_receipt_limit ? world.custody_receipt_cursor_ < count : world.custody_receipt_cursor_ == 0, "Invalid custody receipt cursor."); for (std::size_t i = 0; i < count; ++i) { const auto index = (i + world.custody_receipt_cursor_) % count; const auto& receipt = world.custody_receipts_[index]; require_save(receipt != nullptr, "Missing custody receipt."); request_fields(archive, receipt->request); result_fields(archive, receipt->result); } } } void WorldSaveCodec::validate(const World& world, bool modern) { const auto invalid = [](bool good) { require_save(good, "Save contains inconsistent simulation state."); }; const auto inside = [&](GridPosition p) { return p.x >= 0 && p.x < world.width_ && p.y >= 0 && p.y < world.height_; }; const auto valid_route = [&](const auto& points) { invalid(std::all_of(points.begin(), points.end(), inside)); }; const auto check_ids = [&](const auto& records, std::uint64_t next_id) { std::uint64_t previous = 0; for (const auto& record : records) { invalid(record.id > previous && inside(record.position)); previous = record.id; } invalid(next_id > previous); }; check_ids(world.agents_, world.next_agent_id_); 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_) { invalid(sequence <= std::numeric_limits::max() - revision); revision += sequence; } invalid(revision == world.command_revision_); if (world.scenario_active_) { invalid(world.hunger_enabled_ && world.is_walkable(world.scenario_sawmill_)); } else { invalid(!world.paused_ && !world.scenario_completed_ && !world.staged_beds_ && world.work_priority_ == WorkPriority::Balanced); } invalid(std::all_of(world.blocked_.begin(), world.blocked_.end(), [](std::uint8_t cell) { return cell <= 1; })); std::uint64_t completed = 0; for (const auto& job : world.jobs_) { invalid(job.state <= JobState::Completed && job.work_required > 0 && job.work_remaining <= job.work_required); if (job.state == JobState::Completed) ++completed; } invalid(completed == world.jobs_completed_); for (const auto& node : world.resource_nodes_) { invalid(node.initial_quantity > 0 && node.quantity <= node.initial_quantity && node.reserved_workers <= (node.needs_tending() ? 1U : node.quantity) && (node.foraging_enabled || node.type == ItemType::Berries)); invalid(node.site <= ResourceSite::FlaxField); if (node.site == ResourceSite::Natural) { invalid(node.growth_at == 0 && (node.type == ItemType::Wood || node.type == ItemType::Stone || node.type == ItemType::Berries)); } else { invalid(node.type == site_resource(node.site) && world.is_walkable(node.position)); invalid(node.site == ResourceSite::Mine ? node.growth_at == 0 : (node.growth_at == 0 || node.quantity == 0)); } } for (const auto& storage : world.storages_) { invalid(storage.kind <= StorageKind::Pantry && world.is_walkable(storage.position) && storage.capacity > 0 && storage.total_items() + storage.reserved_slots <= storage.capacity); auto previous = ItemType::None; for (const auto& stack : storage.items) { static_cast(item_index(stack.type)); invalid(stack.type > previous && storage.accepts(stack.type) && stack.count > 0 && stack.reserved <= stack.count); previous = stack.type; } } 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 reserved_items(modern ? 0 : world.storages_.size()); std::vector expected_cargo(modern ? 0 : world.production_orders_.size()); std::vector bed_owners; for (std::size_t i = 0; i < world.production_orders_.size(); ++i) { const auto& order = world.production_orders_[i]; invalid(order.recipe <= RecipeId::CraftLoom && order.state <= JobState::Completed && world.is_walkable(order.position) && (order.recipe != RecipeId::WeaveCloth || order.state != JobState::Completed)); invalid(!is_carpentry_recipe(order.recipe) || world.carpenter_workshop() == order.position); invalid(order.bed_base <= BedBase::Stone && order.bed_stage <= BedStage::Pillow && (order.bed_stage == BedStage::Legacy || (world.staged_beds_ && order.recipe == RecipeId::BuildBed)) && (order.state != JobState::Completed || order.bed_stage == BedStage::Legacy || order.bed_stage == BedStage::Pillow)); if (order.bed_owner != 0) { invalid(world.scenario_active_ && order.recipe == RecipeId::BuildBed && order.state == JobState::Completed); const auto resident = std::lower_bound(world.agents_.begin(), world.agents_.end(), order.bed_owner, [](const Agent& agent, AgentId id) { return agent.id < id; }); invalid(resident != world.agents_.end() && resident->id == order.bed_owner); bed_owners.push_back(order.bed_owner); } if (modern) { invalid(order.materials.size() <= custody_material_limit && order.collected_stops <= order.delivery_stops.size()); for (const auto& material : order.materials) { static_cast(item_index(material.type)); invalid(material.count > 0 && world.find_storage(material.storage_id) != nullptr); } StorageId previous_stop = 0; for (const auto& stop : order.delivery_stops) { invalid(stop.storage_id > previous_stop && world.find_storage(stop.storage_id) != nullptr); previous_stop = stop.storage_id; valid_route(stop.route_to_next); } continue; } if (order.state != JobState::InProgress) { invalid(order.materials.empty() && order.delivery_stops.empty() && order.collected_stops == 0); continue; } const bool delivery = delivers_materials(order.recipe); invalid(order.collected_stops <= order.delivery_stops.size() && (delivery || order.delivery_stops.empty())); StorageId last_storage = 0; bool first_stop = true; for (const auto& stop : order.delivery_stops) { 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_id == stop.storage_id; })); valid_route(stop.route_to_next); first_stop = false; last_storage = stop.storage_id; } ItemCounts ingredients{}; for (const auto& material : order.materials) { const auto type = item_index(material.type); 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[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_id == material.storage_id; }); invalid(stop != order.delivery_stops.end()); if (static_cast(stop - order.delivery_stops.begin()) < order.collected_stops) { expected_cargo[i][type] += material.count; } else { reserved_items[storage_index(material.storage_id)][type] += material.count; } } } // These are the ingredient requirements associated with the saved recipe IDs. ItemCounts required{}; switch (order.recipe) { case RecipeId::SawPlank: required[item_index(ItemType::Wood)] = 1; break; case RecipeId::CutStoneBlock: required[item_index(ItemType::Stone)] = 1; break; case RecipeId::BuildCabin: required[item_index(ItemType::Plank)] = 3; required[item_index(ItemType::StoneBlock)] = 2; break; case RecipeId::BuildBed: required[item_index(order.bed_material())] = 1; break; case RecipeId::WeaveCloth: required[item_index(ItemType::Flax)] = 1; break; case RecipeId::CraftWoodenDoor: case RecipeId::CraftMedicineCabinet: case RecipeId::CraftMiningRack: case RecipeId::CraftLoom: for (const auto& item : world.carpentry_materials(order.recipe)) { if (item.count) required[item_index(item.type)] = item.count; } break; case RecipeId::BuildFloor: case RecipeId::BuildWall: case RecipeId::BuildDoorAlongX: case RecipeId::BuildDoorAlongY: case RecipeId::BuildMedicineCabinet: case RecipeId::BuildMiningRack: case RecipeId::BuildLoom: case RecipeId::InstallDoorAlongX: case RecipeId::InstallDoorAlongY: case RecipeId::InstallMedicineCabinet: case RecipeId::InstallMiningRack: case RecipeId::InstallLoom: for (const auto& item : world.construction_materials(order.recipe, order.bed_base)) { if (item.count) required[item_index(item.type)] = item.count; } break; } invalid(ingredients == required); } std::sort(bed_owners.begin(), bed_owners.end()); invalid(std::adjacent_find(bed_owners.begin(), bed_owners.end()) == bed_owners.end()); std::vector reserved_nodes(world.resource_nodes_.size()); std::vector reserved_slots(world.storages_.size()); std::vector job_claims(world.jobs_.size()); std::vector order_claims(world.production_orders_.size()); std::vector rest_destinations; for (const auto& agent : world.agents_) { using enum AgentState; invalid(agent.state <= (modern ? Returning : Sleeping) && agent.route_cursor <= agent.route.size() && agent.hunger <= max_hunger && (world.hunger_enabled_ || agent.hunger == 0) && agent.fatigue <= max_fatigue && (world.scenario_active_ || agent.fatigue == 0)); invalid(!agent.resting_on_ground || agent.state == Sleeping || agent.state == GoingToSleep); invalid(agent.profession <= Profession::Carpenter); valid_route(agent.route); valid_route(agent.haul_route); const bool has_job = agent.current_job != 0; 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 && is_carpentry_recipe(production->recipe); invalid(modern || agent.haul_route.empty() || has_source || carpentry); if (has_job) { invalid(!has_order && !has_storage && !has_source && agent.inventory.empty() && (agent.state == Travelling || agent.state == Working) && agent.work_remaining > 0); const auto job = std::lower_bound(world.jobs_.begin(), world.jobs_.end(), agent.current_job, [](const WorkJob& entry, JobId id) { return entry.id < id; }); invalid(job != world.jobs_.end() && job->id == agent.current_job && job->state == JobState::InProgress); auto& claimed = job_claims[static_cast(job - world.jobs_.begin())]; invalid(claimed == 0); claimed = 1; } else if (modern && agent.state != GoingToSleep && agent.state != Sleeping) { invalid(!has_source || world.find_resource_node(agent.resource_node_id) != nullptr); // Live property, claims, execution phase and zero-time pending work // are checked together by the authoritative custody validator. continue; } else if (has_order) { invalid(!has_storage && !has_source && agent.work_remaining > 0); const auto order_index = static_cast(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 { invalid(agent.state == Working || (agent.state == Travelling && !delivers_materials(order.recipe))); } if (carpentry) { 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(), [&order](const auto& stop) { return stop.storage_id == order.materials.front().storage_id; }); const bool collected = stops.empty() || static_cast(output_stop - stops.begin()) < order.collected_stops; if (collected) ++reserved_slots[storage]; } for (std::size_t i = 0; i < item_types; ++i) { invalid(agent.inventory.item_count(static_cast(i + 1)) == expected_cargo[order_index][i]); } } else if (has_source) { 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_[node_index(agent.resource_node_id)]; if (has_storage) { 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[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_[storage_index(agent.storage_id)].accepts(cargo)); for (std::size_t i = 1; i <= item_types; ++i) { const auto type = static_cast(i); invalid(type == cargo || agent.inventory.item_count(type) == 0); } ++reserved_slots[storage_index(agent.storage_id)]; } else if (agent.state == GoingToEat) { invalid(world.hunger_enabled_ && has_storage && agent.inventory.empty() && 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 && agent.inventory.first_item() == ItemType::Berries); } else if (agent.state == GoingToSleep) { invalid(world.scenario_active_ && !has_storage && agent.inventory.empty() && agent.work_remaining == 0 && agent.tired() && agent.route_cursor < agent.route.size()); rest_destinations.push_back(agent.route.back()); } else if (agent.state == Sleeping) { invalid(world.scenario_active_ && !has_storage && agent.inventory.empty() && agent.fatigue > 0 && agent.work_remaining == 0 && agent.route.empty()); rest_destinations.push_back(agent.position); } else { invalid(agent.state == Idle && !has_storage && agent.inventory.empty() && agent.work_remaining == 0); } if (agent.state == Sleeping || agent.state == GoingToSleep) { const auto target = rest_destinations.back(); const auto* bed = world.assigned_bed(agent.id); invalid(agent.resting_on_ground ? !world.is_bed_cell(target) : (bed != nullptr && bed->position == target)); } } std::sort(rest_destinations.begin(), rest_destinations.end(), [](GridPosition left, GridPosition right) { return left.y < right.y || (left.y == right.y && left.x < right.x); }); invalid(std::adjacent_find(rest_destinations.begin(), rest_destinations.end()) == rest_destinations.end()); for (std::size_t i = 0; i < world.jobs_.size(); ++i) { invalid((job_claims[i] != 0) == (world.jobs_[i].state == JobState::InProgress)); } if (modern) { world.validate_custody(); return; } for (std::size_t i = 0; i < world.production_orders_.size(); ++i) { invalid((order_claims[i] != 0) == (world.production_orders_[i].state == JobState::InProgress)); } for (std::size_t i = 0; i < world.resource_nodes_.size(); ++i) { invalid(reserved_nodes[i] == world.resource_nodes_[i].reserved_workers); } for (std::size_t i = 0; i < world.storages_.size(); ++i) { invalid(reserved_slots[i] == world.storages_[i].reserved_slots); for (const auto& stack : world.storages_[i].items) { const auto type = item_index(stack.type); invalid(reserved_items[i][type] == stack.reserved); reserved_items[i][type] = 0; } invalid(reserved_items[i] == ItemCounts{}); } } void World::migrate_legacy_custody() { // This function runs only after historical fields, phases, reservations and // (for versions 1–8) the historical footer have all passed validation. next_stack_id_ = next_reservation_id_ = next_transfer_id_ = 1; item_balances_ = {}; custody_receipts_.clear(); custody_receipt_cursor_ = 0; for (auto& order : production_orders_) { if (order.state == JobState::InProgress && delivers_materials(order.recipe) && order.delivery_stops.empty()) { for (const auto& material : order.materials) order.input.add(material.type, material.count); } } const auto identity = [&](ItemType item, std::uint32_t count) { require_save(next_stack_id_ != std::numeric_limits::max(), "Migrated stack identities exhausted."); auto& opening = item_balances_[item_index(item)].opening; require_save(count <= std::numeric_limits::max() - opening, "Migrated opening balance overflow."); opening += count; return next_stack_id_++; }; // Stable owner-kind / owner-ID / item order, independent of worker count. for (auto& storage : storages_) { for (auto& stack : storage.items) stack.id = identity(stack.type, stack.count); } const auto identify_inventory = [&](Inventory& inventory) { for (std::size_t i = 1; i <= item_type_count; ++i) { const auto item = static_cast(i); if (const auto count = inventory.item_count(item)) inventory.set_stack_id(item, identity(item, count)); } }; for (auto& agent : agents_) identify_inventory(agent.inventory); for (auto& order : production_orders_) identify_inventory(order.input); for (auto& agent : agents_) { agent.next_admission = 1; agent.execution.reset(); const bool active = agent.production_id != 0 || agent.resource_node_id != 0 || agent.state == AgentState::Hauling || agent.state == AgentState::GoingToEat || agent.state == AgentState::Eating; if (!active) continue; TransferExecution execution; execution.id = next_transfer_id_++; execution.production = agent.production_id; execution.source = agent.resource_node_id; execution.destination = agent.storage_id; const auto add = [&](Reservation claim) -> ReservationId { require_save(execution.reservation_count < custody_reservation_limit && next_reservation_id_ != std::numeric_limits::max(), "Migrated reservation limit exceeded."); claim.id = next_reservation_id_++; execution.reservations[execution.reservation_count++] = claim; return claim.id; }; const auto storage_stack = [&](StorageId storage, ItemType item) -> StackId { const auto& items = storages_[record_index(storages_, storage)].items; const auto found = std::lower_bound(items.begin(), items.end(), item, [](const auto& stack, ItemType target) { return stack.type < target; }); require_save(found != items.end() && found->type == item, "Missing migrated reserved stock."); return found->id; }; ReservationId capacity_backing = 0; if (agent.production_id != 0) { execution.kind = TransferKind::Production; const auto& order = production_orders_[record_index(production_orders_, agent.production_id)]; const bool delivery = delivers_materials(order.recipe); const bool at_site = delivery && order.delivery_stops.empty(); if (!is_construction(order.recipe) || is_carpentry_recipe(order.recipe)) { execution.destination = order.materials.front().storage_id; } for (const auto& material : order.materials) { StockOwner owner{OwnerKind::Storage, material.storage_id}; StackId stack = 0; if (at_site) { owner = {OwnerKind::Production, order.id}; stack = order.input.stack_id(material.type); } else if (delivery) { const auto stop = std::lower_bound(order.delivery_stops.begin(), order.delivery_stops.end(), material.storage_id, [](const auto& entry, StorageId id) { return entry.storage_id < id; }); if (static_cast(stop - order.delivery_stops.begin()) < order.collected_stops) { owner = {OwnerKind::Resident, agent.id}; stack = agent.inventory.stack_id(material.type); } } if (owner.kind == OwnerKind::Storage) stack = storage_stack(material.storage_id, material.type); const auto claim = add({0, ReservationKind::Item, owner, stack, material.type, material.count, 0, material.storage_id}); if (!capacity_backing && execution.destination == material.storage_id && owner.kind == OwnerKind::Storage) { capacity_backing = claim; } } add({0, ReservationKind::Worksite, {OwnerKind::Production, order.id}, 0, {}, 1}); } else if (agent.resource_node_id != 0) { execution.kind = agent.storage_id ? TransferKind::Harvest : TransferKind::Tending; add({0, agent.storage_id ? ReservationKind::Harvest : ReservationKind::Tending, {}, 0, {}, 1}); } else if (agent.state == AgentState::GoingToEat || agent.state == AgentState::Eating) { execution.kind = TransferKind::Meal; execution.destination = 0; if (agent.state == AgentState::GoingToEat) { add({0, ReservationKind::Item, {OwnerKind::Storage, agent.storage_id}, storage_stack(agent.storage_id, ItemType::Berries), ItemType::Berries, 1, 0, agent.storage_id}); } else { add({0, ReservationKind::Item, {OwnerKind::Resident, agent.id}, agent.inventory.stack_id(ItemType::Berries), ItemType::Berries, 1}); } } else { execution.kind = TransferKind::Return; for (std::size_t i = 1; i <= item_type_count; ++i) { const auto item = static_cast(i); if (const auto count = agent.inventory.item_count(item)) { add({0, ReservationKind::Item, {OwnerKind::Resident, agent.id}, agent.inventory.stack_id(item), item, count}); } } } if (execution.destination != 0) { add({0, ReservationKind::Capacity, {OwnerKind::Storage, execution.destination}, 0, {}, 1, capacity_backing}); } agent.execution = execution; agent.next_admission = 2; } } void World::write_save(std::ostream& stream, WorldSaveFormat format) const { const auto version = static_cast(format); require_save(format == WorldSaveFormat::Legacy13 || format == WorldSaveFormat::Current14 || format == WorldSaveFormat::Current15, "Unsupported save output format."); if (format != WorldSaveFormat::Current15 && !legacy_representable()) { throw UnsupportedLegacyState{}; } if (format == WorldSaveFormat::Current15) WorldSaveCodec::validate(*this, true); SaveWriter archive(stream); for (char letter : signature) archive.field(letter); archive.field(version); archive.field(seed_); archive.field(width_); archive.field(height_); WorldSaveCodec::body(archive, *this, version); if (version >= 15) WorldSaveCodec::custody(archive, *this); } std::unique_ptr World::read_save(std::istream& stream, std::size_t workers, ExecutionMode mode, WorkerPoolOptions worker_options) { SaveReader archive(stream); for (char letter : signature) { char actual = 0; archive.field(actual); require_save(actual == letter, "This file is not a settlement save."); } std::uint32_t version = 0; archive.field(version); require_save(version >= 1 && version <= save_version, "Save file version is not supported."); archive.set_version(version); std::uint64_t seed = 0; std::int32_t width = 0; std::int32_t height = 0; archive.field(seed); archive.field(width); archive.field(height); auto world = std::make_unique(seed, width, height, workers, mode, std::move(worker_options)); WorldSaveCodec::body(archive, *world, version); if (version >= 15) WorldSaveCodec::custody(archive, *world); archive.finish(); if (version < 5) { std::vector occupied_ground; for (auto& agent : world->agents_) { if (agent.state != AgentState::Sleeping) continue; const auto* bed = world->assigned_bed(agent.id); if (bed != nullptr && bed->position == agent.position) continue; if (world->is_bed_cell(agent.position) || std::find(occupied_ground.begin(), occupied_ground.end(), agent.position) != occupied_ground.end()) { agent.state = AgentState::Idle; } else { agent.resting_on_ground = true; occupied_ground.push_back(agent.position); } } } WorldSaveCodec::validate(*world, version >= 15); if (version < 15) { world->migrate_legacy_custody(); world->validate_custody(); } return world; } } // namespace settlement