Files
stoneheart_at_home/engine/src/world.cpp
T

1559 lines
71 KiB
C++

#include "settlement/core/world.hpp"
#include <algorithm>
#include <array>
#include <cassert>
#include <fstream>
#include <limits>
#include <numeric>
#include <queue>
#include <stdexcept>
#include <utility>
#include <future>
namespace settlement {
namespace {
constexpr std::int32_t max_map_dimension = 512;
constexpr std::uint32_t meal_ticks = 5;
constexpr std::uint64_t berry_regrowth_ticks = 12;
constexpr std::uint16_t bed_recovery = 6;
constexpr std::uint16_t ground_recovery = 2;
constexpr std::uint16_t ground_wake_fatigue = fatigue_threshold / 2;
constexpr GridPosition adjacent_cells[] = {{-1, 0}, {0, -1}, {1, 0}, {0, 1}};
std::uint64_t growing_time(ResourceSite site) noexcept {
switch (site) {
case ResourceSite::BerryField: return 70;
case ResourceSite::TreePlot: return 140;
case ResourceSite::FlaxField: return 55;
default: return 0;
}
}
bool is_production_object(RecipeId recipe) noexcept {
return is_construction(recipe) || recipe == RecipeId::WeaveCloth;
}
bool can_take_work(const Agent& agent, Profession profession) noexcept {
return agent.profession == Profession::Generalist || agent.profession == profession;
}
Profession gathering_profession(ItemType item) noexcept {
if (item == ItemType::Wood) return Profession::Woodcutter;
if (item == ItemType::Stone) return Profession::Miner;
return Profession::Farmer;
}
std::uint16_t initial_hunger(AgentId id) {
return static_cast<std::uint16_t>((id * 37) % (hunger_threshold / 2));
}
struct Recipe {
std::array<ItemStack, 2> ingredients;
ItemType output;
std::uint32_t ticks;
};
const Recipe& recipe_for(RecipeId id) {
static constexpr Recipe saw{{ItemStack{ItemType::Wood, 1}, {}}, ItemType::Plank, 12};
static constexpr Recipe cut{{ItemStack{ItemType::Stone, 1}, {}}, ItemType::StoneBlock, 16};
static constexpr Recipe cabin{{ItemStack{ItemType::Plank, 3}, ItemStack{ItemType::StoneBlock, 2}},
ItemType::None, 28};
static constexpr Recipe bed{{ItemStack{ItemType::Plank, 1}, {}}, ItemType::None, 14};
static constexpr Recipe weave{{ItemStack{ItemType::Flax, 1}, {}}, ItemType::Cloth, 12};
switch (id) {
case RecipeId::SawPlank: return saw;
case RecipeId::CutStoneBlock: return cut;
case RecipeId::BuildCabin: return cabin;
case RecipeId::BuildBed: return bed;
case RecipeId::WeaveCloth: return weave;
}
throw std::invalid_argument("unknown production recipe");
}
Recipe recipe_for(const ProductionOrder& order) {
Recipe recipe = recipe_for(order.recipe);
if (order.recipe == RecipeId::BuildBed) recipe.ingredients[0].type = order.bed_material();
return recipe;
}
auto stack_position(Storage& storage, ItemType type) {
return std::lower_bound(storage.items.begin(), storage.items.end(), type,
[](const ItemStack& stack, ItemType target) { return stack.type < target; });
}
std::size_t checked_cell_count(std::int32_t width, std::int32_t height) {
if (width <= 0 || height <= 0 || width > max_map_dimension || height > max_map_dimension) {
throw std::invalid_argument("map dimensions must be in the range 1..512");
}
return static_cast<std::size_t>(width) * static_cast<std::size_t>(height);
}
std::size_t checked_worker_count(std::size_t workers) {
if (workers < min_worker_count || workers > max_worker_count) {
throw std::invalid_argument("worker count must be in the range 2..64");
}
return workers;
}
std::int32_t manhattan_distance(GridPosition left, GridPosition right) noexcept {
const std::int32_t dx = left.x > right.x ? left.x - right.x : right.x - left.x;
const std::int32_t dy = left.y > right.y ? left.y - right.y : right.y - left.y;
return dx + dy;
}
struct OpenNode {
std::int32_t cell = 0;
std::int32_t distance_from_start = 0;
std::int32_t heuristic = 0;
std::int32_t estimated_total = 0;
};
struct OpenNodeLater {
[[nodiscard]] bool operator()(const OpenNode& left, const OpenNode& right) const noexcept {
if (left.estimated_total != right.estimated_total) {
return left.estimated_total > right.estimated_total;
}
if (left.heuristic != right.heuristic) {
return left.heuristic > right.heuristic;
}
return left.cell > right.cell;
}
};
} // namespace
std::uint32_t Inventory::item_count(ItemType type) const noexcept {
const auto index = static_cast<std::size_t>(type);
return index != 0 && index <= counts_.size() ? counts_[index - 1] : 0;
}
bool Inventory::empty() const noexcept { return first_item() == ItemType::None; }
void Inventory::add(ItemType type, std::uint32_t count) noexcept {
const auto index = static_cast<std::size_t>(type);
assert(index != 0 && index <= counts_.size());
assert(count <= std::numeric_limits<std::uint32_t>::max() - counts_[index - 1]);
counts_[index - 1] += count;
}
void Inventory::remove(ItemType type, std::uint32_t count) noexcept {
const auto index = static_cast<std::size_t>(type);
assert(index != 0 && index <= counts_.size() && count <= counts_[index - 1]);
counts_[index - 1] -= count;
}
ItemType Inventory::first_item() const noexcept {
const auto found = std::find_if(counts_.begin(), counts_.end(),
[](std::uint32_t count) { return count != 0; });
return found == counts_.end() ? ItemType::None :
static_cast<ItemType>(found - counts_.begin() + 1);
}
void Storage::add_item(ItemType type) {
assert(accepts(type));
auto stack = stack_position(*this, type);
if (stack != items.end() && stack->type == type) {
++stack->count;
} else {
items.insert(stack, ItemStack{type, 1});
}
}
World::World(std::uint64_t seed, std::int32_t width, std::int32_t height,
std::size_t workers)
: seed_(seed),
width_(width),
height_(height),
worker_count_(checked_worker_count(workers)),
blocked_(checked_cell_count(width, height), 0) {}
std::size_t World::cell_index(GridPosition position) const noexcept {
return static_cast<std::size_t>(position.y) * static_cast<std::size_t>(width_) +
static_cast<std::size_t>(position.x);
}
bool World::is_walkable(GridPosition position) const noexcept {
if (position.x < 0 || position.y < 0 || position.x >= width_ || position.y >= height_) {
return false;
}
return blocked_[cell_index(position)] == 0;
}
void World::set_blocked(GridPosition position, bool blocked) {
if (position.x < 0 || position.y < 0 || position.x >= width_ || position.y >= height_) {
throw std::out_of_range("map cell is outside the world");
}
if (blocked) {
if (scenario_active_ && position == scenario_sawmill_) {
throw std::logic_error("cannot block the scenario sawmill");
}
for (const Agent& agent : agents_) {
if (agent.position.x == position.x && agent.position.y == position.y) {
throw std::logic_error("cannot block a cell occupied by an agent");
}
}
for (const WorkJob& job : jobs_) {
if (job.position.x == position.x && job.position.y == position.y &&
job.state != JobState::Completed) {
throw std::logic_error("cannot block a cell with an active work job");
}
}
for (const ProductionOrder& order : production_orders_) {
if (order.position.x == position.x && order.position.y == position.y) {
throw std::logic_error("cannot block a production site");
}
for (const ConstructionStop& stop : order.delivery_stops) {
if (std::find(stop.route_to_next.begin(), stop.route_to_next.end(), position) !=
stop.route_to_next.end()) {
throw std::logic_error("cannot block a scheduled construction delivery");
}
}
}
for (const Storage& storage : storages_) {
if (storage.position == position) throw std::logic_error("cannot block a storage cell");
}
for (const auto& node : resource_nodes_) {
if (node.site != ResourceSite::Natural && node.position == position) {
throw std::logic_error("cannot block a planted field or mine");
}
}
for (const Agent& agent : agents_) {
if (agent.production_index == no_entity_index &&
agent.state != AgentState::GoingToEat && agent.state != AgentState::GoingToSleep) continue;
const auto remaining = agent.route.begin() + static_cast<std::ptrdiff_t>(agent.route_cursor);
if (std::find(remaining, agent.route.end(), position) != agent.route.end()) {
throw std::logic_error("cannot block an active production, meal, or sleep route");
}
}
}
auto& cell = blocked_[cell_index(position)];
if ((cell != 0) != blocked) assignment_path_cache_.clear();
cell = blocked ? 1 : 0;
}
AgentId World::spawn_agent(GridPosition position) {
if (!is_walkable(position)) {
throw std::invalid_argument("agent spawn cell is not walkable");
}
const AgentId id = next_agent_id_++;
Agent agent;
agent.id = id;
agent.position = position;
if (hunger_enabled_) agent.hunger = initial_hunger(id);
agents_.push_back(std::move(agent));
return id;
}
JobId World::add_job(GridPosition position, std::uint32_t work_required) {
if (!is_walkable(position)) {
throw std::invalid_argument("work job cell is not walkable");
}
if (work_required == 0) {
throw std::invalid_argument("work duration must be greater than zero");
}
const JobId id = next_job_id_++;
jobs_.push_back(WorkJob{id, position, work_required, work_required, JobState::Available});
return id;
}
std::uint64_t World::add_resource_node(GridPosition position, ItemType type,
std::uint32_t quantity) {
if (!is_walkable(position)) {
throw std::invalid_argument("resource node must be on a walkable cell");
}
if ((type != ItemType::Wood && type != ItemType::Stone && type != ItemType::Berries) || quantity == 0) {
throw std::invalid_argument("resource node needs wood, stone, or berries and a positive quantity");
}
const std::uint64_t id = next_resource_node_id_++;
const bool foraging = type != ItemType::Berries || !scenario_active_;
resource_nodes_.push_back(ResourceNode{id, position, type, quantity, quantity, 0, foraging});
return id;
}
std::uint64_t World::add_storage(GridPosition position, std::uint32_t capacity, StorageKind kind) {
if (!is_walkable(position)) {
throw std::invalid_argument("storage must be on a walkable cell");
}
if (capacity == 0) {
throw std::invalid_argument("storage capacity must be positive");
}
if (kind != StorageKind::Materials && kind != StorageKind::Pantry) {
throw std::invalid_argument("unknown storage kind");
}
const std::uint64_t id = next_storage_id_;
Storage storage{id, position, capacity, 0, {}, kind};
storage.items.reserve(kind == StorageKind::Pantry ? 1 : item_type_count - 1);
storages_.push_back(std::move(storage));
++next_storage_id_;
return id;
}
void World::stock_storage(std::uint64_t id, ItemType type, std::uint32_t count) {
const auto storage = std::find_if(storages_.begin(), storages_.end(),
[id](const Storage& entry) { return entry.id == id; });
if (storage == storages_.end() || static_cast<std::size_t>(type) > item_type_count || !storage->accepts(type) ||
storage->total_items() + storage->reserved_slots + count > storage->capacity) {
throw std::invalid_argument("initial stock does not fit the selected storage");
}
if (count == 0) return;
auto stack = stack_position(*storage, type);
if (stack != storage->items.end() && stack->type == type) stack->count += count;
else storage->items.insert(stack, ItemStack{type, count});
}
void World::enable_hunger() noexcept {
if (hunger_enabled_) return;
hunger_enabled_ = true;
for (Agent& agent : agents_) agent.hunger = initial_hunger(agent.id);
}
void World::queue_production(GridPosition position, RecipeId recipe) {
static_cast<void>(recipe_for(recipe));
if (!is_walkable(position)) {
throw std::invalid_argument("production site must be on a walkable cell");
}
if (is_production_object(recipe) && !can_place_storage(position)) {
throw std::invalid_argument("the production site is occupied");
}
for (const ProductionOrder& order : production_orders_) {
if (is_production_object(order.recipe) && order.position == position) {
throw std::invalid_argument("a building occupies the production site");
}
}
ProductionOrder order{};
order.position = position;
order.recipe = recipe;
production_orders_.push_back(std::move(order));
}
bool World::can_place_cabin(GridPosition position) const noexcept {
if (!is_walkable(position)) return false;
const auto occupies_cell = [position](const auto& entity) { return entity.position == position; };
return std::none_of(storages_.begin(), storages_.end(), occupies_cell) &&
std::none_of(resource_nodes_.begin(), resource_nodes_.end(), occupies_cell) &&
std::none_of(jobs_.begin(), jobs_.end(), occupies_cell) &&
std::none_of(production_orders_.begin(), production_orders_.end(), occupies_cell);
}
std::array<ItemStack, 2> World::construction_materials(RecipeId recipe, BedBase base) const {
if (recipe == RecipeId::BuildBed && staged_beds_) {
return {ItemStack{base == BedBase::Stone ? ItemType::Stone : ItemType::Wood, 1},
ItemStack{ItemType::Cloth, 2}};
}
return is_construction(recipe) ? recipe_for(recipe).ingredients : std::array<ItemStack, 2>{};
}
void World::queue_cabin(GridPosition position, GridPosition sawmill, GridPosition stonecutter) {
if (!can_place_cabin(position) || position == sawmill || position == stonecutter ||
(scenario_active_ && position == scenario_sawmill_)) {
throw std::invalid_argument("the cabin site is occupied or blocked");
}
if (!is_walkable(sawmill) || !is_walkable(stonecutter) ||
std::any_of(production_orders_.begin(), production_orders_.end(), [&](const auto& order) {
return is_production_object(order.recipe) && (order.position == sawmill || order.position == stonecutter);
})) {
throw std::invalid_argument("a workshop site is occupied or blocked");
}
if (!find_path(sawmill, position).reachable || !find_path(stonecutter, position).reachable) {
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);
for (std::uint32_t i = 0; i < cabin.ingredients[0].count; ++i) {
queue_production(sawmill, RecipeId::SawPlank);
}
for (std::uint32_t i = 0; i < cabin.ingredients[1].count; ++i) {
queue_production(stonecutter, RecipeId::CutStoneBlock);
}
queue_production(position, RecipeId::BuildCabin);
}
void World::start_scenario(GridPosition sawmill) {
if (scenario_active_ || !can_place_cabin(sawmill)) {
throw std::invalid_argument("scenario needs a free sawmill cell");
}
enable_hunger();
scenario_active_ = true;
staged_beds_ = true;
scenario_sawmill_ = sawmill;
for (auto& node : resource_nodes_) {
if (node.type == ItemType::Berries) node.foraging_enabled = false;
}
}
bool World::can_place_bed(GridPosition position) const noexcept {
return scenario_active_ && can_place_storage(position);
}
bool World::can_place_storage(GridPosition position) const noexcept {
return (!scenario_active_ || position != scenario_sawmill_) && can_place_cabin(position) &&
!resting_at(position);
}
bool World::can_reach_object_cell(GridPosition position) const {
if (scenario_active_) return find_path(scenario_sawmill_, position).reachable;
return std::any_of(agents_.begin(), agents_.end(), [&](const auto& agent) {
return find_path(agent.position, position).reachable;
});
}
bool World::can_place_site(GridPosition position, ResourceSite site) const noexcept {
if (growing_time(site) != 0) return can_place_storage(position);
if (site != ResourceSite::Mine || position.x < 0 || position.y < 0 ||
position.x >= width_ || position.y >= height_ || is_walkable(position)) return false;
if (std::any_of(resource_nodes_.begin(), resource_nodes_.end(),
[position](const auto& node) { return node.position == position; })) return false;
return std::any_of(std::begin(adjacent_cells), std::end(adjacent_cells), [&](GridPosition offset) {
return is_walkable({position.x + offset.x, position.y + offset.y});
});
}
CommandStatus World::object_status(GridPosition position, bool moving) const noexcept {
constexpr auto busy = CommandStatus::Busy;
constexpr auto ready = CommandStatus::Accepted;
for (const auto& order : production_orders_) {
if (order.position != position || !is_production_object(order.recipe)) continue;
return order.state == JobState::InProgress || resting_at(position) ? busy : ready;
}
for (std::size_t i = 0; i < storages_.size(); ++i) {
const auto& storage = storages_[i];
if (storage.position != position) continue;
if (storage.reserved_slots != 0 || std::any_of(storage.items.begin(), storage.items.end(),
[](const auto& item) { return item.reserved != 0; })) return busy;
for (const auto& order : production_orders_) {
if (std::any_of(order.materials.begin(), order.materials.end(),
[i](const auto& material) { return material.storage_index == i; })) return busy;
}
return ready;
}
for (const auto& node : resource_nodes_) {
if (node.position != position) continue;
if (moving && (node.site == ResourceSite::Mine || node.site == ResourceSite::Natural)) {
return CommandStatus::InvalidTarget;
}
return node.reserved_workers != 0 ? busy : ready;
}
return CommandStatus::InvalidTarget;
}
CommandStatus World::edit_object(GridPosition position, const GridPosition* destination) {
const auto status = object_status(position, destination != nullptr);
if (status != CommandStatus::Accepted) return status;
if (destination && (!can_place_storage(*destination) || !can_reach_object_cell(*destination))) {
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) && 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;
}
const auto storage = std::find_if(storages_.begin(), storages_.end(), at_position);
if (storage != storages_.end()) {
if (destination) storage->position = *destination;
else {
const auto removed = static_cast<std::size_t>(storage - storages_.begin());
storages_.erase(storage);
for (auto& agent : agents_) shift_index(agent.storage_index, removed);
for (auto& entry : production_orders_) {
for (auto& material : entry.materials) shift_index(material.storage_index, removed);
for (auto& stop : entry.delivery_stops) shift_index(stop.storage_index, removed);
}
}
return CommandStatus::Accepted;
}
const auto source = std::find_if(resource_nodes_.begin(), resource_nodes_.end(), at_position);
if (source == resource_nodes_.end()) return CommandStatus::InvalidTarget;
if (destination) source->position = *destination;
else {
const auto removed = static_cast<std::size_t>(source - resource_nodes_.begin());
resource_nodes_.erase(source);
for (auto& agent : agents_) shift_index(agent.resource_node_index, removed);
}
return CommandStatus::Accepted;
}
std::uint64_t World::next_command_sequence(std::uint8_t player) const noexcept {
if (player < colony_host || player > colony_player_slots ||
command_revision_ == std::numeric_limits<std::uint64_t>::max()) return 0;
return player_sequences_[player - colony_host] + 1;
}
CommandReceipt World::apply_command(const PlayerCommand& command) {
const auto receipt = [&](CommandStatus status) { return CommandReceipt{status, tick_, command_revision_}; };
const bool object_command = (command.kind >= CommandKind::PlaceBerryField && command.kind <= CommandKind::PlaceStorage) ||
command.kind == CommandKind::PlaceFlaxField || command.kind == CommandKind::PlaceLoom;
if (!scenario_active_ && !object_command && command.kind != CommandKind::AssignProfession &&
command.kind != CommandKind::SetForaging) return receipt(CommandStatus::Unavailable);
if (command.player < colony_host || command.player > colony_player_slots) {
return receipt(CommandStatus::Unauthorized);
}
if (command.sequence == 0 || command.sequence != next_command_sequence(command.player)) {
return receipt(CommandStatus::WrongSequence);
}
switch (command.kind) {
case CommandKind::PlaceBed:
if (command.value > static_cast<std::uint8_t>(BedBase::Stone) ||
!can_place_bed(command.cell) || !find_path(scenario_sawmill_, command.cell).reachable) {
return receipt(CommandStatus::InvalidTarget);
}
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);
}
break;
case CommandKind::SetForaging: {
if (command.value > 1) return receipt(CommandStatus::InvalidTarget);
const auto source = std::find_if(resource_nodes_.begin(), resource_nodes_.end(), [&](const auto& node) {
return node.type == ItemType::Berries && node.position == command.cell;
});
if (source == resource_nodes_.end()) return receipt(CommandStatus::InvalidTarget);
source->foraging_enabled = command.value != 0;
break;
}
case CommandKind::SetPriority:
if (command.value > static_cast<std::uint8_t>(WorkPriority::BuildingFirst)) {
return receipt(CommandStatus::InvalidTarget);
}
work_priority_ = static_cast<WorkPriority>(command.value);
break;
case CommandKind::SetPaused:
if (command.player != colony_host) return receipt(CommandStatus::Unauthorized);
if (command.value > 1) return receipt(CommandStatus::InvalidTarget);
paused_ = command.value != 0;
break;
case CommandKind::PlaceBerryField:
case CommandKind::PlaceTreePlot:
case CommandKind::PlaceFlaxField:
case CommandKind::PlaceMine: {
const bool mine = command.kind == CommandKind::PlaceMine;
auto site = ResourceSite::TreePlot;
std::uint32_t yield = 6;
if (mine) {
site = ResourceSite::Mine;
yield = 24;
} else if (command.kind == CommandKind::PlaceBerryField) {
site = ResourceSite::BerryField;
yield = 8;
} else if (command.kind == CommandKind::PlaceFlaxField) {
site = ResourceSite::FlaxField;
}
if (!can_place_site(command.cell, site)) return receipt(CommandStatus::InvalidTarget);
if (mine) {
const bool reachable = std::any_of(std::begin(adjacent_cells), std::end(adjacent_cells), [&](GridPosition offset) {
return can_reach_object_cell({command.cell.x + offset.x, command.cell.y + offset.y});
});
if (!reachable) return receipt(CommandStatus::InvalidTarget);
} else if (!can_reach_object_cell(command.cell)) {
return receipt(CommandStatus::InvalidTarget);
}
resource_nodes_.push_back({next_resource_node_id_, command.cell, site_resource(site), mine ? yield : 0,
yield, 0, true, site});
++next_resource_node_id_;
if (mine) {
blocked_[cell_index(command.cell)] = 0;
assignment_path_cache_.clear();
}
break;
}
case CommandKind::PlaceLoom:
if (!can_place_storage(command.cell) || !can_reach_object_cell(command.cell)) {
return receipt(CommandStatus::InvalidTarget);
}
queue_production(command.cell, RecipeId::WeaveCloth);
break;
case CommandKind::PlaceStorage:
if (command.value > static_cast<std::uint8_t>(StorageKind::Pantry) ||
!can_place_storage(command.cell) || !can_reach_object_cell(command.cell)) {
return receipt(CommandStatus::InvalidTarget);
}
static_cast<void>(add_storage(command.cell, 18, static_cast<StorageKind>(command.value)));
break;
case CommandKind::MoveObject:
case CommandKind::DemolishObject: {
const auto status = edit_object(command.cell,
command.kind == CommandKind::MoveObject ? &command.destination : nullptr);
if (status != CommandStatus::Accepted) return receipt(status);
break;
}
case CommandKind::AssignProfession: {
if (command.value > static_cast<std::uint8_t>(Profession::Builder) || command.resident == 0) {
return receipt(CommandStatus::InvalidTarget);
}
const auto resident = std::lower_bound(agents_.begin(), agents_.end(), command.resident,
[](const Agent& agent, AgentId id) { return agent.id < id; });
if (resident == agents_.end() || resident->id != command.resident) {
return receipt(CommandStatus::InvalidTarget);
}
resident->profession = static_cast<Profession>(command.value);
break;
}
default:
return receipt(CommandStatus::InvalidTarget);
}
player_sequences_[command.player - colony_host] = command.sequence;
++command_revision_;
return receipt(CommandStatus::Accepted);
}
ScenarioProgress World::scenario_progress() const noexcept {
ScenarioProgress progress{0, agents_.size(), 0, 2 * agents_.size(), scenario_completed_};
for (const auto& order : production_orders_) {
if (order.recipe == RecipeId::BuildBed && order.bed_owner != 0) ++progress.assigned_beds;
}
for (const auto& storage : storages_) {
for (const auto& stack : storage.items) {
if (stack.type == ItemType::Berries) progress.available_food += stack.count - stack.reserved;
}
}
return progress;
}
void World::update_scenario() {
for (auto& bed : production_orders_) {
if (bed.recipe != RecipeId::BuildBed || bed.state != JobState::Completed || bed.bed_owner != 0) continue;
const auto resident = std::find_if(agents_.begin(), agents_.end(), [&](const auto& agent) {
return std::none_of(production_orders_.begin(), production_orders_.end(), [&](const auto& order) {
return order.bed_owner == agent.id;
});
});
if (resident == agents_.end()) break;
bed.bed_owner = resident->id;
}
if (!scenario_completed_) {
const auto progress = scenario_progress();
scenario_completed_ = progress.residents > 0 && progress.assigned_beds == progress.residents &&
progress.available_food >= progress.food_goal;
}
}
const ProductionOrder* World::assigned_bed(AgentId agent) const noexcept {
if (agent == 0) return nullptr;
const auto order = std::find_if(production_orders_.begin(), production_orders_.end(),
[agent](const auto& bed) { return bed.bed_owner == agent; });
return order == production_orders_.end() ? nullptr : &*order;
}
bool World::is_bed_cell(GridPosition position) const noexcept {
return std::any_of(production_orders_.begin(), production_orders_.end(), [&](const auto& order) {
return order.recipe == RecipeId::BuildBed && order.state == JobState::Completed &&
order.position == position;
});
}
bool World::resting_at(GridPosition position, AgentId except) const noexcept {
return std::any_of(agents_.begin(), agents_.end(), [&](const Agent& agent) {
if (agent.id == except) return false;
if (agent.state == AgentState::Sleeping) return agent.position == position;
return agent.state == AgentState::GoingToSleep && !agent.route.empty() && agent.route.back() == position;
});
}
bool World::ground_rest_cell(GridPosition position, AgentId agent) const noexcept {
return is_walkable(position) && !is_bed_cell(position) && !resting_at(position, agent) &&
std::none_of(agents_.begin(), agents_.end(), [&](const Agent& other) {
return other.id != agent && other.position == position;
}) &&
std::none_of(production_orders_.begin(), production_orders_.end(), [&](const auto& order) {
return order.position == position && is_construction(order.recipe);
});
}
World::PathResult World::find_path(GridPosition start, GridPosition goal) const {
PathResult result;
if (!is_walkable(start) || !is_walkable(goal)) {
return result;
}
const std::size_t cell_count = blocked_.size();
const auto start_index = static_cast<std::int32_t>(cell_index(start));
const auto goal_index = static_cast<std::int32_t>(cell_index(goal));
std::vector<std::int32_t> distance(cell_count, std::numeric_limits<std::int32_t>::max());
std::vector<std::int32_t> parent(cell_count, -1);
std::priority_queue<OpenNode, std::vector<OpenNode>, OpenNodeLater> open;
distance[static_cast<std::size_t>(start_index)] = 0;
parent[static_cast<std::size_t>(start_index)] = start_index;
const std::int32_t start_heuristic = manhattan_distance(start, goal);
open.push(OpenNode{start_index, 0, start_heuristic, start_heuristic});
constexpr GridPosition offsets[] = {{0, -1}, {1, 0}, {0, 1}, {-1, 0}};
while (!open.empty()) {
const OpenNode current = open.top();
open.pop();
if (current.distance_from_start != distance[static_cast<std::size_t>(current.cell)]) {
continue;
}
++result.nodes_visited;
if (current.cell == goal_index) {
result.reachable = true;
break;
}
const GridPosition current_position{
current.cell % width_,
current.cell / width_
};
for (const GridPosition offset : offsets) {
const GridPosition next{current_position.x + offset.x, current_position.y + offset.y};
if (!is_walkable(next)) {
continue;
}
const std::int32_t next_cell = static_cast<std::int32_t>(cell_index(next));
const std::int32_t next_distance = current.distance_from_start + 1;
const std::size_t next_index = static_cast<std::size_t>(next_cell);
if (next_distance >= distance[next_index]) {
continue;
}
distance[next_index] = next_distance;
parent[next_index] = current.cell;
const std::int32_t heuristic = manhattan_distance(next, goal);
open.push(OpenNode{next_cell, next_distance, heuristic, next_distance + heuristic});
}
}
if (!result.reachable) {
return result;
}
std::int32_t cursor = goal_index;
while (cursor != start_index) {
result.positions.push_back(GridPosition{cursor % width_, cursor / width_});
cursor = parent[static_cast<std::size_t>(cursor)];
if (cursor < 0) {
result.positions.clear();
result.reachable = false;
return result;
}
}
std::reverse(result.positions.begin(), result.positions.end());
return result;
}
void World::assign_idle_agents() {
if (jobs_.empty() || agents_.empty()) return;
struct Request {
std::size_t agent_index;
std::size_t job_index;
GridPosition start;
GridPosition goal;
};
// Failed routes are rare, so keep their per-agent exclusions sparse instead of
// clearing an agents-by-jobs matrix on every tick.
std::vector<std::vector<std::size_t>> tried(agents_.size());
std::vector<std::uint8_t> pending(agents_.size(), 0);
for (;;) {
std::vector<Request> requests;
const std::size_t chunk_count = std::min(worker_count_, agents_.size());
const auto chunk_start = [this, chunk_count](std::size_t chunk) {
const auto size = agents_.size() / chunk_count;
const auto extra = agents_.size() % chunk_count;
return chunk * size + std::min(chunk, extra);
};
const auto choose_jobs = [this, &tried, &pending](std::size_t begin, std::size_t end) {
std::vector<std::size_t> choices(end - begin, jobs_.size());
for (std::size_t agent_index = begin; agent_index < end; ++agent_index) {
const Agent& agent = agents_[agent_index];
if (agent.state != AgentState::Idle || pending[agent_index] != 0 ||
!can_take_work(agent, Profession::Builder)) continue;
std::size_t best_index = jobs_.size();
std::int32_t best_distance = std::numeric_limits<std::int32_t>::max();
for (std::size_t job_index = 0; job_index < jobs_.size(); ++job_index) {
const WorkJob& candidate = jobs_[job_index];
if (candidate.state != JobState::Available ||
std::find(tried[agent_index].begin(), tried[agent_index].end(), job_index) !=
tried[agent_index].end()) continue;
const std::int32_t distance = manhattan_distance(agent.position, candidate.position);
if (distance < best_distance || (distance == best_distance &&
(best_index == jobs_.size() || candidate.id < jobs_[best_index].id))) {
best_distance = distance;
best_index = job_index;
}
}
choices[agent_index - begin] = best_index;
}
return choices;
};
std::vector<std::future<std::vector<std::size_t>>> choice_futures;
choice_futures.reserve(chunk_count);
for (std::size_t chunk = 0; chunk < chunk_count; ++chunk) {
const std::size_t begin = chunk_start(chunk);
const std::size_t end = chunk_start(chunk + 1);
choice_futures.push_back(worker_pool_->submit([&choose_jobs, begin, end] {
return choose_jobs(begin, end);
}));
}
std::vector<std::vector<std::size_t>> choices;
choices.reserve(chunk_count);
for (auto& future : choice_futures) choices.push_back(future.get());
for (std::size_t chunk = 0; chunk < chunk_count; ++chunk) {
const std::size_t begin = chunk_start(chunk);
for (std::size_t offset = 0; offset < choices[chunk].size(); ++offset) {
const std::size_t agent_index = begin + offset;
const std::size_t job_index = choices[chunk][offset];
if (job_index == jobs_.size() || jobs_[job_index].state != JobState::Available) continue;
Agent& agent = agents_[agent_index];
WorkJob& job = jobs_[job_index];
job.state = JobState::InProgress;
agent.current_job = job.id;
pending[agent_index] = 1;
requests.push_back(Request{agent_index, job_index, agent.position, job.position});
}
}
if (requests.empty()) return;
std::vector<std::future<PathResult>> futures;
futures.reserve(requests.size());
for (const Request& request : requests) {
futures.push_back(worker_pool_->submit([this, start = request.start, goal = request.goal] {
return find_path(start, goal);
}));
}
for (std::size_t index = 0; index < requests.size(); ++index) {
auto path = futures[index].get();
++path_searches_;
path_nodes_visited_ += path.nodes_visited;
const Request& request = requests[index];
Agent& agent = agents_[request.agent_index];
WorkJob& job = jobs_[request.job_index];
if (!path.reachable) {
job.state = JobState::Available;
agent.current_job = 0;
pending[request.agent_index] = 0;
tried[request.agent_index].push_back(request.job_index);
continue;
}
agent.route = std::move(path.positions);
agent.route_cursor = 0;
agent.work_remaining = job.work_required;
agent.state = agent.route.empty() ? AgentState::Working : AgentState::Travelling;
}
}
}
World::PathResult World::assignment_path(GridPosition start, GridPosition goal) {
++path_searches_;
if (!is_walkable(start) || !is_walkable(goal)) return {};
const auto key = (static_cast<std::uint64_t>(cell_index(start)) << 32) | cell_index(goal);
if (const auto found = assignment_path_cache_.find(key); found != assignment_path_cache_.end()) {
++assignment_path_cache_hits_;
// Logical path counters stay identical after loading a save with an empty cache.
path_nodes_visited_ += found->second.nodes_visited;
return found->second;
}
auto path = find_path(start, goal);
path_nodes_visited_ += path.nodes_visited;
constexpr std::size_t cache_capacity = 8192;
constexpr std::size_t max_cached_route_length = 256;
if (path.positions.size() > max_cached_route_length) return path;
if (assignment_path_cache_.size() == cache_capacity) assignment_path_cache_.clear();
assignment_path_cache_.emplace(key, path);
return path;
}
void World::assign_resource_tasks(ResourceFocus focus) {
if (resource_nodes_.empty()) return;
constexpr std::uint32_t gather_ticks = 3;
constexpr std::uint32_t tending_ticks = 6;
const auto has_space = [](const Storage& storage) {
return storage.total_items() + storage.reserved_slots < storage.capacity;
};
std::size_t open_pantry_count = 0;
std::size_t open_material_store_count = 0;
for (const Storage& storage : storages_) {
if (!has_space(storage)) continue;
if (storage.kind == StorageKind::Pantry) ++open_pantry_count;
else ++open_material_store_count;
}
std::array<std::vector<std::size_t>, static_cast<std::size_t>(Profession::Builder)> available;
std::size_t untended_sites = 0;
for (std::size_t index = 0; index < resource_nodes_.size(); ++index) {
const auto& node = resource_nodes_[index];
const bool food = node.type == ItemType::Berries;
if (!node.foraging_enabled || (focus != ResourceFocus::Any && food != (focus == ResourceFocus::Food))) continue;
const bool tending = node.needs_tending() && node.reserved_workers == 0;
if (!tending && (node.quantity <= node.reserved_workers ||
(food ? open_pantry_count == 0 : open_material_store_count == 0))) continue;
if (tending) ++untended_sites;
available[static_cast<std::size_t>(Profession::Generalist)].push_back(index);
available[static_cast<std::size_t>(gathering_profession(node.type))].push_back(index);
}
for (Agent& agent : agents_) {
if (open_pantry_count == 0 && open_material_store_count == 0 && untended_sites == 0) break;
if (agent.profession == Profession::Builder || agent.state != AgentState::Idle || agent.current_job != 0 ||
!agent.inventory.empty()) continue;
const auto& candidates = available[static_cast<std::size_t>(agent.profession)];
if (candidates.empty()) continue;
std::vector<std::uint8_t> tried_nodes(candidates.size(), 0);
for (;;) {
std::size_t chosen = candidates.size();
std::int32_t best_distance = std::numeric_limits<std::int32_t>::max();
for (std::size_t index = 0; index < candidates.size(); ++index) {
if (tried_nodes[index] != 0) continue;
const ResourceNode& node = resource_nodes_[candidates[index]];
if (node.needs_tending()) {
if (node.reserved_workers != 0) continue;
} else if (node.quantity <= node.reserved_workers ||
(node.type == ItemType::Berries ? open_pantry_count == 0 : open_material_store_count == 0)) {
continue;
}
const std::int32_t distance = manhattan_distance(agent.position, node.position);
// Candidate order follows the resource IDs, so the first wins ties.
if (distance < best_distance) {
best_distance = distance;
chosen = index;
}
}
if (chosen == candidates.size()) break;
const auto node_index = candidates[chosen];
const ResourceNode& node = resource_nodes_[node_index];
auto path_to_node = assignment_path(agent.position, node.position);
if (!path_to_node.reachable) {
tried_nodes[chosen] = 1;
continue;
}
if (node.needs_tending()) {
++resource_nodes_[node_index].reserved_workers;
--untended_sites;
agent.resource_node_index = node_index;
agent.route = std::move(path_to_node.positions);
agent.route_cursor = 0;
agent.work_remaining = tending_ticks;
agent.state = agent.route.empty() ? AgentState::Gathering : AgentState::Travelling;
break;
}
std::vector<std::uint8_t> tried_storages(storages_.size(), 0);
std::size_t storage_index = storages_.size();
PathResult path_to_storage;
for (;;) {
storage_index = storages_.size();
std::int32_t storage_distance = std::numeric_limits<std::int32_t>::max();
for (std::size_t index = 0; index < storages_.size(); ++index) {
const Storage& storage = storages_[index];
if (tried_storages[index] != 0 || !storage.accepts(node.type) || !has_space(storage)) continue;
const std::int32_t distance = manhattan_distance(node.position, storage.position);
if (distance < storage_distance || (distance == storage_distance &&
(storage_index == storages_.size() || storage.id < storages_[storage_index].id))) {
storage_distance = distance;
storage_index = index;
}
}
if (storage_index == storages_.size()) break;
path_to_storage = assignment_path(node.position, storages_[storage_index].position);
if (path_to_storage.reachable) break;
tried_storages[storage_index] = 1;
}
if (storage_index == storages_.size()) {
tried_nodes[chosen] = 1;
continue;
}
++resource_nodes_[node_index].reserved_workers;
Storage& storage = storages_[storage_index];
++storage.reserved_slots;
if (!has_space(storage)) {
if (storage.kind == StorageKind::Pantry) --open_pantry_count;
else --open_material_store_count;
}
agent.resource_node_index = node_index;
agent.storage_index = storage_index;
agent.haul_route = std::move(path_to_storage.positions);
agent.route = std::move(path_to_node.positions);
agent.route_cursor = 0;
agent.work_remaining = node.site == ResourceSite::Mine ? 12U : gather_ticks;
agent.state = agent.route.empty() ? AgentState::Gathering : AgentState::Travelling;
break;
}
}
}
void World::assign_production_tasks(bool weaving) {
if (production_orders_.empty() || storages_.empty() ||
std::none_of(agents_.begin(), agents_.end(),
[](const Agent& agent) {
return agent.state == AgentState::Idle && can_take_work(agent, Profession::Builder);
})) return;
for (std::size_t index = 0; index < production_orders_.size(); ++index) {
ProductionOrder& order = production_orders_[index];
if (order.state != JobState::Available || (order.recipe == RecipeId::WeaveCloth) != weaving) continue;
const bool site_busy = std::any_of(production_orders_.begin(), production_orders_.end(),
[&order](const ProductionOrder& other) {
return other.state == JobState::InProgress &&
other.position.x == order.position.x && other.position.y == order.position.y;
});
if (site_busy) continue;
const Recipe recipe = recipe_for(order);
const bool construction = is_construction(order.recipe);
enum class Access { Unknown, Reachable, Unreachable };
std::vector<Access> storage_access(construction || weaving ? storages_.size() : 0, Access::Unknown);
std::vector<MaterialReservation> materials;
bool supplied = true;
for (const ItemStack& ingredient : recipe.ingredients) {
std::uint32_t remaining = ingredient.count;
for (std::size_t storage_index = 0; storage_index < storages_.size() && remaining > 0;
++storage_index) {
Storage& storage = storages_[storage_index];
const auto stack = stack_position(storage, ingredient.type);
if (stack == storage.items.end() || stack->type != ingredient.type) continue;
const auto count = std::min(remaining, stack->count - stack->reserved);
if (count == 0) continue;
if (!storage_access.empty()) {
auto& access = storage_access[storage_index];
if (access == Access::Unknown) {
access = assignment_path(storage.position, order.position).reachable
? Access::Reachable : Access::Unreachable;
}
if (access == Access::Unreachable) continue;
}
materials.push_back({storage_index, ingredient.type, count});
remaining -= count;
}
if (remaining != 0) {
supplied = false;
break;
}
}
if (!supplied) continue;
std::vector<ConstructionStop> stops;
if (construction) {
for (std::size_t s = 0; s < storage_access.size(); ++s) {
if (storage_access[s] == Access::Reachable) stops.push_back({s, {}});
}
for (std::size_t i = 0; i < stops.size(); ++i) {
const auto from = storages_[stops[i].storage_index].position;
const auto to = i + 1 == stops.size()
? order.position : storages_[stops[i + 1].storage_index].position;
auto path = assignment_path(from, to);
// Each stop can reach the site on the same undirected map.
assert(path.reachable);
stops[i].route_to_next = std::move(path.positions);
}
}
const GridPosition destination = construction
? storages_[stops.front().storage_index].position : order.position;
for (Agent& agent : agents_) {
if (agent.state != AgentState::Idle || !can_take_work(agent, Profession::Builder)) continue;
auto path = assignment_path(agent.position, destination);
if (!path.reachable) continue;
for (const auto& material : materials) {
stack_position(storages_[material.storage_index], material.type)->reserved += material.count;
}
order.materials = std::move(materials);
order.delivery_stops = std::move(stops);
order.state = JobState::InProgress;
agent.production_index = index;
agent.route = std::move(path.positions);
agent.route_cursor = 0;
agent.work_remaining = recipe.ticks;
agent.state = construction ? AgentState::FetchingMaterials :
(agent.route.empty() ? AgentState::Working : AgentState::Travelling);
break;
}
}
}
namespace {
void take_reserved_material(Storage& storage, const MaterialReservation& material) {
auto stack = stack_position(storage, material.type);
assert(stack != storage.items.end() && stack->type == material.type);
assert(stack->reserved >= material.count && stack->count >= stack->reserved);
stack->reserved -= material.count;
stack->count -= material.count;
if (stack->count == 0) storage.items.erase(stack);
}
} // namespace
void World::assign_meals() {
for (Agent& agent : agents_) {
if (agent.hunger < max_hunger) ++agent.hunger;
}
std::vector<std::size_t> stocked_pantries;
for (std::size_t i = 0; i < storages_.size(); ++i) {
Storage& storage = storages_[i];
if (storage.kind != StorageKind::Pantry) continue;
const auto stack = stack_position(storage, ItemType::Berries);
if (stack != storage.items.end() && stack->count > stack->reserved) stocked_pantries.push_back(i);
}
for (Agent& agent : agents_) {
if (stocked_pantries.empty()) break;
if (agent.state != AgentState::Idle || !agent.hungry()) continue;
std::sort(stocked_pantries.begin(), stocked_pantries.end(), [&](std::size_t left, std::size_t right) {
const auto left_distance = manhattan_distance(agent.position, storages_[left].position);
const auto right_distance = manhattan_distance(agent.position, storages_[right].position);
return left_distance == right_distance ? left < right : left_distance < right_distance;
});
for (auto pantry = stocked_pantries.begin(); pantry != stocked_pantries.end(); ++pantry) {
Storage& storage = storages_[*pantry];
auto path = assignment_path(agent.position, storage.position);
if (!path.reachable) continue;
auto stack = stack_position(storage, ItemType::Berries);
++stack->reserved;
agent.storage_index = *pantry;
agent.state = AgentState::GoingToEat;
agent.route = std::move(path.positions);
agent.route_cursor = 0;
if (stack->count == stack->reserved) stocked_pantries.erase(pantry);
break;
}
}
}
void World::finish_meal_step(Agent& agent) {
if (agent.state == AgentState::GoingToEat) {
if (agent.route_cursor != agent.route.size()) return;
take_reserved_material(storages_[agent.storage_index], {agent.storage_index, ItemType::Berries, 1});
agent.inventory.add(ItemType::Berries);
agent.storage_index = no_entity_index;
agent.route.clear();
agent.route_cursor = 0;
agent.work_remaining = meal_ticks;
agent.state = AgentState::Eating;
return;
}
if (--agent.work_remaining != 0) return;
agent.inventory.remove(ItemType::Berries);
agent.hunger = 0;
agent.state = AgentState::Idle;
++meals_eaten_;
}
void World::assign_rest() {
for (Agent& agent : agents_) {
if (agent.state != AgentState::Sleeping && agent.fatigue < max_fatigue) ++agent.fatigue;
if (agent.state != AgentState::Idle || !agent.tired()) continue;
const auto* bed = assigned_bed(agent.id);
if (bed != nullptr && !resting_at(bed->position, agent.id)) {
auto path = assignment_path(agent.position, bed->position);
if (path.reachable) {
agent.route = std::move(path.positions);
agent.route_cursor = 0;
agent.state = AgentState::GoingToSleep;
agent.resting_on_ground = false;
continue;
}
}
if (agent.fatigue != max_fatigue) continue;
if (ground_rest_cell(agent.position, agent.id)) {
agent.resting_on_ground = true;
agent.state = AgentState::Sleeping;
continue;
}
for (const auto offset : adjacent_cells) {
const GridPosition nearby{agent.position.x + offset.x, agent.position.y + offset.y};
if (!ground_rest_cell(nearby, agent.id)) continue;
agent.route = {nearby};
agent.route_cursor = 0;
agent.resting_on_ground = true;
agent.state = AgentState::GoingToSleep;
break;
}
}
}
void World::finish_rest_step(Agent& agent) {
if (agent.state == AgentState::GoingToSleep) {
if (agent.route_cursor != agent.route.size()) return;
agent.route.clear();
agent.route_cursor = 0;
agent.state = AgentState::Sleeping;
return;
}
const bool in_bed = !agent.resting_on_ground;
const auto recovery = in_bed ? bed_recovery : ground_recovery;
agent.fatigue -= std::min(agent.fatigue, recovery);
if (agent.fatigue <= (in_bed ? 0 : ground_wake_fatigue)) {
agent.resting_on_ground = false;
agent.state = AgentState::Idle;
}
}
void World::advance_construction_delivery(Agent& agent) {
ProductionOrder& order = production_orders_[agent.production_index];
if (order.collected_stops == order.delivery_stops.size()) {
for (const auto& material : order.materials) {
agent.inventory.remove(material.type, material.count);
}
order.delivery_stops.clear();
order.collected_stops = 0;
agent.state = AgentState::Working;
agent.route.clear();
agent.route_cursor = 0;
return;
}
auto& stop = order.delivery_stops[order.collected_stops];
for (const auto& material : order.materials) {
if (material.storage_index == stop.storage_index) {
take_reserved_material(storages_[stop.storage_index], material);
agent.inventory.add(material.type, material.count);
}
}
++order.collected_stops;
agent.route = std::move(stop.route_to_next);
agent.route_cursor = 0;
agent.state = AgentState::Hauling;
}
void World::finish_production(Agent& agent) {
ProductionOrder& order = production_orders_[agent.production_index];
const Recipe recipe = recipe_for(order);
assert(!order.materials.empty());
if (recipe.output != ItemType::None) {
for (const auto& material : order.materials) {
take_reserved_material(storages_[material.storage_index], material);
}
// Crafting replaces one raw item with one finished item in the same store.
storages_[order.materials.front().storage_index].add_item(recipe.output);
}
order.materials.clear();
if (order.recipe == RecipeId::BuildBed &&
(order.bed_stage == BedStage::Foundation || order.bed_stage == BedStage::Bedding)) {
order.bed_stage = order.bed_stage == BedStage::Foundation ? BedStage::Bedding : BedStage::Pillow;
order.state = JobState::Available;
} else if (order.recipe == RecipeId::WeaveCloth) {
order.state = JobState::Available;
} else {
order.state = JobState::Completed;
}
agent.production_index = no_entity_index;
agent.state = AgentState::Idle;
agent.route.clear();
agent.route_cursor = 0;
}
void World::grow_sites() {
for (auto& node : resource_nodes_) {
if (node.site == ResourceSite::Natural) {
if (tick_ % berry_regrowth_ticks == 0 && node.type == ItemType::Berries &&
node.quantity < node.initial_quantity) ++node.quantity;
} else if (node.growth_at != 0 && tick_ >= node.growth_at) {
node.quantity = node.initial_quantity;
node.growth_at = 0;
}
}
}
void World::step(TickProfile* profile) {
if (paused_) return;
if (!worker_pool_ && !agents_.empty()) worker_pool_ = std::make_unique<WorkerPool>(worker_count_);
using Clock = std::chrono::steady_clock;
auto phase_start = profile ? Clock::now() : Clock::time_point{};
const auto finish_phase = [&](std::chrono::nanoseconds TickProfile::*phase) {
if (!profile) return;
const auto now = Clock::now();
profile->*phase += std::chrono::duration_cast<std::chrono::nanoseconds>(now - phase_start);
phase_start = now;
};
if (scenario_active_ || command_revision_ != 0 || tick_ % berry_regrowth_ticks == 0) grow_sites();
if (hunger_enabled_) assign_meals();
if (scenario_active_) assign_rest();
finish_phase(&TickProfile::growth_and_needs);
if (work_priority_ == WorkPriority::FoodFirst) assign_resource_tasks(ResourceFocus::Food);
finish_phase(&TickProfile::resource_assignment);
assign_production_tasks(false);
if (std::any_of(production_orders_.begin(), production_orders_.end(), [](const auto& order) {
return order.recipe == RecipeId::WeaveCloth && order.state == JobState::Available;
})) assign_production_tasks(true);
finish_phase(&TickProfile::production_assignment);
assign_idle_agents();
finish_phase(&TickProfile::generic_assignment);
if (work_priority_ == WorkPriority::BuildingFirst) assign_resource_tasks(ResourceFocus::Materials);
assign_resource_tasks();
finish_phase(&TickProfile::resource_assignment);
const auto can_work = [this](const Agent& agent) {
if (!scenario_active_) return true;
const auto interval = 1U + static_cast<unsigned>(agent.hungry()) + static_cast<unsigned>(agent.tired());
return tick_ % interval == 0;
};
const auto advance_agents = [this, can_work](std::size_t begin, std::size_t end) {
std::uint64_t completed = 0;
for (std::size_t index = begin; index < end; ++index) {
Agent& agent = agents_[index];
if ((agent.state == AgentState::Travelling || agent.state == AgentState::Hauling ||
agent.state == AgentState::FetchingMaterials || agent.state == AgentState::GoingToEat ||
agent.state == AgentState::GoingToSleep) &&
agent.route_cursor < agent.route.size()) {
agent.position = agent.route[agent.route_cursor++];
if (agent.state == AgentState::Travelling && agent.route_cursor == agent.route.size()) {
agent.state = agent.resource_node_index == no_entity_index
? AgentState::Working : AgentState::Gathering;
}
}
if (agent.state == AgentState::Gathering) {
if (agent.work_remaining > 0 && can_work(agent)) --agent.work_remaining;
continue;
}
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;
const auto job = std::lower_bound(
jobs_.begin(), jobs_.end(), agent.current_job,
[](const WorkJob& candidate, JobId id) { return candidate.id < id; });
if (job != jobs_.end() && job->id == agent.current_job) {
job->state = JobState::Completed;
++completed;
}
agent.current_job = 0;
agent.state = AgentState::Idle;
agent.route.clear();
agent.route_cursor = 0;
}
return completed;
};
if (!agents_.empty()) {
const auto chunk_count = std::min(worker_count_, agents_.size());
std::vector<std::future<std::uint64_t>> futures;
futures.reserve(chunk_count);
for (std::size_t chunk = 0; chunk < chunk_count; ++chunk) {
const std::size_t begin = chunk * agents_.size() / chunk_count;
const std::size_t end = (chunk + 1) * agents_.size() / chunk_count;
futures.push_back(worker_pool_->submit([&advance_agents, begin, end] {
return advance_agents(begin, end);
}));
}
for (auto& future : futures) jobs_completed_ += future.get();
}
for (Agent& agent : agents_) {
if (agent.state == AgentState::GoingToEat || agent.state == AgentState::Eating) {
finish_meal_step(agent);
continue;
}
if (agent.state == AgentState::GoingToSleep || agent.state == AgentState::Sleeping) {
finish_rest_step(agent);
continue;
}
if (agent.production_index != no_entity_index && 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 &&
agent.work_remaining == 0) {
finish_production(agent);
}
if (agent.state == AgentState::Gathering) {
if (agent.work_remaining == 0 && agent.resource_node_index < resource_nodes_.size()) {
ResourceNode& node = resource_nodes_[agent.resource_node_index];
if (agent.storage_index == no_entity_index) {
node.growth_at = tick_ + growing_time(node.site);
--node.reserved_workers;
agent.resource_node_index = no_entity_index;
agent.state = AgentState::Idle;
agent.route.clear();
agent.route_cursor = 0;
continue;
}
if (node.quantity > 0) --node.quantity;
if (node.reserved_workers > 0) --node.reserved_workers;
agent.inventory.add(node.type);
agent.resource_node_index = no_entity_index;
agent.route = std::move(agent.haul_route);
agent.haul_route.clear();
agent.route_cursor = 0;
agent.state = AgentState::Hauling;
}
}
if (agent.state == AgentState::Hauling && agent.route_cursor == agent.route.size() &&
agent.storage_index < storages_.size()) {
Storage& storage = storages_[agent.storage_index];
const ItemType cargo = agent.inventory.first_item();
if (storage.reserved_slots > 0) --storage.reserved_slots;
storage.add_item(cargo);
agent.inventory.remove(cargo);
agent.storage_index = no_entity_index;
agent.state = AgentState::Idle;
agent.route.clear();
agent.route_cursor = 0;
}
}
if (scenario_active_) update_scenario();
++tick_;
finish_phase(&TickProfile::advancement);
}
void World::write_svg(const std::string& path) const {
std::ofstream output(path);
if (!output) {
throw std::runtime_error("could not open SVG output path");
}
constexpr std::int32_t cell_size = 10;
const std::int32_t pixel_width = width_ * cell_size;
const std::int32_t pixel_height = height_ * cell_size;
output << "<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 "
<< pixel_width << ' ' << pixel_height + 60 << "\" width=\"" << pixel_width
<< "\" height=\"" << pixel_height + 60 << "\">\n"
<< "<rect width=\"100%\" height=\"100%\" fill=\"#f5f1e8\"/>\n"
<< "<rect x=\"0\" y=\"0\" width=\"" << pixel_width << "\" height=\""
<< pixel_height << "\" fill=\"#e8e0cf\"/>\n";
output << "<path d=\"";
for (std::int32_t x = 0; x <= width_; ++x) {
const std::int32_t pixel_x = x * cell_size;
output << 'M' << pixel_x << " 0 V" << pixel_height << ' ';
}
for (std::int32_t y = 0; y <= height_; ++y) {
const std::int32_t pixel_y = y * cell_size;
output << 'M' << 0 << ' ' << pixel_y << " H" << pixel_width << ' ';
}
output << "\" stroke=\"#d2c8b4\" stroke-width=\"0.5\"/>\n";
for (std::int32_t y = 0; y < height_; ++y) {
for (std::int32_t x = 0; x < width_; ++x) {
if (blocked_[cell_index(GridPosition{x, y})] != 0) {
output << "<rect x=\"" << x * cell_size << "\" y=\"" << y * cell_size
<< "\" width=\"" << cell_size << "\" height=\"" << cell_size
<< "\" fill=\"#5b6470\"/>\n";
}
}
}
for (const WorkJob& job : jobs_) {
const std::int32_t cx = job.position.x * cell_size + cell_size / 2;
const std::int32_t cy = job.position.y * cell_size + cell_size / 2;
const char* fill = job.state == JobState::Available ? "#4b9b67" :
job.state == JobState::InProgress ? "#e6a23c" : "#a9adaf";
output << "<rect x=\"" << cx - 3 << "\" y=\"" << cy - 3
<< "\" width=\"6\" height=\"6\" rx=\"1\" fill=\"" << fill << "\"/>\n";
}
for (const ResourceNode& node : resource_nodes_) {
if (node.quantity == 0) continue;
const std::int32_t cx = node.position.x * cell_size + cell_size / 2;
const std::int32_t cy = node.position.y * cell_size + cell_size / 2;
const char* fill = node.type == ItemType::Berries ? "#ad507b" :
node.type == ItemType::Wood ? "#4b8f55" : "#78878b";
output << "<circle cx=\"" << cx << "\" cy=\"" << cy << "\" r=\"4\" fill=\""
<< fill << "\" stroke=\"#34433d\" stroke-width=\"1\"/>\n";
}
for (const Storage& storage : storages_) {
const std::int32_t cx = storage.position.x * cell_size + cell_size / 2;
const std::int32_t cy = storage.position.y * cell_size + cell_size / 2;
const char* fill = storage.kind == StorageKind::Pantry ? "#ad507b" : "#a66e36";
output << "<rect x=\"" << cx - 4 << "\" y=\"" << cy - 4
<< "\" width=\"8\" height=\"8\" fill=\"" << fill << "\" stroke=\"#60452d\"/>\n";
}
for (const ProductionOrder& order : production_orders_) {
if (!is_construction(order.recipe)) continue;
const auto cx = order.position.x * cell_size + cell_size / 2;
const auto cy = order.position.y * cell_size + cell_size / 2;
const char* fill = order.state == JobState::Completed ? "#ae694a" :
order.state == JobState::InProgress ? "#dfa54b" : "#93b8c8";
output << "<polygon points=\"" << cx - 4 << ',' << cy - 1 << ' ' << cx << ',' << cy - 5
<< ' ' << cx + 4 << ',' << cy - 1 << ' ' << cx + 4 << ',' << cy + 4
<< ' ' << cx - 4 << ',' << cy + 4 << "\" fill=\"" << fill
<< "\" stroke=\"#454b4b\"/>\n";
}
for (const Agent& agent : agents_) {
if ((agent.state == AgentState::Travelling || agent.state == AgentState::Hauling ||
agent.state == AgentState::FetchingMaterials || agent.state == AgentState::GoingToEat ||
agent.state == AgentState::GoingToSleep) &&
agent.route_cursor < agent.route.size()) {
const std::uint32_t hue = static_cast<std::uint32_t>((agent.id * 67ULL) % 360ULL);
output << "<polyline fill=\"none\" stroke=\"hsl(" << hue
<< ",65%,43%)\" stroke-width=\"1.5\" stroke-opacity=\"0.65\" points=\""
<< agent.position.x * cell_size + cell_size / 2 << ','
<< agent.position.y * cell_size + cell_size / 2 << ' ';
for (std::size_t index = agent.route_cursor; index < agent.route.size(); ++index) {
output << agent.route[index].x * cell_size + cell_size / 2 << ','
<< agent.route[index].y * cell_size + cell_size / 2 << ' ';
}
output << "\"/>\n";
}
}
for (const Agent& agent : agents_) {
const std::int32_t cx = agent.position.x * cell_size + cell_size / 2;
const std::int32_t cy = agent.position.y * cell_size + cell_size / 2;
const char* fill = agent.state == AgentState::Idle ? "#3f6fba" :
(agent.state == AgentState::Travelling ||
agent.state == AgentState::FetchingMaterials) ? "#7b4cc2" :
agent.state == AgentState::Working ? "#cf5746" :
agent.state == AgentState::Gathering ? "#b98034" :
agent.state == AgentState::Hauling ? "#328e89" :
(agent.state == AgentState::GoingToSleep || agent.state == AgentState::Sleeping)
? "#536690" : "#ad507b";
output << "<circle cx=\"" << cx << "\" cy=\"" << cy << "\" r=\"3\" fill=\""
<< fill << "\" stroke=\"white\" stroke-width=\"0.7\"/>\n";
}
output << "<text x=\"6\" y=\"" << pixel_height + 19
<< "\" font-family=\"sans-serif\" font-size=\"12\" fill=\"#263238\">"
<< "Residents: " << agents_.size() << " | Jobs completed: " << jobs_completed_
<< " | Stored wood: " << std::accumulate(storages_.begin(), storages_.end(), std::uint64_t{0},
[](std::uint64_t total, const Storage& storage) { return total + storage.item_count(ItemType::Wood); })
<< " | Stone: " << std::accumulate(storages_.begin(), storages_.end(), std::uint64_t{0},
[](std::uint64_t total, const Storage& storage) { return total + storage.item_count(ItemType::Stone); })
<< " | Tick: " << tick_ << "</text>\n"
<< "<text x=\"6\" y=\"" << pixel_height + 42
<< "\" font-family=\"sans-serif\" font-size=\"11\" fill=\"#263238\">"
<< "Residents: blue idle, purple travelling, red working, gold gathering, teal hauling"
<< " | Resources: green wood, gray stone, brown storage"
<< " | Routes: colored lines</text>\n</svg>\n";
}
std::uint64_t World::tick() const noexcept { return tick_; }
std::uint64_t World::seed() const noexcept { return seed_; }
std::int32_t World::width() const noexcept { return width_; }
std::int32_t World::height() const noexcept { return height_; }
const std::vector<Agent>& World::agents() const noexcept { return agents_; }
const std::vector<WorkJob>& World::jobs() const noexcept { return jobs_; }
const std::vector<ResourceNode>& World::resource_nodes() const noexcept { return resource_nodes_; }
const std::vector<Storage>& World::storages() const noexcept { return storages_; }
const std::vector<ProductionOrder>& World::production_orders() const noexcept { return production_orders_; }
std::uint64_t World::path_searches() const noexcept { return path_searches_; }
std::uint64_t World::path_nodes_visited() const noexcept { return path_nodes_visited_; }
std::uint64_t World::jobs_completed() const noexcept { return jobs_completed_; }
std::uint64_t World::meals_eaten() const noexcept { return meals_eaten_; }
std::size_t World::worker_count() const noexcept { return worker_count_; }
} // namespace settlement