diff --git a/app/d3d_scene_win32.cpp b/app/d3d_scene_win32.cpp index 0eb447b..d7f4574 100644 --- a/app/d3d_scene_win32.cpp +++ b/app/d3d_scene_win32.cpp @@ -252,7 +252,7 @@ void draw_room_roofs(Mesh& mesh, const World& world) { if (is_room_part(order.recipe) && order.state == JobState::Completed) { cell.structure = room_part_shape(order.recipe); } - switch (order.recipe) { + switch (furnishing_shape(order.recipe)) { case RecipeId::BuildMedicineCabinet: cell.furnishing = RoomTemplate::Doctor; break; case RecipeId::BuildMiningRack: cell.furnishing = RoomTemplate::Miner; break; case RecipeId::BuildLoom: @@ -334,8 +334,9 @@ void construction(Mesh& mesh, const World& world, BuildingView building_view) { mesh.box(x + .34f, y, .30f, .052f, .13f, .13f, rgb(229, 195, 124)); } for (const auto& order : world.production_orders()) { - if (order.recipe == RecipeId::CraftWoodenDoor || + if (is_carpentry_recipe(order.recipe) || (order.recipe == RecipeId::SawPlank && workshop == order.position)) continue; + const auto fixture = furnishing_shape(order.recipe); const float x = static_cast(order.position.x), y = static_cast(order.position.y); if (order.recipe == RecipeId::WeaveCloth) { draw_furnishing(mesh, order.position, order.recipe, rgb(185, 140, 86), rgb(235, 225, 193)); @@ -359,14 +360,14 @@ void construction(Mesh& mesh, const World& world, BuildingView building_view) { room_part(mesh, order.position, shape, order.state == JobState::Available ? rgb(121, 178, 195) : rgb(214, 171, 99), true); } - } else if (order.recipe == RecipeId::BuildMedicineCabinet || order.recipe == RecipeId::BuildMiningRack || - order.recipe == RecipeId::BuildLoom) { + } else if (fixture == RecipeId::BuildMedicineCabinet || fixture == RecipeId::BuildMiningRack || + fixture == RecipeId::BuildLoom) { const bool finished = order.state == JobState::Completed; const auto wood = finished ? rgb(175, 123, 78) : rgb(117, 168, 181); const auto detail = finished - ? (order.recipe == RecipeId::BuildMedicineCabinet ? rgb(169, 214, 183) : rgb(153, 166, 172)) + ? (fixture == RecipeId::BuildMedicineCabinet ? rgb(169, 214, 183) : rgb(153, 166, 172)) : rgb(158, 202, 209); - draw_furnishing(mesh, order.position, order.recipe, wood, detail); + draw_furnishing(mesh, order.position, fixture, wood, detail); } else if (order.recipe == RecipeId::BuildBed && (order.state == JobState::Completed || order.bed_stage == BedStage::Bedding || order.bed_stage == BedStage::Pillow)) { mesh.box(x, y, .045f, .77f, .43f, .18f, @@ -452,7 +453,7 @@ void residents(Mesh& mesh, const World& world, const SceneView& view) { mesh.box(x, y, .167f, .27f, .22f, .22f, clothes); mesh.box(x, y, .387f, .25f, .24f, .23f, rgb(232, 191, 144)); mesh.box(x - .025f, y - .02f, .59f, .27f, .25f, .065f, rgb(92, 73, 56)); - if (agent.inventory.item_count(ItemType::WoodenDoor) != 0) { + if (is_carpentry_item(agent.inventory.first_item())) { mesh.box(x - .14f, y - .12f, .09f, .13f, .30f, .39f, rgb(177, 116, 70)); } else if (!agent.inventory.empty()) { mesh.box(x - .11f, y - .12f, .14f, .19f, .18f, .24f, rgb(200, 156, 92)); diff --git a/app/lan_session_win32.cpp b/app/lan_session_win32.cpp index c24e5c6..103aba7 100644 --- a/app/lan_session_win32.cpp +++ b/app/lan_session_win32.cpp @@ -24,7 +24,7 @@ namespace { using Clock = std::chrono::steady_clock; using namespace std::chrono_literals; -constexpr std::uint32_t protocol_version = 10; +constexpr std::uint32_t protocol_version = 11; constexpr std::size_t frame_limit = 4 * 1024 * 1024; constexpr auto poll_budget = 16; constexpr std::size_t command_queue_limit = 32; diff --git a/app/viewer_win32.cpp b/app/viewer_win32.cpp index abeded6..02255fa 100644 --- a/app/viewer_win32.cpp +++ b/app/viewer_win32.cpp @@ -70,6 +70,7 @@ constexpr int furnished_room_tool_id = 1045; constexpr int house_list_back_id = 1046; constexpr int carpenter_menu_id = 1047; constexpr int craft_door_id = 1048; +constexpr int first_furniture_craft_id = 1143; constexpr int first_work_choice_id = 1050; constexpr int resident_list_id = 1060; constexpr int first_role_id = 1070; @@ -160,8 +161,14 @@ constexpr std::array woodcutter_choices = { constexpr std::array miner_choices = { WorkChoice{mine_id, L"Шахта", WorkIcon::Pickaxe, 98, PlacementMode::Mine}, }; +constexpr std::array furniture_products = { + settlement::ItemType::MedicineCabinet, settlement::ItemType::MiningRack, settlement::ItemType::Loom, +}; constexpr std::array carpenter_choices = { WorkChoice{craft_door_id, L"Изготовить дверь", WorkIcon::Wood, 190}, + WorkChoice{first_furniture_craft_id, L"Аптечный шкаф", WorkIcon::Crate, 163}, + WorkChoice{first_furniture_craft_id + 1, L"Стойка шахтёра", WorkIcon::Pickaxe, 168}, + WorkChoice{first_furniture_craft_id + 2, L"Ткацкий станок", WorkIcon::Loom, 163}, }; constexpr std::array builder_choices = { WorkChoice{cabin_button_id, L"Спальное место", WorkIcon::Bed, 153, PlacementMode::Building}, @@ -697,7 +704,7 @@ void set_work_panel(HWND window, WorkPanel panel) { const auto& choice = choices[index]; SetWindowTextW(button, choice.command == cabin_button_id && world && !world->scenario_active() ? L"Чертёж домика" : choice.title); - EnableWindow(button, choice.command != craft_door_id || (world && world->scenario_active())); + EnableWindow(button, work_panel != WorkPanel::Carpenter || (world && world->scenario_active())); ShowWindow(button, SW_SHOWNA); } for (const auto button : dock_section_buttons) InvalidateRect(button, nullptr, FALSE); @@ -1856,7 +1863,9 @@ std::wstring resident_details() { constexpr std::pair items[] = { {ItemType::Wood, L"древесина"}, {ItemType::Stone, L"камень"}, {ItemType::Plank, L"доски"}, {ItemType::StoneBlock, L"блоки"}, {ItemType::Berries, L"ягоды"}, {ItemType::Cloth, L"ткань"}, - {ItemType::Flax, L"лён"}, {ItemType::WoodenDoor, L"деревянная дверь"} + {ItemType::Flax, L"лён"}, {ItemType::WoodenDoor, L"деревянная дверь"}, + {ItemType::MedicineCabinet, L"аптечный шкаф"}, {ItemType::MiningRack, L"стойка шахтёра"}, + {ItemType::Loom, L"ткацкий станок"} }; std::wstring cargo; for (const auto& [type, name] : items) { @@ -1871,9 +1880,9 @@ std::wstring resident_details() { if (resident->state == settlement::AgentState::GoingToEat) text += L" Идёт к кладовой"; else if (resident->state == settlement::AgentState::Eating) text += L" Ест"; else if (resident->production_index != settlement::no_entity_index && - world->production_orders()[resident->production_index].recipe == settlement::RecipeId::CraftWoodenDoor) { - text += resident->state == settlement::AgentState::Working ? L" Изготавливает дверь" : - L" Везёт дерево в мастерскую"; + settlement::is_carpentry_recipe(world->production_orders()[resident->production_index].recipe)) { + text += resident->state == settlement::AgentState::Working ? L" Работает за верстаком" : + L" Везёт материалы в мастерскую"; } else if (resident->resource_node_index != settlement::no_entity_index && resident->storage_index == settlement::no_entity_index) { @@ -1912,10 +1921,14 @@ std::wstring blueprint_details() { }; constexpr Material materials[] = {{ItemType::Wood, L"дерево"}, {ItemType::Stone, L"камень"}, {ItemType::Cloth, L"ткань"}, {ItemType::Plank, L"доски"}, {ItemType::StoneBlock, L"каменные блоки"}, - {ItemType::WoodenDoor, L"готовые двери"}}; + {ItemType::WoodenDoor, L"готовые двери"}, {ItemType::MedicineCabinet, L"аптечные шкафы"}, + {ItemType::MiningRack, L"стойки шахтёра"}, {ItemType::Loom, L"ткацкие станки"}}; std::array totals{}; for (const auto& part : blueprint) { - for (const auto& material : world->construction_materials(part.recipe, part.base)) { + using settlement::RecipeId; + const auto recipe = part.recipe == RecipeId::WeaveCloth && world->scenario_active() ? + world->room_construction_recipe(RecipeId::BuildLoom) : part.recipe; + for (const auto& material : world->construction_materials(recipe, part.base)) { totals[static_cast(material.type)] += material.count; } } @@ -1929,7 +1942,8 @@ std::wstring blueprint_details() { } if (const auto furnishings = room.furnishings()) { for (const auto& part : *furnishings) { - for (const auto& item : world->construction_materials(part.recipe, part.bed_base)) { + const auto recipe = world->room_construction_recipe(part.recipe); + for (const auto& item : world->construction_materials(recipe, part.bed_base)) { totals[static_cast(item.type)] += item.count; } } @@ -2005,7 +2019,7 @@ void draw_world(HDC dc, int width, int height) { } else if (work_panel == WorkPanel::Houses) { hint = L"Выберите проект дома для площадки 4×4."; } else if (work_panel == WorkPanel::Carpenter) { - hint = L"Плотник делает дверь из двух единиц дерева. При подтверждении дома заказ создаётся автоматически."; + hint = L"Дверь и станок требуют по 2 дерева, шкаф — 1 дерево, стойка — по 1 дереву и камню."; } const auto previous_font = dock_font ? SelectObject(dc, dock_font) : nullptr; const int margin = dock_pixels(12); @@ -2018,9 +2032,17 @@ void draw_world(HDC dc, int width, int height) { if (work_panel == WorkPanel::Carpenter) { const auto orders = std::count_if(world->production_orders().begin(), world->production_orders().end(), [](const auto& order) { - return order.recipe == settlement::RecipeId::CraftWoodenDoor && order.state != settlement::JobState::Completed; + return settlement::is_carpentry_recipe(order.recipe) && order.state != settlement::JobState::Completed; }); - details = L"Заказов на двери " + std::to_wstring(orders); + using settlement::ItemType; + const auto stock = [](ItemType item) { + std::uint64_t count = 0; + for (const auto& storage : world->storages()) count += storage.available_item_count(item); + return std::to_wstring(count); + }; + details = L"Заказы " + std::to_wstring(orders) + L" Двери " + stock(ItemType::WoodenDoor) + + L" Шкафы " + stock(ItemType::MedicineCabinet) + L" Стойки " + stock(ItemType::MiningRack) + + L" Станки " + stock(ItemType::Loom); if (!has_carpenter()) { details += L" Назначьте плотника в списке «Жители»."; } @@ -2420,10 +2442,17 @@ LRESULT CALLBACK window_proc(HWND window, UINT message, WPARAM wparam, LPARAM lp update_status(); return 0; } - if (LOWORD(wparam) == craft_door_id && HIWORD(wparam) == BN_CLICKED && + if (HIWORD(wparam) == BN_CLICKED && + (LOWORD(wparam) == craft_door_id || (LOWORD(wparam) >= first_furniture_craft_id && + LOWORD(wparam) < first_furniture_craft_id + static_cast(furniture_products.size()))) && world && world->carpenter_workshop() && can_give_orders()) { - if (send_command(settlement::CommandKind::CraftDoor)) { - placement_message = lan.is_guest() ? L"Заказ на дверь отправлен." : L"Дверь заказана в мастерской."; + const bool is_furniture_order = LOWORD(wparam) != craft_door_id; + const int furniture_index = static_cast(LOWORD(wparam)) - first_furniture_craft_id; + const bool accepted = is_furniture_order ? send_command(settlement::CommandKind::CraftFurniture, {}, + static_cast(furniture_products[static_cast(furniture_index)])) : + send_command(settlement::CommandKind::CraftDoor); + if (accepted) { + placement_message = lan.is_guest() ? L"Заказ отправлен хозяину." : L"Заказ принят мастерской."; } SetFocus(window); invalidate_scene(window); diff --git a/docs/viewer.md b/docs/viewer.md index 38815eb..455b74f 100644 --- a/docs/viewer.md +++ b/docs/viewer.md @@ -30,6 +30,8 @@ powershell.exe -NoProfile -ExecutionPolicy Bypass -File .\build.ps1 Новые комнаты и готовые дома требуют деревянную дверь как предмет. Если на складе нет свободной двери, «Начать стройку» автоматически ставит заказ в мастерскую. В списке «Жители» назначьте плотника. Он заберёт со склада две единицы дерева, сделает дверь за верстаком и отнесёт её на склад. Строитель или разнорабочий заберёт оттуда готовую дверь и установит её. Чтобы заготовить двери заранее, откройте «Работы → Плотник» и выберите «Изготовить дверь». +Аптечный шкаф, стойка шахтёра и ткацкий станок для готовых домов также заказываются у плотника. Для шкафа нужно одно дерево, для стойки — дерево и камень, для станка — два дерева. Плотник доставляет готовый предмет на склад, а строитель забирает и устанавливает его после укладки пола. Подходящие предметы из запаса идут в работу без нового заказа. Изготовить мебель заранее можно в панели «Работы → Плотник». Отдельный станок из меню «Строительство» тоже требует готовый станок со склада. Если запаса нет, утверждение чертежа создаст заказ для плотника. + Жители отдельно доставляют основу, ткань для настила и ткань для подушки. Каждая деталь появляется после завершения своего этапа. Камень и ткань доступны в стартовых запасах. Жители получают по одному готовому месту. Уставшие жители работают медленнее и после поручения идут к закреплённой кровати. На земле они отдыхают только при сильной усталости и восстанавливают меньше сил. Щелчок по жителю показывает усталость и состояние сна. diff --git a/engine/include/settlement/core/world.hpp b/engine/include/settlement/core/world.hpp index eb81080..fc70338 100644 --- a/engine/include/settlement/core/world.hpp +++ b/engine/include/settlement/core/world.hpp @@ -53,9 +53,16 @@ enum class ItemType : std::uint8_t { Berries, Cloth, Flax, - WoodenDoor + WoodenDoor, + MedicineCabinet, + MiningRack, + Loom }; -inline constexpr std::size_t item_type_count = static_cast(ItemType::WoodenDoor); +inline constexpr std::size_t item_type_count = static_cast(ItemType::Loom); + +constexpr bool is_carpentry_item(ItemType item) noexcept { + return item >= ItemType::WoodenDoor && item <= ItemType::Loom; +} enum class StorageKind : std::uint8_t { Materials, Pantry }; enum class ResourceSite : std::uint8_t { Natural, BerryField, TreePlot, Mine, FlaxField }; @@ -86,7 +93,13 @@ enum class RecipeId : std::uint8_t { BuildLoom, InstallDoorAlongX, InstallDoorAlongY, - CraftWoodenDoor + CraftWoodenDoor, + InstallMedicineCabinet, + InstallMiningRack, + InstallLoom, + CraftMedicineCabinet, + CraftMiningRack, + CraftLoom }; enum class BedBase : std::uint8_t { Wood, Stone }; enum class BedStage : std::uint8_t { Legacy, Foundation, Bedding, Pillow }; @@ -104,11 +117,26 @@ constexpr bool is_room_part(RecipeId recipe) noexcept { constexpr bool is_construction(RecipeId recipe) noexcept { return recipe == RecipeId::BuildCabin || recipe == RecipeId::BuildBed || - (recipe >= RecipeId::BuildFloor && recipe <= RecipeId::InstallDoorAlongY); + (recipe >= RecipeId::BuildFloor && recipe <= RecipeId::InstallDoorAlongY) || + (recipe >= RecipeId::InstallMedicineCabinet && recipe <= RecipeId::InstallLoom); +} + +constexpr bool is_carpentry_recipe(RecipeId recipe) noexcept { + return recipe == RecipeId::CraftWoodenDoor || + (recipe >= RecipeId::CraftMedicineCabinet && recipe <= RecipeId::CraftLoom); +} + +constexpr RecipeId furnishing_shape(RecipeId recipe) noexcept { + switch (recipe) { + case RecipeId::InstallMedicineCabinet: return RecipeId::BuildMedicineCabinet; + case RecipeId::InstallMiningRack: return RecipeId::BuildMiningRack; + case RecipeId::InstallLoom: return RecipeId::BuildLoom; + default: return recipe; + } } constexpr bool delivers_materials(RecipeId recipe) noexcept { - return is_construction(recipe) || recipe == RecipeId::CraftWoodenDoor; + return is_construction(recipe) || is_carpentry_recipe(recipe); } enum class RoomSide : std::uint8_t { North, East, South, West }; @@ -141,7 +169,7 @@ enum class CommandKind : std::uint8_t { PlaceBed = 0, SetForaging = 1, SetPriority = 2, SetPaused = 3, PlaceBerryField = 4, PlaceTreePlot = 5, PlaceMine = 6, MoveObject = 7, DemolishObject = 8, PlaceStorage = 9, AssignProfession = 10, PlaceFlaxField = 11, PlaceLoom = 12, PlaceRoom = 13, - CraftDoor = 14 + CraftDoor = 14, CraftFurniture = 15 }; enum class CommandStatus : std::uint8_t { Accepted, Unavailable, Unauthorized, WrongSequence, InvalidTarget, Busy }; @@ -336,6 +364,7 @@ public: [[nodiscard]] bool can_place_room(const RoomPlan& plan) const noexcept; [[nodiscard]] std::array construction_materials(RecipeId recipe, BedBase base) const; [[nodiscard]] RecipeId room_construction_recipe(RecipeId part) const noexcept; + [[nodiscard]] std::array carpentry_materials(RecipeId recipe) const; [[nodiscard]] std::optional carpenter_workshop() const noexcept { if (!scenario_active_) return std::nullopt; return scenario_sawmill_; @@ -397,7 +426,7 @@ private: void finish_rest_step(Agent& agent); void advance_construction_delivery(Agent& agent); void finish_production(Agent& agent); - [[nodiscard]] std::size_t missing_door_orders(std::size_t new_installations = 0) const; + [[nodiscard]] std::size_t missing_carpentry_orders(ItemType product, std::size_t new_installations = 0) const; void update_scenario(); [[nodiscard]] bool resting_at(GridPosition position, AgentId except = 0) const noexcept; [[nodiscard]] bool ground_rest_cell(GridPosition position, AgentId agent) const noexcept; diff --git a/engine/src/world.cpp b/engine/src/world.cpp index 10b05e2..fcadab4 100644 --- a/engine/src/world.cpp +++ b/engine/src/world.cpp @@ -75,6 +75,12 @@ const Recipe& recipe_for(RecipeId id) { 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 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}; switch (id) { case RecipeId::SawPlank: return saw; case RecipeId::CutStoneBlock: return cut; @@ -91,10 +97,30 @@ const Recipe& recipe_for(RecipeId id) { case RecipeId::InstallDoorAlongX: case RecipeId::InstallDoorAlongY: return install_door; case RecipeId::CraftWoodenDoor: return craft_door; + case RecipeId::CraftMedicineCabinet: return craft_cabinet; + case RecipeId::CraftMiningRack: return craft_rack; + case RecipeId::CraftLoom: return craft_loom; + case RecipeId::InstallMedicineCabinet: return install_cabinet; + case RecipeId::InstallMiningRack: return install_rack; + case RecipeId::InstallLoom: return install_loom; } throw std::invalid_argument("unknown production recipe"); } +constexpr ItemType carpentry_products[] = { + ItemType::WoodenDoor, ItemType::MedicineCabinet, ItemType::MiningRack, ItemType::Loom, +}; + +RecipeId recipe_for_carpentry_item(ItemType item) { + switch (item) { + case ItemType::WoodenDoor: return RecipeId::CraftWoodenDoor; + case ItemType::MedicineCabinet: return RecipeId::CraftMedicineCabinet; + case ItemType::MiningRack: return RecipeId::CraftMiningRack; + case ItemType::Loom: return RecipeId::CraftLoom; + default: throw std::invalid_argument("unknown carpentry item"); + } +} + Recipe recipe_for(const ProductionOrder& order) { Recipe recipe = recipe_for(order.recipe); if (order.recipe == RecipeId::BuildBed) recipe.ingredients[0].type = order.bed_material(); @@ -301,13 +327,13 @@ void World::set_blocked(GridPosition position, bool blocked) { } for (const Agent& agent : agents_) { if (agent.production_index != no_entity_index && - production_orders_[agent.production_index].recipe == RecipeId::CraftWoodenDoor && + is_carpentry_recipe(production_orders_[agent.production_index].recipe) && std::find(agent.haul_route.begin(), agent.haul_route.end(), position) != agent.haul_route.end()) { throw std::logic_error("cannot block the carpenter's delivery route"); } if (agent.production_index == no_entity_index && agent.state != AgentState::GoingToEat && agent.state != AgentState::GoingToSleep && - agent.inventory.item_count(ItemType::WoodenDoor) == 0) continue; + !is_carpentry_item(agent.inventory.first_item())) continue; const auto remaining = agent.route.begin() + static_cast(agent.route_cursor); if (std::find(remaining, agent.route.end(), position) != agent.route.end()) { throw std::logic_error("cannot block an active production, meal, or sleep route"); @@ -400,8 +426,8 @@ void World::queue_production(GridPosition position, RecipeId recipe) { if (!is_walkable(position)) { throw std::invalid_argument("production site must be on a walkable cell"); } - if (recipe == RecipeId::CraftWoodenDoor && carpenter_workshop() != position) { - throw std::invalid_argument("wooden doors need the carpenter's workshop"); + if (is_carpentry_recipe(recipe) && carpenter_workshop() != position) { + throw std::invalid_argument("carpentry orders need the carpenter's workshop"); } if (is_production_object(recipe) && !can_place_storage(position)) { throw std::invalid_argument("the production site is occupied"); @@ -464,26 +490,34 @@ RecipeId World::room_construction_recipe(RecipeId part) const noexcept { if (scenario_active_) { if (part == RecipeId::BuildDoorAlongX) return RecipeId::InstallDoorAlongX; if (part == RecipeId::BuildDoorAlongY) return RecipeId::InstallDoorAlongY; + if (part == RecipeId::BuildMedicineCabinet) return RecipeId::InstallMedicineCabinet; + if (part == RecipeId::BuildMiningRack) return RecipeId::InstallMiningRack; + if (part == RecipeId::BuildLoom) return RecipeId::InstallLoom; } return part; } -std::size_t World::missing_door_orders(std::size_t new_installations) const { +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) const { + const auto craft = recipe_for_carpentry_item(product); std::uint64_t waiting_installations = new_installations, supply = 0; for (const auto& order : production_orders_) { - if (order.recipe == RecipeId::CraftWoodenDoor && order.state != JobState::Completed) ++supply; - if (order.state == JobState::Available && - (order.recipe == RecipeId::InstallDoorAlongX || order.recipe == RecipeId::InstallDoorAlongY)) { + if (order.recipe == craft && order.state != JobState::Completed) ++supply; + if (order.state == JobState::Available && is_construction(order.recipe) && + recipe_for(order).ingredients.front().type == product) { ++waiting_installations; } } for (const auto& agent : agents_) { if (agent.state == AgentState::Hauling && agent.production_index == no_entity_index) { - supply += agent.inventory.item_count(ItemType::WoodenDoor); + supply += agent.inventory.item_count(product); } } for (const auto& storage : storages_) { - const auto available = storage.available_item_count(ItemType::WoodenDoor); + const auto available = storage.available_item_count(product); if (available != 0 && find_path(scenario_sawmill_, storage.position).reachable) supply += available; } return waiting_installations > supply ? static_cast(waiting_installations - supply) : 0; @@ -613,7 +647,10 @@ CommandStatus World::edit_object(GridPosition position, const GridPosition* dest if (storage != storages_.end()) { if (destination) storage->position = *destination; else { - const bool loses_doors = storage->item_count(ItemType::WoodenDoor) != 0; + std::array lost_products{}; + for (std::size_t i = 0; i < std::size(carpentry_products); ++i) { + lost_products[i] = storage->item_count(carpentry_products[i]) != 0; + } const auto removed = static_cast(storage - storages_.begin()); storages_.erase(storage); for (auto& agent : agents_) shift_index(agent.storage_index, removed); @@ -621,9 +658,15 @@ CommandStatus World::edit_object(GridPosition position, const GridPosition* dest for (auto& material : entry.materials) shift_index(material.storage_index, removed); for (auto& stop : entry.delivery_stops) shift_index(stop.storage_index, removed); } - if (scenario_active_ && loses_doors) { - const auto missing = missing_door_orders(); - for (std::size_t i = 0; i < missing; ++i) queue_production(scenario_sawmill_, RecipeId::CraftWoodenDoor); + if (scenario_active_) { + for (std::size_t i = 0; i < std::size(carpentry_products); ++i) { + if (!lost_products[i]) continue; + const auto product = carpentry_products[i]; + const auto missing = missing_carpentry_orders(product); + for (std::size_t j = 0; j < missing; ++j) { + queue_production(scenario_sawmill_, recipe_for_carpentry_item(product)); + } + } } } return CommandStatus::Accepted; @@ -740,11 +783,24 @@ CommandReceipt World::apply_command(const PlayerCommand& command) { if (!can_place_storage(command.cell) || !can_reach_object_cell(command.cell)) { return receipt(CommandStatus::InvalidTarget); } - queue_production(command.cell, RecipeId::WeaveCloth); + if (scenario_active_) { + const auto missing = missing_carpentry_orders(ItemType::Loom, 1); + production_orders_.reserve(production_orders_.size() + 1 + missing); + queue_production(command.cell, RecipeId::InstallLoom); + for (std::size_t i = 0; i < missing; ++i) queue_production(scenario_sawmill_, RecipeId::CraftLoom); + } else { + queue_production(command.cell, RecipeId::WeaveCloth); + } break; case CommandKind::CraftDoor: queue_production(scenario_sawmill_, RecipeId::CraftWoodenDoor); break; + case CommandKind::CraftFurniture: { + const auto product = static_cast(command.value); + if (!is_carpentry_item(product) || product == ItemType::WoodenDoor) return receipt(CommandStatus::InvalidTarget); + queue_production(scenario_sawmill_, recipe_for_carpentry_item(product)); + break; + } case CommandKind::PlaceRoom: { const auto plan = RoomPlan::from_placement(command.cell, command.destination, command.value); if (!can_place_room(plan) || !can_reach_object_cell(plan.first)) { @@ -754,15 +810,18 @@ CommandReceipt World::apply_command(const PlayerCommand& command) { const auto height = static_cast(plan.last.y - plan.first.y + 1); const auto furnishings = plan.furnishings(); const bool legacy_bed = furnishings.has_value() && !staged_beds_; - const auto door_orders = scenario_active_ ? missing_door_orders(1) : 0; + const auto door_orders = scenario_active_ ? missing_carpentry_orders(ItemType::WoodenDoor, 1) : 0; + const auto fixture = furnishings ? room_construction_recipe(furnishings->back().recipe) : RecipeId::BuildFloor; + const auto fixture_item = furnishings ? recipe_for(fixture).ingredients.front().type : ItemType::None; + const auto fixture_orders = furnishings ? missing_carpentry_orders(fixture_item, 1) : 0; production_orders_.reserve(production_orders_.size() + width * height + - (furnishings ? furnishings->size() : 0) + (legacy_bed ? 1U : 0U) + door_orders); + (furnishings ? furnishings->size() : 0) + (legacy_bed ? 1U : 0U) + door_orders + fixture_orders); if (legacy_bed) queue_production(scenario_sawmill_, RecipeId::SawPlank); if (furnishings) { for (const auto& part : *furnishings) { ProductionOrder order{}; order.position = part.position; - order.recipe = part.recipe; + order.recipe = room_construction_recipe(part.recipe); order.bed_base = part.bed_base; if (order.recipe == RecipeId::BuildBed && staged_beds_) order.bed_stage = BedStage::Foundation; production_orders_.push_back(std::move(order)); @@ -778,6 +837,9 @@ CommandReceipt World::apply_command(const PlayerCommand& command) { } } for (std::size_t i = 0; i < door_orders; ++i) queue_production(scenario_sawmill_, RecipeId::CraftWoodenDoor); + for (std::size_t i = 0; i < fixture_orders; ++i) { + queue_production(scenario_sawmill_, recipe_for_carpentry_item(fixture_item)); + } break; } case CommandKind::PlaceStorage: @@ -1217,7 +1279,7 @@ void World::assign_production_tasks(bool weaving) { if (site_busy) continue; const Recipe recipe = recipe_for(order); - const bool door_craft = order.recipe == RecipeId::CraftWoodenDoor; + const bool carpentry = is_carpentry_recipe(order.recipe); const bool deliver_ingredients = delivers_materials(order.recipe); enum class Access { Unknown, Reachable, Unreachable }; std::vector storage_access(deliver_ingredients || weaving ? storages_.size() : 0, Access::Unknown); @@ -1269,12 +1331,12 @@ void World::assign_production_tasks(bool weaving) { ? storages_[stops.front().storage_index].position : order.position; for (Agent& agent : agents_) { const bool can_craft = agent.profession == Profession::Carpenter; - const bool eligible = door_craft ? can_craft : + const bool eligible = carpentry ? can_craft : can_take_work(agent, Profession::Builder) || (can_craft && order.recipe == RecipeId::SawPlank); if (agent.state != AgentState::Idle || !eligible) continue; auto path = assignment_path(agent.position, destination); if (!path.reachable) continue; - if (door_craft) { + if (carpentry) { agent.haul_route = assignment_path(order.position, storages_[materials.front().storage_index].position).positions; } @@ -1437,8 +1499,8 @@ void World::advance_construction_delivery(Agent& agent) { agent.inventory.add(material.type, material.count); } } - if (order.recipe == RecipeId::CraftWoodenDoor && stop.storage_index == order.materials.front().storage_index) { - // The wood just collected frees a slot for the completed door. + if (is_carpentry_recipe(order.recipe) && stop.storage_index == order.materials.front().storage_index) { + // Collecting the first ingredient frees a slot for the finished item. ++storages_[stop.storage_index].reserved_slots; } ++order.collected_stops; @@ -1451,7 +1513,7 @@ void World::finish_production(Agent& agent) { ProductionOrder& order = production_orders_[agent.production_index]; const Recipe recipe = recipe_for(order); assert(!order.materials.empty()); - if (order.recipe == RecipeId::CraftWoodenDoor) { + if (is_carpentry_recipe(order.recipe)) { agent.inventory.add(recipe.output); agent.storage_index = order.materials.front().storage_index; agent.route = std::move(agent.haul_route); @@ -1475,7 +1537,7 @@ void World::finish_production(Agent& agent) { (order.bed_stage == BedStage::Foundation || order.bed_stage == BedStage::Bedding)) { order.bed_stage = order.bed_stage == BedStage::Foundation ? BedStage::Bedding : BedStage::Pillow; order.state = JobState::Available; - } else if (order.recipe == RecipeId::BuildLoom) { + } else if (furnishing_shape(order.recipe) == RecipeId::BuildLoom) { order.recipe = RecipeId::WeaveCloth; order.state = JobState::Available; } else if (order.recipe == RecipeId::WeaveCloth) { diff --git a/engine/src/world_save.cpp b/engine/src/world_save.cpp index f723d46..217d3b2 100644 --- a/engine/src/world_save.cpp +++ b/engine/src/world_save.cpp @@ -13,7 +13,7 @@ namespace settlement { namespace { constexpr std::string_view signature = "SETTLERS"; -constexpr std::uint32_t save_version = 12; +constexpr std::uint32_t save_version = 13; constexpr std::uint32_t last_legacy_footer_version = 8; constexpr std::size_t max_records = 1'000'000; constexpr std::size_t max_save_bytes = 128 * 1024 * 1024; @@ -174,7 +174,8 @@ void flag(Archive& archive, Flag& value) { struct WorldSaveCodec { template static void body(Archive& archive, State& world, std::uint32_t version) { - const auto max_item = version >= 12 ? ItemType::WoodenDoor : (version >= 7 ? ItemType::Flax : ItemType::Cloth); + const auto max_item = version >= 13 ? ItemType::Loom : + version >= 12 ? ItemType::WoodenDoor : (version >= 7 ? ItemType::Flax : ItemType::Cloth); const auto max_item_count = static_cast(max_item); archive.field(world.tick_); archive.field(world.path_searches_); @@ -259,6 +260,7 @@ struct WorldSaveCodec { require_save(version >= 10 || order.recipe <= RecipeId::WeaveCloth, "Unknown recipe for save version."); require_save(version >= 11 || order.recipe <= RecipeId::BuildDoorAlongY, "Unknown recipe for save version."); require_save(version >= 12 || order.recipe <= RecipeId::BuildLoom, "Unknown recipe for save version."); + require_save(version >= 13 || order.recipe <= RecipeId::CraftWoodenDoor, "Unknown recipe for save version."); archive.field(order.state); sequence(archive, order.materials, item_types, [&](auto& material) { index(archive, material.storage_index); @@ -365,10 +367,10 @@ void WorldSaveCodec::validate(const World& world) { std::vector bed_owners; for (std::size_t i = 0; i < world.production_orders_.size(); ++i) { const auto& order = world.production_orders_[i]; - invalid(order.recipe <= RecipeId::CraftWoodenDoor && order.state <= JobState::Completed && + invalid(order.recipe <= RecipeId::CraftLoom && order.state <= JobState::Completed && world.is_walkable(order.position) && (order.recipe != RecipeId::WeaveCloth || order.state != JobState::Completed)); - invalid(order.recipe != RecipeId::CraftWoodenDoor || world.carpenter_workshop() == order.position); + invalid(!is_carpentry_recipe(order.recipe) || world.carpenter_workshop() == order.position); invalid(order.bed_base <= BedBase::Stone && order.bed_stage <= BedStage::Pillow && (order.bed_stage == BedStage::Legacy || (world.staged_beds_ && order.recipe == RecipeId::BuildBed)) && @@ -429,7 +431,14 @@ void WorldSaveCodec::validate(const World& world) { break; case RecipeId::BuildBed: required[item_index(order.bed_material())] = 1; break; case RecipeId::WeaveCloth: required[item_index(ItemType::Flax)] = 1; break; - case RecipeId::CraftWoodenDoor: required[item_index(ItemType::Wood)] = 2; break; + case RecipeId::CraftWoodenDoor: + case RecipeId::CraftMedicineCabinet: + case RecipeId::CraftMiningRack: + case RecipeId::CraftLoom: + for (const auto& item : world.carpentry_materials(order.recipe)) { + if (item.count) required[item_index(item.type)] = item.count; + } + break; case RecipeId::BuildFloor: case RecipeId::BuildWall: case RecipeId::BuildDoorAlongX: @@ -439,6 +448,9 @@ void WorldSaveCodec::validate(const World& world) { case RecipeId::BuildLoom: case RecipeId::InstallDoorAlongX: case RecipeId::InstallDoorAlongY: + case RecipeId::InstallMedicineCabinet: + case RecipeId::InstallMiningRack: + case RecipeId::InstallLoom: for (const auto& item : world.construction_materials(order.recipe, order.bed_base)) { if (item.count) required[item_index(item.type)] = item.count; } @@ -468,9 +480,9 @@ void WorldSaveCodec::validate(const World& world) { const bool has_source = agent.resource_node_index != no_entity_index; const bool has_storage = agent.storage_index != no_entity_index; invalid(!has_storage || agent.storage_index < world.storages_.size()); - const bool door_craft = has_order && agent.production_index < world.production_orders_.size() && - world.production_orders_[agent.production_index].recipe == RecipeId::CraftWoodenDoor; - invalid(agent.haul_route.empty() || has_source || door_craft); + const bool carpentry = has_order && agent.production_index < world.production_orders_.size() && + is_carpentry_recipe(world.production_orders_[agent.production_index].recipe); + invalid(agent.haul_route.empty() || has_source || carpentry); if (has_job) { invalid(!has_order && !has_storage && !has_source && agent.inventory.empty() && (agent.state == Travelling || agent.state == Working) && agent.work_remaining > 0); @@ -491,11 +503,16 @@ void WorldSaveCodec::validate(const World& world) { } else { invalid(agent.state == Working || (agent.state == Travelling && !delivers_materials(order.recipe))); } - if (door_craft) { + if (carpentry) { const auto storage = order.materials.front().storage_index; const auto destination = world.storages_[storage].position; invalid(agent.haul_route.empty() ? destination == order.position : agent.haul_route.back() == destination); - if (order.delivery_stops.empty() || order.collected_stops > 0) ++reserved_slots[storage]; + const auto& stops = order.delivery_stops; + const auto output_stop = std::find_if(stops.begin(), stops.end(), + [storage](const auto& stop) { return stop.storage_index == storage; }); + const bool collected = stops.empty() || + static_cast(output_stop - stops.begin()) < order.collected_stops; + if (collected) ++reserved_slots[storage]; } for (std::size_t i = 0; i < item_types; ++i) { invalid(agent.inventory.item_count(static_cast(i + 1)) == expected_cargo[agent.production_index][i]); @@ -515,7 +532,7 @@ void WorldSaveCodec::validate(const World& world) { } else if (agent.state == Hauling) { const auto cargo = agent.inventory.first_item(); invalid(has_storage && (cargo == ItemType::Wood || cargo == ItemType::Stone || - cargo == ItemType::Berries || cargo == ItemType::Flax || cargo == ItemType::WoodenDoor) && + cargo == ItemType::Berries || cargo == ItemType::Flax || is_carpentry_item(cargo)) && agent.inventory.item_count(cargo) == 1 && agent.work_remaining == 0 && world.storages_[agent.storage_index].accepts(cargo)); for (std::size_t i = 1; i <= item_types; ++i) { diff --git a/tests/core_tests.cpp b/tests/core_tests.cpp index 3ef6b6c..e7de8ea 100644 --- a/tests/core_tests.cpp +++ b/tests/core_tests.cpp @@ -60,6 +60,7 @@ struct CoreTests : Void::Testing::Suite { [[= Void::Testing::tag("construction")]] Test test_room_builds_and_saves_as_separate_parts(); [[= Void::Testing::tag("construction")]] Test test_furnished_rooms_queue_and_build_their_contents(); [[= Void::Testing::tag("construction")]] Test test_carpenter_delivers_the_door_before_installation(); + [[= Void::Testing::tag("construction")]] Test test_carpenter_makes_furnishings_for_rooms(); }; Test CoreTests::test_parallel_pathfinding_completes_the_jobs() { @@ -643,10 +644,12 @@ Test CoreTests::test_flax_and_loom_supply_a_bed_without_starting_cloth() { World world(92, 12, 12, 3); const auto farmer = world.spawn_agent({2, 3}); const auto builder = world.spawn_agent({4, 4}); + const auto carpenter = world.spawn_agent({5, 2}); 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.stock_storage(materials, ItemType::Wood, 2); world.start_scenario({4, 2}); const auto send = [&](CommandKind kind, GridPosition cell = {}, std::uint8_t value = 0, GridPosition destination = {}, AgentId resident = 0) { @@ -665,13 +668,24 @@ Test CoreTests::test_flax_and_loom_supply_a_bed_without_starting_cloth() { 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.production_orders().front().recipe == RecipeId::InstallLoom && + world.production_orders().front().position == moved_loom && + world.production_orders()[1].recipe == RecipeId::CraftLoom, + "placing or moving the loom bypassed or duplicated its craft order"); require(world.resource_nodes().front().needs_tending(), "flax started growing before being planted"); + for (int i = 0; i < 24; ++i) world.step(); + require(world.production_orders().front().state == JobState::Available && + world.production_orders()[1].state == JobState::Available && + world.storages().front().available_item_count(ItemType::Wood) == 2, + "the loom was installed or crafted without a carpenter"); + require(send(CommandKind::AssignProfession, {}, static_cast(Profession::Carpenter), {}, carpenter) == + CommandStatus::Accepted, "could not assign a carpenter for the loom"); 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) { + for (int i = 0; i < 500; ++i) { world.step(); restored->step(); require(save_contents(world) == save_contents(*restored), "textile work diverged after loading"); @@ -680,8 +694,8 @@ Test CoreTests::test_flax_and_loom_supply_a_bed_without_starting_cloth() { 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 && + if (!saved_active_weaving && loom_order.recipe == RecipeId::WeaveCloth && loom_order.state == JobState::InProgress) { + require(world.agents()[1].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); @@ -696,6 +710,9 @@ Test CoreTests::test_flax_and_loom_supply_a_bed_without_starting_cloth() { 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"); + require(world.storages().front().item_count(ItemType::Wood) == 0 && + world.storages().front().item_count(ItemType::Loom) == 0, + "the installed loom did not consume the materials and finished item exactly once"); return {}; } @@ -855,9 +872,9 @@ Test CoreTests::test_furnished_rooms_queue_and_build_their_contents() { require(place(2, 255) == CommandStatus::InvalidTarget && world.production_orders().empty(), "an unknown layout partially queued a room"); require(place(2, plan.placement_value()) == CommandStatus::Accepted && - world.production_orders().size() == 19, "the furnished room did not queue construction and the door"); + world.production_orders().size() == 20, "the furnished room did not queue construction and carpentry"); require(place(1, plan.placement_value()) == CommandStatus::InvalidTarget && - world.production_orders().size() == 19, "an overlapping furnished room left duplicate orders"); + world.production_orders().size() == 20, "an overlapping furnished room left duplicate orders"); const auto floor_is_done = [&](const World& state, GridPosition cell) { return std::any_of(state.production_orders().begin(), state.production_orders().end(), [cell](const auto& order) { @@ -885,7 +902,7 @@ Test CoreTests::test_furnished_rooms_queue_and_build_their_contents() { require(furniture.recipe == WeaveCloth && resumed->storages().front().item_count(ItemType::Cloth) == 1, "the built loom did not process flax"); } else { - require(furniture.recipe == fixture && furniture.state == JobState::Completed, + require(furnishing_shape(furniture.recipe) == fixture && furniture.state == JobState::Completed, "the themed furnishing did not finish"); } static_cast(save_roundtrip(*resumed)); @@ -981,6 +998,118 @@ Test CoreTests::test_carpenter_delivers_the_door_before_installation() { return {}; } +Test CoreTests::test_carpenter_makes_furnishings_for_rooms() { + using namespace settlement; + struct Variant { + RoomTemplate layout; + ItemType item; + RecipeId craft; + RecipeId installation; + }; + const Variant variants[] = { + {RoomTemplate::Doctor, ItemType::MedicineCabinet, RecipeId::CraftMedicineCabinet, RecipeId::InstallMedicineCabinet}, + {RoomTemplate::Miner, ItemType::MiningRack, RecipeId::CraftMiningRack, RecipeId::InstallMiningRack}, + {RoomTemplate::Weaver, ItemType::Loom, RecipeId::CraftLoom, RecipeId::InstallLoom}, + }; + for (const auto& variant : variants) { + auto world = std::make_unique(64, 20, 18); + const auto builder = world->spawn_agent({5, 3}); + const auto carpenter = world->spawn_agent({3, 3}); + // Stone is at the first delivery stop, but the product returns to the wood store. + const auto stone = world->add_storage({2, 3}, 6); + const auto wood = world->add_storage({3, 4}, 48); + world->stock_storage(stone, ItemType::Stone, 4); + world->stock_storage(wood, ItemType::Wood, 38); + world->stock_storage(wood, ItemType::Cloth, 2); + world->stock_storage(wood, ItemType::Flax, 1); + const GridPosition workshop{4, 3}; + world->start_scenario(workshop); + auto send = [&](CommandKind kind, GridPosition cell = {}, std::uint8_t value = 0, + GridPosition target = {}, AgentId resident = 0) { + return world->apply_command({1, world->next_command_sequence(1), kind, cell, value, target, resident}).status; + }; + const RoomPlan plan{{6, 5}, {9, 8}, RoomSide::East, variant.layout}; + require(send(CommandKind::AssignProfession, {}, static_cast(Profession::Builder), {}, builder) == + CommandStatus::Accepted && + send(CommandKind::PlaceRoom, plan.first, plan.placement_value(), plan.last) == CommandStatus::Accepted, + "could not place the furnished room"); + const auto count_orders = [&](RecipeId recipe) { + return std::count_if(world->production_orders().begin(), world->production_orders().end(), + [recipe](const auto& order) { return order.recipe == recipe; }); + }; + require(count_orders(variant.craft) == 1 && count_orders(variant.installation) == 1, + "the blueprint did not request its furnishing"); + for (int tick = 0; tick < 180; ++tick) world->step(); + require(std::all_of(world->production_orders().begin(), world->production_orders().end(), + [&](const auto& order) { + return (order.recipe != variant.craft && order.recipe != variant.installation) || + order.state == JobState::Available; + }), "a generalist or builder bypassed the carpenter"); + require(send(CommandKind::AssignProfession, {}, static_cast(Profession::Carpenter), {}, carpenter) == + CommandStatus::Accepted, "could not assign the carpenter"); + + bool saved_stone_stop = false, saved_workshop = false, saved_delivery = false, saved_installation = false; + const auto fixture = plan.furnishings()->back().position; + for (int tick = 0; tick < 900; ++tick) { + world->step(); + const auto& maker = world->agents()[1]; + if (variant.item == ItemType::MiningRack && !saved_stone_stop && + maker.production_index != no_entity_index && + world->production_orders()[maker.production_index].recipe == variant.craft && + maker.inventory.item_count(ItemType::Stone) != 0 && maker.inventory.item_count(ItemType::Wood) == 0) { + require(world->storages()[1].reserved_slots == 0, "output space was reserved before collecting wood"); + saved_stone_stop = true; + world = save_roundtrip(*world); + continue; + } + if (!saved_workshop && maker.state == AgentState::Working && maker.position == workshop && + maker.production_index != no_entity_index && + world->production_orders()[maker.production_index].recipe == variant.craft) { + require(world->storages()[1].reserved_slots == 1, "output space was not reserved while crafting"); + saved_workshop = true; + world = save_roundtrip(*world); + continue; + } + if (!saved_delivery && maker.inventory.item_count(variant.item) != 0) { + require(maker.state == AgentState::Hauling && world->storages()[1].item_count(variant.item) == 0, + "the furnishing appeared in stock before delivery"); + saved_delivery = true; + world = save_roundtrip(*world); + continue; + } + if (!saved_installation && world->agents()[0].inventory.item_count(variant.item) != 0) { + saved_installation = true; + world = save_roundtrip(*world); + } + } + require(saved_workshop && saved_delivery && saved_installation && + (variant.item != ItemType::MiningRack || saved_stone_stop), + "the furnishing did not survive every stage of crafting and delivery"); + const auto active_recipe = variant.item == ItemType::Loom ? RecipeId::WeaveCloth : variant.installation; + require(std::any_of(world->production_orders().begin(), world->production_orders().end(), + [&](const auto& order) { + return order.position == fixture && order.recipe == active_recipe && + (active_recipe == RecipeId::WeaveCloth || order.state == JobState::Completed); + }), "the stored furnishing was not installed"); + if (variant.item == ItemType::Loom) { + require(world->storages()[1].item_count(ItemType::Cloth) == 1, "the installed loom did not weave"); + } + + const auto existing_work = world->production_orders().size(); + require(send(CommandKind::CraftFurniture, {}, static_cast(ItemType::Wood)) == CommandStatus::InvalidTarget && + world->production_orders().size() == existing_work, "an invalid craft queued an order"); + require(send(CommandKind::CraftFurniture, {}, static_cast(variant.item)) == CommandStatus::Accepted, + "could not order a spare furnishing"); + for (int tick = 0; tick < 450 && world->storages()[1].available_item_count(variant.item) == 0; ++tick) world->step(); + require(world->storages()[1].available_item_count(variant.item) == 1, "the manual order yielded no spare"); + const RoomPlan second{{11, 5}, {14, 8}, RoomSide::East, variant.layout}; + require(send(CommandKind::PlaceRoom, second.first, second.placement_value(), second.last) == CommandStatus::Accepted && + count_orders(variant.craft) == 2, "a room ignored the matching furnishing already in stock"); + static_cast(save_roundtrip(*world)); + } + return {}; +} + } // namespace int main(int argc, char** argv) { diff --git a/tests/lan_tests.cpp b/tests/lan_tests.cpp index d3e64a9..907d1df 100644 --- a/tests/lan_tests.cpp +++ b/tests/lan_tests.cpp @@ -129,9 +129,11 @@ Test LanTests::test_shared_colony_over_loopback() { }, "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"); + const auto& orders = client_view->production_orders(); + return orders.size() >= 2 && orders.back().recipe == RecipeId::CraftLoom && + orders[orders.size() - 2].recipe == RecipeId::InstallLoom && + orders[orders.size() - 2].position == new_field; + }, "the loom installation and workshop order did not arrive in the guest snapshot"); for (int i = 0; i < 160 && authoritative->resource_nodes().back().reserved_workers == 0; ++i) { authoritative->step(); }