Import multithreaded simulation core

This commit is contained in:
Lagg1ng committed 2026-11-28 16:39:23 +00:00
1 parent c72c388fe9
commit 65686db1a1
4 files changed
+2239

No files matched your search

+35
View File
@@ -0,0 +1,35 @@
#include "settlement/core/deterministic_rng.hpp"
#include "settlement/core/world.hpp"
#include <cstdlib>
namespace settlement {
std::unique_ptr<World> make_first_colony(std::size_t workers) {
constexpr auto size = first_colony_map_size;
auto world = std::make_unique<World>(2026, size, size, workers);
DeterministicRng terrain_rng(0x534554544C454D45ULL);
for (int y = 2; y < size - 2; ++y) {
for (int x = 2; x < size - 2; ++x) {
const int distance = std::abs(x - size / 2) + std::abs(y - size / 2);
if (distance > 7 && terrain_rng.bounded(100) < 5) world->set_blocked({x, y});
}
}
for (const auto position : {GridPosition{16, 16}, {17, 15}, {15, 15}}) {
static_cast<void>(world->spawn_agent(position));
}
static_cast<void>(world->add_storage({15, 16}, 9));
static_cast<void>(world->add_storage({16, 13}, 15, StorageKind::Pantry));
const auto provisions = world->add_storage({18, 16}, 18);
world->stock_storage(provisions, ItemType::Cloth, 12);
world->stock_storage(provisions, ItemType::Stone, 6);
static_cast<void>(world->add_resource_node({12, 16}, ItemType::Wood, 12));
static_cast<void>(world->add_resource_node({13, 17}, ItemType::Wood, 12));
for (const auto position : {GridPosition{13, 14}, {14, 12}, {18, 12}, {19, 14}}) {
static_cast<void>(world->add_resource_node(position, ItemType::Berries, 16));
}
world->start_scenario({15, 14});
return world;
}
} // namespace settlement
+56
View File
@@ -0,0 +1,56 @@
#include "settlement/core/worker_pool.hpp"
#include <stdexcept>
namespace settlement {
WorkerPool::WorkerPool(std::size_t thread_count) {
if (thread_count < 2) {
throw std::invalid_argument("worker pool needs at least two threads");
}
workers_.reserve(thread_count);
try {
for (std::size_t index = 0; index < thread_count; ++index) {
workers_.emplace_back([this] { worker_loop(); });
}
} catch (...) {
{
std::lock_guard<std::mutex> lock(mutex_);
stopping_ = true;
}
work_available_.notify_all();
for (std::thread& worker : workers_) {
if (worker.joinable()) worker.join();
}
throw;
}
}
WorkerPool::~WorkerPool() {
{
std::lock_guard<std::mutex> lock(mutex_);
stopping_ = true;
}
work_available_.notify_all();
for (std::thread& worker : workers_) {
if (worker.joinable()) worker.join();
}
}
std::size_t WorkerPool::thread_count() const noexcept { return workers_.size(); }
void WorkerPool::worker_loop() {
for (;;) {
std::function<void()> task;
{
std::unique_lock<std::mutex> lock(mutex_);
work_available_.wait(lock, [this] { return stopping_ || !tasks_.empty(); });
if (stopping_ && tasks_.empty()) return;
task = std::move(tasks_.front());
tasks_.pop();
}
task();
}
}
} // namespace settlement
+1550
View File
File diff suppressed because it is too large. Load diff
+598
View File
@@ -0,0 +1,598 @@
#include "settlement/core/world.hpp"
#include <algorithm>
#include <bit>
#include <istream>
#include <limits>
#include <ostream>
#include <stdexcept>
#include <string_view>
#include <type_traits>
namespace settlement {
namespace {
constexpr std::string_view signature = "SETTLERS";
constexpr std::uint32_t save_version = 9;
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;
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<class T>
void field(T value) {
if constexpr (std::is_enum_v<T>) {
field(static_cast<std::underlying_type_t<T>>(value));
} else {
using Bits = std::make_unsigned_t<T>;
std::uint64_t bits = std::bit_cast<Bits>(value);
for (std::size_t i = 0; i < sizeof(T); ++i) {
const auto byte = static_cast<std::uint8_t>(bits);
require_save(bytes_ < max_save_bytes, "Save exceeds the 128 MiB limit.");
++bytes_;
stream_.put(std::bit_cast<char>(byte));
require_save(static_cast<bool>(stream_), "Could not write the save.");
bits >>= 8;
}
}
}
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<class T>
void field(T& value, bool payload = true) {
if constexpr (std::is_enum_v<T>) {
std::underlying_type_t<T> bits = 0;
field(bits, payload);
value = static_cast<T>(bits);
} else {
std::uint64_t bits = 0;
for (std::size_t i = 0; i < sizeof(T); ++i) {
const int next = stream_.get();
require_save(next != std::char_traits<char>::eof(), "Save is incomplete or unreadable.");
const auto byte = static_cast<std::uint8_t>(next);
if (payload) {
require_save(bytes_ < max_save_bytes, "Save exceeds the 128 MiB limit.");
++bytes_;
if (legacy_footer_) legacy_digest_ = (legacy_digest_ ^ byte) * 1099511628211ULL;
}
bits |= static_cast<std::uint64_t>(byte) << (8 * i);
}
value = std::bit_cast<T>(static_cast<std::make_unsigned_t<T>>(bits));
}
}
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<char>::eof() && !stream_.bad(),
"Save contains unexpected trailing data.");
}
private:
std::istream& stream_;
std::size_t bytes_ = 0;
bool legacy_footer_ = true;
std::uint64_t legacy_digest_ = 14695981039346656037ULL;
};
template<class Archive, class Vector, class Visit>
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<std::uint32_t>(values.size());
archive.field(length);
require_save(length <= limit, "Save contains too many records.");
if constexpr (Archive::reading) {
for (std::uint32_t i = 0; i < length; ++i) {
values.emplace_back();
visit(values.back());
}
} else {
for (const auto& value : values) visit(value);
}
}
template<class Archive, class Position>
void position(Archive& archive, Position& value) {
archive.field(value.x);
archive.field(value.y);
}
template<class Archive, class Route>
void route(Archive& archive, Route& points, std::size_t cells) {
sequence(archive, points, cells, [&](auto& point) { position(archive, point); });
}
template<class Archive, class Index>
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<std::uint64_t>(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<std::size_t>(wire - 1);
}
}
template<class Archive, class Size>
void offset(Archive& archive, Size& value) {
auto wire = static_cast<std::uint64_t>(value);
archive.field(wire);
require_save(wire <= max_records, "Save contains an invalid offset.");
if constexpr (Archive::reading) value = static_cast<std::size_t>(wire);
}
constexpr std::size_t item_types = item_type_count;
using ItemCounts = std::array<std::uint64_t, item_types>;
std::size_t item_index(ItemType type) {
const auto raw = static_cast<std::size_t>(type);
require_save(raw > 0 && raw <= item_types, "Save contains an unknown item.");
return raw - 1;
}
template<class Stack>
void stack_fields(auto& archive, Stack& stack) {
archive.field(stack.type);
archive.field(stack.count);
archive.field(stack.reserved);
}
template<class Archive, class Flag>
void flag(Archive& archive, Flag& value) {
auto wire = static_cast<std::uint8_t>(value);
archive.field(wire);
require_save(wire <= 1, "Save contains an invalid flag.");
if constexpr (Archive::reading) value = wire != 0;
}
} // namespace
struct WorldSaveCodec {
template<class Archive, class State>
static void body(Archive& archive, State& world, std::uint32_t version) {
const auto max_item = version >= 7 ? ItemType::Flax : ItemType::Cloth;
const auto max_item_count = static_cast<std::size_t>(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_);
const auto cells = world.blocked_.size();
for (auto& cell : world.blocked_) archive.field(cell);
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);
index(archive, agent.resource_node_index);
index(archive, agent.storage_index);
const auto inventory_types = version >= 3 ? max_item_count : static_cast<std::size_t>(ItemType::Berries);
for (std::size_t i = 1; i <= inventory_types; ++i) {
const auto type = static_cast<ItemType>(i);
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);
index(archive, agent.production_index);
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);
});
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);
}
});
sequence(archive, world.production_orders_, max_records, [&](auto& order) {
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.");
archive.field(order.state);
sequence(archive, order.materials, item_types, [&](auto& material) {
index(archive, material.storage_index);
archive.field(material.type);
require_save(material.type <= max_item, "Unknown material for save version.");
archive.field(material.count);
});
sequence(archive, order.delivery_stops, item_types, [&](auto& stop) {
index(archive, stop.storage_index);
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 (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_);
}
}
static void validate(const World& world);
};
void WorldSaveCodec::validate(const World& world) {
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_);
invalid(world.work_priority_ <= WorkPriority::BuildingFirst);
std::uint64_t revision = 0;
for (const auto sequence : world.player_sequences_) {
invalid(sequence <= std::numeric_limits<std::uint64_t>::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<void>(item_index(stack.type));
invalid(stack.type > previous && storage.accepts(stack.type) && stack.count > 0 &&
stack.reserved <= stack.count);
previous = stack.type;
}
}
std::vector<ItemCounts> reserved_items(world.storages_.size());
std::vector<ItemCounts> expected_cargo(world.production_orders_.size());
std::vector<AgentId> 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::WeaveCloth && order.state <= JobState::Completed &&
world.is_walkable(order.position) &&
(order.recipe != RecipeId::WeaveCloth || order.state != JobState::Completed));
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 (order.state != JobState::InProgress) {
invalid(order.materials.empty() && order.delivery_stops.empty() && order.collected_stops == 0);
continue;
}
const bool construction = is_construction(order.recipe);
invalid(order.collected_stops <= order.delivery_stops.size() && (construction || order.delivery_stops.empty()));
std::size_t last_storage = 0;
bool first_stop = true;
for (const auto& stop : order.delivery_stops) {
invalid(stop.storage_index < world.storages_.size() && (first_stop || last_storage < stop.storage_index));
invalid(std::any_of(order.materials.begin(), order.materials.end(),
[&](const auto& material) { return material.storage_index == stop.storage_index; }));
valid_route(stop.route_to_next);
first_stop = false;
last_storage = stop.storage_index;
}
ItemCounts ingredients{};
for (const auto& material : order.materials) {
const auto type = item_index(material.type);
invalid(material.storage_index < world.storages_.size() && material.count > 0 &&
world.storages_[material.storage_index].kind == StorageKind::Materials);
ingredients[type] += material.count;
if (!construction) {
reserved_items[material.storage_index][type] += material.count;
} else if (!order.delivery_stops.empty()) {
const auto stop = std::find_if(order.delivery_stops.begin(), order.delivery_stops.end(),
[&](const auto& entry) { return entry.storage_index == material.storage_index; });
invalid(stop != order.delivery_stops.end());
if (static_cast<std::size_t>(stop - order.delivery_stops.begin()) < order.collected_stops) {
expected_cargo[i][type] += material.count;
} else {
reserved_items[material.storage_index][type] += material.count;
}
}
}
// 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;
}
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<std::uint64_t> reserved_nodes(world.resource_nodes_.size());
std::vector<std::uint64_t> reserved_slots(world.storages_.size());
std::vector<std::uint8_t> job_claims(world.jobs_.size());
std::vector<std::uint8_t> order_claims(world.production_orders_.size());
std::vector<GridPosition> rest_destinations;
for (const auto& agent : world.agents_) {
using enum AgentState;
invalid(agent.state <= 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::Builder);
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_source = agent.resource_node_index != no_entity_index;
const bool has_storage = agent.storage_index != no_entity_index;
invalid(!has_storage || agent.storage_index < world.storages_.size());
invalid(agent.haul_route.empty() || has_source);
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<std::size_t>(job - world.jobs_.begin())];
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;
if (!order.delivery_stops.empty()) {
invalid(agent.state == (order.collected_stops == 0 ? FetchingMaterials : Hauling));
} else {
invalid(agent.state == Working || (agent.state == Travelling && !is_construction(order.recipe)));
}
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]);
}
} else if (has_source) {
invalid(agent.resource_node_index < world.resource_nodes_.size() &&
(agent.state == Travelling || agent.state == Gathering) && agent.inventory.empty() &&
agent.work_remaining > 0);
const auto& source = world.resource_nodes_[agent.resource_node_index];
if (has_storage) {
invalid(source.quantity > 0 && world.storages_[agent.storage_index].accepts(source.type));
++reserved_slots[agent.storage_index];
} else {
invalid(source.needs_tending() && agent.haul_route.empty());
}
++reserved_nodes[agent.resource_node_index];
} 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) &&
agent.inventory.item_count(cargo) == 1 && agent.work_remaining == 0 &&
world.storages_[agent.storage_index].accepts(cargo));
for (std::size_t i = 1; i <= item_types; ++i) {
const auto type = static_cast<ItemType>(i);
invalid(type == cargo || agent.inventory.item_count(type) == 0);
}
++reserved_slots[agent.storage_index];
} else if (agent.state == GoingToEat) {
invalid(world.hunger_enabled_ && has_storage && agent.inventory.empty() &&
world.storages_[agent.storage_index].kind == StorageKind::Pantry);
++reserved_items[agent.storage_index][item_index(ItemType::Berries)];
} 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));
}
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::write_save(std::ostream& stream) const {
SaveWriter archive(stream);
for (char letter : signature) archive.field(letter);
archive.field(save_version);
archive.field(seed_);
archive.field(width_);
archive.field(height_);
WorldSaveCodec::body(archive, *this, save_version);
}
std::unique_ptr<World> World::read_save(std::istream& stream, std::size_t workers) {
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<World>(seed, width, height, workers);
WorldSaveCodec::body(archive, *world, version);
archive.finish();
if (version < 5) {
std::vector<GridPosition> 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);
return world;
}
} // namespace settlement