diff --git a/tests/core_tests.cpp b/tests/core_tests.cpp new file mode 100644 index 0000000..e5e13ba --- /dev/null +++ b/tests/core_tests.cpp @@ -0,0 +1,756 @@ +#include "settlement/core/deterministic_rng.hpp" +#include "settlement/core/world.hpp" + +#include +#include +#include +#include + +namespace { + +void require(bool condition, const char* message) { + if (!condition) { + throw std::runtime_error(message); + } +} + +std::string save_contents(const settlement::World& world) { + std::ostringstream file(std::ios::binary); + world.write_save(file); + return file.str(); +} + +std::unique_ptr save_roundtrip(const settlement::World& world) { + const auto bytes = save_contents(world); + std::istringstream file(bytes, std::ios::binary); + auto restored = settlement::World::read_save(file, world.worker_count()); + require(restored->worker_count() == world.worker_count(), "loading did not use the requested worker count"); + require(save_contents(*restored) == bytes, + "roundtrip changed the saved state"); + return restored; +} + +void test_parallel_pathfinding_completes_the_jobs() { + settlement::World world(123, 48, 48, 6); + for (std::int32_t y = 0; y < 48; ++y) { + if (y != 31) world.set_blocked({24, y}); + } + for (std::int32_t index = 0; index < 24; ++index) { + static_cast(world.spawn_agent({2 + index % 6, 2 + index / 6})); + static_cast(world.add_job({38 + index % 8, 4 + index * 3 % 40}, + static_cast(5 + index % 7))); + } + for (int tick = 0; tick < 120; ++tick) world.step(); + require(world.jobs_completed() == 24, "parallel pathfinding did not finish every job"); +} + +void test_single_worker_configuration_is_rejected() { + try { + settlement::World world(8, 8, 8, 1); + } catch (const std::invalid_argument&) { + return; + } + throw std::runtime_error("world accepted a single worker"); +} + +void test_rng_repeats_for_same_seed() { + settlement::DeterministicRng left(12345); + settlement::DeterministicRng right(12345); + for (int index = 0; index < 1000; ++index) { + require(left.next_u64() == right.next_u64(), "RNG diverged for matching seeds"); + } +} + +void test_work_jobs_complete() { + settlement::World world(1, 10, 10); + const settlement::AgentId agent_id = world.spawn_agent({1, 1}); + const settlement::JobId job_id = world.add_job({3, 1}, 2); + + world.step(); + require(world.agents().front().state == settlement::AgentState::Travelling, + "agent did not start travelling to assigned work"); + require(world.agents().front().current_job == job_id, + "agent did not claim the available job"); + + world.step(); + world.step(); + + require(world.agents().front().id == agent_id, "agent id changed during work"); + require(world.jobs_completed() == 1, "work job did not complete after its duration"); + require(world.jobs().front().state == settlement::JobState::Completed, + "completed job retained an active state"); + require(world.agents().front().state == settlement::AgentState::Idle, + "worker did not return to idle after completing a job"); +} + +void test_astar_route_uses_opening_in_wall() { + settlement::World world(2, 10, 10); + for (std::int32_t y = 0; y < 10; ++y) { + if (y != 8) { + world.set_blocked({4, y}); + } + } + static_cast(world.spawn_agent({1, 1})); + static_cast(world.add_job({8, 1}, 100)); + world.step(); + + const settlement::Agent& agent = world.agents().front(); + require(agent.state == settlement::AgentState::Travelling, + "agent did not receive a route through the map"); + require(agent.route.size() > 7, "pathfinder ignored the wall detour"); + for (const settlement::GridPosition position : agent.route) { + require(world.is_walkable(position), "A* route crossed a blocked map cell"); + } + require(world.path_searches() > 0, "path search counter was not updated"); + require(world.path_nodes_visited() > 0, "A* did not report expanded nodes"); +} + +void test_residents_gather_and_deliver_resources() { + settlement::World world(51, 16, 16, 4); + static_cast(world.add_storage({1, 1}, 10)); + static_cast(world.spawn_agent({1, 2})); + static_cast(world.add_resource_node({4, 1}, settlement::ItemType::Wood, 2)); + static_cast(world.add_resource_node({4, 4}, settlement::ItemType::Stone, 1)); + + for (int tick = 0; tick < 80; ++tick) world.step(); + + require(world.storages().front().item_count(settlement::ItemType::Wood) == 2, + "resident did not deliver both units of wood to storage"); + require(world.storages().front().item_count(settlement::ItemType::Stone) == 1, + "resident did not deliver stone to storage"); + require(world.storages().front().items.size() == 2, + "storage did not merge matching resources into item stacks"); + require(world.storages().front().total_items() == 3, + "storage inventory total does not match its item stacks"); + require(world.storages().front().reserved_slots == 0, + "storage retained reservations after deliveries completed"); + require(world.resource_nodes()[0].quantity == 0 && world.resource_nodes()[1].quantity == 0, + "resource nodes retained units after deliveries completed"); +} + +void test_production_reservations_and_construction() { + using settlement::ItemType; + using settlement::JobState; + using settlement::RecipeId; + + settlement::World world(19, 12, 12, 8); + static_cast(world.add_storage({1, 1}, 3)); + static_cast(world.add_storage({9, 1}, 2)); + static_cast(world.add_resource_node({2, 1}, ItemType::Wood, 3)); + static_cast(world.add_resource_node({8, 1}, ItemType::Stone, 2)); + for (int i = 0; i < 13; ++i) static_cast(world.spawn_agent({5, 1})); + static_cast(world.add_job({5, 1}, 1)); + for (int tick = 0; tick < 40; ++tick) world.step(); + + require(world.storages()[0].item_count(ItemType::Wood) == 3 && + world.storages()[1].item_count(ItemType::Stone) == 2, + "the production scenario did not fill its two stores"); + world.queue_production({5, 6}, RecipeId::BuildCabin); + for (std::int32_t x = 2; x < 6; ++x) world.queue_production({x, 4}, RecipeId::SawPlank); + world.queue_production({7, 4}, RecipeId::CutStoneBlock); + world.queue_production({8, 4}, RecipeId::CutStoneBlock); + world.step(); + + const auto& orders = world.production_orders(); + require(orders[0].state == JobState::Available && orders[4].state == JobState::Available, + "an order started without sufficient unreserved materials"); + require(world.storages()[0].items.front().reserved == 3 && + world.storages()[1].items.front().reserved == 2, + "craft orders failed to reserve the raw material"); + bool saw_first_pickup = false; + bool saw_final_haul = false; + bool saw_building_at_site = false; + std::unique_ptr restored; + for (int tick = 0; tick < 150 && orders[0].state != JobState::Completed; ++tick) { + world.step(); + if (restored) { + restored->step(); + require(save_contents(*restored) == save_contents(world), "resumed construction diverged"); + } + if (orders[0].collected_stops == 1) { + if (!restored) restored = save_roundtrip(world); + saw_first_pickup = true; + require(world.storages()[0].item_count(ItemType::Plank) == 0 && + world.storages()[1].item_count(ItemType::StoneBlock) == 2, + "materials left a store before the builder reached it"); + for (const auto& agent : world.agents()) { + if (agent.production_index != 0) continue; + require(agent.inventory.item_count(ItemType::Plank) == 3 && + agent.inventory.item_count(ItemType::StoneBlock) == 0, + "the builder's bag does not match the first pickup"); + } + } + if (orders[0].collected_stops == 2) { + saw_final_haul = true; + require(world.storages()[1].item_count(ItemType::StoneBlock) == 0, + "the builder did not pick up the second shipment"); + for (const auto& agent : world.agents()) { + if (agent.production_index != 0) continue; + require(agent.inventory.item_count(ItemType::Plank) == 3 && + agent.inventory.item_count(ItemType::StoneBlock) == 2, + "the builder's bag does not match the complete haul"); + } + } + for (const auto& agent : world.agents()) { + if (agent.production_index != 0 || agent.state != settlement::AgentState::Working) continue; + require(agent.position == orders[0].position && orders[0].delivery_stops.empty(), + "construction started before the builder reached the site with its materials"); + require(agent.inventory.empty(), "the builder retained the cargo after unloading"); + saw_building_at_site = true; + } + } + + require(orders[0].state == JobState::Completed && orders[4].state == JobState::Available, + "the cabin was not built or the extra plank was crafted without wood"); + require(saw_first_pickup && saw_final_haul && saw_building_at_site, + "the builder skipped a delivery or construction stage"); + require(world.storages()[0].items.empty() && world.storages()[1].items.empty(), + "building did not consume the crafted materials from both stores"); + +} + +void test_cabin_placement_queues_a_complete_order() { + using settlement::RecipeId; + settlement::World world(1, 10, 10); + world.set_blocked({1, 1}); + static_cast(world.add_storage({1, 2}, 5)); + require(!world.can_place_cabin({-1, 1}) && !world.can_place_cabin({1, 1}) && + !world.can_place_cabin({1, 2}), "placement accepted an invalid cell"); + const settlement::GridPosition site{5, 5}; + world.queue_cabin(site, {3, 3}, {4, 3}); + require(!world.can_place_cabin(site), "placement accepted an existing blueprint"); + const auto& orders = world.production_orders(); + require(orders.size() == 6 && orders.back().position == site && + orders.back().recipe == RecipeId::BuildCabin, + "placement did not queue the cabin and its five material orders"); + try { + world.queue_cabin(site, {3, 3}, {4, 3}); + require(false, "duplicate placement succeeded"); + } catch (const std::invalid_argument&) { + require(orders.size() == 6, "invalid placement partially queued new orders"); + } +} + +void test_hungry_resident_reserves_and_eats_a_berry() { + using settlement::AgentState; + using settlement::ItemType; + const settlement::GridPosition pantry{1, 1}; + settlement::World world(29, 12, 12); + static_cast(world.add_storage(pantry, 1, settlement::StorageKind::Pantry)); + static_cast(world.add_storage({2, 1}, 10)); + static_cast(world.add_resource_node({2, 2}, ItemType::Berries, 1)); + static_cast(world.spawn_agent({2, 1})); + for (int i = 0; i < 30; ++i) world.step(); + require(world.storages()[0].item_count(ItemType::Berries) == 1 && + world.storages()[1].items.empty(), "berries did not go to the pantry"); + static_cast(world.add_job({8, 1}, 1)); + for (int i = 0; i < 8; ++i) world.step(); + const auto& resident = world.agents().front(); + require(resident.position == settlement::GridPosition{8, 1}, "resident did not leave the pantry"); + world.enable_hunger(); + + bool travelled = false; + bool held_berry = false; + std::unique_ptr from_route; + std::unique_ptr from_meal; + for (int i = 0; i < 220 && world.meals_eaten() == 0; ++i) { + world.step(); + for (auto* restored : {from_route.get(), from_meal.get()}) { + if (restored == nullptr) continue; + restored->step(); + require(save_contents(*restored) == save_contents(world), "meal diverged after loading"); + } + if (resident.state == AgentState::GoingToEat) { + if (!from_route) from_route = save_roundtrip(world); + travelled = true; + require(world.storages()[0].items.front().reserved == 1 && resident.inventory.empty(), + "the berry must stay reserved in the pantry during the walk"); + } + if (resident.state == AgentState::Eating) { + if (!from_meal) from_meal = save_roundtrip(world); + held_berry = true; + require(resident.position == pantry && resident.inventory.item_count(ItemType::Berries) == 1, + "the resident did not pick up the berry on arrival"); + } + } + require(travelled && held_berry && world.meals_eaten() == 1 && + resident.inventory.empty() && resident.hunger == 0, "the meal did not clear hunger and consume the berry"); + static_cast(world.add_job(pantry, 1)); + world.step(); + require(world.jobs_completed() == 2, "the resident did not resume work after eating"); +} + +void test_invalid_save_is_rejected() { + const settlement::World world(5, 5, 5); + auto bytes = save_contents(world); + const auto rejected = [](const std::string& save) { + std::istringstream file(save, std::ios::binary); + try { + static_cast(settlement::World::read_save(file)); + } catch (const std::runtime_error&) { + return true; + } + return false; + }; + require(rejected(bytes.substr(0, bytes.size() - 1)), "truncated save was accepted"); + require(rejected(bytes + 'x'), "save with trailing data was accepted"); + bytes[8] = 127; + require(rejected(bytes), "unknown save version was accepted"); +} + +void test_two_players_share_the_first_colony() { + using settlement::CommandKind; + using settlement::CommandStatus; + auto world = settlement::make_first_colony(2); + const auto submit = [&](std::uint8_t player, CommandKind kind, settlement::GridPosition cell = {}, + std::uint8_t value = 0) { + return world->apply_command({player, world->next_command_sequence(player), kind, cell, value}); + }; + require(submit(1, CommandKind::SetPaused, {}, 1).status == CommandStatus::Accepted, + "the host could not pause the shared colony"); + require(submit(2, CommandKind::SetPaused, {}, 0).status == CommandStatus::Unauthorized, + "a guest could change the host's pause setting"); + require(submit(1, CommandKind::PlaceBed, {16, 18}).status == CommandStatus::Accepted && + submit(2, CommandKind::PlaceBed, {17, 18}, 1).status == CommandStatus::Accepted, + "both players should be able to build in the shared colony"); + require(world->apply_command({2, 1, CommandKind::PlaceBed, {18, 18}}).status == CommandStatus::WrongSequence, + "a repeated command could create another bed"); + require(submit(2, CommandKind::PlaceBed, {16, 18}).status == CommandStatus::InvalidTarget, + "two players placed a bed on the same tile"); + require(submit(2, CommandKind::PlaceBed, {18, 18}).status == CommandStatus::Accepted, + "the second player could not submit a corrected command"); + world->step(); + require(world->tick() == 0, "the shared colony moved while paused"); + world = save_roundtrip(*world); + require(world->paused() && world->next_command_sequence(2) == 3, + "pause or player command sequence was lost in the save"); + require(submit(1, CommandKind::SetPaused, {}, 0).status == CommandStatus::Accepted, + "the host could not resume the loaded party"); + for (int i = 0; i < 300; ++i) world->step(); + const auto no_food = world->scenario_progress(); + require(no_food.assigned_beds == 3 && no_food.residents == 3 && + no_food.available_food == 0 && !no_food.completed, + "unmarked berries were gathered or the objective was bypassed"); + require(submit(2, CommandKind::SetForaging, {14, 12}, 1).status == CommandStatus::Accepted && + submit(1, CommandKind::SetPriority, {}, 1).status == CommandStatus::Accepted, + "players could not mark food or change the work priority"); + for (int i = 0; i < 450 && !world->scenario_progress().completed; ++i) { + world->step(); + } + require(world->scenario_progress().completed && world->meals_eaten() >= 3, + "the shared colony could not feed its residents and complete the objective"); + auto replay = save_roundtrip(*world); + require(replay->scenario_progress().completed, "completion was lost after loading"); +} + +void test_bed_parts_are_delivered_separately() { + using namespace settlement; + auto world = make_first_colony(2); + const GridPosition wood_bed{16, 18}; + const GridPosition stone_bed{17, 18}; + require(world->apply_command({1, 1, CommandKind::PlaceBed, wood_bed, 0}).status == CommandStatus::Accepted && + world->apply_command({1, 2, CommandKind::PlaceBed, stone_bed, 1}).status == CommandStatus::Accepted, + "both types of bed foundation must be available"); + std::array seen{}; + for (int tick = 0; tick < 250 && world->scenario_progress().assigned_beds < 2; ++tick) { + world->step(); + for (const auto& agent : world->agents()) { + if (agent.production_index == no_entity_index || agent.state != AgentState::Hauling) continue; + const auto& order = world->production_orders()[agent.production_index]; + const auto expected = order.bed_stage == BedStage::Foundation + ? (order.position == wood_bed ? ItemType::Wood : ItemType::Stone) : ItemType::Cloth; + require(agent.inventory.item_count(expected) == 1, + "the resident did not carry the raw material required by this stage"); + const auto bit = 1U << static_cast(order.bed_stage); + if ((seen[agent.production_index] & bit) == 0) { + seen[agent.production_index] |= bit; + auto copy = save_roundtrip(*world); + copy->step(); + } + } + } + require(world->scenario_progress().assigned_beds == 2 && seen[0] == 14 && seen[1] == 14, + "the beds were not completed through three separate deliveries"); + require(world->storages().back().item_count(ItemType::Cloth) == 8, + "two beds must consume four pieces of cloth"); +} + +void test_resident_uses_assigned_bed_and_sleep_survives_save() { + using namespace settlement; + World world(4, 16, 16, 2); + const auto owner = world.spawn_agent({1, 2}); + const auto other = world.spawn_agent({1, 3}); + const auto storage = world.add_storage({3, 2}, 6); + world.stock_storage(storage, ItemType::Stone, 1); + world.stock_storage(storage, ItemType::Cloth, 2); + world.start_scenario({4, 3}); + const GridPosition bed_cell{12, 10}; + require(world.apply_command({1, 1, CommandKind::PlaceBed, bed_cell, 1}).status == CommandStatus::Accepted, + "could not place a bed for the sleep test"); + for (int i = 0; i < 160 && world.assigned_bed(owner) == nullptr; ++i) world.step(); + require(world.assigned_bed(owner) != nullptr && world.assigned_bed(other) == nullptr, + "bed ownership was not exclusive"); + static_cast(world.add_job({2, 5}, 1)); + static_cast(world.add_job({2, 6}, 1)); + + bool woke_rested = false; + bool rested_on_ground = false; + std::unique_ptr from_route; + std::unique_ptr from_sleep; + for (int tick = 0; tick < 320 && (!woke_rested || !rested_on_ground); ++tick) { + world.step(); + for (auto* resumed : {from_route.get(), from_sleep.get()}) { + if (resumed == nullptr) continue; + resumed->step(); + require(save_contents(*resumed) == save_contents(world), "sleep went out of sync after loading"); + } + const auto& resident = world.agents().front(); + if (resident.state == AgentState::GoingToSleep && !from_route) { + require(!resident.route.empty() && resident.route.back() == bed_cell, + "the route did not lead to the assigned bed"); + from_route = save_roundtrip(world); + } + if (resident.state == AgentState::Sleeping && !from_sleep) { + require(resident.position == bed_cell, "the owner did not sleep in the assigned bed"); + from_sleep = save_roundtrip(world); + } + if (from_sleep && resident.state == AgentState::Idle && resident.fatigue == 0) woke_rested = true; + const auto& unassigned = world.agents().back(); + if (unassigned.state == AgentState::Sleeping) { + require(unassigned.position != bed_cell, "an unassigned resident used another resident's bed"); + rested_on_ground = true; + } + } + require(from_route && woke_rested && rested_on_ground, "sleep and recovery phases were not observed"); + require(world.jobs_completed() == 2, "residents did not finish their existing work"); +} + +void test_fatigue_slows_work_without_interrupting_it() { + using namespace settlement; + World world(6, 10, 10); + static_cast(world.spawn_agent({2, 2})); + const auto job = world.add_job({2, 2}, 500); + world.start_scenario({4, 4}); + for (int i = 0; i < fatigue_threshold; ++i) world.step(); + const auto& resident = world.agents().front(); + require(resident.tired() && resident.hungry() && resident.current_job == job, + "the resident interrupted their work when they became tired"); + const auto before = resident.work_remaining; + for (int i = 0; i < 6; ++i) world.step(); + require(before - resident.work_remaining == 2, "hunger and fatigue did not slow the ongoing work"); +} + +void test_ground_rest_never_uses_another_residents_bed() { + using namespace settlement; + World world(15, 14, 14); + const GridPosition cell{7, 6}; + const auto owner = world.spawn_agent({2, 2}); + const auto storage = world.add_storage({3, 2}, 4); + world.stock_storage(storage, ItemType::Stone, 1); + world.stock_storage(storage, ItemType::Cloth, 2); + world.start_scenario({4, 3}); + require(world.apply_command({1, 1, CommandKind::PlaceBed, cell, 1}).status == CommandStatus::Accepted, + "could not set up a bed for the collision test"); + for (int i = 0; i < 155 && world.assigned_bed(owner) == nullptr; ++i) world.step(); + require(world.assigned_bed(owner) != nullptr, "the owner did not get a bed"); + static_cast(world.spawn_agent(cell)); + bool observed_owner = false; + bool observed_ground = false; + for (int i = 0; i < 450 && (!observed_owner || !observed_ground); ++i) { + world.step(); + const auto& guest = world.agents()[1]; + if (world.agents()[0].state == AgentState::Sleeping && !observed_owner) { + observed_owner = true; + require(world.apply_command({1, 2, CommandKind::MoveObject, cell, 0, {8, 6}}).status == + CommandStatus::Busy && + world.apply_command({1, 2, CommandKind::DemolishObject, cell}).status == CommandStatus::Busy, + "an occupied bed could be moved or demolished"); + } + if (guest.state == AgentState::Sleeping) { + require(guest.position != cell && guest.resting_on_ground, "a visitor fell asleep on the owner's bed"); + if (!observed_ground) static_cast(save_roundtrip(world)); + observed_ground = true; + } + } + require(observed_owner && observed_ground, "the bed collision regression did not reach both types of rest"); + const GridPosition new_cell{8, 6}; + require(world.apply_command({1, 2, CommandKind::MoveObject, cell, 0, new_cell}).status == CommandStatus::Accepted, + "a free bed could not be moved"); + require(world.assigned_bed(owner)->position == new_cell, "moving a bed lost its owner"); + require(world.apply_command({1, 3, CommandKind::DemolishObject, new_cell}).status == CommandStatus::Accepted && + world.assigned_bed(owner) == nullptr, "demolishing a bed left a stale assignment"); +} + +void test_fields_mines_and_reindexing_active_hauls() { + using namespace settlement; + World world(22, 18, 18, 2); + const GridPosition rock{9, 5}; + const GridPosition berry_cell{7, 7}; + const GridPosition tree_cell{8, 8}; + world.set_blocked(rock); + static_cast(world.add_storage({1, 1}, 5)); + const auto stone_store = world.add_storage({10, 5}, 80); + world.stock_storage(stone_store, ItemType::Stone, 2); + static_cast(world.add_storage({7, 8}, 30, StorageKind::Pantry)); + for (int i = 0; i < 4; ++i) static_cast(world.spawn_agent({8, 5})); + world.start_scenario({4, 4}); + const auto apply = [&](CommandKind kind, GridPosition cell, GridPosition to = {}) { + return world.apply_command({2, world.next_command_sequence(2), kind, cell, 0, to}).status; + }; + require(apply(CommandKind::PlaceBerryField, berry_cell) == CommandStatus::Accepted && + apply(CommandKind::PlaceTreePlot, tree_cell) == CommandStatus::Accepted && + apply(CommandKind::PlaceMine, rock) == CommandStatus::Accepted, + "an accessible field or mine could not be placed"); + require(world.resource_nodes()[0].quantity == 0 && world.resource_nodes()[1].quantity == 0 && + world.is_walkable(rock), "fields ripened immediately or the mine entrance stayed blocked"); + require(apply(CommandKind::MoveObject, rock, {11, 5}) == CommandStatus::InvalidTarget, + "terrain mines should not be movable"); + require(apply(CommandKind::MoveObject, {10, 5}, {10, 6}) == CommandStatus::Accepted && + world.storages()[1].item_count(ItemType::Stone) == 2, "moving a store lost its contents"); + world.step(); + require(apply(CommandKind::DemolishObject, rock) == CommandStatus::Busy && + apply(CommandKind::DemolishObject, {10, 6}) == CommandStatus::Busy && + apply(CommandKind::DemolishObject, {1, 1}) == CommandStatus::Accepted, + "active source or destination was editable, or the unused store could not be removed"); + auto copy = save_roundtrip(world); + bool had_food = false; + bool had_wood = false; + int berry_crops = 0; + std::uint64_t last_berry_growth = 0; + for (int i = 0; i < 450; ++i) { + world.step(); + copy->step(); + require(save_contents(*copy) == save_contents(world), "simulation diverged after editing a site and loading"); + had_food = had_food || world.storages()[1].item_count(ItemType::Berries) > 0; + had_wood = had_wood || world.storages()[0].item_count(ItemType::Wood) > 0; + if (world.resource_nodes()[0].growth_at > last_berry_growth) { + last_berry_growth = world.resource_nodes()[0].growth_at; + ++berry_crops; + } + } + require(had_food && had_wood && berry_crops >= 2 && world.storages()[0].item_count(ItemType::Stone) > 2, + "growing, regrowing, or mining did not deliver resources"); + require(apply(CommandKind::PlaceStorage, {11, 7}) == CommandStatus::Accepted, + "a new storage could not be placed"); +} + +void test_specialists_take_their_own_jobs_and_finish_prior_assignments() { + using namespace settlement; + World world(54, 14, 14, 2); + const auto farmer = world.spawn_agent({2, 2}); + const auto woodcutter = world.spawn_agent({3, 2}); + const auto miner = world.spawn_agent({4, 2}); + const auto builder = world.spawn_agent({5, 2}); + const auto storage = world.add_storage({6, 3}, 40); + world.stock_storage(storage, ItemType::Stone, 4); + world.stock_storage(storage, ItemType::Cloth, 2); + static_cast(world.add_storage({3, 3}, 30, StorageKind::Pantry)); + static_cast(world.add_resource_node({9, 2}, ItemType::Berries, 10)); + static_cast(world.add_resource_node({2, 9}, ItemType::Wood, 10)); + static_cast(world.add_resource_node({9, 9}, ItemType::Stone, 10)); + world.start_scenario({6, 6}); + const auto assign = [&](AgentId id, Profession role) { + return world.apply_command({1, world.next_command_sequence(1), CommandKind::AssignProfession, {}, + static_cast(role), {}, id}).status; + }; + require(assign(999, Profession::Farmer) == CommandStatus::InvalidTarget, + "a nonexistent resident could receive a profession"); + require(assign(farmer, Profession::Farmer) == CommandStatus::Accepted && + assign(woodcutter, Profession::Woodcutter) == CommandStatus::Accepted && + assign(miner, Profession::Miner) == CommandStatus::Accepted && + assign(builder, Profession::Builder) == CommandStatus::Accepted, + "could not assign one of the professions"); + require(world.apply_command({1, world.next_command_sequence(1), CommandKind::SetForaging, {9, 2}, 1}).status == + CommandStatus::Accepted && + world.apply_command({1, world.next_command_sequence(1), CommandKind::PlaceBed, {8, 8}, 1}).status == + CommandStatus::Accepted, "could not schedule the specialist jobs"); + world.step(); + for (std::size_t index = 0; index < 3; ++index) { + require(world.agents()[index].resource_node_index == index, "a specialist chose the wrong resource"); + } + require(world.agents()[3].production_index == 0 && world.agents()[3].resource_node_index == no_entity_index, + "the builder did not take the construction job"); + require(assign(miner, Profession::Woodcutter) == CommandStatus::Accepted && + world.agents()[2].resource_node_index == 2, + "changing professions interrupted a reserved mining job"); + + auto copy = save_roundtrip(world); + bool delivered_stone = false; + bool later_cut_wood = false; + for (int i = 0; i < 110; ++i) { + world.step(); + copy->step(); + require(save_contents(world) == save_contents(*copy), "specialist jobs diverged after loading"); + const auto& resident = world.agents()[2]; + if (resident.inventory.item_count(ItemType::Stone) > 0) delivered_stone = true; + if (resident.resource_node_index == 1) later_cut_wood = true; + if (later_cut_wood) require(resident.resource_node_index != 2, "a woodcutter kept selecting mining jobs"); + } + require(delivered_stone && later_cut_wood, "the reassigned miner did not finish mining and then cut wood"); + require(world.scenario_progress().assigned_beds == 1, "the builder did not complete the bed"); +} + +void test_flax_and_loom_supply_a_bed_without_starting_cloth() { + using namespace settlement; + World world(92, 12, 12, 3); + const auto farmer = world.spawn_agent({2, 3}); + const auto builder = world.spawn_agent({4, 4}); + const auto materials = world.add_storage({3, 3}, 30); + const auto pantry = world.add_storage({3, 4}, 12, StorageKind::Pantry); + world.stock_storage(pantry, ItemType::Berries, 12); + world.stock_storage(materials, ItemType::Stone, 1); + world.start_scenario({4, 2}); + const auto send = [&](CommandKind kind, GridPosition cell = {}, std::uint8_t value = 0, + GridPosition destination = {}, AgentId resident = 0) { + return world.apply_command({1, world.next_command_sequence(1), kind, cell, value, destination, resident}).status; + }; + const GridPosition field{2, 4}; + const GridPosition loom{4, 3}; + const GridPosition moved_loom{5, 3}; + require(send(CommandKind::AssignProfession, {}, static_cast(Profession::Farmer), {}, farmer) == + CommandStatus::Accepted && + send(CommandKind::AssignProfession, {}, static_cast(Profession::Builder), {}, builder) == + CommandStatus::Accepted, "could not assign textile workers"); + require(send(CommandKind::PlaceFlaxField, field) == CommandStatus::Accepted && + send(CommandKind::PlaceLoom, field) == CommandStatus::InvalidTarget && + send(CommandKind::PlaceLoom, loom) == CommandStatus::Accepted && + send(CommandKind::MoveObject, loom, 0, moved_loom) == CommandStatus::Accepted && + send(CommandKind::PlaceBed, {5, 4}, static_cast(BedBase::Stone)) == CommandStatus::Accepted, + "a textile object collided with a field or could not be placed or moved"); + require(world.resource_nodes().front().needs_tending(), "flax started growing before being planted"); + auto restored = save_roundtrip(world); + bool saved_flax_in_transit = false; + bool saved_active_weaving = false; + int sowings = 0; + std::uint64_t last_growth = 0; + for (int i = 0; i < 360; ++i) { + world.step(); + restored->step(); + require(save_contents(world) == save_contents(*restored), "textile work diverged after loading"); + const auto& loom_order = world.production_orders().front(); + if (!saved_flax_in_transit && world.agents().front().inventory.item_count(ItemType::Flax) > 0) { + restored = save_roundtrip(world); + saved_flax_in_transit = true; + } + if (!saved_active_weaving && loom_order.state == JobState::InProgress) { + require(world.agents().back().production_index == 0 && + world.object_status(moved_loom, true) == CommandStatus::Busy, + "the loom was assigned to the wrong worker or could move while active"); + restored = save_roundtrip(world); + saved_active_weaving = true; + } + if (world.resource_nodes().front().growth_at > last_growth) { + last_growth = world.resource_nodes().front().growth_at; + ++sowings; + } + } + require(saved_flax_in_transit && saved_active_weaving && sowings >= 2, "the textile supply chain did not repeat"); + require(world.scenario_progress().assigned_beds == 1 && + world.storages().front().item_count(ItemType::Cloth) > 0, + "the loom did not make enough cloth to finish and replenish a bed order"); +} + +void test_field_growth_requires_a_worker() { + using namespace settlement; + World world(58, 14, 14); + const auto resident = world.spawn_agent({2, 2}); + const auto apply = [&](CommandKind kind, GridPosition cell = {}, Profession role = Profession::Builder) { + return world.apply_command({1, world.next_command_sequence(1), kind, cell, + static_cast(role), {}, resident}).status; + }; + const GridPosition field{7, 5}; + require(apply(CommandKind::AssignProfession) == CommandStatus::Accepted && + apply(CommandKind::PlaceFlaxField, field) == CommandStatus::Accepted, "could not prepare the flax field"); + for (int i = 0; i < 100; ++i) world.step(); + require(world.resource_nodes().front().needs_tending() && world.agents().front().state == AgentState::Idle, + "a field grew without a farmer"); + require(apply(CommandKind::AssignProfession, {}, Profession::Farmer) == CommandStatus::Accepted, + "could not assign the farmer"); + world.step(); + require(world.agents().front().state == AgentState::Travelling && + world.agents().front().storage_index == no_entity_index && + world.object_status(field, true) == CommandStatus::Busy, "the farmer did not reserve and walk to the field"); + auto restored = save_roundtrip(world); + for (int i = 0; i < 100; ++i) { + world.step(); + restored->step(); + require(save_contents(world) == save_contents(*restored), "sowing did not resume after loading"); + } + require(world.resource_nodes().front().quantity > 0, "planting without a storage did not grow flax"); +} + +void test_opening_a_mine_invalidates_unreachable_routes() { + using namespace settlement; + World world(44, 8, 8); + const auto resident = world.spawn_agent({1, 4}); + static_cast(world.add_storage({1, 5}, 10)); + static_cast(world.add_resource_node({5, 4}, ItemType::Wood, 3)); + for (int y = 0; y < 8; ++y) world.set_blocked({3, y}); + require(world.apply_command({1, 1, CommandKind::AssignProfession, {}, + static_cast(Profession::Woodcutter), {}, resident}).status == CommandStatus::Accepted, + "failed to assign a woodcutter"); + world.step(); + world.step(); + require(world.assignment_path_cache_hits() != 0 && world.agents().front().state == AgentState::Idle, + "failed to reuse an unreachable route"); + require(world.apply_command({1, 2, CommandKind::PlaceMine, {3, 4}}).status == CommandStatus::Accepted, + "failed to open a passage"); + world.step(); + require(world.agents().front().resource_node_index == 0 && + world.agents().front().state == AgentState::Travelling, "terrain edit left a stale route in the cache"); +} + +void test_object_tools_work_in_an_older_demo_world() { + using namespace settlement; + World legacy(12, 12, 12); + static_cast(legacy.spawn_agent({4, 4})); + legacy.set_blocked({5, 5}); + auto world = save_roundtrip(legacy); + require(!world->scenario_active(), "loading a demonstration started a new scenario"); + const auto edit = [&](CommandKind command, GridPosition source, GridPosition destination = {}) { + return world->apply_command({1, world->next_command_sequence(1), command, source, 0, destination}).status; + }; + require(edit(CommandKind::PlaceBerryField, {5, 4}) == CommandStatus::Accepted && + edit(CommandKind::PlaceMine, {5, 5}) == CommandStatus::Accepted && + edit(CommandKind::MoveObject, {5, 4}, {4, 5}) == CommandStatus::Accepted, + "the new actions were still hidden behind the scenario flag"); + for (int i = 0; i < 85; ++i) world->step(); + require(world->resource_nodes()[0].quantity > 0, "the field did not ripen in the demonstration"); + require(edit(CommandKind::DemolishObject, {4, 5}) == CommandStatus::Accepted, + "a field in a demonstration could not be demolished"); + static_cast(save_roundtrip(*world)); +} + +} // namespace + +int main() { + try { + test_rng_repeats_for_same_seed(); + test_work_jobs_complete(); + test_astar_route_uses_opening_in_wall(); + test_parallel_pathfinding_completes_the_jobs(); + test_single_worker_configuration_is_rejected(); + test_residents_gather_and_deliver_resources(); + test_production_reservations_and_construction(); + test_cabin_placement_queues_a_complete_order(); + test_hungry_resident_reserves_and_eats_a_berry(); + test_invalid_save_is_rejected(); + test_two_players_share_the_first_colony(); + test_bed_parts_are_delivered_separately(); + test_resident_uses_assigned_bed_and_sleep_survives_save(); + test_fatigue_slows_work_without_interrupting_it(); + test_ground_rest_never_uses_another_residents_bed(); + test_fields_mines_and_reindexing_active_hauls(); + test_specialists_take_their_own_jobs_and_finish_prior_assignments(); + test_flax_and_loom_supply_a_bed_without_starting_cloth(); + test_field_growth_requires_a_worker(); + test_opening_a_mine_invalidates_unreachable_routes(); + test_object_tools_work_in_an_older_demo_world(); + } catch (const std::exception& error) { + std::cerr << "Test failed: " << error.what() << '\n'; + return 1; + } + + std::cout << "All core checks passed.\n"; + return 0; +} diff --git a/tests/lan_tests.cpp b/tests/lan_tests.cpp new file mode 100644 index 0000000..4cb2771 --- /dev/null +++ b/tests/lan_tests.cpp @@ -0,0 +1,144 @@ +#include "lan_session.hpp" + +#include +#include +#include +#include + +namespace { + +using namespace std::chrono_literals; +using namespace settlement; +using namespace settlement::viewer; + +void require(bool condition, const char* message) { + if (!condition) throw std::runtime_error(message); +} + +void test_shared_colony_over_loopback() { + auto authoritative = make_first_colony(4); + auto client_view = make_first_colony(4); + for (int i = 0; i < 25; ++i) authoritative->step(); + LanSession host; + LanSession guest; + host.host(0, true); + const auto port = host.port(); + const auto code = host.join_code(); + auto wrong_code = code; + wrong_code.front() = wrong_code.front() == 'f' ? 'e' : 'f'; + const auto pump_until = [&](auto success, const char* message) { + const auto deadline = std::chrono::steady_clock::now() + 3s; + while (std::chrono::steady_clock::now() < deadline) { + static_cast(host.poll(*authoritative)); + if (auto snapshot = guest.poll(*client_view)) client_view = std::move(snapshot); + if (success()) return; + std::this_thread::sleep_for(1ms); + } + throw std::runtime_error(message); + }; + guest.join("127.0.0.1", wrong_code, port); + pump_until([&] { return guest.state() == LanState::GuestDisconnected; }, + "a guest with the wrong code was not disconnected"); + require(host.state() == LanState::Hosting, "an invalid guest occupied the player slot"); + + guest.join("127.0.0.1", code, port); + pump_until([&] { return guest.state() == LanState::GuestConnected; }, "the guest could not join"); + require(client_view->tick() == 25 && client_view->agents().size() == authoritative->agents().size(), + "joining did not deliver the host's current snapshot"); + require(!guest.submit(CommandKind::SetPaused, {}, 1), "a guest could control pause"); + require(guest.submit(CommandKind::PlaceBed, {16, 18}, static_cast(BedBase::Stone)), + "the guest could not send a build command"); + pump_until([&] { + return client_view->production_orders().size() == 1 && + client_view->production_orders().front().position == GridPosition{16, 18} && + client_view->production_orders().front().bed_base == BedBase::Stone; + }, "the guest's bed was not applied and synchronized"); + require(authoritative->production_orders().front().bed_base == BedBase::Stone, + "the guest's choice of bed material was lost"); + require(guest.submit(CommandKind::PlaceBed, {16, 18}, 0), "the guest could not send a conflicting command"); + pump_until([&] { return guest.take_rejection() == CommandStatus::InvalidTarget; }, + "a conflicting guest command did not return a rejection"); + require(authoritative->production_orders().size() == 1, "the same cell was claimed twice"); + + guest.leave(); + pump_until([&] { return host.state() == LanState::Hosting; }, "the guest slot was not released"); + for (int i = 0; i < 10; ++i) authoritative->step(); + guest.join("127.0.0.1", code, port); + pump_until([&] { return guest.state() == LanState::GuestConnected; }, "the guest could not rejoin"); + require(client_view->tick() == authoritative->tick() && client_view->next_command_sequence(2) == 2 && + client_view->production_orders().size() == 1, + "rejoining did not restore the current colony and guest sequence"); + require(guest.submit(CommandKind::SetForaging, {14, 12}, 1), "the reconnected guest could not send a command"); + pump_until([&] { + if (client_view->next_command_sequence(2) != 3) return false; + for (const auto& node : client_view->resource_nodes()) { + if (node.position == GridPosition{14, 12}) return node.foraging_enabled; + } + return false; + }, "the reconnected guest's command did not synchronize"); + const auto owner_sleeping = [](const World& simulation) { + for (const auto& agent : simulation.agents()) { + if (agent.state == AgentState::Sleeping && simulation.assigned_bed(agent.id) != nullptr) return true; + } + return false; + }; + for (int i = 0; i < 600 && !owner_sleeping(*authoritative); ++i) authoritative->step(); + require(owner_sleeping(*authoritative), "the owner went without sleep"); + pump_until([&] { + return client_view->tick() == authoritative->tick() && owner_sleeping(*client_view); + }, "the host's sleep state did not reach the guest"); + const GridPosition field{14, 15}; + const GridPosition new_field{14, 17}; + require(guest.submit(CommandKind::PlaceBerryField, field, 0), "the guest could not plant a field"); + const auto has_field = [&](GridPosition position) { + for (const auto& node : client_view->resource_nodes()) { + if (node.site == ResourceSite::BerryField && node.position == position) return true; + } + return false; + }; + pump_until([&] { return has_field(field); }, "the planted field was not synchronized"); + require(guest.submit(CommandKind::MoveObject, field, 0, new_field), "the guest could not move the field"); + pump_until([&] { return has_field(new_field) && !has_field(field); }, "the move destination was not synchronized"); + require(guest.submit(CommandKind::DemolishObject, new_field, 0), "the guest could not remove the field"); + pump_until([&] { return !has_field(new_field); }, + "demolishing a field was not synchronized"); + const auto resident = authoritative->agents().back().id; + require(guest.submit(CommandKind::AssignProfession, {}, static_cast(Profession::Miner), {}, resident), + "the guest could not assign a profession"); + pump_until([&] { + return client_view->agents().back().id == resident && + client_view->agents().back().profession == Profession::Miner; + }, "the assigned profession was not synchronized"); + require(guest.submit(CommandKind::PlaceFlaxField, field, 0), "the guest could not plant flax"); + pump_until([&] { + return client_view->resource_nodes().back().site == ResourceSite::FlaxField && + client_view->resource_nodes().back().position == field; + }, "the flax field did not arrive in the guest snapshot"); + require(guest.submit(CommandKind::PlaceLoom, new_field, 0), "the guest could not place a loom"); + pump_until([&] { + return client_view->production_orders().back().recipe == RecipeId::WeaveCloth && + client_view->production_orders().back().position == new_field; + }, "the loom did not arrive in the guest snapshot"); + for (int i = 0; i < 160 && authoritative->resource_nodes().back().reserved_workers == 0; ++i) { + authoritative->step(); + } + require(authoritative->resource_nodes().back().needs_tending() && + authoritative->resource_nodes().back().reserved_workers == 1, "no resident reserved the field for sowing"); + pump_until([&] { + return client_view->tick() == authoritative->tick() && + client_view->resource_nodes().back().needs_tending() && + client_view->resource_nodes().back().reserved_workers == 1; + }, "a snapshot lost the resident's sowing assignment"); + std::cout << "Loopback LAN checks passed.\n"; +} + +} // namespace + +int main() { + try { + test_shared_colony_over_loopback(); + } catch (const std::exception& error) { + std::cerr << error.what() << '\n'; + return 1; + } +}