2096 lines
101 KiB
C++
2096 lines
101 KiB
C++
#include "settlement/core/world.hpp"
|
|
#include "settlement/core/inventory_transaction.hpp"
|
|
|
|
#include <Void/Core/Scope.hpp>
|
|
#include <Void/Math/Numeric.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 is_finished_floor(const ProductionOrder& order) noexcept {
|
|
return order.recipe == RecipeId::BuildFloor && order.state == JobState::Completed;
|
|
}
|
|
|
|
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<ItemAmount, 2> ingredients;
|
|
ItemType output;
|
|
std::uint32_t ticks;
|
|
};
|
|
|
|
const Recipe& recipe_for(RecipeId id) {
|
|
static constexpr Recipe saw{{ItemAmount{ItemType::Wood, 1}, {}}, ItemType::Plank, 12};
|
|
static constexpr Recipe cut{{ItemAmount{ItemType::Stone, 1}, {}}, ItemType::StoneBlock, 16};
|
|
static constexpr Recipe cabin{{ItemAmount{ItemType::Plank, 3}, ItemAmount{ItemType::StoneBlock, 2}},
|
|
ItemType::None, 28};
|
|
static constexpr Recipe bed{{ItemAmount{ItemType::Plank, 1}, {}}, ItemType::None, 14};
|
|
static constexpr Recipe weave{{ItemAmount{ItemType::Flax, 1}, {}}, ItemType::Cloth, 12};
|
|
static constexpr Recipe floor{{ItemAmount{ItemType::Wood, 1}, {}}, ItemType::None, 6};
|
|
static constexpr Recipe wall{{ItemAmount{ItemType::Wood, 1}, {}}, ItemType::None, 9};
|
|
static constexpr Recipe door{{ItemAmount{ItemType::Wood, 2}, {}}, ItemType::None, 12};
|
|
static constexpr Recipe cabinet{{ItemAmount{ItemType::Wood, 1}, {}}, ItemType::None, 10};
|
|
static constexpr Recipe mining_rack{{ItemAmount{ItemType::Wood, 1}, ItemAmount{ItemType::Stone, 1}},
|
|
ItemType::None, 10};
|
|
static constexpr Recipe loom{{ItemAmount{ItemType::Wood, 2}, {}}, ItemType::None, 12};
|
|
static constexpr Recipe install_door{{ItemAmount{ItemType::WoodenDoor, 1}, {}}, ItemType::None, 8};
|
|
static constexpr Recipe craft_door{{ItemAmount{ItemType::Wood, 2}, {}}, ItemType::WoodenDoor, 14};
|
|
static constexpr Recipe craft_cabinet{cabinet.ingredients, ItemType::MedicineCabinet, 14};
|
|
static constexpr Recipe craft_rack{mining_rack.ingredients, ItemType::MiningRack, 14};
|
|
static constexpr Recipe craft_loom{loom.ingredients, ItemType::Loom, 16};
|
|
static constexpr Recipe install_cabinet{{ItemAmount{ItemType::MedicineCabinet, 1}, {}}, ItemType::None, 8};
|
|
static constexpr Recipe install_rack{{ItemAmount{ItemType::MiningRack, 1}, {}}, ItemType::None, 8};
|
|
static constexpr Recipe install_loom{{ItemAmount{ItemType::Loom, 1}, {}}, ItemType::None, 8};
|
|
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;
|
|
case RecipeId::BuildFloor: return floor;
|
|
case RecipeId::BuildWall: return wall;
|
|
case RecipeId::BuildDoorAlongX:
|
|
case RecipeId::BuildDoorAlongY: return door;
|
|
case RecipeId::BuildMedicineCabinet: return cabinet;
|
|
case RecipeId::BuildMiningRack: return mining_rack;
|
|
case RecipeId::BuildLoom: return loom;
|
|
case RecipeId::InstallDoorAlongX:
|
|
case RecipeId::InstallDoorAlongY: return install_door;
|
|
case RecipeId::CraftWoodenDoor: return craft_door;
|
|
case RecipeId::CraftMedicineCabinet: return craft_cabinet;
|
|
case RecipeId::CraftMiningRack: return craft_rack;
|
|
case RecipeId::CraftLoom: return craft_loom;
|
|
case RecipeId::InstallMedicineCabinet: return install_cabinet;
|
|
case RecipeId::InstallMiningRack: return install_rack;
|
|
case RecipeId::InstallLoom: return install_loom;
|
|
}
|
|
throw std::invalid_argument("unknown production recipe");
|
|
}
|
|
|
|
constexpr ItemType carpentry_products[] = {
|
|
ItemType::WoodenDoor, ItemType::MedicineCabinet, ItemType::MiningRack, ItemType::Loom,
|
|
};
|
|
|
|
RecipeId recipe_for_carpentry_item(ItemType item) {
|
|
switch (item) {
|
|
case ItemType::WoodenDoor: return RecipeId::CraftWoodenDoor;
|
|
case ItemType::MedicineCabinet: return RecipeId::CraftMedicineCabinet;
|
|
case ItemType::MiningRack: return RecipeId::CraftMiningRack;
|
|
case ItemType::Loom: return RecipeId::CraftLoom;
|
|
default: throw std::invalid_argument("unknown carpentry item");
|
|
}
|
|
}
|
|
|
|
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; });
|
|
}
|
|
|
|
template<class Records>
|
|
auto record_position(Records& records, std::uint64_t id) {
|
|
return std::lower_bound(records.begin(), records.end(), id,
|
|
[](const auto& record, std::uint64_t target) { return record.id < target; });
|
|
}
|
|
|
|
template<class Records>
|
|
auto& require_record(Records& records, std::uint64_t id) {
|
|
const auto found = record_position(records, id);
|
|
if (found == records.end() || found->id != id) throw std::logic_error("Missing simulation object ID.");
|
|
return *found;
|
|
}
|
|
|
|
std::size_t checked_cell_count(std::int32_t width, std::int32_t height) {
|
|
if (width <= 0 || height <= 0 || width > max_map_dimension || height > max_map_dimension) {
|
|
throw std::invalid_argument("map dimensions must be in the range 1..512");
|
|
}
|
|
return static_cast<std::size_t>(width) * static_cast<std::size_t>(height);
|
|
}
|
|
|
|
std::size_t checked_worker_count(std::size_t workers, ExecutionMode mode) {
|
|
switch (mode) {
|
|
case ExecutionMode::SerialReference:
|
|
if (workers != 1) {
|
|
throw std::invalid_argument("serial reference requires one logical worker");
|
|
}
|
|
return workers;
|
|
case ExecutionMode::Parallel:
|
|
break;
|
|
default:
|
|
throw std::invalid_argument("execution mode is not supported");
|
|
}
|
|
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
|
|
|
|
RoomPlan make_room_plan(GridPosition first, GridPosition last) noexcept {
|
|
return {{std::min(first.x, last.x), std::min(first.y, last.y)},
|
|
{std::max(first.x, last.x), std::max(first.y, last.y)}};
|
|
}
|
|
|
|
bool RoomPlan::valid_size() const noexcept {
|
|
const auto width = static_cast<std::int64_t>(last.x) - first.x + 1;
|
|
const auto height = static_cast<std::int64_t>(last.y) - first.y + 1;
|
|
if (entrance > RoomSide::West || layout > RoomTemplate::Weaver) return false;
|
|
if (layout == RoomTemplate::Empty) return width >= 3 && width <= 12 && height >= 3 && height <= 12;
|
|
return width == furnished_room_size && height == furnished_room_size;
|
|
}
|
|
|
|
bool RoomPlan::contains(GridPosition cell) const noexcept {
|
|
return cell.x >= first.x && cell.x <= last.x && cell.y >= first.y && cell.y <= last.y;
|
|
}
|
|
|
|
RecipeId RoomPlan::recipe_at(GridPosition cell) const noexcept {
|
|
const auto middle_x = std::midpoint(first.x, last.x), middle_y = std::midpoint(first.y, last.y);
|
|
if (cell.y == first.y || cell.y == last.y) {
|
|
if (cell.x == middle_x && (cell.y == first.y ? entrance == RoomSide::North : entrance == RoomSide::South)) {
|
|
return RecipeId::BuildDoorAlongX;
|
|
}
|
|
return RecipeId::BuildWall;
|
|
}
|
|
if (cell.x == first.x || cell.x == last.x) {
|
|
if (cell.y == middle_y && (cell.x == first.x ? entrance == RoomSide::West : entrance == RoomSide::East)) {
|
|
return RecipeId::BuildDoorAlongY;
|
|
}
|
|
return RecipeId::BuildWall;
|
|
}
|
|
return RecipeId::BuildFloor;
|
|
}
|
|
|
|
std::optional<std::array<RoomFurnishing, 2>> RoomPlan::furnishings() const noexcept {
|
|
if (layout == RoomTemplate::Empty || !valid_size()) return std::nullopt;
|
|
// Keep the entry aisle clear by placing both pieces against the back wall.
|
|
const GridPosition bed_offsets[] = {{1, 2}, {1, 1}, {1, 1}, {2, 1}};
|
|
const GridPosition fixture_offsets[] = {{2, 2}, {1, 2}, {2, 1}, {2, 2}};
|
|
const RecipeId fixtures[] = {RecipeId::BuildMedicineCabinet, RecipeId::BuildMiningRack, RecipeId::BuildLoom};
|
|
const auto side = static_cast<std::size_t>(entrance);
|
|
const auto bed = bed_offsets[side];
|
|
const auto fixture = fixture_offsets[side];
|
|
return std::array{RoomFurnishing{{first.x + bed.x, first.y + bed.y}, RecipeId::BuildBed,
|
|
layout == RoomTemplate::Miner ? BedBase::Stone : BedBase::Wood},
|
|
RoomFurnishing{{first.x + fixture.x, first.y + fixture.y},
|
|
fixtures[static_cast<std::size_t>(layout) - 1]}};
|
|
}
|
|
|
|
std::uint8_t RoomPlan::placement_value() const noexcept {
|
|
return static_cast<std::uint8_t>((static_cast<unsigned>(layout) << 2) | static_cast<unsigned>(entrance));
|
|
}
|
|
|
|
RoomPlan RoomPlan::from_placement(GridPosition first, GridPosition last, std::uint8_t value) noexcept {
|
|
return {first, last, static_cast<RoomSide>(value & 3U), static_cast<RoomTemplate>(value >> 2)};
|
|
}
|
|
|
|
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;
|
|
if (counts_[index - 1] == 0) stack_ids_[index - 1] = 0;
|
|
}
|
|
|
|
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, ExecutionMode mode, WorkerPoolOptions worker_options)
|
|
: WorldState(seed, width, height),
|
|
worker_count_(checked_worker_count(workers, mode)),
|
|
execution_mode_(mode),
|
|
worker_options_(std::move(worker_options)) {
|
|
blocked_.resize(checked_cell_count(width, height), 0);
|
|
}
|
|
|
|
World::World(CaptureTag, const World& source)
|
|
: WorldState(source),
|
|
worker_count_(source.worker_count_),
|
|
execution_mode_(source.execution_mode_) {}
|
|
|
|
std::shared_ptr<const World> World::capture() const {
|
|
return std::shared_ptr<const World>(new const World(CaptureTag{}, *this));
|
|
}
|
|
|
|
const Storage* World::find_storage(StorageId id) const noexcept {
|
|
const auto found = record_position(storages_, id);
|
|
return found == storages_.end() || found->id != id ? nullptr : &*found;
|
|
}
|
|
|
|
const ResourceNode* World::find_resource_node(ResourceNodeId id) const noexcept {
|
|
const auto found = record_position(resource_nodes_, id);
|
|
return found == resource_nodes_.end() || found->id != id ? nullptr : &*found;
|
|
}
|
|
|
|
const ProductionOrder* World::find_production(ProductionId id) const noexcept {
|
|
const auto found = record_position(production_orders_, id);
|
|
return found == production_orders_.end() || found->id != id ? nullptr : &*found;
|
|
}
|
|
|
|
ProductionOrder& World::production_by_id(ProductionId id) {
|
|
return require_record(production_orders_, id);
|
|
}
|
|
|
|
// Replace with a restorable checked sequence when Void/Library#7 is available:
|
|
// https://git.faumaray.com/Void/Library/issues/7
|
|
bool World::reserve_production(std::size_t count) {
|
|
if (!Void::Numeric::checked_add(next_production_id_, static_cast<std::uint64_t>(count))) return false;
|
|
production_orders_.reserve(production_orders_.size() + count);
|
|
return true;
|
|
}
|
|
|
|
void World::append_production(ProductionOrder order) {
|
|
order.id = next_production_id_;
|
|
production_orders_.push_back(std::move(order));
|
|
++next_production_id_;
|
|
}
|
|
|
|
Storage& World::storage_by_id(StorageId id) {
|
|
return require_record(storages_, id);
|
|
}
|
|
|
|
ResourceNode& World::resource_node_by_id(ResourceNodeId id) {
|
|
return require_record(resource_nodes_, id);
|
|
}
|
|
|
|
std::size_t World::cell_index(GridPosition position) const noexcept {
|
|
return static_cast<std::size_t>(position.y) * static_cast<std::size_t>(width_) +
|
|
static_cast<std::size_t>(position.x);
|
|
}
|
|
|
|
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_id != 0 &&
|
|
is_carpentry_recipe(production_by_id(agent.production_id).recipe) &&
|
|
std::find(agent.haul_route.begin(), agent.haul_route.end(), position) != agent.haul_route.end()) {
|
|
throw std::logic_error("cannot block the carpenter's delivery route");
|
|
}
|
|
if (agent.production_id == 0 &&
|
|
agent.state != AgentState::GoingToEat && agent.state != AgentState::GoingToSleep &&
|
|
!is_carpentry_item(agent.inventory.first_item())) continue;
|
|
const auto remaining = agent.route.begin() + static_cast<std::ptrdiff_t>(agent.route_cursor);
|
|
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_;
|
|
const auto successor = Void::Numeric::checked_add(id, AgentId{1});
|
|
if (id == 0 || !successor) throw std::overflow_error("resident identities exhausted");
|
|
Agent agent;
|
|
agent.id = id;
|
|
agent.position = position;
|
|
if (hunger_enabled_) agent.hunger = initial_hunger(id);
|
|
agents_.push_back(std::move(agent));
|
|
next_agent_id_ = *successor;
|
|
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_;
|
|
const auto successor = Void::Numeric::checked_add(id, JobId{1});
|
|
if (id == 0 || !successor) throw std::overflow_error("job identities exhausted");
|
|
jobs_.push_back(WorkJob{id, position, work_required, work_required, JobState::Available});
|
|
next_job_id_ = *successor;
|
|
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");
|
|
}
|
|
// Restorable counters stay with each World. Replacement contract and limits
|
|
// are tracked at https://git.faumaray.com/Void/Library/issues/7.
|
|
const std::uint64_t id = next_resource_node_id_;
|
|
const auto successor = Void::Numeric::checked_add(id, std::uint64_t{1});
|
|
if (!successor) throw std::overflow_error("resource node IDs exhausted");
|
|
const bool foraging = type != ItemType::Berries || !scenario_active_;
|
|
resource_nodes_.push_back(ResourceNode{id, position, type, quantity, quantity, 0, foraging});
|
|
next_resource_node_id_ = *successor;
|
|
return id;
|
|
}
|
|
|
|
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_;
|
|
const auto successor = Void::Numeric::checked_add(id, std::uint64_t{1});
|
|
if (!successor) throw std::overflow_error("storage IDs exhausted");
|
|
Storage storage{id, position, capacity, 0, {}, kind};
|
|
storage.items.reserve(kind == StorageKind::Pantry ? 1 : item_type_count - 1);
|
|
storages_.push_back(std::move(storage));
|
|
next_storage_id_ = *successor;
|
|
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);
|
|
auto& balance = item_balances_[static_cast<std::size_t>(type) - 1];
|
|
const auto grant = Void::Numeric::checked_add(balance.grant, std::uint64_t{count});
|
|
if (!grant) throw std::overflow_error("stock grant balance exhausted");
|
|
if (stack != storage->items.end() && stack->type == type) {
|
|
const auto amount = Void::Numeric::checked_add(stack->count, count);
|
|
if (!amount) throw std::overflow_error("stock quantity exhausted");
|
|
stack->count = *amount;
|
|
} else {
|
|
const auto next = Void::Numeric::checked_add(next_stack_id_, std::uint64_t{1});
|
|
if (next_stack_id_ == 0 || !next) throw std::overflow_error("stack identities exhausted");
|
|
storage->items.insert(stack, ItemStack{type, count, 0, next_stack_id_});
|
|
next_stack_id_ = *next;
|
|
}
|
|
balance.grant = *grant;
|
|
}
|
|
|
|
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_carpentry_recipe(recipe) && carpenter_workshop() != position) {
|
|
throw std::invalid_argument("carpentry orders need the carpenter's workshop");
|
|
}
|
|
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 && !is_finished_floor(order)) {
|
|
throw std::invalid_argument("a building occupies the production site");
|
|
}
|
|
}
|
|
if (!reserve_production(1)) throw ProductionCapacityError{};
|
|
ProductionOrder order{};
|
|
order.position = position;
|
|
order.recipe = recipe;
|
|
append_production(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(),
|
|
[&](const auto& order) { return occupies_cell(order) && !is_finished_floor(order); });
|
|
}
|
|
|
|
bool World::can_place_room(const RoomPlan& plan) const noexcept {
|
|
if (!plan.valid_size() || (plan.layout != RoomTemplate::Empty && !scenario_active_) ||
|
|
!is_walkable(plan.first) || !is_walkable(plan.last)) return false;
|
|
const int middle_x = std::midpoint(plan.first.x, plan.last.x);
|
|
const int middle_y = std::midpoint(plan.first.y, plan.last.y);
|
|
const GridPosition exits[] = {{middle_x, plan.first.y - 1}, {plan.last.x + 1, middle_y},
|
|
{middle_x, plan.last.y + 1}, {plan.first.x - 1, middle_y}};
|
|
if (!is_walkable(exits[static_cast<std::size_t>(plan.entrance)]) ||
|
|
(scenario_active_ && plan.contains(scenario_sawmill_))) return false;
|
|
for (int y = plan.first.y; y <= plan.last.y; ++y) {
|
|
for (int x = plan.first.x; x <= plan.last.x; ++x) {
|
|
if (!is_walkable({x, y})) return false;
|
|
}
|
|
}
|
|
const auto inside = [&](const auto& entity) { return plan.contains(entity.position); };
|
|
return std::none_of(production_orders_.begin(), production_orders_.end(), inside) &&
|
|
std::none_of(resource_nodes_.begin(), resource_nodes_.end(), inside) &&
|
|
std::none_of(storages_.begin(), storages_.end(), inside) &&
|
|
std::none_of(jobs_.begin(), jobs_.end(), inside) &&
|
|
std::none_of(agents_.begin(), agents_.end(), [&](const Agent& agent) {
|
|
return (agent.state == AgentState::Sleeping && inside(agent)) ||
|
|
(agent.state == AgentState::GoingToSleep && !agent.route.empty() && plan.contains(agent.route.back()));
|
|
});
|
|
}
|
|
|
|
std::array<ItemAmount, 2> World::construction_materials(RecipeId recipe, BedBase base) const {
|
|
if (recipe == RecipeId::BuildBed && staged_beds_) {
|
|
return {ItemAmount{base == BedBase::Stone ? ItemType::Stone : ItemType::Wood, 1},
|
|
ItemAmount{ItemType::Cloth, 2}};
|
|
}
|
|
return is_construction(recipe) ? recipe_for(recipe).ingredients : std::array<ItemAmount, 2>{};
|
|
}
|
|
|
|
RecipeId World::room_construction_recipe(RecipeId part) const noexcept {
|
|
if (scenario_active_) {
|
|
if (part == RecipeId::BuildDoorAlongX) return RecipeId::InstallDoorAlongX;
|
|
if (part == RecipeId::BuildDoorAlongY) return RecipeId::InstallDoorAlongY;
|
|
if (part == RecipeId::BuildMedicineCabinet) return RecipeId::InstallMedicineCabinet;
|
|
if (part == RecipeId::BuildMiningRack) return RecipeId::InstallMiningRack;
|
|
if (part == RecipeId::BuildLoom) return RecipeId::InstallLoom;
|
|
}
|
|
return part;
|
|
}
|
|
|
|
std::array<ItemAmount, 2> World::carpentry_materials(RecipeId recipe) const {
|
|
return is_carpentry_recipe(recipe) ? recipe_for(recipe).ingredients : std::array<ItemAmount, 2>{};
|
|
}
|
|
|
|
std::size_t World::missing_carpentry_orders(ItemType product, std::size_t new_installations,
|
|
StorageId excluded_storage) const {
|
|
const auto craft = recipe_for_carpentry_item(product);
|
|
std::uint64_t waiting_installations = new_installations, supply = 0;
|
|
for (const auto& order : production_orders_) {
|
|
if (order.recipe == craft && order.state != JobState::Completed) ++supply;
|
|
if (order.state == JobState::Available && is_construction(order.recipe) &&
|
|
recipe_for(order).ingredients.front().type == product) {
|
|
++waiting_installations;
|
|
}
|
|
}
|
|
for (const auto& agent : agents_) {
|
|
if (agent.state == AgentState::Hauling && agent.production_id == 0) {
|
|
supply += agent.inventory.item_count(product);
|
|
}
|
|
}
|
|
for (const auto& storage : storages_) {
|
|
if (storage.id == excluded_storage) continue;
|
|
const auto available = storage.available_item_count(product);
|
|
if (available != 0 && find_path(scenario_sawmill_, storage.position).reachable) supply += available;
|
|
}
|
|
return waiting_installations > supply ? static_cast<std::size_t>(waiting_installations - supply) : 0;
|
|
}
|
|
|
|
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);
|
|
if (!reserve_production(1 + cabin.ingredients[0].count + cabin.ingredients[1].count)) {
|
|
throw ProductionCapacityError{};
|
|
}
|
|
for (std::uint32_t i = 0; i < cabin.ingredients[0].count; ++i) {
|
|
queue_production(sawmill, RecipeId::SawPlank);
|
|
}
|
|
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, BedConstructionMode beds) {
|
|
if (scenario_active_ || !can_place_cabin(sawmill) ||
|
|
(beds != BedConstructionMode::Staged && beds != BedConstructionMode::Plank)) {
|
|
throw std::invalid_argument("scenario needs a free sawmill cell");
|
|
}
|
|
enable_hunger();
|
|
scenario_active_ = true;
|
|
staged_beds_ = beds == BedConstructionMode::Staged;
|
|
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;
|
|
if (is_finished_floor(order)) continue;
|
|
if (moving && is_room_part(order.recipe)) return CommandStatus::InvalidTarget;
|
|
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(),
|
|
[&storage](const auto& material) { return material.storage_id == storage.id; })) 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;
|
|
}
|
|
if (!moving && !resting_at(position) && std::any_of(production_orders_.begin(), production_orders_.end(),
|
|
[position](const auto& order) { return order.position == position && is_finished_floor(order); })) return 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 order = std::find_if(production_orders_.begin(), production_orders_.end(), [&](const auto& entry) {
|
|
return is_production_object(entry.recipe) && !is_finished_floor(entry) && at_position(entry);
|
|
});
|
|
if (order != production_orders_.end()) {
|
|
if (destination) order->position = *destination;
|
|
else {
|
|
production_orders_.erase(order);
|
|
}
|
|
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 {
|
|
std::array<std::size_t, std::size(carpentry_products)> replacements{};
|
|
std::size_t total = 0;
|
|
if (scenario_active_) {
|
|
for (std::size_t i = 0; i < replacements.size(); ++i) {
|
|
const auto product = carpentry_products[i];
|
|
if (storage->item_count(product) == 0) continue;
|
|
replacements[i] = missing_carpentry_orders(product, 0, storage->id);
|
|
total += replacements[i];
|
|
}
|
|
}
|
|
// Demand is evaluated against the post-removal inventory, without
|
|
// losing stock or issuing any order until the entire batch fits.
|
|
if (!reserve_production(total)) return CommandStatus::Busy;
|
|
auto balances = item_balances_;
|
|
for (const auto& stack : storage->items) {
|
|
auto& sink = balances[static_cast<std::size_t>(stack.type) - 1].demolition;
|
|
const auto amount = Void::Numeric::checked_add(sink, std::uint64_t{stack.count});
|
|
if (!amount) return CommandStatus::Busy;
|
|
sink = *amount;
|
|
}
|
|
item_balances_ = balances;
|
|
storages_.erase(storage);
|
|
for (std::size_t i = 0; i < replacements.size(); ++i) {
|
|
for (std::size_t j = 0; j < replacements[i]; ++j) {
|
|
queue_production(scenario_sawmill_, recipe_for_carpentry_item(carpentry_products[i]));
|
|
}
|
|
}
|
|
}
|
|
return CommandStatus::Accepted;
|
|
}
|
|
const auto source = std::find_if(resource_nodes_.begin(), resource_nodes_.end(), at_position);
|
|
if (source == resource_nodes_.end()) {
|
|
const auto floor = std::find_if(production_orders_.begin(), production_orders_.end(),
|
|
[&](const auto& entry) { return is_finished_floor(entry) && at_position(entry); });
|
|
if (floor == production_orders_.end() || destination) return CommandStatus::InvalidTarget;
|
|
production_orders_.erase(floor);
|
|
return CommandStatus::Accepted;
|
|
}
|
|
if (destination) source->position = *destination;
|
|
else {
|
|
resource_nodes_.erase(source);
|
|
}
|
|
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 ||
|
|
command.kind == CommandKind::PlaceRoom;
|
|
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 (!reserve_production(staged_beds_ ? 1 : 2)) return receipt(CommandStatus::Busy);
|
|
if (staged_beds_) {
|
|
queue_production(command.cell, RecipeId::BuildBed);
|
|
production_orders_.back().bed_base = static_cast<BedBase>(command.value);
|
|
production_orders_.back().bed_stage = BedStage::Foundation;
|
|
} else {
|
|
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);
|
|
}
|
|
const auto successor = Void::Numeric::checked_add(next_resource_node_id_, std::uint64_t{1});
|
|
if (!successor) return receipt(CommandStatus::Busy);
|
|
resource_nodes_.push_back({next_resource_node_id_, command.cell, site_resource(site), mine ? yield : 0,
|
|
yield, 0, true, site});
|
|
next_resource_node_id_ = *successor;
|
|
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);
|
|
}
|
|
if (scenario_active_) {
|
|
const auto missing = missing_carpentry_orders(ItemType::Loom, 1);
|
|
if (!reserve_production(1 + missing)) return receipt(CommandStatus::Busy);
|
|
queue_production(command.cell, RecipeId::InstallLoom);
|
|
for (std::size_t i = 0; i < missing; ++i) queue_production(scenario_sawmill_, RecipeId::CraftLoom);
|
|
} else {
|
|
if (!reserve_production(1)) return receipt(CommandStatus::Busy);
|
|
queue_production(command.cell, RecipeId::WeaveCloth);
|
|
}
|
|
break;
|
|
case CommandKind::CraftDoor:
|
|
if (!reserve_production(1)) return receipt(CommandStatus::Busy);
|
|
queue_production(scenario_sawmill_, RecipeId::CraftWoodenDoor);
|
|
break;
|
|
case CommandKind::CraftFurniture: {
|
|
const auto product = static_cast<ItemType>(command.value);
|
|
if (!is_carpentry_item(product) || product == ItemType::WoodenDoor) return receipt(CommandStatus::InvalidTarget);
|
|
if (!reserve_production(1)) return receipt(CommandStatus::Busy);
|
|
queue_production(scenario_sawmill_, recipe_for_carpentry_item(product));
|
|
break;
|
|
}
|
|
case CommandKind::PlaceRoom: {
|
|
const auto plan = RoomPlan::from_placement(command.cell, command.destination, command.value);
|
|
if (!can_place_room(plan) || !can_reach_object_cell(plan.first)) {
|
|
return receipt(CommandStatus::InvalidTarget);
|
|
}
|
|
const auto width = static_cast<std::size_t>(plan.last.x - plan.first.x + 1);
|
|
const auto height = static_cast<std::size_t>(plan.last.y - plan.first.y + 1);
|
|
const auto furnishings = plan.furnishings();
|
|
const bool legacy_bed = furnishings.has_value() && !staged_beds_;
|
|
const auto door_orders = scenario_active_ ? missing_carpentry_orders(ItemType::WoodenDoor, 1) : 0;
|
|
const auto fixture = furnishings ? room_construction_recipe(furnishings->back().recipe) : RecipeId::BuildFloor;
|
|
const auto fixture_item = furnishings ? recipe_for(fixture).ingredients.front().type : ItemType::None;
|
|
const auto fixture_orders = furnishings ? missing_carpentry_orders(fixture_item, 1) : 0;
|
|
if (!reserve_production(width * height + (furnishings ? furnishings->size() : 0) +
|
|
(legacy_bed ? 1U : 0U) + door_orders + fixture_orders)) return receipt(CommandStatus::Busy);
|
|
if (legacy_bed) queue_production(scenario_sawmill_, RecipeId::SawPlank);
|
|
if (furnishings) {
|
|
for (const auto& part : *furnishings) {
|
|
ProductionOrder order{};
|
|
order.position = part.position;
|
|
order.recipe = room_construction_recipe(part.recipe);
|
|
order.bed_base = part.bed_base;
|
|
if (order.recipe == RecipeId::BuildBed && staged_beds_) order.bed_stage = BedStage::Foundation;
|
|
append_production(std::move(order));
|
|
}
|
|
}
|
|
for (int y = plan.first.y; y <= plan.last.y; ++y) {
|
|
for (int x = plan.first.x; x <= plan.last.x; ++x) {
|
|
const GridPosition cell{x, y};
|
|
ProductionOrder order{};
|
|
order.position = cell;
|
|
order.recipe = room_construction_recipe(plan.recipe_at(cell));
|
|
append_production(std::move(order));
|
|
}
|
|
}
|
|
for (std::size_t i = 0; i < door_orders; ++i) queue_production(scenario_sawmill_, RecipeId::CraftWoodenDoor);
|
|
for (std::size_t i = 0; i < fixture_orders; ++i) {
|
|
queue_production(scenario_sawmill_, recipe_for_carpentry_item(fixture_item));
|
|
}
|
|
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);
|
|
}
|
|
if (!Void::Numeric::checked_add(next_storage_id_, std::uint64_t{1})) return receipt(CommandStatus::Busy);
|
|
static_cast<void>(add_storage(command.cell, 18, static_cast<StorageKind>(command.value)));
|
|
break;
|
|
case CommandKind::MoveObject:
|
|
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::Carpenter) || 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::vector<std::size_t>> choices;
|
|
choices.reserve(chunk_count);
|
|
if (execution_mode_ == ExecutionMode::SerialReference) {
|
|
choices.push_back(choose_jobs(0, agents_.size()));
|
|
} else {
|
|
std::vector<std::future<std::vector<std::size_t>>> choice_futures;
|
|
choice_futures.reserve(chunk_count);
|
|
const auto drain_choices = Void::Scope::on_exit([&choice_futures] {
|
|
for (auto& future : choice_futures) {
|
|
if (future.valid()) future.wait();
|
|
}
|
|
});
|
|
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);
|
|
}));
|
|
}
|
|
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;
|
|
const auto drain_paths = Void::Scope::on_exit([&futures] {
|
|
for (auto& future : futures) {
|
|
if (future.valid()) future.wait();
|
|
}
|
|
});
|
|
if (execution_mode_ == ExecutionMode::Parallel) {
|
|
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) {
|
|
const Request& request = requests[index];
|
|
auto path = execution_mode_ == ExecutionMode::SerialReference
|
|
? find_path(request.start, request.goal) : futures[index].get();
|
|
++path_searches_;
|
|
path_nodes_visited_ += path.nodes_visited;
|
|
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;
|
|
const auto profession = static_cast<std::size_t>(agent.profession);
|
|
if (profession >= available.size() || agent.state != AgentState::Idle || agent.current_job != 0 ||
|
|
!agent.inventory.empty()) continue;
|
|
|
|
const auto& candidates = available[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()) {
|
|
if (!admit_custody(agent, TransferKind::Tending, 0, node.id, 0, {})) break;
|
|
++resource_nodes_[node_index].reserved_workers;
|
|
--untended_sites;
|
|
agent.resource_node_id = node.id;
|
|
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;
|
|
}
|
|
|
|
Storage& storage = storages_[storage_index];
|
|
if (!admit_custody(agent, TransferKind::Harvest, 0, node.id, storage.id, {})) break;
|
|
++resource_nodes_[node_index].reserved_workers;
|
|
++storage.reserved_slots;
|
|
if (!has_space(storage)) {
|
|
if (storage.kind == StorageKind::Pantry) --open_pantry_count;
|
|
else --open_material_store_count;
|
|
}
|
|
agent.resource_node_id = node.id;
|
|
agent.storage_id = storage.id;
|
|
agent.haul_route = std::move(path_to_storage.positions);
|
|
agent.route = std::move(path_to_node.positions);
|
|
agent.route_cursor = 0;
|
|
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) || agent.profession == Profession::Carpenter);
|
|
})) return;
|
|
for (std::size_t index = 0; index < production_orders_.size(); ++index) {
|
|
ProductionOrder& order = production_orders_[index];
|
|
if (order.suspended || 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.position == order.position &&
|
|
(other.state == JobState::InProgress ||
|
|
(order.recipe != RecipeId::BuildFloor && other.recipe == RecipeId::BuildFloor &&
|
|
other.state != JobState::Completed));
|
|
});
|
|
if (site_busy) continue;
|
|
|
|
const Recipe recipe = recipe_for(order);
|
|
const bool carpentry = is_carpentry_recipe(order.recipe);
|
|
const bool deliver_ingredients = delivers_materials(order.recipe);
|
|
enum class Access { Unknown, Reachable, Unreachable };
|
|
std::vector<Access> storage_access(deliver_ingredients || weaving ? storages_.size() : 0, Access::Unknown);
|
|
std::vector<MaterialReservation> materials;
|
|
bool supplied = true;
|
|
for (const ItemAmount& 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.id, ingredient.type, count});
|
|
remaining -= count;
|
|
}
|
|
if (remaining != 0) {
|
|
supplied = false;
|
|
break;
|
|
}
|
|
}
|
|
if (!supplied) continue;
|
|
|
|
std::vector<ConstructionStop> stops;
|
|
if (deliver_ingredients) {
|
|
for (std::size_t s = 0; s < storage_access.size(); ++s) {
|
|
if (storage_access[s] == Access::Reachable) stops.push_back({storages_[s].id, {}});
|
|
}
|
|
for (std::size_t i = 0; i < stops.size(); ++i) {
|
|
const auto from = storage_by_id(stops[i].storage_id).position;
|
|
const auto to = i + 1 == stops.size()
|
|
? order.position : storage_by_id(stops[i + 1].storage_id).position;
|
|
auto path = assignment_path(from, to);
|
|
// Each stop can reach the site on the same undirected map.
|
|
assert(path.reachable);
|
|
stops[i].route_to_next = std::move(path.positions);
|
|
}
|
|
}
|
|
const GridPosition destination = deliver_ingredients
|
|
? storage_by_id(stops.front().storage_id).position : order.position;
|
|
for (Agent& agent : agents_) {
|
|
const bool can_craft = agent.profession == Profession::Carpenter;
|
|
const bool eligible = carpentry ? can_craft :
|
|
can_take_work(agent, Profession::Builder) || (can_craft && order.recipe == RecipeId::SawPlank);
|
|
if (agent.state != AgentState::Idle || !eligible) continue;
|
|
auto path = assignment_path(agent.position, destination);
|
|
if (!path.reachable) continue;
|
|
std::vector<GridPosition> haul_route;
|
|
if (carpentry) {
|
|
haul_route = assignment_path(order.position, storage_by_id(materials.front().storage_id).position).positions;
|
|
}
|
|
const auto output_storage = recipe.output == ItemType::None ? 0 : materials.front().storage_id;
|
|
if (!admit_custody(agent, TransferKind::Production, order.id, 0, output_storage, materials)) break;
|
|
if (carpentry) agent.haul_route = std::move(haul_route);
|
|
for (const auto& material : materials) {
|
|
stack_position(storage_by_id(material.storage_id), material.type)->reserved += material.count;
|
|
}
|
|
order.materials = std::move(materials);
|
|
order.delivery_stops = std::move(stops);
|
|
order.state = JobState::InProgress;
|
|
agent.production_id = order.id;
|
|
agent.route = std::move(path.positions);
|
|
agent.route_cursor = 0;
|
|
agent.work_remaining = recipe.ticks;
|
|
agent.state = deliver_ingredients ? AgentState::FetchingMaterials :
|
|
(agent.route.empty() ? AgentState::Working : AgentState::Travelling);
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
|
|
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;
|
|
|
|
const std::vector meal{MaterialReservation{storage.id, ItemType::Berries, 1}};
|
|
if (!admit_custody(agent, TransferKind::Meal, 0, 0, 0, meal)) break;
|
|
auto stack = stack_position(storage, ItemType::Berries);
|
|
++stack->reserved;
|
|
agent.storage_id = storage.id;
|
|
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;
|
|
const std::vector meal{MaterialReservation{agent.storage_id, ItemType::Berries, 1}};
|
|
if (!pickup_custody(agent, storage_by_id(agent.storage_id), meal, false)) {
|
|
if (agent.execution->blocked == CustodyStatus::Invalid) throw std::logic_error("invalid reserved meal pickup");
|
|
return;
|
|
}
|
|
agent.storage_id = 0;
|
|
agent.route.clear();
|
|
agent.route_cursor = 0;
|
|
agent.work_remaining = meal_ticks;
|
|
agent.state = AgentState::Eating;
|
|
return;
|
|
}
|
|
if (agent.work_remaining > 0) --agent.work_remaining;
|
|
if (agent.work_remaining != 0) return;
|
|
auto& sink = item_balances_[static_cast<std::size_t>(ItemType::Berries) - 1].meal;
|
|
const auto amount = Void::Numeric::checked_add(sink, std::uint64_t{1});
|
|
const auto meals = Void::Numeric::checked_add(meals_eaten_, std::uint64_t{1});
|
|
auto receipt = std::const_pointer_cast<CustodyReceipt>(prepare_custody(agent, CustodyOperation::Eat,
|
|
amount && meals ? CustodyStatus::Accepted : CustodyStatus::Overflow));
|
|
if (!receipt) return;
|
|
receipt->result.terminal = amount && meals;
|
|
receipt->result.effects[0] = {{OwnerKind::Resident, agent.id}, agent.inventory.stack_id(ItemType::Berries), ItemType::Berries,
|
|
amount && meals ? 0U : 1U};
|
|
receipt->result.effect_count = 1;
|
|
commit_custody(agent, receipt);
|
|
if (!amount || !meals) return;
|
|
sink = *amount;
|
|
agent.inventory.remove(ItemType::Berries);
|
|
finish_custody(agent);
|
|
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_by_id(agent.production_id);
|
|
if (order.collected_stops == order.delivery_stops.size()) {
|
|
if (!deliver_custody(agent, order.input, {OwnerKind::Production, order.id})) return;
|
|
order.delivery_stops.clear();
|
|
order.collected_stops = 0;
|
|
agent.state = AgentState::Working;
|
|
agent.route.clear();
|
|
agent.route_cursor = 0;
|
|
return;
|
|
}
|
|
|
|
if (order.collected_stops > order.delivery_stops.size() || order.materials.empty()) {
|
|
throw std::logic_error("invalid construction pickup stop");
|
|
}
|
|
auto& stop = order.delivery_stops[order.collected_stops];
|
|
const bool reserve_output = is_carpentry_recipe(order.recipe) &&
|
|
stop.storage_id == order.materials.front().storage_id;
|
|
if (!pickup_custody(agent, storage_by_id(stop.storage_id), order.materials, reserve_output)) {
|
|
if (agent.execution->blocked == CustodyStatus::Invalid) throw std::logic_error("invalid reserved construction pickup");
|
|
return;
|
|
}
|
|
++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_by_id(agent.production_id);
|
|
const Recipe recipe = recipe_for(order);
|
|
auto balances = item_balances_;
|
|
auto input = order.input;
|
|
auto inventory = agent.inventory;
|
|
auto next = next_stack_id_;
|
|
std::vector<Storage> stores;
|
|
const bool delivered = delivers_materials(order.recipe);
|
|
const bool carpentry = is_carpentry_recipe(order.recipe);
|
|
auto status = CustodyStatus::Accepted;
|
|
for (const auto& material : order.materials) {
|
|
auto& balance = balances[static_cast<std::size_t>(material.type) - 1];
|
|
auto& sink = recipe.output == ItemType::None ? balance.installation : balance.recipe_input;
|
|
const auto amount = Void::Numeric::checked_add(sink, std::uint64_t{material.count});
|
|
if (!amount) { status = CustodyStatus::Overflow; break; }
|
|
sink = *amount;
|
|
if (delivered) {
|
|
if (input.item_count(material.type) < material.count) { status = CustodyStatus::Invalid; break; }
|
|
input.remove(material.type, material.count);
|
|
} else {
|
|
auto store = std::find_if(stores.begin(), stores.end(), [&](const auto& s) { return s.id == material.storage_id; });
|
|
if (store == stores.end()) { stores.push_back(storage_by_id(material.storage_id)); store = std::prev(stores.end()); }
|
|
const auto stack = stack_position(*store, material.type);
|
|
if (stack == store->items.end() || stack->type != material.type || stack->reserved < material.count || stack->count < material.count) {
|
|
status = CustodyStatus::Invalid; break;
|
|
}
|
|
stack->count -= material.count;
|
|
stack->reserved -= material.count;
|
|
if (stack->count == 0) store->items.erase(stack);
|
|
}
|
|
}
|
|
StackId output_id = 0;
|
|
if (status == CustodyStatus::Accepted && recipe.output != ItemType::None) {
|
|
auto& balance = balances[static_cast<std::size_t>(recipe.output) - 1].recipe_output;
|
|
const auto amount = Void::Numeric::checked_add(balance, std::uint64_t{1});
|
|
if (!amount) status = CustodyStatus::Overflow;
|
|
else balance = *amount;
|
|
if (carpentry) {
|
|
if (next == 0 || next == std::numeric_limits<StackId>::max()) status = CustodyStatus::Exhausted;
|
|
else { output_id = next++; inventory.add(recipe.output); inventory.set_stack_id(recipe.output, output_id); }
|
|
} else {
|
|
auto& store = stores.front();
|
|
auto stack = stack_position(store, recipe.output);
|
|
if (stack != store.items.end() && stack->type == recipe.output) { ++stack->count; output_id = stack->id; }
|
|
else if (next == 0 || next == std::numeric_limits<StackId>::max()) status = CustodyStatus::Exhausted;
|
|
else { output_id = next++; store.items.insert(stack, {recipe.output, 1, 0, output_id}); }
|
|
}
|
|
}
|
|
auto receipt = std::const_pointer_cast<CustodyReceipt>(prepare_custody(agent, CustodyOperation::Complete, status));
|
|
if (!receipt) return;
|
|
if (status == CustodyStatus::Accepted) {
|
|
receipt->result.terminal = !carpentry;
|
|
for (const auto& material : order.materials) {
|
|
const auto& original_store = storage_by_id(material.storage_id);
|
|
StackId consumed_id = 0;
|
|
std::uint32_t remaining = 0;
|
|
StockOwner owner{OwnerKind::Production, order.id};
|
|
if (delivered) { consumed_id = order.input.stack_id(material.type); remaining = input.item_count(material.type); }
|
|
else {
|
|
owner = {OwnerKind::Storage, material.storage_id};
|
|
for (const auto& stack : original_store.items) if (stack.type == material.type) consumed_id = stack.id;
|
|
for (const auto& store : stores) if (store.id == material.storage_id) remaining = store.item_count(material.type);
|
|
}
|
|
// Several source lines can have merged into one physical site stack.
|
|
// Record its final outcome once, retaining the first material order.
|
|
const auto end = receipt->result.effects.begin() + receipt->result.effect_count;
|
|
const bool recorded = std::any_of(receipt->result.effects.begin(), end, [&](const auto& effect) {
|
|
return effect.owner == owner && effect.stack == consumed_id && effect.item == material.type;
|
|
});
|
|
if (!recorded) receipt->result.effects[receipt->result.effect_count++] = {owner, consumed_id, material.type, remaining};
|
|
}
|
|
if (output_id) {
|
|
receipt->result.effects[receipt->result.effect_count++] = {carpentry ? StockOwner{OwnerKind::Resident, agent.id} :
|
|
StockOwner{OwnerKind::Storage, stores.front().id}, output_id, recipe.output,
|
|
carpentry ? inventory.item_count(recipe.output) : stores.front().item_count(recipe.output)};
|
|
}
|
|
}
|
|
commit_custody(agent, receipt);
|
|
if (status != CustodyStatus::Accepted) return;
|
|
for (auto& store : stores) storage_by_id(store.id).items.swap(store.items);
|
|
item_balances_ = balances;
|
|
next_stack_id_ = next;
|
|
order.input = input;
|
|
agent.inventory = inventory;
|
|
for (auto& claim : agent.execution->reservations) if (claim.kind != ReservationKind::Capacity) claim = {};
|
|
if (carpentry) {
|
|
agent.storage_id = order.materials.front().storage_id;
|
|
agent.route = std::move(agent.haul_route);
|
|
agent.haul_route.clear();
|
|
agent.route_cursor = 0;
|
|
agent.production_id = 0;
|
|
agent.execution->production = 0;
|
|
agent.state = AgentState::Hauling;
|
|
order.materials.clear();
|
|
order.state = JobState::Completed;
|
|
return;
|
|
}
|
|
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 (furnishing_shape(order.recipe) == RecipeId::BuildLoom) {
|
|
order.recipe = RecipeId::WeaveCloth;
|
|
order.state = JobState::Available;
|
|
} else if (order.recipe == RecipeId::WeaveCloth) {
|
|
order.state = JobState::Available;
|
|
} else order.state = JobState::Completed;
|
|
agent.production_id = 0;
|
|
agent.state = AgentState::Idle;
|
|
agent.route.clear();
|
|
agent.route_cursor = 0;
|
|
finish_custody(agent);
|
|
}
|
|
|
|
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 (execution_mode_ == ExecutionMode::Parallel && !worker_pool_ && !agents_.empty()) {
|
|
worker_pool_ = std::make_unique<WorkerPool>(worker_count_, worker_options_);
|
|
}
|
|
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.state == AgentState::Returning) &&
|
|
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_id == 0
|
|
? 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_id != 0) 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 (execution_mode_ == ExecutionMode::SerialReference) {
|
|
jobs_completed_ += advance_agents(0, agents_.size());
|
|
} else 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);
|
|
const auto drain_advancement = Void::Scope::on_exit([&futures] {
|
|
for (auto& future : futures) {
|
|
if (future.valid()) future.wait();
|
|
}
|
|
});
|
|
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::Returning) { advance_return(agent); continue; }
|
|
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_id != 0 && agent.route_cursor == agent.route.size() &&
|
|
(agent.state == AgentState::FetchingMaterials || agent.state == AgentState::Hauling)) {
|
|
advance_construction_delivery(agent);
|
|
continue;
|
|
}
|
|
if (agent.state == AgentState::Working && agent.production_id != 0 &&
|
|
agent.work_remaining == 0) {
|
|
finish_production(agent);
|
|
}
|
|
if (agent.state == AgentState::Gathering) {
|
|
if (agent.work_remaining == 0 && agent.resource_node_id != 0) {
|
|
ResourceNode& node = resource_node_by_id(agent.resource_node_id);
|
|
if (agent.storage_id == 0) {
|
|
const auto growth = Void::Numeric::checked_add(tick_, growing_time(node.site));
|
|
auto receipt = std::const_pointer_cast<CustodyReceipt>(prepare_custody(agent, CustodyOperation::Tend, growth ? CustodyStatus::Accepted : CustodyStatus::Overflow, node.id));
|
|
if (!receipt) continue;
|
|
receipt->result.terminal = growth.has_value();
|
|
commit_custody(agent, receipt);
|
|
if (!growth) continue;
|
|
node.growth_at = *growth;
|
|
finish_custody(agent);
|
|
--node.reserved_workers;
|
|
agent.resource_node_id = 0;
|
|
agent.state = AgentState::Idle;
|
|
agent.route.clear();
|
|
agent.route_cursor = 0;
|
|
continue;
|
|
}
|
|
auto& balance = item_balances_[static_cast<std::size_t>(node.type) - 1].harvest;
|
|
const auto amount = Void::Numeric::checked_add(balance, std::uint64_t{1});
|
|
const auto next = Void::Numeric::checked_add(next_stack_id_, std::uint64_t{1});
|
|
auto receipt = std::const_pointer_cast<CustodyReceipt>(prepare_custody(agent, CustodyOperation::Harvest,
|
|
!next ? CustodyStatus::Exhausted : !amount ? CustodyStatus::Overflow : CustodyStatus::Accepted, node.id));
|
|
if (!receipt) continue;
|
|
if (next && amount) {
|
|
receipt->result.effects[0] = {{OwnerKind::Resident, agent.id}, next_stack_id_, node.type, 1};
|
|
receipt->result.effect_count = 1;
|
|
}
|
|
commit_custody(agent, receipt);
|
|
if (!next || !amount) continue;
|
|
--node.quantity;
|
|
--node.reserved_workers;
|
|
balance = *amount;
|
|
agent.inventory.add(node.type);
|
|
agent.inventory.set_stack_id(node.type, next_stack_id_);
|
|
next_stack_id_ = *next;
|
|
for (auto& claim : agent.execution->reservations) if (claim.kind == ReservationKind::Harvest) claim = {};
|
|
agent.execution->source = 0;
|
|
agent.resource_node_id = 0;
|
|
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_id != 0) {
|
|
Storage& storage = storage_by_id(agent.storage_id);
|
|
const ItemType cargo = agent.inventory.first_item();
|
|
if (!deposit_custody(agent, storage, cargo, 1)) continue;
|
|
finish_custody(agent);
|
|
agent.storage_id = 0;
|
|
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
|