diff --git a/CMakeLists.txt b/CMakeLists.txt index 6e6f933..dae9f5f 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -39,6 +39,7 @@ endif() find_package(Threads REQUIRED) add_library(settlement_core + engine/src/custody.cpp engine/src/checkpoint.cpp engine/src/checkpoint_files.cpp engine/src/colony_profile.cpp @@ -121,6 +122,7 @@ if(BUILD_TESTING) add_executable(settlement_core_tests tests/checkpoint_tests.cpp tests/checkpoint_file_tests.cpp + tests/custody_tests.cpp tests/core_tests.cpp tests/executor_tests.cpp tests/identity_tests.cpp diff --git a/engine/src/custody.cpp b/engine/src/custody.cpp new file mode 100644 index 0000000..8662c9b --- /dev/null +++ b/engine/src/custody.cpp @@ -0,0 +1,606 @@ +#include "settlement/core/world.hpp" +#include "settlement/core/inventory_transaction.hpp" +#include +#include +#include +#include +#include + +namespace settlement { +namespace { +constexpr auto maximum = std::numeric_limits::max(); +bool room(std::uint64_t next, std::uint64_t count) noexcept { + return next != 0 && count <= maximum - next; +} +auto stock(Storage& storage, ItemType item) { + return std::find_if(storage.items.begin(), storage.items.end(), [item](const auto& s) { return s.type == item; }); +} +void retarget(TransferExecution& execution, StockOwner from, StackId old_id, + StockOwner to, StackId new_id) noexcept { + for (auto& claim : execution.reservations) { + if (claim.id && claim.kind == ReservationKind::Item && claim.owner == from && claim.stack == old_id) { + claim.owner = to; + claim.stack = new_id; + } + } +} +CustodyRequest operation_request(const Agent& agent, CustodyOperation operation, + StorageId source, StorageId destination) { + CustodyRequest request; + request.key = {CustodyKeyKind::Operation, agent.execution->id, agent.execution->next_operation}; + request.operation = operation; + request.kind = agent.execution->kind; + request.production = agent.execution->production; + request.source = source; + request.destination = destination; + return request; +} +void effects(CustodyResult& result, const Inventory& inventory, StockOwner owner) { + for (std::size_t i = 1; i <= item_type_count; ++i) { + const auto item = static_cast(i); + if (inventory.item_count(item)) result.effects[result.effect_count++] = + {owner, inventory.stack_id(item), item, inventory.item_count(item)}; + } +} +} + +StackId Inventory::stack_id(ItemType type) const noexcept { + const auto i = static_cast(type); + return i > 0 && i <= stack_ids_.size() ? stack_ids_[i - 1] : 0; +} +void Inventory::set_stack_id(ItemType type, StackId id) noexcept { + const auto i = static_cast(type); + if (i > 0 && i <= stack_ids_.size()) stack_ids_[i - 1] = id; +} + +void World::record_custody(std::shared_ptr receipt) noexcept { + if (custody_receipts_.size() < custody_receipt_limit) custody_receipts_.push_back(std::move(receipt)); + else { + custody_receipts_[custody_receipt_cursor_] = std::move(receipt); + custody_receipt_cursor_ = (custody_receipt_cursor_ + 1) % custody_receipt_limit; + } +} +std::shared_ptr World::prepare_custody(Agent& agent, CustodyOperation operation, + CustodyStatus status, StorageId source, StorageId destination) { + if (!agent.execution || !room(agent.execution->next_operation, 1)) return {}; + custody_receipts_.reserve(custody_receipt_limit); + auto receipt = std::make_shared(); + receipt->request = operation_request(agent, operation, source, destination); + receipt->result.status = status; + receipt->result.transfer = agent.execution->id; + return receipt; +} +void World::commit_custody(Agent& agent, std::shared_ptr receipt) noexcept { + agent.execution->blocked = receipt->result.status; + ++agent.execution->next_operation; + record_custody(std::move(receipt)); +} +CustodyResult World::custody_request(const CustodyRequest& request) { + // The scheduler issues operations. This endpoint recovers their exact result; + // it never admits unissued work through an out-of-order retry. + for (const auto& receipt : custody_receipts_) { + if (receipt->request.key == request.key) { + return receipt->request == request ? receipt->result : CustodyResult{CustodyStatus::Conflict}; + } + } + if (request.key.id == 0 || request.key.ordinal == 0) return {CustodyStatus::Invalid}; + if (request.key.kind == CustodyKeyKind::Admission) { + const auto actor = std::find_if(agents_.begin(), agents_.end(), [&](const auto& a) { return a.id == request.key.id; }); + if (actor == agents_.end()) return {CustodyStatus::Invalid}; + return {request.key.ordinal < actor->next_admission ? CustodyStatus::Stale : CustodyStatus::Future}; + } + if (request.key.kind != CustodyKeyKind::Operation) return {CustodyStatus::Invalid}; + for (const auto& agent : agents_) { + if (agent.execution && agent.execution->id == request.key.id) { + return {request.key.ordinal < agent.execution->next_operation ? CustodyStatus::Stale : CustodyStatus::Future}; + } + } + return {request.key.id < next_transfer_id_ ? CustodyStatus::Stale : CustodyStatus::Future}; +} + +bool World::admit_custody(Agent& agent, TransferKind kind, ProductionId production, + ResourceNodeId source, StorageId destination, const std::vector& materials) { + if (agent.execution || !room(next_transfer_id_, 1) || !room(agent.next_admission, 1) || + materials.size() > custody_material_limit) return false; + TransferExecution execution; + execution.id = next_transfer_id_; + execution.kind = kind; + execution.production = production; + execution.source = source; + execution.destination = destination; + auto next = next_reservation_id_; + const auto add = [&](Reservation claim) { + if (!room(next, 1) || execution.reservation_count == custody_reservation_limit) return false; + claim.id = next++; + execution.reservations[execution.reservation_count++] = claim; + return true; + }; + CustodyRequest request; + request.key = {CustodyKeyKind::Admission, agent.id, agent.next_admission}; + request.kind = kind; + request.production = production; + request.source = source; + request.destination = destination; + for (const auto& material : materials) { + auto& store = storage_by_id(material.storage_id); + const auto stack = stock(store, material.type); + if (material.count == 0 || stack == store.items.end() || stack->id == 0 || + stack->reserved > stack->count || material.count > stack->count - stack->reserved) return false; + if (!add({0, ReservationKind::Item, {OwnerKind::Storage, store.id}, stack->id, + material.type, material.count, 0, store.id})) return false; + request.lines[request.line_count++] = {store.id, material.type, material.count}; + } + if (production && !add({0, ReservationKind::Worksite, {OwnerKind::Production, production}, 0, {}, 1})) return false; + if (source && !add({0, kind == TransferKind::Tending ? ReservationKind::Tending : ReservationKind::Harvest, + {}, 0, {}, 1})) return false; + if (destination) { + auto& store = storage_by_id(destination); + ReservationId backing = 0; + if (production) { + // Every production output replaces claimed input in this exact store. + for (const auto& claim : execution.reservations) { + if (claim.id && claim.kind == ReservationKind::Item && claim.origin_storage == destination) { + backing = claim.id; + break; + } + } + } + if (!backing && store.total_items() + store.reserved_slots >= store.capacity) return false; + if (!add({0, ReservationKind::Capacity, {OwnerKind::Storage, destination}, 0, {}, 1, backing})) return false; + } + custody_receipts_.reserve(custody_receipt_limit); + auto receipt = std::make_shared(); + receipt->request = request; + receipt->result = {CustodyStatus::Accepted, execution.id}; + receipt->result.reservation_count = execution.reservation_count; + for (std::size_t i = 0; i < execution.reservation_count; ++i) receipt->result.reservations[i] = execution.reservations[i].id; + // The caller has already allocated routes and material vectors. No operation + // below can throw; its existing cache increments follow immediately. + agent.execution = execution; + ++agent.next_admission; + ++next_transfer_id_; + next_reservation_id_ = next; + record_custody(std::move(receipt)); + return true; +} + +bool World::pickup_custody(Agent& agent, Storage& source, + const std::vector& materials, bool reserve_output) { + Storage planned_source = source; + Inventory planned_inventory = agent.inventory; + auto execution = *agent.execution; + auto next = next_stack_id_; + custody_receipts_.reserve(custody_receipt_limit); + auto receipt = std::make_shared(); + receipt->request = operation_request(agent, CustodyOperation::Pickup, source.id, 0); + receipt->result = {CustodyStatus::Accepted, execution.id}; + const auto fail = [&](CustodyStatus status) { + receipt->result.status = status; + commit_custody(agent, receipt); + return false; + }; + if (!room(execution.next_operation, 1)) return false; + if (!withdraw_reserved_materials(planned_source, planned_inventory, materials, reserve_output)) return fail(CustodyStatus::Invalid); + for (const auto& stack : source.items) { + const auto remaining = planned_source.item_count(stack.type); + if (remaining == stack.count) continue; + auto id = agent.inventory.stack_id(stack.type); + if (!id) { + if (remaining) { + if (!room(next, 1)) return fail(CustodyStatus::Exhausted); + id = next++; + } else id = stack.id; + } + if (!id) return fail(CustodyStatus::Invalid); + planned_inventory.set_stack_id(stack.type, id); + retarget(execution, {OwnerKind::Storage, source.id}, stack.id, {OwnerKind::Resident, agent.id}, id); + if (execution.kind == TransferKind::Meal) for (auto& claim : execution.reservations) { + if (claim.kind == ReservationKind::Item) claim.origin_storage = 0; + } + } + if (reserve_output) { + for (auto& claim : execution.reservations) { + if (claim.id && claim.kind == ReservationKind::Capacity && claim.owner.id == source.id) claim.backing = 0; + } + } + effects(receipt->result, planned_inventory, {OwnerKind::Resident, agent.id}); + source.items.swap(planned_source.items); + source.reserved_slots = planned_source.reserved_slots; + agent.inventory = planned_inventory; + agent.execution = execution; + next_stack_id_ = next; + commit_custody(agent, receipt); + return true; +} + +bool World::deliver_custody(Agent& agent, Inventory& destination, StockOwner owner) { + auto planned = destination; + auto execution = *agent.execution; + custody_receipts_.reserve(custody_receipt_limit); + auto receipt = std::make_shared(); + receipt->request = operation_request(agent, CustodyOperation::Deliver, 0, 0); + receipt->result = {CustodyStatus::Accepted, execution.id}; + if (!room(execution.next_operation, 1)) return false; + for (std::size_t i = 1; i <= item_type_count; ++i) { + const auto type = static_cast(i); + const auto count = agent.inventory.item_count(type); + if (!count) continue; + if (!Void::Numeric::checked_add(planned.item_count(type), count)) { + receipt->result.status = CustodyStatus::Overflow; + commit_custody(agent, receipt); + return false; + } + auto id = planned.stack_id(type); + if (!id) id = agent.inventory.stack_id(type); + planned.add(type, count); + planned.set_stack_id(type, id); + retarget(execution, {OwnerKind::Resident, agent.id}, agent.inventory.stack_id(type), owner, id); + } + effects(receipt->result, planned, owner); + destination = planned; + agent.inventory = {}; + agent.execution = execution; + commit_custody(agent, receipt); + return true; +} + +bool World::deposit_custody(Agent& agent, Storage& destination, ItemType type, std::uint32_t count) { + if (!count || count > agent.inventory.item_count(type) || !destination.accepts(type)) return false; + auto planned = destination; + auto inventory = agent.inventory; + auto next = next_stack_id_; + auto execution = *agent.execution; + custody_receipts_.reserve(custody_receipt_limit); + auto receipt = std::make_shared(); + receipt->request = operation_request(agent, execution.kind == TransferKind::Return ? CustodyOperation::Return : CustodyOperation::Deliver, 0, destination.id); + receipt->request.lines[0] = {destination.id, type, count}; + receipt->request.line_count = 1; + receipt->result = {CustodyStatus::Accepted, execution.id}; + if (!room(execution.next_operation, 1)) return false; + auto slots = planned.reserved_slots; + for (auto& claim : execution.reservations) { + if (claim.id && claim.kind == ReservationKind::Capacity && claim.owner.id == destination.id && !claim.backing) { + if (slots < claim.count) return false; + slots -= claim.count; + claim = {}; + } + } + if (planned.total_items() + slots + count > planned.capacity) return false; + auto target = stock(planned, type); + StackId id = 0; + if (target != planned.items.end()) { + const auto amount = Void::Numeric::checked_add(target->count, count); + if (!amount) return false; + target->count = *amount; + id = target->id; + } else { + id = inventory.stack_id(type); + if (count < inventory.item_count(type)) { + if (!room(next, 1)) return false; + id = next++; + } + planned.items.push_back({type, count, 0, id}); + std::sort(planned.items.begin(), planned.items.end(), [](const auto& a, const auto& b) { return a.type < b.type; }); + } + inventory.remove(type, count); + receipt->result.effects[0] = {{OwnerKind::Storage, destination.id}, id, type, planned.item_count(type)}; + receipt->result.effect_count = 1; + receipt->result.terminal = inventory.empty(); + for (auto& claim : execution.reservations) { + if (claim.id && claim.kind == ReservationKind::Item && claim.owner == StockOwner{OwnerKind::Resident, agent.id} && claim.item == type) { + if (claim.count <= count) claim = {}; + else claim.count -= count; + } + } + destination.items.swap(planned.items); + destination.reserved_slots = slots; + agent.inventory = inventory; + agent.execution = execution; + next_stack_id_ = next; + commit_custody(agent, receipt); + return true; +} + +void World::finish_custody(Agent& agent) noexcept { agent.execution.reset(); } + +bool World::legacy_representable() const noexcept { + for (const auto& order : production_orders_) if (order.suspended) return false; + for (const auto& agent : agents_) { + if (agent.state == AgentState::Returning || (agent.execution && agent.execution->kind == TransferKind::Return && agent.state != AgentState::Hauling)) return false; + if ((agent.state == AgentState::Working || agent.state == AgentState::Gathering || agent.state == AgentState::Eating) && agent.work_remaining == 0) return false; + if (agent.production_id == 0 && !agent.inventory.empty()) { + const auto type = agent.inventory.first_item(); + if (agent.state == AgentState::Eating) { + if (type != ItemType::Berries || agent.inventory.item_count(type) != 1) return false; + } else if (agent.state != AgentState::Hauling || agent.storage_id == 0 || + type == ItemType::Plank || type == ItemType::StoneBlock || type == ItemType::Cloth || + agent.inventory.item_count(type) != 1) return false; + for (std::size_t i = 1; i <= item_type_count; ++i) { + if (static_cast(i) != type && agent.inventory.item_count(static_cast(i))) return false; + } + } + } + return true; +} + +CommandStatus World::cancel_production(ProductionId id) { + auto it = std::find_if(production_orders_.begin(), production_orders_.end(), [id](const auto& p) { return p.id == id; }); + if (it == production_orders_.end()) return CommandStatus::InvalidTarget; + if (it->state == JobState::Completed || it->suspended) return CommandStatus::Busy; + auto actor = std::find_if(agents_.begin(), agents_.end(), [id](const auto& a) { return a.production_id == id; }); + const bool retain = it->recipe == RecipeId::WeaveCloth || + (it->recipe == RecipeId::BuildBed && (it->bed_stage == BedStage::Bedding || it->bed_stage == BedStage::Pillow)); + if (actor != agents_.end()) { + if (!actor->execution) return CommandStatus::Busy; + auto inventory = actor->inventory; + for (std::size_t i = 1; i <= item_type_count; ++i) { + const auto item = static_cast(i); + const auto count = it->input.item_count(item); + if (!Void::Numeric::checked_add(inventory.item_count(item), count)) return CommandStatus::Busy; + if (count) { + if (!inventory.stack_id(item)) inventory.set_stack_id(item, it->input.stack_id(item)); + inventory.add(item, count); + } + } + auto receipt = std::const_pointer_cast(prepare_custody(*actor, CustodyOperation::Cancel)); + if (!receipt) return CommandStatus::Busy; + effects(receipt->result, inventory, {OwnerKind::Resident, actor->id}); + receipt->result.terminal = inventory.empty(); + for (auto& claim : actor->execution->reservations) { + if (!claim.id) continue; + if (claim.kind == ReservationKind::Item && claim.owner.kind == OwnerKind::Storage) { + auto& store = storage_by_id(claim.owner.id); + stock(store, claim.item)->reserved -= claim.count; + } else if (claim.kind == ReservationKind::Capacity && !claim.backing) { + storage_by_id(claim.owner.id).reserved_slots -= claim.count; + } + claim = {}; + } + actor->execution->reservation_count = 0; + actor->execution->kind = TransferKind::Return; + actor->execution->production = 0; + actor->execution->source = 0; + actor->execution->destination = 0; + actor->inventory = inventory; + actor->production_id = 0; + actor->storage_id = 0; + actor->work_remaining = 0; + actor->route.clear(); + actor->route_cursor = 0; + actor->haul_route.clear(); + actor->state = inventory.empty() ? AgentState::Idle : AgentState::Returning; + commit_custody(*actor, receipt); + if (inventory.empty()) finish_custody(*actor); + } + if (retain) { + it->input = {}; + it->materials.clear(); + it->delivery_stops.clear(); + it->collected_stops = 0; + it->state = JobState::Available; + it->suspended = true; + } else production_orders_.erase(it); + return CommandStatus::Accepted; +} +CommandStatus World::resume_production(ProductionId id) { + auto it = std::find_if(production_orders_.begin(), production_orders_.end(), [id](const auto& p) { return p.id == id; }); + if (it == production_orders_.end()) return CommandStatus::InvalidTarget; + if (!it->suspended || it->state != JobState::Available) return CommandStatus::Busy; + it->suspended = false; + return CommandStatus::Accepted; +} +void World::advance_return(Agent& agent) { + if (agent.route_cursor < agent.route.size()) return; + agent.route.clear(); + agent.route_cursor = 0; + const auto type = agent.inventory.first_item(); + if (type == ItemType::None) { agent.state = AgentState::Idle; finish_custody(agent); return; } + for (auto& store : storages_) { + if (!store.accepts(type) || store.total_items() + store.reserved_slots >= store.capacity) continue; + auto path = assignment_path(agent.position, store.position); + if (!path.reachable) continue; + if (!path.positions.empty()) { + agent.route = std::move(path.positions); + agent.execution->blocked = CustodyStatus::Accepted; + return; + } + const auto free = store.capacity - store.total_items() - store.reserved_slots; + const auto count = static_cast(std::min(free, agent.inventory.item_count(type))); + if (!deposit_custody(agent, store, type, count)) return; + if (agent.inventory.empty()) { agent.state = AgentState::Idle; finish_custody(agent); } + return; + } + agent.execution->blocked = CustodyStatus::NoDestination; +} + +void World::validate_custody() const { + const auto require = [](bool condition) { if (!condition) throw std::runtime_error("inconsistent custody state"); }; + require(next_stack_id_ && next_reservation_id_ && next_transfer_id_); + struct Physical { StockOwner owner; ItemType item; std::uint32_t count; std::uint64_t claimed = 0; }; + std::unordered_map physical; + std::unordered_map> reserved; + std::unordered_map slots; + std::unordered_map workers; + std::array live{}; + const auto add = [&](StockOwner owner, ItemType item, std::uint32_t count, StackId id) { + require((count == 0) == (id == 0)); + if (!count) return; + require(item > ItemType::None && item <= ItemType::Loom && id < next_stack_id_); + require(physical.emplace(id, Physical{owner, item, count}).second); + auto& total = live[static_cast(item) - 1]; + const auto amount = Void::Numeric::checked_add(total, std::uint64_t{count}); + require(amount.has_value()); total = *amount; + }; + const auto add_inventory = [&](const Inventory& inventory, StockOwner owner) { + for (std::size_t i = 1; i <= item_type_count; ++i) { + const auto item = static_cast(i); + add(owner, item, inventory.item_count(item), inventory.stack_id(item)); + } + }; + for (const auto& store : storages_) { + auto previous = ItemType::None; + for (const auto& stack : store.items) { + require(stack.type > previous && stack.count && store.accepts(stack.type) && stack.reserved <= stack.count); + previous = stack.type; + add({OwnerKind::Storage, store.id}, stack.type, stack.count, stack.id); + } + require(store.total_items() + store.reserved_slots <= store.capacity); + } + for (const auto& actor : agents_) add_inventory(actor.inventory, {OwnerKind::Resident, actor.id}); + for (const auto& order : production_orders_) add_inventory(order.input, {OwnerKind::Production, order.id}); + std::unordered_map actors; + std::unordered_map producers; + for (const auto& actor : agents_) { + require(actors.emplace(actor.id, &actor).second); + if (actor.production_id) require(producers.emplace(actor.production_id, &actor).second); + } + std::set transfers; + std::set reservation_ids; + std::set work_sites; + std::set backed; + for (const auto& actor : agents_) { + require(actor.next_admission != 0 && actor.route_cursor <= actor.route.size()); + if (!actor.execution) { + require(actor.inventory.empty() && actor.production_id == 0 && actor.resource_node_id == 0 && + actor.state != AgentState::Returning && actor.state != AgentState::Hauling && + actor.state != AgentState::Eating && actor.state != AgentState::GoingToEat); + continue; + } + const auto& execution = *actor.execution; + require(execution.id && execution.id < next_transfer_id_ && transfers.insert(execution.id).second && + execution.kind <= TransferKind::Return && execution.next_operation && actor.next_admission >= 2 && + execution.reservation_count <= custody_reservation_limit && execution.blocked <= CustodyStatus::NoDestination); + require(execution.production == actor.production_id && execution.source == actor.resource_node_id); + if (execution.kind == TransferKind::Return) { + require(!actor.inventory.empty() && !actor.production_id && !actor.resource_node_id && actor.work_remaining == 0); + require((actor.state == AgentState::Returning && !actor.storage_id) || + (actor.state == AgentState::Hauling && actor.storage_id && find_storage(actor.storage_id) && + execution.destination == actor.storage_id)); + } else if (execution.kind == TransferKind::Meal) { + require(actor.state == AgentState::GoingToEat || actor.state == AgentState::Eating); + require(execution.production == 0 && execution.source == 0 && execution.destination == 0); + } else if (execution.kind == TransferKind::Harvest || execution.kind == TransferKind::Tending) { + require(actor.state == AgentState::Travelling || actor.state == AgentState::Gathering || actor.state == AgentState::Hauling); + require(execution.production == 0 && (execution.kind != TransferKind::Tending || actor.storage_id == 0)); + } else { + require(actor.state == AgentState::Travelling || actor.state == AgentState::Working || + actor.state == AgentState::FetchingMaterials || actor.state == AgentState::Hauling); + if (execution.production) require(find_production(execution.production) != nullptr); + else require(actor.state == AgentState::Hauling && is_carpentry_item(actor.inventory.first_item())); + } + for (std::size_t index = 0; index < custody_reservation_limit; ++index) { + const auto& claim = execution.reservations[index]; + if (claim.id == 0) { require(claim == Reservation{}); continue; } + require(index < execution.reservation_count && claim.id < next_reservation_id_ && + reservation_ids.insert(claim.id).second && claim.kind <= ReservationKind::Tending && claim.count); + if (claim.kind == ReservationKind::Item) { + auto entry = physical.find(claim.stack); + require(entry != physical.end() && entry->second.owner == claim.owner && entry->second.item == claim.item); + require(!claim.backing); + if (claim.origin_storage) require(find_storage(claim.origin_storage) != nullptr); + else require(claim.owner.kind == OwnerKind::Resident && + (execution.kind == TransferKind::Meal || (execution.kind == TransferKind::Return && actor.state == AgentState::Hauling))); + require(claim.owner.kind != OwnerKind::Resident || claim.owner.id == actor.id); + require(claim.owner.kind != OwnerKind::Production || claim.owner.id == actor.production_id); + auto& amount = entry->second.claimed; + require(claim.count <= entry->second.count - amount); + amount += claim.count; + if (claim.owner.kind == OwnerKind::Storage) { + require(claim.owner.id == claim.origin_storage); + reserved[claim.owner.id][static_cast(claim.item) - 1] += claim.count; + } + } else if (claim.kind == ReservationKind::Capacity) { + require(claim.owner.kind == OwnerKind::Storage && claim.owner.id == execution.destination && + find_storage(claim.owner.id) && !claim.stack && claim.item == ItemType::None && !claim.origin_storage && claim.count == 1); + if (claim.backing) { + const auto input = std::find_if(execution.reservations.begin(), execution.reservations.end(), + [&](const auto& c) { return c.id == claim.backing; }); + require(input != execution.reservations.end() && input->kind == ReservationKind::Item && + input->owner == claim.owner && input->count >= claim.count && backed.insert(claim.backing).second); + } else slots[claim.owner.id] += claim.count; + } else if (claim.kind == ReservationKind::Worksite) { + require(claim.owner == StockOwner{OwnerKind::Production, execution.production} && execution.production && + !claim.stack && claim.item == ItemType::None && claim.count == 1 && !claim.backing && !claim.origin_storage); + require(work_sites.insert(execution.production).second); + } else { + require(claim.owner == StockOwner{} && !claim.stack && claim.item == ItemType::None && + claim.count == 1 && !claim.backing && !claim.origin_storage && execution.source && find_resource_node(execution.source)); + workers[execution.source] += claim.count; + } + } + } + for (const auto& store : storages_) { + require(slots[store.id] == store.reserved_slots); + for (const auto& stack : store.items) require(reserved[store.id][static_cast(stack.type) - 1] == stack.reserved); + } + for (const auto& node : resource_nodes_) require(workers[node.id] == node.reserved_workers); + for (const auto& order : production_orders_) { + require(order.state <= JobState::Completed); + if (order.state == JobState::InProgress) { + require(!order.suspended && work_sites.contains(order.id) && !order.materials.empty()); + const auto found_actor = producers.find(order.id); + require(found_actor != producers.end()); + const auto actor = found_actor->second; + if (delivers_materials(order.recipe) && actor->state == AgentState::Working) { + std::array expected{}; + for (const auto& line : order.materials) { + require(line.type > ItemType::None && line.type <= ItemType::Loom && line.count); + const auto i = static_cast(line.type) - 1; + const auto amount = Void::Numeric::checked_add(expected[i], line.count); + require(amount.has_value()); expected[i] = *amount; + } + for (std::size_t i = 0; i < item_type_count; ++i) require(order.input.item_count(static_cast(i + 1)) == expected[i]); + require(actor->inventory.empty()); + } else require(order.input.empty()); + } else require(order.input.empty() && order.materials.empty() && order.delivery_stops.empty()); + if (order.suspended) require(order.state == JobState::Available && + (order.recipe == RecipeId::WeaveCloth || (order.recipe == RecipeId::BuildBed && + (order.bed_stage == BedStage::Bedding || order.bed_stage == BedStage::Pillow)))); + } + for (std::size_t i = 0; i < item_type_count; ++i) { + const auto& b = item_balances_[i]; + std::uint64_t in = 0, out = live[i]; + for (const auto value : {b.opening, b.grant, b.harvest, b.recipe_output}) { + const auto amount = Void::Numeric::checked_add(in, value); require(amount.has_value()); in = *amount; + } + for (const auto value : {b.recipe_input, b.meal, b.installation, b.demolition}) { + const auto amount = Void::Numeric::checked_add(out, value); require(amount.has_value()); out = *amount; + } + require(in == out); + } + require(custody_receipts_.size() <= custody_receipt_limit && + (custody_receipts_.size() == custody_receipt_limit ? custody_receipt_cursor_ < custody_receipt_limit : custody_receipt_cursor_ == 0)); + std::set> keys; + for (const auto& receipt : custody_receipts_) { + require(static_cast(receipt)); + const auto& request = receipt->request; + const auto& result = receipt->result; + require(request.key.kind <= CustodyKeyKind::Operation && request.key.id && request.key.ordinal && + request.kind <= TransferKind::Return && request.operation <= CustodyOperation::Tend && + request.line_count <= custody_material_limit && request.production < next_production_id_ && + request.destination < next_storage_id_ && keys.emplace(request.key.kind, request.key.id, request.key.ordinal).second); + if (request.key.kind == CustodyKeyKind::Admission) { + require(request.key.id < next_agent_id_ && request.operation == CustodyOperation::Admit); + const auto actor = actors.find(request.key.id); + if (actor != actors.end()) require(request.key.ordinal < actor->second->next_admission); + } else require(request.key.id < next_transfer_id_ && request.operation != CustodyOperation::Admit); + for (std::size_t i = 0; i < custody_material_limit; ++i) { + const auto& line = request.lines[i]; + if (i >= request.line_count) require(line == CustodyLine{}); + else require(line.storage && line.storage < next_storage_id_ && line.item > ItemType::None && line.item <= ItemType::Loom && line.count); + } + require(result.status <= CustodyStatus::NoDestination && result.transfer && result.transfer < next_transfer_id_ && + result.reservation_count <= custody_reservation_limit && result.effect_count <= item_type_count); + for (std::size_t i = 0; i < custody_reservation_limit; ++i) require(i < result.reservation_count ? + result.reservations[i] > 0 && result.reservations[i] < next_reservation_id_ : result.reservations[i] == 0); + for (std::size_t i = 0; i < item_type_count; ++i) { + const auto& effect = result.effects[i]; + if (i >= result.effect_count) { require(effect == CustodyEffect{}); continue; } + require(effect.stack && effect.stack < next_stack_id_ && effect.item > ItemType::None && effect.item <= ItemType::Loom && effect.owner.id); + if (effect.owner.kind == OwnerKind::Storage) require(effect.owner.id < next_storage_id_); + else if (effect.owner.kind == OwnerKind::Resident) require(effect.owner.id < next_agent_id_); + else { require(effect.owner.kind == OwnerKind::Production); require(effect.owner.id < next_production_id_); } + } + } +} +} // namespace settlement diff --git a/engine/src/world.cpp b/engine/src/world.cpp index 9b3d106..221d60b 100644 --- a/engine/src/world.cpp +++ b/engine/src/world.cpp @@ -58,33 +58,33 @@ std::uint16_t initial_hunger(AgentId id) { } struct Recipe { - std::array ingredients; + std::array ingredients; ItemType output; std::uint32_t ticks; }; const Recipe& recipe_for(RecipeId id) { - static constexpr Recipe saw{{ItemStack{ItemType::Wood, 1}, {}}, ItemType::Plank, 12}; - static constexpr Recipe cut{{ItemStack{ItemType::Stone, 1}, {}}, ItemType::StoneBlock, 16}; - static constexpr Recipe cabin{{ItemStack{ItemType::Plank, 3}, ItemStack{ItemType::StoneBlock, 2}}, + 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{{ItemStack{ItemType::Plank, 1}, {}}, ItemType::None, 14}; - static constexpr Recipe weave{{ItemStack{ItemType::Flax, 1}, {}}, ItemType::Cloth, 12}; - static constexpr Recipe floor{{ItemStack{ItemType::Wood, 1}, {}}, ItemType::None, 6}; - static constexpr Recipe wall{{ItemStack{ItemType::Wood, 1}, {}}, ItemType::None, 9}; - static constexpr Recipe door{{ItemStack{ItemType::Wood, 2}, {}}, ItemType::None, 12}; - static constexpr Recipe cabinet{{ItemStack{ItemType::Wood, 1}, {}}, ItemType::None, 10}; - static constexpr Recipe mining_rack{{ItemStack{ItemType::Wood, 1}, ItemStack{ItemType::Stone, 1}}, + 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{{ItemStack{ItemType::Wood, 2}, {}}, ItemType::None, 12}; - static constexpr Recipe install_door{{ItemStack{ItemType::WoodenDoor, 1}, {}}, ItemType::None, 8}; - static constexpr Recipe craft_door{{ItemStack{ItemType::Wood, 2}, {}}, ItemType::WoodenDoor, 14}; + 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{{ItemStack{ItemType::MedicineCabinet, 1}, {}}, ItemType::None, 8}; - static constexpr Recipe install_rack{{ItemStack{ItemType::MiningRack, 1}, {}}, ItemType::None, 8}; - static constexpr Recipe install_loom{{ItemStack{ItemType::Loom, 1}, {}}, ItemType::None, 8}; + 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; @@ -276,6 +276,7 @@ void Inventory::remove(ItemType type, std::uint32_t count) noexcept { const auto index = static_cast(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 { @@ -497,8 +498,20 @@ void World::stock_storage(std::uint64_t id, ItemType type, std::uint32_t count) } if (count == 0) return; auto stack = stack_position(*storage, type); - if (stack != storage->items.end() && stack->type == type) stack->count += count; - else storage->items.insert(stack, ItemStack{type, count}); + auto& balance = item_balances_[static_cast(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 { @@ -565,12 +578,12 @@ bool World::can_place_room(const RoomPlan& plan) const noexcept { }); } -std::array World::construction_materials(RecipeId recipe, BedBase base) const { +std::array World::construction_materials(RecipeId recipe, BedBase base) const { if (recipe == RecipeId::BuildBed && staged_beds_) { - return {ItemStack{base == BedBase::Stone ? ItemType::Stone : ItemType::Wood, 1}, - ItemStack{ItemType::Cloth, 2}}; + return {ItemAmount{base == BedBase::Stone ? ItemType::Stone : ItemType::Wood, 1}, + ItemAmount{ItemType::Cloth, 2}}; } - return is_construction(recipe) ? recipe_for(recipe).ingredients : std::array{}; + return is_construction(recipe) ? recipe_for(recipe).ingredients : std::array{}; } RecipeId World::room_construction_recipe(RecipeId part) const noexcept { @@ -584,8 +597,8 @@ RecipeId World::room_construction_recipe(RecipeId part) const noexcept { return part; } -std::array World::carpentry_materials(RecipeId recipe) const { - return is_carpentry_recipe(recipe) ? recipe_for(recipe).ingredients : std::array{}; +std::array World::carpentry_materials(RecipeId recipe) const { + return is_carpentry_recipe(recipe) ? recipe_for(recipe).ingredients : std::array{}; } std::size_t World::missing_carpentry_orders(ItemType product, std::size_t new_installations, @@ -746,6 +759,14 @@ CommandStatus World::edit_object(GridPosition position, const GridPosition* dest // 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(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) { @@ -1305,6 +1326,7 @@ void World::assign_resource_tasks(ResourceFocus focus) { } 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; @@ -1341,8 +1363,9 @@ void World::assign_resource_tasks(ResourceFocus focus) { continue; } - ++resource_nodes_[node_index].reserved_workers; 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; @@ -1369,7 +1392,7 @@ void World::assign_production_tasks(bool weaving) { })) return; for (std::size_t index = 0; index < production_orders_.size(); ++index) { ProductionOrder& order = production_orders_[index]; - if (order.state != JobState::Available || (order.recipe == RecipeId::WeaveCloth) != weaving) continue; + 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) { @@ -1387,7 +1410,7 @@ void World::assign_production_tasks(bool weaving) { std::vector storage_access(deliver_ingredients || weaving ? storages_.size() : 0, Access::Unknown); std::vector materials; bool supplied = true; - for (const ItemStack& ingredient : recipe.ingredients) { + 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) { @@ -1438,10 +1461,13 @@ void World::assign_production_tasks(bool weaving) { if (agent.state != AgentState::Idle || !eligible) continue; auto path = assignment_path(agent.position, destination); if (!path.reachable) continue; + std::vector haul_route; if (carpentry) { - agent.haul_route = assignment_path(order.position, storage_by_id(materials.front().storage_id).position).positions; + 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; } @@ -1459,19 +1485,6 @@ void World::assign_production_tasks(bool weaving) { } } -namespace { - -void take_reserved_material(Storage& storage, const MaterialReservation& material) { - auto stack = stack_position(storage, material.type); - assert(stack != storage.items.end() && stack->type == material.type); - assert(stack->reserved >= material.count && stack->count >= stack->reserved); - stack->reserved -= material.count; - stack->count -= material.count; - if (stack->count == 0) storage.items.erase(stack); -} - -} // namespace - void World::assign_meals() { for (Agent& agent : agents_) { if (agent.hunger < max_hunger) ++agent.hunger; @@ -1497,6 +1510,8 @@ void World::assign_meals() { 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; @@ -1512,9 +1527,10 @@ void World::assign_meals() { void World::finish_meal_step(Agent& agent) { if (agent.state == AgentState::GoingToEat) { if (agent.route_cursor != agent.route.size()) return; - const std::array meal{MaterialReservation{agent.storage_id, ItemType::Berries, 1}}; - if (!withdraw_reserved_materials(storage_by_id(agent.storage_id), agent.inventory, meal)) { - throw std::logic_error("invalid reserved meal pickup"); + 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(); @@ -1523,8 +1539,19 @@ void World::finish_meal_step(Agent& agent) { agent.state = AgentState::Eating; return; } - if (--agent.work_remaining != 0) return; + if (agent.work_remaining > 0) --agent.work_remaining; + if (agent.work_remaining != 0) return; + auto& sink = item_balances_[static_cast(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 = prepare_custody(agent, CustodyOperation::Eat, + amount && meals ? CustodyStatus::Accepted : CustodyStatus::Overflow); + if (!receipt) return; + 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_; @@ -1585,9 +1612,7 @@ void World::finish_rest_step(Agent& agent) { void World::advance_construction_delivery(Agent& agent) { ProductionOrder& order = production_by_id(agent.production_id); if (order.collected_stops == order.delivery_stops.size()) { - for (const auto& material : order.materials) { - agent.inventory.remove(material.type, material.count); - } + if (!deliver_custody(agent, order.input, {OwnerKind::Production, order.id})) return; order.delivery_stops.clear(); order.collected_stops = 0; agent.state = AgentState::Working; @@ -1602,8 +1627,9 @@ void World::advance_construction_delivery(Agent& agent) { 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 (!withdraw_reserved_materials(storage_by_id(stop.storage_id), agent.inventory, order.materials, reserve_output)) { - throw std::logic_error("invalid reserved construction pickup"); + 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); @@ -1614,26 +1640,83 @@ void World::advance_construction_delivery(Agent& agent) { void World::finish_production(Agent& agent) { ProductionOrder& order = production_by_id(agent.production_id); const Recipe recipe = recipe_for(order); - assert(!order.materials.empty()); - if (is_carpentry_recipe(order.recipe)) { - agent.inventory.add(recipe.output); + auto balances = item_balances_; + auto input = order.input; + auto inventory = agent.inventory; + auto next = next_stack_id_; + std::vector 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(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(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::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::max()) status = CustodyStatus::Exhausted; + else { output_id = next++; store.items.insert(stack, {recipe.output, 1, 0, output_id}); } + } + } + auto receipt = std::const_pointer_cast(prepare_custody(agent, CustodyOperation::Complete, status)); + if (!receipt) return; + if (status == CustodyStatus::Accepted) { + receipt->result.terminal = !carpentry; + if (output_id) { + receipt->result.effects[0] = {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)}; + receipt->result.effect_count = 1; + } + } + 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; } - if (recipe.output != ItemType::None) { - for (const auto& material : order.materials) { - take_reserved_material(storage_by_id(material.storage_id), material); - } - // Crafting replaces one raw item with one finished item in the same store. - storage_by_id(order.materials.front().storage_id).add_item(recipe.output); - } order.materials.clear(); if (order.recipe == RecipeId::BuildBed && (order.bed_stage == BedStage::Foundation || order.bed_stage == BedStage::Bedding)) { @@ -1644,13 +1727,12 @@ void World::finish_production(Agent& agent) { order.state = JobState::Available; } else if (order.recipe == RecipeId::WeaveCloth) { order.state = JobState::Available; - } else { - order.state = JobState::Completed; - } + } 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() { @@ -1707,7 +1789,7 @@ void World::step(TickProfile* profile) { 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::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()) { @@ -1762,6 +1844,7 @@ void World::step(TickProfile* profile) { } 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; @@ -1783,7 +1866,13 @@ void World::step(TickProfile* profile) { 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) { - node.growth_at = tick_ + growing_time(node.site); + const auto growth = Void::Numeric::checked_add(tick_, growing_time(node.site)); + auto receipt = prepare_custody(agent, CustodyOperation::Tend, growth ? CustodyStatus::Accepted : CustodyStatus::Overflow); + if (!receipt) continue; + 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; @@ -1791,9 +1880,26 @@ void World::step(TickProfile* profile) { agent.route_cursor = 0; continue; } - if (node.quantity > 0) --node.quantity; - if (node.reserved_workers > 0) --node.reserved_workers; + auto& balance = item_balances_[static_cast(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(prepare_custody(agent, CustodyOperation::Harvest, + !next ? CustodyStatus::Exhausted : !amount ? CustodyStatus::Overflow : CustodyStatus::Accepted)); + 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(); @@ -1806,9 +1912,8 @@ void World::step(TickProfile* profile) { agent.storage_id != 0) { Storage& storage = storage_by_id(agent.storage_id); const ItemType cargo = agent.inventory.first_item(); - if (storage.reserved_slots > 0) --storage.reserved_slots; - storage.add_item(cargo); - agent.inventory.remove(cargo); + if (!deposit_custody(agent, storage, cargo, 1)) continue; + finish_custody(agent); agent.storage_id = 0; agent.state = AgentState::Idle; agent.route.clear(); diff --git a/tests/custody_tests.cpp b/tests/custody_tests.cpp new file mode 100644 index 0000000..b0f0d75 --- /dev/null +++ b/tests/custody_tests.cpp @@ -0,0 +1,187 @@ +#include "settlement/core/world.hpp" +#include +#include +#include +#include +#include +#include +#include + +namespace { +using namespace settlement; +using Void::Testing::Test; +void require(bool ok, const char* message) { if (!ok) throw std::runtime_error(message); } +void ticks(World& world, int count) { for (int i = 0; i < count; ++i) { world.step(); world.validate_custody(); } } +std::unique_ptr cabin(std::uint32_t stock = 3) { + auto w = std::make_unique(7, 32, 32, 1, ExecutionMode::SerialReference); + auto storage = w->add_storage({3, 3}, 50); + w->stock_storage(storage, ItemType::Plank, stock); + w->stock_storage(storage, ItemType::StoneBlock, 2); + (void)w->spawn_agent({1, 3}); + w->queue_production({16, 3}, RecipeId::BuildCabin); + return w; +} +struct [[= Void::Testing::name("CustodyTests")]] CustodyTests : Void::Testing::Suite { + [[= Void::Testing::tag("custody")]] Test ownership_delivery_and_consumption(); + [[= Void::Testing::tag("custody")]] Test cancel_site_returns_all_types(); + [[= Void::Testing::tag("custody")]] Test split_merge_and_snapshot(); + [[= Void::Testing::tag("custody")]] Test exact_receipt_and_conflict(); + [[= Void::Testing::tag("custody")]] Test original_colony_continuous_balance(); + [[= Void::Testing::tag("custody")]] Test five_sources(); + [[= Void::Testing::tag("custody")]] Test blocked_return_retains_every_item(); + [[= Void::Testing::tag("custody")]] Test suspended_bed_and_loom_resume(); + [[= Void::Testing::tag("custody")]] Test admission_exhaustion_and_receipt_eviction(); + [[= Void::Testing::tag("custody")]] Test recipes_meals_and_harvest_balance(); + [[= Void::Testing::tag("custody-metrics")]] Test snapshot_metrics(); +}; +Test CustodyTests::ownership_delivery_and_consumption() { + auto w = cabin(); + const auto plank = w->storages()[0].items[0].id; + ticks(*w, 2); + require(w->agents()[0].inventory.stack_id(ItemType::Plank) == plank, "whole pickup changed ID"); + for (int i = 0; i < 20 && w->agents()[0].state != AgentState::Working; ++i) ticks(*w, 1); + require(w->production_orders()[0].input.stack_id(ItemType::Plank) == plank, "site lost ID"); + require(w->production_orders()[0].input.item_count(ItemType::Plank) == 3, "site lost physical count"); + ticks(*w, 40); + require(w->production_orders()[0].state == JobState::Completed, "construction incomplete"); + require(w->item_balances()[2].installation == 3, "installation sink missing"); +} +Test CustodyTests::cancel_site_returns_all_types() { + auto w = cabin(); + ticks(*w, 16); + require(w->cancel_production(w->production_orders()[0].id) == CommandStatus::Accepted, "cancel refused"); + w->validate_custody(); + require(w->agents()[0].state == AgentState::Returning && !w->legacy_representable(), "cancel phase lost"); + ticks(*w, 40); + require(w->agents()[0].inventory.empty() && w->storages()[0].item_count(ItemType::Plank) == 3 && + w->storages()[0].item_count(ItemType::StoneBlock) == 2, "return lost cargo"); +} +Test CustodyTests::split_merge_and_snapshot() { + auto w = cabin(5); + const auto original = w->storages()[0].items[0].id; + auto snapshot = w->capture(); + ticks(*w, 2); + require(w->storages()[0].items[0].id == original && w->agents()[0].inventory.stack_id(ItemType::Plank) != original, "split identity wrong"); + require(snapshot->storages()[0].item_count(ItemType::Plank) == 5 && snapshot->custody_receipts().empty(), "snapshot mutated"); + require(w->cancel_production(w->production_orders()[0].id) == CommandStatus::Accepted, "cancel refused"); + ticks(*w, 10); + require(w->storages()[0].items[0].id == original && w->storages()[0].item_count(ItemType::Plank) == 5, "merge identity wrong"); +} +Test CustodyTests::exact_receipt_and_conflict() { + auto w = cabin(); ticks(*w, 1); + auto receipt = *w->custody_receipts().front(); + require(w->custody_request(receipt.request) == receipt.result, "exact retry differed"); + ++receipt.request.destination; + require(w->custody_request(receipt.request).status == CustodyStatus::Conflict, "changed retry accepted"); + receipt.request.key.ordinal += 100; + require(w->custody_request(receipt.request).status == CustodyStatus::Future, "future retry accepted"); + ticks(*w, 60); +} +Test CustodyTests::original_colony_continuous_balance() { + auto w = make_first_colony(1, BedConstructionMode::Staged, ExecutionMode::SerialReference); + w->validate_custody(); + ticks(*w, 1000); +} +Test CustodyTests::five_sources() { + auto w = std::make_unique(7, 32, 32, 1, ExecutionMode::SerialReference); + for (int i = 0; i < 5; ++i) { + const auto store = w->add_storage({3 + i, 3}, 10); + w->stock_storage(store, i < 3 ? ItemType::Plank : ItemType::StoneBlock, 1); + } + (void)w->spawn_agent({1, 3}); w->queue_production({16, 3}, RecipeId::BuildCabin); + ticks(*w, 1); + require(w->custody_receipts()[0]->request.line_count == 5, "admission omitted sources"); + ticks(*w, 80); + require(w->production_orders()[0].state == JobState::Completed, "five-source cabin incomplete"); +} + +Test CustodyTests::blocked_return_retains_every_item() { + auto w = cabin(); ticks(*w, 16); + require(w->cancel_production(w->production_orders()[0].id) == CommandStatus::Accepted, "cancel refused"); + auto& store = const_cast(w->storages()[0]); store.capacity = 1; + ticks(*w, 40); + require(w->agents()[0].state == AgentState::Returning && w->agents()[0].execution && + w->agents()[0].execution->blocked == CustodyStatus::NoDestination, "blocked return lost execution"); + require(w->agents()[0].inventory.item_count(ItemType::Plank) == 2 && + w->agents()[0].inventory.item_count(ItemType::StoneBlock) == 2, "partial return lost items"); + auto id = w->add_storage({4, 3}, 20); + ticks(*w, 20); + require(w->agents()[0].inventory.empty() && w->find_storage(id)->total_items() == 4, "unblocked return incomplete"); +} +Test CustodyTests::suspended_bed_and_loom_resume() { + World w(9, 20, 20, 1, ExecutionMode::SerialReference); + const auto store = w.add_storage({2, 2}, 30); + w.stock_storage(store, ItemType::Wood, 4); w.stock_storage(store, ItemType::Cloth, 2); + const auto actor = w.spawn_agent({2, 2}); (void)actor; w.start_scenario({8, 8}); + require(w.apply_command({1, 1, CommandKind::PlaceBed, {4, 2}}).status == CommandStatus::Accepted, "bed placement refused"); + const auto id = w.production_orders()[0].id; + for (int i = 0; i < 80 && w.find_production(id)->bed_stage == BedStage::Foundation; ++i) ticks(w, 1); + require(w.find_production(id)->bed_stage == BedStage::Bedding, "bed foundation absent"); + require(w.cancel_production(id) == CommandStatus::Accepted && w.find_production(id)->suspended, "partial bed not suspended"); + ticks(w, 20); require(!w.legacy_representable(), "suspended bed projected"); + require(w.resume_production(id) == CommandStatus::Accepted, "resume refused"); + ticks(w, 100); require(w.find_production(id)->state == JobState::Completed, "bed resumed wrong stage"); + require(w.item_balances()[0].installation == 1 && w.item_balances()[5].installation == 2, "bed installed twice"); + require(w.cancel_production(id) == CommandStatus::Busy, "completed bed canceled"); + w.queue_production({6, 2}, RecipeId::WeaveCloth); const auto loom = w.production_orders().back().id; + require(w.cancel_production(loom) == CommandStatus::Accepted && w.find_production(loom)->suspended, "loom not retained"); + w.stock_storage(store, ItemType::Flax, 1); + require(w.resume_production(loom) == CommandStatus::Accepted, "loom resume refused"); + ticks(w, 60); require(w.find_storage(store)->item_count(ItemType::Cloth) == 1, "loom failed after resume"); +} +Test CustodyTests::admission_exhaustion_and_receipt_eviction() { + auto w = cabin(); + auto& actor = const_cast(w->agents()[0]); actor.next_admission = std::numeric_limits::max(); + ticks(*w, 2); + require(!actor.execution && w->custody_receipts().empty() && w->storages()[0].items[0].reserved == 0, "exhausted admission mutated stock"); + World loom(1, 16, 16, 1, ExecutionMode::SerialReference); + const auto store = loom.add_storage({2, 2}, 4000); loom.stock_storage(store, ItemType::Flax, 3000); + (void)loom.spawn_agent({3, 2}); loom.queue_production({3, 2}, RecipeId::WeaveCloth); + loom.step(); auto first = *loom.custody_receipts()[0]; auto snapshot = loom.capture(); + for (int i = 0; i < 26000; ++i) loom.step(); + loom.validate_custody(); + require(loom.custody_receipts().size() == custody_receipt_limit && + loom.custody_request(first.request).status == CustodyStatus::Stale, "evicted admission not stale"); + require(snapshot->custody_receipts()[0]->request == first.request && snapshot->custody_receipts()[0]->result == first.result, + "retained snapshot receipt mutated"); + for (const auto& receipt : loom.custody_receipts()) require(loom.custody_request(receipt->request) == receipt->result, "retained replay differed"); +} +Test CustodyTests::recipes_meals_and_harvest_balance() { + World w(1, 20, 20, 1, ExecutionMode::SerialReference); + const auto store = w.add_storage({2, 2}, 100); + const auto pantry = w.add_storage({2, 3}, 20, StorageKind::Pantry); + w.stock_storage(store, ItemType::Wood, 10); w.stock_storage(store, ItemType::Stone, 3); + w.stock_storage(pantry, ItemType::Berries, 4); + (void)w.spawn_agent({2, 2}); (void)w.add_resource_node({3, 3}, ItemType::Wood, 5); + w.queue_production({4, 2}, RecipeId::SawPlank); w.queue_production({5, 2}, RecipeId::CutStoneBlock); + w.enable_hunger(); ticks(w, 300); + require(w.meals_eaten() > 0 && w.item_balances()[0].harvest == 5 && w.item_balances()[0].recipe_input == 1 && + w.item_balances()[2].recipe_output == 1 && w.item_balances()[3].recipe_output == 1, "recipe/source/sink path omitted"); +} +Test CustodyTests::snapshot_metrics() { + for (bool full : {false, true}) { + World w(1, 512, 512, 1, ExecutionMode::SerialReference); + if (full) { + auto store = w.add_storage({1, 1}, 4000); w.stock_storage(store, ItemType::Flax, 3000); + (void)w.spawn_agent({2, 1}); w.queue_production({2, 1}, RecipeId::WeaveCloth); + for (int i = 0; i < 26000; ++i) w.step(); + } + while (w.agents().size() < 500) (void)w.spawn_agent({1, 1}); + for (int i = 0; i < 1000; ++i) { + auto store = w.add_storage({i % 500, i / 500 + 5}, 1000); + for (std::size_t j = 1; j <= item_type_count; ++j) if (static_cast(j) != ItemType::Berries) + w.stock_storage(store, static_cast(j), 1); + } + while (w.production_orders().size() < 2000) w.queue_production({3, 3}, RecipeId::SawPlank); + w.validate_custody(); + std::vector samples; + for (int i = 0; i < 101; ++i) { + const auto begin = std::chrono::steady_clock::now(); auto snapshot = w.capture(); + samples.push_back(std::chrono::duration(std::chrono::steady_clock::now() - begin).count()); + } + std::sort(samples.begin(), samples.end()); std::ostringstream bytes; w.write_save(bytes); + std::cout << "custody metrics residents=500 stacks=" << (full ? 10002 : 10000) << " orders=2000 receipts=" << w.custody_receipts().size() + << " capture_ms_p50=" << samples[50] << " p95=" << samples[95] << " raw13_bytes=" << bytes.str().size() << '\n'; + } +} +}