#define NOMINMAX #define UNICODE #define _UNICODE #include #include #include #include #include "isometric_camera.hpp" #include "lan_session.hpp" #include "settlement/core/world.hpp" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include namespace { constexpr wchar_t window_class[] = L"SettlementIsometricViewer"; constexpr wchar_t resident_window_class[] = L"SettlementResidentRoster"; constexpr int worker_combo_id = 1001; constexpr int apply_button_id = 1002; constexpr int status_label_id = 1003; constexpr int cabin_button_id = 1004; constexpr int save_menu_id = 1005; constexpr int load_menu_id = 1006; constexpr int forage_action_id = 1007; constexpr int priority_button_id = 1008; constexpr int pause_button_id = 1009; constexpr int reset_camera_id = 1010; constexpr int wood_bed_button_id = 1011; constexpr int stone_bed_button_id = 1012; constexpr int lan_host_id = 1020; constexpr int lan_join_id = 1021; constexpr int lan_info_id = 1022; constexpr int lan_reconnect_id = 1023; constexpr int lan_leave_id = 1024; constexpr int berry_field_id = 1030; constexpr int tree_plot_id = 1031; constexpr int mine_id = 1032; constexpr int storage_id = 1033; constexpr int pantry_id = 1034; constexpr int move_id = 1035; constexpr int demolish_id = 1036; constexpr int residents_button_id = 1037; constexpr int flax_field_id = 1038; constexpr int loom_id = 1039; constexpr int farmer_menu_id = 1040; constexpr int builder_menu_id = 1043; constexpr int first_work_choice_id = 1050; constexpr int resident_list_id = 1060; constexpr int first_role_id = 1070; constexpr int first_dock_section_id = 1080; constexpr int timer_id = 1; constexpr int map_size = settlement::first_colony_map_size; constexpr int tile_width = 24; constexpr int tile_height = 14; constexpr int map_origin_y = 86; constexpr int map_top = 76; constexpr int map_footer = 166; constexpr int dock_sections_offset = 40; constexpr int dock_actions_offset = 110; constexpr int dock_materials_offset = 77; constexpr int bed_choice_width = 78; constexpr int bed_choice_height = 28; constexpr int work_button_gap = 8; constexpr settlement::GridPosition sawmill{15, 14}; constexpr settlement::GridPosition stonecutter{17, 14}; HWND worker_combo = nullptr; HWND apply_button = nullptr; HWND status_label = nullptr; HWND production_label = nullptr; HWND wood_bed_button = nullptr; HWND stone_bed_button = nullptr; HWND priority_button = nullptr; HWND pause_button = nullptr; HWND residents_button = nullptr; std::array dock_section_buttons{}; std::unique_ptr world; using settlement::viewer::LanState; settlement::viewer::LanSession lan; LanState displayed_lan_state = LanState::Offline; std::size_t selected_workers = settlement::min_worker_count; enum class PlacementMode { None, Building, Foraging, BerryField, FlaxField, TreePlot, Mine, Loom, Storage, Pantry, Move, Demolish }; PlacementMode placement_mode = PlacementMode::None; enum class WorkPanel { Farmer, Woodcutter, Miner, Builder, Gathering, Zones, Construction, None }; WorkPanel work_panel = WorkPanel::None; enum class WorkIcon { Berries, Field, Flax, Tree, Pickaxe, Hammer, Loom, Resident, Bed, Wood, Stone, Crate, Pantry, Move, Demolish }; struct WorkChoice { int command; const wchar_t* title; WorkIcon icon; int width; PlacementMode mode = PlacementMode::None; }; constexpr std::array farmer_choices = { WorkChoice{forage_action_id, L"Сбор ягод", WorkIcon::Berries, 113, PlacementMode::Foraging}, WorkChoice{berry_field_id, L"Поле ягод", WorkIcon::Field, 113, PlacementMode::BerryField}, WorkChoice{flax_field_id, L"Поле льна", WorkIcon::Flax, 112, PlacementMode::FlaxField}, }; constexpr std::array woodcutter_choices = { WorkChoice{tree_plot_id, L"Посадить деревья", WorkIcon::Tree, 168, PlacementMode::TreePlot}, }; constexpr std::array miner_choices = { WorkChoice{mine_id, L"Шахта", WorkIcon::Pickaxe, 98, PlacementMode::Mine}, }; constexpr std::array builder_choices = { WorkChoice{cabin_button_id, L"Спальное место", WorkIcon::Bed, 153, PlacementMode::Building}, WorkChoice{loom_id, L"Ткацкий станок", WorkIcon::Loom, 149, PlacementMode::Loom}, WorkChoice{storage_id, L"Склад", WorkIcon::Crate, 84, PlacementMode::Storage}, WorkChoice{pantry_id, L"Кладовая", WorkIcon::Pantry, 103, PlacementMode::Pantry}, WorkChoice{move_id, L"Перенести", WorkIcon::Move, 108, PlacementMode::Move}, WorkChoice{demolish_id, L"Снести", WorkIcon::Demolish, 90, PlacementMode::Demolish}, }; std::array work_choice_buttons{}; constexpr std::array gathering_choices = {farmer_choices[0], miner_choices[0]}; constexpr std::array zones_choices = {farmer_choices[1], farmer_choices[2], woodcutter_choices[0], builder_choices[2], builder_choices[3]}; constexpr std::array construction_choices = {builder_choices[0], builder_choices[1], builder_choices[4], builder_choices[5]}; struct DockSection { WorkPanel panel; const wchar_t* title; WorkIcon icon; }; constexpr std::array dock_sections = { DockSection{WorkPanel::Gathering, L"Добыча", WorkIcon::Pickaxe}, DockSection{WorkPanel::Zones, L"Участки", WorkIcon::Field}, DockSection{WorkPanel::Construction, L"Строительство", WorkIcon::Hammer}, }; using settlement::Profession; struct RoleChoice { Profession role; const wchar_t* title; WorkIcon icon; }; constexpr std::array role_choices = { RoleChoice{Profession::Generalist, L"Разнорабочий", WorkIcon::Resident}, RoleChoice{Profession::Farmer, L"Фермер", WorkIcon::Berries}, RoleChoice{Profession::Woodcutter, L"Лесоруб", WorkIcon::Tree}, RoleChoice{Profession::Miner, L"Шахтёр", WorkIcon::Pickaxe}, RoleChoice{Profession::Builder, L"Строитель", WorkIcon::Hammer}, }; struct ResidentRow { settlement::AgentId id; Profession role; }; struct ResidentRoster { HWND window = nullptr; HWND list = nullptr; HWND current_role = nullptr; HWND notice = nullptr; HWND apply = nullptr; std::array roles{}; std::vector rows; std::optional pending_role; bool updating_selection = false; }; ResidentRoster roster; std::optional selected_bed_base; std::optional move_source; settlement::viewer::IsometricCamera camera; struct CameraDrag { POINT previous; bool left_button; bool moved; }; std::optional camera_drag; bool file_dialog_active = false; std::optional hover_cell; std::optional selected_resident; std::wstring placement_message; COLORREF color(int red, int green, int blue) { return RGB(red, green, blue); } void fill_polygon(HDC dc, const POINT* points, int count, COLORREF fill, COLORREF outline) { HBRUSH brush = CreateSolidBrush(fill); HPEN pen = CreatePen(PS_SOLID, 1, outline); HGDIOBJ old_brush = SelectObject(dc, brush); HGDIOBJ old_pen = SelectObject(dc, pen); Polygon(dc, points, count); SelectObject(dc, old_brush); SelectObject(dc, old_pen); DeleteObject(brush); DeleteObject(pen); } void fill_ellipse(HDC dc, int left, int top, int right, int bottom, COLORREF fill, COLORREF outline) { HBRUSH brush = CreateSolidBrush(fill); HPEN pen = CreatePen(PS_SOLID, 1, outline); HGDIOBJ old_brush = SelectObject(dc, brush); HGDIOBJ old_pen = SelectObject(dc, pen); Ellipse(dc, left, top, right, bottom); SelectObject(dc, old_brush); SelectObject(dc, old_pen); DeleteObject(brush); DeleteObject(pen); } void draw_work_icon(HDC dc, WorkIcon icon, int x, int y) { const auto ink = color(54, 61, 58); const auto wood = color(158, 101, 52); const auto leaf = color(76, 137, 74); const auto metal = color(143, 168, 180); const auto berry = color(180, 62, 103); const auto blue = color(91, 136, 184); const int state = SaveDC(dc); if (state == 0) return; OffsetViewportOrgEx(dc, x, y, nullptr); const auto shape = [&](std::initializer_list points, COLORREF fill) { fill_polygon(dc, points.begin(), static_cast(points.size()), fill, ink); }; const auto box = [&](int left, int top, int right, int bottom, COLORREF fill) { shape({{left, top}, {right, top}, {right, bottom}, {left, bottom}}, fill); }; const auto circle = [&](int left, int top, int right, int bottom, COLORREF fill) { fill_ellipse(dc, left, top, right, bottom, fill, ink); }; switch (icon) { case WorkIcon::Berries: shape({{8, 7}, {8, 3}, {14, 1}, {13, 5}}, leaf); circle(2, 5, 9, 12, berry); circle(9, 5, 16, 12, berry); circle(5, 9, 13, 17, berry); break; case WorkIcon::Field: shape({{1, 10}, {8, 6}, {16, 10}, {16, 12}, {8, 16}, {1, 12}}, wood); shape({{8, 11}, {3, 7}, {3, 4}, {7, 5}, {9, 8}, {12, 3}, {15, 3}, {14, 8}}, leaf); break; case WorkIcon::Flax: shape({{5, 15}, {6, 6}, {9, 8}, {10, 4}, {12, 14}, {9, 16}}, leaf); circle(3, 3, 9, 9, blue); circle(8, 1, 14, 7, blue); break; case WorkIcon::Tree: box(7, 11, 10, 16, wood); shape({{8, 1}, {13, 8}, {11, 8}, {15, 13}, {2, 13}, {6, 8}, {4, 8}}, leaf); break; case WorkIcon::Pickaxe: shape({{2, 14}, {10, 4}, {13, 6}, {5, 16}}, wood); shape({{3, 3}, {8, 1}, {14, 4}, {17, 9}, {12, 6}, {8, 4}}, metal); break; case WorkIcon::Hammer: shape({{2, 14}, {10, 5}, {13, 7}, {5, 16}}, wood); shape({{9, 1}, {16, 7}, {13, 11}, {6, 5}}, metal); break; case WorkIcon::Loom: box(2, 2, 5, 16, wood); box(12, 2, 15, 16, wood); box(2, 2, 15, 5, wood); box(5, 5, 12, 12, color(240, 230, 201)); box(2, 12, 15, 14, wood); break; case WorkIcon::Resident: circle(2, 8, 15, 17, blue); circle(5, 1, 12, 9, color(232, 194, 143)); break; case WorkIcon::Bed: box(1, 4, 3, 15, wood); box(13, 10, 16, 15, wood); box(3, 6, 7, 11, color(249, 240, 213)); box(7, 7, 16, 12, blue); break; case WorkIcon::Wood: box(2, 4, 16, 13, wood); circle(1, 4, 8, 14, color(214, 166, 98)); break; case WorkIcon::Stone: shape({{1, 12}, {4, 5}, {10, 2}, {15, 7}, {16, 13}, {6, 16}}, metal); break; case WorkIcon::Crate: case WorkIcon::Pantry: box(2, 4, 15, 15, icon == WorkIcon::Crate ? wood : leaf); box(1, 3, 16, 7, icon == WorkIcon::Crate ? color(214, 166, 98) : color(152, 183, 108)); box(7, 8, 10, 11, color(241, 205, 119)); break; case WorkIcon::Move: shape({{1, 8}, {6, 3}, {6, 6}, {11, 6}, {11, 3}, {16, 8}, {11, 13}, {11, 10}, {6, 10}, {6, 13}}, blue); break; case WorkIcon::Demolish: shape({{3, 5}, {14, 5}, {13, 16}, {4, 16}}, color(181, 102, 87)); box(6, 2, 11, 5, metal); box(2, 5, 15, 7, metal); break; } RestoreDC(dc, state); } POINT iso_point(int x, int y, int origin_x, int origin_y) { return POINT{origin_x + (x - y) * tile_width / 2, origin_y + (x + y) * tile_height / 2}; } bool shows_bed_choices() { return world && world->staged_beds() && placement_mode == PlacementMode::Building; } bool is_map_point(const RECT& client, POINT point) { return point.x >= 0 && point.x < client.right && point.y >= map_top && point.y < client.bottom - map_footer; } POINT client_point(LPARAM coordinates) { return {GET_X_LPARAM(coordinates), GET_Y_LPARAM(coordinates)}; } void invalidate_scene(HWND window) { RECT scene{}; GetClientRect(window, &scene); scene.top = map_top; if (scene.bottom > scene.top) InvalidateRect(window, &scene, FALSE); } void update_camera_drag(POINT point) { if (!camera_drag) return; const auto dx = point.x - camera_drag->previous.x; const auto dy = point.y - camera_drag->previous.y; if (camera_drag->left_button && !camera_drag->moved && std::abs(dx) < 4 && std::abs(dy) < 4) return; camera.pan(dx, dy); camera_drag->previous = point; camera_drag->moved = true; } std::optional map_cell(const RECT& client, POINT point) { if (!is_map_point(client, point)) return std::nullopt; const auto scene = camera.to_scene({static_cast(point.x), static_cast(point.y)}); const double horizontal = (scene.x - client.right / 2) / (tile_width / 2.0); const double vertical = (scene.y - map_origin_y) / (tile_height / 2.0); const double x = std::floor((vertical + horizontal) / 2.0 + 0.5); const double y = std::floor((vertical - horizontal) / 2.0 + 0.5); if (x < 0 || y < 0 || x >= map_size || y >= map_size) return std::nullopt; return settlement::GridPosition{static_cast(x), static_cast(y)}; } void update_map_hover(HWND window, POINT point) { if (placement_mode == PlacementMode::None) return; TRACKMOUSEEVENT tracking{sizeof(tracking), TME_LEAVE, window, 0}; TrackMouseEvent(&tracking); RECT client{}; GetClientRect(window, &client); const auto cell = map_cell(client, point); if (cell == hover_cell) return; hover_cell = cell; placement_message.clear(); invalidate_scene(window); } void draw_ground_tile(HDC dc, POINT center, COLORREF fill, COLORREF outline) { const POINT diamond[] = { {center.x, center.y - tile_height / 2}, {center.x + tile_width / 2, center.y}, {center.x, center.y + tile_height / 2}, {center.x - tile_width / 2, center.y} }; fill_polygon(dc, diamond, 4, fill, outline); } void draw_rock(HDC dc, POINT ground_center) { constexpr int block_height = 17; const int x = ground_center.x; const int y = ground_center.y; const POINT left_face[] = { {x - tile_width / 2, y}, {x, y + tile_height / 2}, {x, y + tile_height / 2 - block_height}, {x - tile_width / 2, y - block_height} }; const POINT right_face[] = { {x, y + tile_height / 2}, {x + tile_width / 2, y}, {x + tile_width / 2, y - block_height}, {x, y + tile_height / 2 - block_height} }; const POINT top_face[] = { {x, y - tile_height / 2 - block_height}, {x + tile_width / 2, y - block_height}, {x, y + tile_height / 2 - block_height}, {x - tile_width / 2, y - block_height} }; fill_polygon(dc, left_face, 4, color(91, 109, 103), color(70, 87, 81)); fill_polygon(dc, right_face, 4, color(67, 84, 79), color(60, 76, 71)); fill_polygon(dc, top_face, 4, color(132, 148, 132), color(76, 94, 83)); } void draw_resource(HDC dc, POINT center, settlement::ItemType type) { if (type == settlement::ItemType::Berries) { fill_ellipse(dc, center.x - 7, center.y - 7, center.x + 7, center.y + 3, color(77, 135, 67), color(51, 98, 57)); for (const POINT berry : {POINT{-3, -4}, POINT{1, -1}, POINT{3, -5}}) { fill_ellipse(dc, center.x + berry.x - 1, center.y + berry.y - 1, center.x + berry.x + 2, center.y + berry.y + 2, color(190, 76, 112), color(115, 48, 76)); } } else if (type == settlement::ItemType::Flax) { for (const POINT stalk : {POINT{-5, -4}, POINT{0, -10}, POINT{5, -6}}) { const LONG x = center.x + stalk.x; const LONG y = center.y + stalk.y; const POINT stem[] = {{x - 1, y}, {x + 1, y}, {x + 2, y + 8}, {x, y + 8}}; fill_polygon(dc, stem, 4, color(114, 160, 79), color(64, 106, 65)); fill_ellipse(dc, x - 2, y - 3, x + 3, y + 2, color(117, 160, 234), color(61, 86, 156)); } } else if (type == settlement::ItemType::Wood) { HPEN trunk = CreatePen(PS_SOLID, 2, color(104, 83, 54)); HGDIOBJ old_pen = SelectObject(dc, trunk); MoveToEx(dc, center.x, center.y + 3, nullptr); LineTo(dc, center.x, center.y - 8); SelectObject(dc, old_pen); DeleteObject(trunk); fill_ellipse(dc, center.x - 7, center.y - 13, center.x + 1, center.y - 5, color(71, 128, 69), color(62, 104, 61)); fill_ellipse(dc, center.x - 1, center.y - 17, center.x + 7, center.y - 9, color(92, 148, 77), color(62, 104, 61)); } else { const POINT rock[] = { {center.x - 7, center.y + 2}, {center.x - 5, center.y - 5}, {center.x + 2, center.y - 8}, {center.x + 7, center.y - 2}, {center.x + 6, center.y + 3} }; fill_polygon(dc, rock, 5, color(133, 143, 143), color(86, 100, 101)); } } void draw_site(HDC dc, POINT center, const settlement::ResourceNode& node) { using settlement::ResourceSite; if (node.site == ResourceSite::Mine) { const int x = center.x; const int y = center.y; const POINT pit[] = {{x - 10, y - 1}, {x, y + 5}, {x + 10, y - 1}, {x, y - 7}}; const POINT beam[] = {{x - 7, y - 2}, {x - 6, y - 10}, {x + 5, y - 10}, {x + 6, y - 2}}; fill_polygon(dc, beam, 4, color(124, 104, 78), color(66, 62, 53)); fill_polygon(dc, pit, 4, node.quantity != 0 ? color(68, 75, 79) : color(122, 122, 113), color(55, 63, 65)); return; } if (node.site != ResourceSite::Natural) { draw_ground_tile(dc, center, color(161, 125, 80), color(107, 95, 64)); if (node.quantity == 0) { if (!node.needs_tending()) { fill_ellipse(dc, center.x - 4, center.y - 3, center.x + 3, center.y + 1, color(91, 139, 80), color(64, 91, 62)); } else if (node.reserved_workers > 0) { fill_ellipse(dc, center.x - 3, center.y - 2, center.x + 3, center.y + 2, color(225, 192, 117), color(122, 99, 56)); } return; } } draw_resource(dc, center, node.type); } void draw_storage(HDC dc, POINT center, settlement::StorageKind kind) { const POINT front[] = {{center.x - 7, center.y - 1}, {center.x, center.y + 3}, {center.x, center.y - 6}, {center.x - 7, center.y - 10}}; const POINT side[] = {{center.x, center.y + 3}, {center.x + 7, center.y - 1}, {center.x + 7, center.y - 10}, {center.x, center.y - 6}}; const POINT lid[] = {{center.x - 7, center.y - 10}, {center.x, center.y - 14}, {center.x + 7, center.y - 10}, {center.x, center.y - 6}}; fill_polygon(dc, front, 4, color(165, 111, 59), color(93, 66, 42)); fill_polygon(dc, side, 4, color(128, 82, 45), color(93, 66, 42)); const COLORREF lid_color = kind == settlement::StorageKind::Pantry ? color(176, 89, 125) : color(193, 143, 84); fill_polygon(dc, lid, 4, lid_color, color(93, 66, 42)); } void draw_production(HDC dc, POINT center, const settlement::ProductionOrder& order) { using settlement::JobState; using settlement::RecipeId; if (order.recipe == RecipeId::WeaveCloth) { const auto [x, y] = center; const POINT frame[] = {{x - 8, y + 3}, {x - 8, y - 14}, {x + 8, y - 10}, {x + 8, y + 6}}; const POINT fabric[] = {{x - 5, y - 11}, {x + 5, y - 8}, {x + 5, y + 1}, {x - 5, y - 2}}; fill_polygon(dc, frame, 4, color(176, 124, 74), color(91, 63, 45)); fill_polygon(dc, fabric, 4, order.state == JobState::InProgress ? color(250, 230, 170) : color(227, 216, 194), color(127, 112, 85)); return; } if (!settlement::is_construction(order.recipe)) { const POINT bench[] = {{center.x - 8, center.y - 4}, {center.x, center.y}, {center.x + 8, center.y - 4}, {center.x, center.y - 8}}; const COLORREF fill = order.recipe == RecipeId::SawPlank ? color(180, 118, 69) : color(131, 145, 151); fill_polygon(dc, bench, 4, fill, color(65, 62, 50)); return; } if (order.state != JobState::Completed) { const COLORREF fill = order.state == JobState::Available ? color(145, 191, 205) : order.delivery_stops.empty() ? color(223, 165, 72) : color(83, 162, 150); draw_ground_tile(dc, center, fill, color(74, 111, 126)); if (order.recipe != RecipeId::BuildBed || order.bed_stage == settlement::BedStage::Legacy || order.bed_stage == settlement::BedStage::Foundation) return; } const int x = center.x; const int y = center.y; if (order.recipe == RecipeId::BuildBed) { const POINT frame[] = {{x - 10, y - 4}, {x, y + 2}, {x + 10, y - 4}, {x, y - 10}}; const POINT mattress[] = {{x - 8, y - 6}, {x, y - 1}, {x + 8, y - 6}, {x, y - 11}}; const POINT pillow[] = {{x - 6, y - 6}, {x - 3, y - 4}, {x + 1, y - 6}, {x - 2, y - 8}}; const auto frame_color = order.bed_base == settlement::BedBase::Stone ? color(148, 153, 156) : color(156, 103, 63); fill_polygon(dc, frame, 4, frame_color, color(87, 61, 44)); if (order.state == JobState::Completed || order.bed_stage == settlement::BedStage::Pillow) { fill_polygon(dc, mattress, 4, color(116, 146, 186), color(67, 85, 111)); } if (order.state == JobState::Completed) { fill_polygon(dc, pillow, 4, color(244, 234, 206), color(143, 132, 113)); } return; } const COLORREF outline = color(89, 60, 47); const POINT front[] = {{x - 11, y - 10}, {x, y - 4}, {x, y + 6}, {x - 11, y}}; const POINT side[] = {{x, y - 4}, {x + 11, y - 10}, {x + 11, y}, {x, y + 6}}; const POINT roof_left[] = {{x - 12, y - 10}, {x - 5, y - 20}, {x + 6, y - 14}, {x, y - 4}}; const POINT roof_right[] = {{x + 6, y - 14}, {x + 12, y - 10}, {x, y - 4}}; fill_polygon(dc, front, 4, color(210, 158, 98), outline); fill_polygon(dc, side, 4, color(172, 125, 74), outline); fill_polygon(dc, roof_left, 4, color(173, 83, 62), outline); fill_polygon(dc, roof_right, 3, color(135, 63, 53), outline); } POINT resident_position(POINT center, settlement::AgentId id) { const int offset = static_cast(id % 5) - 2; return {center.x + offset * 2, center.y - 4}; } POINT resident_anchor(POINT center, const settlement::Agent& agent) { if (agent.state != settlement::AgentState::Sleeping && world->is_bed_cell(agent.position) && std::any_of(world->agents().begin(), world->agents().end(), [&](const auto& other) { return other.state == settlement::AgentState::Sleeping && !other.resting_on_ground && other.position == agent.position; })) { center.x += tile_width / 2; center.y += tile_height / 2; } return resident_position(center, agent.id); } void draw_resident(HDC dc, POINT center, const settlement::Agent& agent) { using settlement::AgentState; using settlement::ItemType; COLORREF body = color(51, 145, 137); switch (agent.state) { case AgentState::Idle: body = color(56, 111, 174); break; case AgentState::Travelling: case AgentState::FetchingMaterials: body = color(125, 81, 181); break; case AgentState::Working: body = color(199, 88, 65); break; case AgentState::Gathering: body = color(193, 143, 64); break; case AgentState::GoingToEat: case AgentState::Eating: body = color(189, 89, 134); break; case AgentState::GoingToSleep: case AgentState::Sleeping: body = color(78, 99, 147); break; case AgentState::Hauling: break; } const auto [x, y] = resident_anchor(center, agent); const COLORREF ground = selected_resident == agent.id ? color(248, 218, 107) : color(116, 108, 90); fill_ellipse(dc, x - 6, y + 7, x + 6, y + 11, ground, color(116, 108, 90)); if (agent.state == AgentState::Sleeping) { fill_ellipse(dc, x - 7, y + 1, x + 6, y + 8, body, color(55, 66, 98)); fill_ellipse(dc, x + 3, y, x + 8, y + 6, color(232, 194, 143), color(113, 88, 64)); return; } fill_ellipse(dc, x - 4, y, x + 4, y + 8, body, color(255, 255, 255)); fill_ellipse(dc, x - 3, y - 5, x + 3, y + 1, color(232, 194, 143), color(113, 88, 64)); if (!agent.inventory.empty()) { const POINT pack[] = {{x + 2, y + 2}, {x + 8, y + 2}, {x + 8, y + 8}, {x + 2, y + 8}}; COLORREF cargo = color(229, 186, 112); if (agent.inventory.item_count(ItemType::Berries) > 0) cargo = color(211, 108, 149); if (agent.inventory.item_count(ItemType::Flax) > 0) cargo = color(135, 172, 235); if (agent.inventory.item_count(ItemType::Cloth) > 0) cargo = color(244, 232, 204); fill_polygon(dc, pack, 4, cargo, color(97, 73, 48)); } } const wchar_t* profession_name(settlement::Profession profession) { const auto choice = std::find_if(role_choices.begin(), role_choices.end(), [profession](const auto& entry) { return entry.role == profession; }); return choice == role_choices.end() ? L"" : choice->title; } const settlement::Agent* selected_agent() { if (!world || !selected_resident) return nullptr; const auto& agents = world->agents(); const auto agent = std::find_if(agents.begin(), agents.end(), [](const auto& entry) { return entry.id == *selected_resident; }); return agent == agents.end() ? nullptr : &*agent; } std::span work_choices() { switch (work_panel) { case WorkPanel::Farmer: return farmer_choices; case WorkPanel::Woodcutter: return woodcutter_choices; case WorkPanel::Miner: return miner_choices; case WorkPanel::Builder: return builder_choices; case WorkPanel::Gathering: return gathering_choices; case WorkPanel::Zones: return zones_choices; case WorkPanel::Construction: return construction_choices; case WorkPanel::None: return {}; } return {}; } void layout_command_dock(HWND window) { const auto choices = work_choices(); RECT client{}; GetClientRect(window, &client); const auto width = static_cast(client.right); const auto height = static_cast(client.bottom); constexpr int section_widths[] = {112, 112, 112, 160}; constexpr int sections_width = 112 * 3 + 160 + 3 * work_button_gap; int section_x = std::max(16, (width - sections_width) / 2); const auto place = [](HWND button, int x, int y, int w, int h) { SetWindowPos(button, nullptr, x, y, w, h, SWP_NOZORDER | SWP_NOACTIVATE); }; place(residents_button, section_x, height - dock_sections_offset, section_widths[0], 31); section_x += section_widths[0] + work_button_gap; for (std::size_t index = 0; index < dock_section_buttons.size(); ++index) { const int button_width = section_widths[index + 1]; place(dock_section_buttons[index], section_x, height - dock_sections_offset, button_width, 31); section_x += button_width + work_button_gap; } int row_width = choices.empty() ? 0 : -work_button_gap; for (const auto& choice : choices) row_width += choice.width + work_button_gap; int x = std::max(16, (width - row_width) / 2); for (std::size_t index = 0; index < choices.size(); ++index) { const auto& choice = choices[index]; place(work_choice_buttons[index], x, height - dock_actions_offset, choice.width, 28); if (choice.command == cabin_button_id) { place(wood_bed_button, x, height - dock_materials_offset, bed_choice_width, bed_choice_height); place(stone_bed_button, x + bed_choice_width + 4, height - dock_materials_offset, bed_choice_width, bed_choice_height); } x += choice.width + work_button_gap; } } void invalidate_work_choices() { const auto choices = work_choices(); for (std::size_t index = 0; index < choices.size(); ++index) { InvalidateRect(work_choice_buttons[index], nullptr, FALSE); } } void set_work_panel(HWND window, WorkPanel panel) { if (work_panel == panel) return; work_panel = panel; const auto choices = work_choices(); layout_command_dock(window); for (std::size_t index = 0; index < work_choice_buttons.size(); ++index) { const auto button = work_choice_buttons[index]; if (index >= choices.size()) { ShowWindow(button, SW_HIDE); continue; } const auto& choice = choices[index]; SetWindowTextW(button, choice.command == cabin_button_id && world && !world->scenario_active() ? L"Чертёж домика" : choice.title); ShowWindow(button, SW_SHOWNA); } for (const auto button : dock_section_buttons) InvalidateRect(button, nullptr, FALSE); invalidate_work_choices(); RECT row{}; GetClientRect(window, &row); row.top = row.bottom - map_footer; InvalidateRect(window, &row, FALSE); } void draw_icon_button(const DRAWITEMSTRUCT& item, WorkIcon icon, bool active, bool dock = false) { const bool disabled = (item.itemState & ODS_DISABLED) != 0; const bool pressed = (item.itemState & ODS_SELECTED) != 0; const auto dc = item.hDC; RECT box = item.rcItem; if (dock) { const bool highlighted = !disabled && (active || pressed); const auto brush = CreateSolidBrush(highlighted ? color(85, 105, 72) : color(48, 62, 55)); const auto border = CreateSolidBrush(highlighted ? color(206, 177, 114) : color(92, 106, 86)); FillRect(dc, &box, brush); FrameRect(dc, &box, border); DeleteObject(border); DeleteObject(brush); } else { DrawFrameControl(dc, &box, DFC_BUTTON, DFCS_BUTTONPUSH | (pressed || active ? DFCS_PUSHED : 0U)); } InflateRect(&box, -3, -3); if (!dock && active && !disabled) { const auto brush = CreateSolidBrush(color(211, 229, 194)); FillRect(dc, &box, brush); DeleteObject(brush); } wchar_t title[64]{}; const int length = GetWindowTextW(item.hwndItem, title, static_cast(std::size(title))); const auto font = reinterpret_cast(SendMessageW(item.hwndItem, WM_GETFONT, 0, 0)); const auto previous_font = SelectObject(dc, font ? font : GetStockObject(DEFAULT_GUI_FONT)); SIZE caption{}; GetTextExtentPoint32W(dc, title, length, &caption); constexpr int icon_width = 17; constexpr int gap = 5; const int left = std::max(box.left + 2, (box.left + box.right - icon_width - gap - caption.cx) / 2); const int offset = pressed ? 1 : 0; draw_work_icon(dc, icon, left + offset, (box.top + box.bottom - icon_width) / 2 + offset); RECT caption_box{left + icon_width + gap + offset, box.top + offset, box.right - 1, box.bottom + offset}; const auto previous_mode = SetBkMode(dc, TRANSPARENT); const auto previous_color = SetTextColor(dc, dock ? (disabled ? color(165, 174, 162) : color(246, 240, 220)) : GetSysColor(disabled ? COLOR_GRAYTEXT : COLOR_BTNTEXT)); DrawTextW(dc, title, length, &caption_box, DT_SINGLELINE | DT_VCENTER | DT_END_ELLIPSIS | DT_NOPREFIX); SetTextColor(dc, previous_color); SetBkMode(dc, previous_mode); if (previous_font) SelectObject(dc, previous_font); if ((item.itemState & (ODS_FOCUS | ODS_NOFOCUSRECT)) == ODS_FOCUS) DrawFocusRect(dc, &box); } bool draw_toolbar_button(const DRAWITEMSTRUCT& item) { const auto id = static_cast(item.CtlID); switch (id) { case wood_bed_button_id: draw_icon_button(item, WorkIcon::Wood, selected_bed_base == settlement::BedBase::Wood, true); return true; case stone_bed_button_id: draw_icon_button(item, WorkIcon::Stone, selected_bed_base == settlement::BedBase::Stone, true); return true; case residents_button_id: draw_icon_button(item, WorkIcon::Resident, roster.window != nullptr, true); return true; } if (id >= first_dock_section_id && static_cast(id - first_dock_section_id) < dock_sections.size()) { const auto& section = dock_sections[static_cast(id - first_dock_section_id)]; draw_icon_button(item, section.icon, work_panel == section.panel, true); return true; } const auto choices = work_choices(); if (id < first_work_choice_id || static_cast(id - first_work_choice_id) >= choices.size()) return false; const auto& choice = choices[static_cast(id - first_work_choice_id)]; draw_icon_button(item, choice.icon, placement_mode == choice.mode, true); return true; } bool can_give_orders() { return !lan.is_guest() || lan.state() == LanState::GuestConnected; } void update_roster_details() { const auto* resident = selected_agent(); const auto role = resident ? profession_name(resident->profession) : L""; const std::wstring title = resident ? L"Текущая роль: " + std::wstring(role) : L"Выберите жителя в списке."; SetWindowTextW(roster.current_role, title.c_str()); const bool can_assign = resident && can_give_orders(); EnableWindow(roster.apply, can_assign && roster.pending_role && *roster.pending_role != resident->profession); for (const auto button : roster.roles) { EnableWindow(button, can_assign); InvalidateRect(button, nullptr, FALSE); } } void sync_resident_roster(bool update_selection = false) { if (!roster.window) return; const auto& agents = world->agents(); const bool rows_changed = !std::equal(agents.begin(), agents.end(), roster.rows.begin(), roster.rows.end(), [](const auto& agent, const auto& row) { return agent.id == row.id && agent.profession == row.role; }); if (!rows_changed && !update_selection) return; if (rows_changed) { const auto old_count = roster.rows.size(); roster.rows.clear(); roster.rows.reserve(agents.size()); for (const auto& agent : agents) roster.rows.push_back({agent.id, agent.profession}); roster.updating_selection = true; if (old_count != roster.rows.size()) { ListView_SetItemCountEx(roster.list, static_cast(roster.rows.size()), LVSICF_NOSCROLL); } roster.updating_selection = false; InvalidateRect(roster.list, nullptr, FALSE); std::array counts{}; for (const auto& row : roster.rows) { for (std::size_t index = 0; index < role_choices.size(); ++index) { if (row.role == role_choices[index].role) ++counts[index]; } } for (std::size_t index = 0; index < role_choices.size(); ++index) { const auto title = std::wstring(role_choices[index].title) + L" (" + std::to_wstring(counts[index]) + L")"; SetWindowTextW(roster.roles[index], title.c_str()); } } if (update_selection) { roster.pending_role.reset(); SetWindowTextW(roster.notice, L""); } const auto row = std::find_if(roster.rows.begin(), roster.rows.end(), [](const auto& entry) { return selected_resident == entry.id; }); const int index = row == roster.rows.end() ? -1 : static_cast(row - roster.rows.begin()); if (ListView_GetNextItem(roster.list, -1, LVNI_SELECTED) != index) { roster.updating_selection = true; ListView_SetItemState(roster.list, -1, 0, LVIS_SELECTED | LVIS_FOCUSED); if (index >= 0) { ListView_SetItemState(roster.list, index, LVIS_SELECTED | LVIS_FOCUSED, LVIS_SELECTED | LVIS_FOCUSED); if (update_selection) ListView_EnsureVisible(roster.list, index, FALSE); } roster.updating_selection = false; } update_roster_details(); } void update_status() { if (status_label == nullptr || !world) return; const auto busy = std::count_if(world->agents().begin(), world->agents().end(), [](const settlement::Agent& agent) { return agent.state != settlement::AgentState::Idle; }); std::uint64_t wood = 0; std::uint64_t stone = 0; std::uint64_t planks = 0; std::uint64_t blocks = 0; std::uint64_t berries = 0; std::uint64_t cloth = 0; std::uint64_t flax = 0; for (const settlement::Storage& storage : world->storages()) { wood += storage.item_count(settlement::ItemType::Wood); stone += storage.item_count(settlement::ItemType::Stone); planks += storage.item_count(settlement::ItemType::Plank); blocks += storage.item_count(settlement::ItemType::StoneBlock); berries += storage.item_count(settlement::ItemType::Berries); cloth += storage.item_count(settlement::ItemType::Cloth); flax += storage.item_count(settlement::ItemType::Flax); } const std::wstring text = L"Жители: " + std::to_wstring(world->agents().size()) + L" Заняты: " + std::to_wstring(busy) + L" Выполнено работ: " + std::to_wstring(world->jobs_completed()) + L" Дерево: " + std::to_wstring(wood) + L" Камень: " + std::to_wstring(stone) + L" Ход: " + std::to_wstring(world->tick()) + (lan.is_guest() ? L" Симуляция у хозяина" : L" Потоков: " + std::to_wstring(world->worker_count())); SetWindowTextW(status_label, text.c_str()); const bool scenario = world->scenario_active(); const bool can_play = can_give_orders(); if (work_panel != WorkPanel::None && !can_play) { set_work_panel(GetParent(residents_button), WorkPanel::None); } for (const HWND button : dock_section_buttons) EnableWindow(button, can_play); EnableWindow(priority_button, scenario && can_play); EnableWindow(pause_button, scenario && !lan.is_guest()); const wchar_t* priority = L"Равный приоритет"; if (world->work_priority() == settlement::WorkPriority::FoodFirst) priority = L"Сначала еда"; else if (world->work_priority() == settlement::WorkPriority::BuildingFirst) priority = L"Сначала стройка"; SetWindowTextW(priority_button, priority); SetWindowTextW(pause_button, world->paused() ? L"Продолжить" : L"Пауза"); if (scenario && production_label != nullptr) { const auto progress = world->scenario_progress(); const auto sleeping = std::count_if(world->agents().begin(), world->agents().end(), [](const auto& agent) { return agent.state == settlement::AgentState::Sleeping; }); const std::wstring goal = (progress.completed ? std::wstring(L"Цель выполнена ") : std::wstring{}) + L"Спальные места " + std::to_wstring(progress.assigned_beds) + L"/" + std::to_wstring(progress.residents) + L" Еда " + std::to_wstring(progress.available_food) + L"/" + std::to_wstring(progress.food_goal) + L" Ткань " + std::to_wstring(cloth) + L" Лён " + std::to_wstring(flax) + L" Спят " + std::to_wstring(sleeping); SetWindowTextW(production_label, goal.c_str()); return; } if (production_label != nullptr) { unsigned waiting = 0; unsigned carrying = 0; unsigned building = 0; unsigned built = 0; for (const auto& order : world->production_orders()) { if (order.recipe != settlement::RecipeId::BuildCabin) continue; if (order.state == settlement::JobState::Available) ++waiting; else if (order.state == settlement::JobState::Completed) ++built; else if (order.delivery_stops.empty()) ++building; else ++carrying; } const auto hungry = std::count_if(world->agents().begin(), world->agents().end(), [](const settlement::Agent& agent) { return agent.hungry(); }); const std::wstring production = L"Ягоды: " + std::to_wstring(berries) + L" Голодны: " + std::to_wstring(hungry) + L" Доски: " + std::to_wstring(planks) + L" Блоки: " + std::to_wstring(blocks) + L" Лён: " + std::to_wstring(flax) + L" Ткань: " + std::to_wstring(cloth) + L" Домики В очереди: " + std::to_wstring(waiting) + L" Доставка: " + std::to_wstring(carrying) + L" Строятся: " + std::to_wstring(building) + L" Готовы: " + std::to_wstring(built); SetWindowTextW(production_label, production.c_str()); } } void update_bed_choices() { const int visibility = shows_bed_choices() ? SW_SHOW : SW_HIDE; ShowWindow(wood_bed_button, visibility); ShowWindow(stone_bed_button, visibility); InvalidateRect(wood_bed_button, nullptr, FALSE); InvalidateRect(stone_bed_button, nullptr, FALSE); } void set_placement_mode(HWND window, PlacementMode mode, const wchar_t* message = L"") { placement_mode = mode; selected_bed_base.reset(); move_source.reset(); hover_cell.reset(); placement_message = message; update_bed_choices(); invalidate_work_choices(); invalidate_scene(window); } void toggle_work_panel(HWND window, WorkPanel panel) { if (!can_give_orders()) return; set_placement_mode(window, PlacementMode::None); set_work_panel(window, work_panel == panel ? WorkPanel::None : panel); SetFocus(window); } void reset_world(HWND window) { world = settlement::make_first_colony(selected_workers); camera = {}; selected_resident.reset(); sync_resident_roster(true); set_work_panel(window, WorkPanel::None); set_placement_mode(window, PlacementMode::None); update_status(); invalidate_scene(window); } std::optional choose_save_file(HWND window, bool saving) { wchar_t filename[32768]{}; constexpr std::wstring_view default_name = L"Поселение.settlement"; if (saving) std::copy(default_name.begin(), default_name.end(), filename); OPENFILENAMEW dialog{}; dialog.lStructSize = sizeof(dialog); dialog.hwndOwner = window; dialog.lpstrFilter = L"Сохранение поселения (*.settlement)\0*.settlement\0Все файлы\0*.*\0"; dialog.lpstrFile = filename; dialog.nMaxFile = static_cast(std::size(filename)); dialog.lpstrDefExt = L"settlement"; dialog.Flags = OFN_EXPLORER | OFN_NOCHANGEDIR | OFN_PATHMUSTEXIST | (saving ? OFN_OVERWRITEPROMPT : OFN_FILEMUSTEXIST); const BOOL accepted = saving ? GetSaveFileNameW(&dialog) : GetOpenFileNameW(&dialog); if (accepted) return std::filesystem::path(filename); if (CommDlgExtendedError() != 0) throw std::runtime_error("Could not open the file picker."); return std::nullopt; } void save_world_file(const std::filesystem::path& path) { // Stage the complete file beside its destination before replacing an existing save. wchar_t temporary[MAX_PATH]{}; if (GetTempFileNameW(path.parent_path().c_str(), L"stl", 0, temporary) == 0) { throw std::runtime_error("Could not create a temporary save in this folder."); } try { std::ofstream stream(std::filesystem::path(temporary), std::ios::binary | std::ios::trunc); if (!stream) throw std::runtime_error("Could not open the temporary save for writing."); world->write_save(stream); stream.close(); if (!stream) throw std::runtime_error("Could not finish writing the temporary save."); if (!MoveFileExW(temporary, path.c_str(), MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH)) { throw std::runtime_error("Could not move the completed save into place."); } } catch (...) { DeleteFileW(temporary); throw; } } void handle_save_menu(HWND window, bool saving) { if (file_dialog_active || !world) return; if (lan.is_guest() || (!saving && lan.state() != LanState::Offline)) return; file_dialog_active = true; struct RestoreTimer { ~RestoreTimer() { file_dialog_active = false; } } restore_timer; try { const auto path = choose_save_file(window, saving); if (!path) return; if (saving) { save_world_file(*path); placement_message = L"Поселение сохранено."; invalidate_scene(window); return; } std::ifstream stream(*path, std::ios::binary); if (!stream) throw std::runtime_error("Could not open the requested save."); auto loaded = settlement::World::read_save(stream, selected_workers); if (loaded->width() != map_size || loaded->height() != map_size) { throw std::runtime_error("This viewer opens saves with a 32 by 32 map."); } world = std::move(loaded); selected_resident.reset(); sync_resident_roster(true); set_work_panel(window, WorkPanel::None); set_placement_mode(window, PlacementMode::None, L"Поселение загружено."); update_status(); } catch (const std::exception& error) { const std::string_view details(error.what()); const std::wstring message = std::wstring(saving ? L"Не удалось сохранить поселение.\n" : L"Не удалось загрузить поселение.\n") + std::wstring(details.begin(), details.end()); MessageBoxW(window, message.c_str(), L"Поселение", MB_OK | MB_ICONERROR); } } std::wstring widen_ascii(std::string_view text) { return {text.begin(), text.end()}; } struct JoinForm { std::array address{}; std::array code{}; }; INT_PTR CALLBACK join_dialog_proc(HWND dialog, UINT message, WPARAM wparam, LPARAM lparam) { constexpr int address_id = 10; constexpr int code_id = 11; switch (message) { case WM_INITDIALOG: { SetWindowLongPtrW(dialog, DWLP_USER, static_cast(lparam)); SetWindowTextW(dialog, L"Подключиться к поселению"); const auto control = [&](const wchar_t* type, const wchar_t* title, DWORD style, DWORD ex_style, int id, RECT units) { MapDialogRect(dialog, &units); const HWND child = CreateWindowExW(ex_style, type, title, WS_CHILD | WS_VISIBLE | style, units.left, units.top, units.right - units.left, units.bottom - units.top, dialog, reinterpret_cast(static_cast(id)), GetModuleHandleW(nullptr), nullptr); SendMessageW(child, WM_SETFONT, reinterpret_cast(GetStockObject(DEFAULT_GUI_FONT)), TRUE); return child; }; control(L"STATIC", L"IPv4 хозяина", 0, 0, 0, {10, 13, 77, 26}); const HWND address = control(L"EDIT", L"", WS_TABSTOP | ES_AUTOHSCROLL, WS_EX_CLIENTEDGE, address_id, {82, 10, 216, 25}); control(L"STATIC", L"Код партии", 0, 0, 0, {10, 38, 77, 51}); const HWND code = control(L"EDIT", L"", WS_TABSTOP | ES_AUTOHSCROLL, WS_EX_CLIENTEDGE, code_id, {82, 35, 216, 50}); SendMessageW(address, EM_SETLIMITTEXT, 63, 0); SendMessageW(code, EM_SETLIMITTEXT, 31, 0); control(L"BUTTON", L"Подключиться", WS_TABSTOP | BS_DEFPUSHBUTTON, 0, IDOK, {68, 62, 151, 79}); control(L"BUTTON", L"Отмена", WS_TABSTOP | BS_PUSHBUTTON, 0, IDCANCEL, {158, 62, 216, 79}); SendMessageW(dialog, DM_SETDEFID, IDOK, 0); SetFocus(address); return FALSE; } case WM_COMMAND: if (LOWORD(wparam) == IDOK) { auto* form = reinterpret_cast(GetWindowLongPtrW(dialog, DWLP_USER)); GetDlgItemTextW(dialog, address_id, form->address.data(), static_cast(form->address.size())); GetDlgItemTextW(dialog, code_id, form->code.data(), static_cast(form->code.size())); EndDialog(dialog, IDOK); return TRUE; } if (LOWORD(wparam) == IDCANCEL) { EndDialog(dialog, IDCANCEL); return TRUE; } break; case WM_CLOSE: EndDialog(dialog, IDCANCEL); return TRUE; } return FALSE; } std::optional ask_join_address(HWND window) { struct alignas(DWORD) EmptyDialog { DLGTEMPLATE header{}; WORD menu = 0; WORD window_class = 0; WORD title = 0; } layout; layout.header.style = WS_POPUP | WS_CAPTION | WS_SYSMENU | DS_MODALFRAME | DS_CENTER; layout.header.cx = 226; layout.header.cy = 91; JoinForm values; const auto result = DialogBoxIndirectParamW(GetModuleHandleW(nullptr), &layout.header, window, join_dialog_proc, reinterpret_cast(&values)); if (result == -1) throw std::runtime_error("Could not display the connection window."); if (result != IDOK) return std::nullopt; return values; } std::string narrow_lan_input(std::wstring_view value) { const auto begin = value.find_first_not_of(L" \t"); if (begin == std::wstring_view::npos) return {}; value = value.substr(begin, value.find_last_not_of(L" \t") - begin + 1); std::string ascii; for (const auto letter : value) { if (letter > 127) throw std::invalid_argument("Use ASCII digits and letters for the address and code."); ascii.push_back(static_cast(letter)); } return ascii; } void show_lan_info(HWND window) { const auto addresses = settlement::viewer::local_lan_addresses(); const auto text = L"Передайте другу IPv4 вашего компьютера и код партии.\n\nIPv4: " + (addresses.empty() ? std::wstring(L"см. ipconfig") : widen_ascii(addresses)) + L"\nКод партии: " + widen_ascii(lan.join_code()) + L"\nПорт TCP: " + std::to_wstring(lan.port()) + L"\n\nДруг в той же сети выбирает «Кооператив → Подключиться…»."; MessageBoxW(window, text.c_str(), L"Кооператив по локальной сети", MB_OK | MB_ICONINFORMATION); } void refresh_lan_controls(HWND window) { const auto state = lan.state(); displayed_lan_state = state; const bool offline = state == LanState::Offline; const bool hosting = state == LanState::Hosting || state == LanState::HostConnected; const bool disconnected = state == LanState::GuestDisconnected; EnableWindow(worker_combo, offline); EnableWindow(apply_button, offline); const auto menu = GetMenu(window); const auto enable = [&](UINT command, bool enabled) { EnableMenuItem(menu, command, MF_BYCOMMAND | (enabled ? MF_ENABLED : MF_GRAYED)); }; enable(lan_host_id, offline); enable(lan_join_id, offline || disconnected); enable(lan_info_id, hosting); enable(lan_reconnect_id, disconnected); enable(lan_leave_id, !offline); enable(save_menu_id, !lan.is_guest()); enable(load_menu_id, offline); const wchar_t* suffix = L""; switch (state) { case LanState::Offline: break; case LanState::Hosting: suffix = L" · ждём гостя"; break; case LanState::HostConnected: suffix = L" · хозяин, гость подключён"; break; case LanState::Connecting: suffix = L" · подключение"; break; case LanState::GuestConnected: suffix = L" · гость"; break; case LanState::GuestDisconnected: suffix = L" · связь потеряна"; break; } const std::wstring title = std::wstring(L"Settlement — Первое поселение") + suffix; SetWindowTextW(window, title.c_str()); if (disconnected) { set_placement_mode(window, PlacementMode::None); placement_message = L"Связь прервана. «Кооператив → Подключиться снова». " + widen_ascii(lan.detail()); } else if (state == LanState::GuestConnected) { placement_message = L"Подключено к колонии хозяина."; } DrawMenuBar(window); if (roster.window) update_roster_details(); update_status(); invalidate_scene(window); } void handle_lan_menu(HWND window, int command) { try { if (command == lan_host_id && lan.state() == LanState::Offline) { if (!world->scenario_active()) { throw std::runtime_error("Start the playable colony before hosting."); } lan.host(); refresh_lan_controls(window); show_lan_info(window); } else if (command == lan_join_id && (lan.state() == LanState::Offline || lan.state() == LanState::GuestDisconnected)) { const auto request = ask_join_address(window); if (!request) return; lan.join(narrow_lan_input(request->address.data()), narrow_lan_input(request->code.data())); selected_resident.reset(); sync_resident_roster(true); set_work_panel(window, WorkPanel::None); set_placement_mode(window, PlacementMode::None, L"Подключаемся к хозяину…"); } else if (command == lan_info_id && !lan.is_guest() && lan.state() != LanState::Offline) { show_lan_info(window); return; } else if (command == lan_reconnect_id) { lan.reconnect(); } else if (command == lan_leave_id) { lan.leave(); set_work_panel(window, WorkPanel::None); set_placement_mode(window, PlacementMode::None, L"Сетевая игра завершена."); } refresh_lan_controls(window); } catch (const std::exception& error) { const auto text = L"Не удалось выполнить действие.\n" + widen_ascii(error.what()); MessageBoxW(window, text.c_str(), L"Кооператив", MB_OK | MB_ICONERROR); } } const settlement::ResourceNode* berry_source(settlement::GridPosition cell) { for (const auto& node : world->resource_nodes()) { if (node.position == cell && node.type == settlement::ItemType::Berries) return &node; } return nullptr; } settlement::CommandStatus submit_command(settlement::CommandKind kind, settlement::GridPosition cell, std::uint8_t value, settlement::GridPosition destination = {}, settlement::AgentId resident = 0) { if (lan.is_guest()) { return lan.submit(kind, cell, value, destination, resident) ? settlement::CommandStatus::Accepted : settlement::CommandStatus::Unavailable; } constexpr auto host = settlement::colony_host; return world->apply_command({host, world->next_command_sequence(host), kind, cell, value, destination, resident}).status; } bool send_command(settlement::CommandKind kind, settlement::GridPosition cell = {}, std::uint8_t value = 0) { return submit_command(kind, cell, value) == settlement::CommandStatus::Accepted; } bool valid_edit_cell(settlement::GridPosition cell) { using settlement::CommandStatus; using settlement::ResourceSite; switch (placement_mode) { case PlacementMode::Foraging: return berry_source(cell) != nullptr; case PlacementMode::BerryField: return world->can_place_site(cell, ResourceSite::BerryField); case PlacementMode::FlaxField: return world->can_place_site(cell, ResourceSite::FlaxField); case PlacementMode::TreePlot: return world->can_place_site(cell, ResourceSite::TreePlot); case PlacementMode::Mine: return world->can_place_site(cell, ResourceSite::Mine); case PlacementMode::Storage: case PlacementMode::Loom: case PlacementMode::Pantry: return world->can_place_storage(cell); case PlacementMode::Move: return move_source ? world->can_place_storage(cell) : world->object_status(cell, true) == CommandStatus::Accepted; case PlacementMode::Demolish: return world->object_status(cell, false) == CommandStatus::Accepted; case PlacementMode::Building: return world->scenario_active() ? world->can_place_bed(cell) : world->can_place_cabin(cell); case PlacementMode::None: return false; } return false; } void edit_at_cell(HWND window, settlement::GridPosition cell) { using settlement::CommandKind; using settlement::CommandStatus; using settlement::StorageKind; CommandKind command = CommandKind::DemolishObject; auto source = cell; settlement::GridPosition destination{}; std::uint8_t value = 0; if (placement_mode == PlacementMode::Move) { if (!move_source) { const auto status = world->object_status(cell, true); if (status == CommandStatus::Accepted) { move_source = cell; placement_message = L"Объект выбран. Щёлкните по свободной клетке для переноса."; } else if (status == CommandStatus::Busy) { placement_message = L"Объект сейчас используется. Дождитесь завершения работы или сна."; } else { placement_message = L"Выберите кровать, склад, станок или посаженный участок."; } invalidate_scene(window); return; } command = CommandKind::MoveObject; source = *move_source; destination = cell; } else if (placement_mode == PlacementMode::Demolish) { const auto store = std::find_if(world->storages().begin(), world->storages().end(), [&](const auto& storage) { return storage.position == cell; }); if (store != world->storages().end() && store->total_items() > 0 && world->object_status(cell, false) == CommandStatus::Accepted && MessageBoxW(window, L"Снести склад вместе с его запасами?", L"Снос склада", MB_YESNO | MB_ICONQUESTION | MB_DEFBUTTON2) != IDYES) return; } else if (placement_mode == PlacementMode::BerryField) { command = CommandKind::PlaceBerryField; } else if (placement_mode == PlacementMode::FlaxField) { command = CommandKind::PlaceFlaxField; } else if (placement_mode == PlacementMode::TreePlot) { command = CommandKind::PlaceTreePlot; } else if (placement_mode == PlacementMode::Mine) { command = CommandKind::PlaceMine; } else if (placement_mode == PlacementMode::Loom) { command = CommandKind::PlaceLoom; } else { command = CommandKind::PlaceStorage; value = static_cast(placement_mode == PlacementMode::Pantry ? StorageKind::Pantry : StorageKind::Materials); } const auto result = submit_command(command, source, value, destination); if (result == CommandStatus::Accepted) { move_source.reset(); placement_message = lan.is_guest() ? L"Команда отправлена хозяину." : L"Готово."; } else if (result == CommandStatus::Busy) { placement_message = L"Объект сейчас используется. Дождитесь завершения работы или сна."; } else { if (command == CommandKind::MoveObject && world->object_status(source, true) != CommandStatus::Accepted) { move_source.reset(); } placement_message = L"Действие недоступно для выбранной клетки."; } update_status(); invalidate_scene(window); } HMENU create_work_menu() { HMENU menu = CreatePopupMenu(); if (menu == nullptr) return nullptr; for (std::size_t index = 0; index + 1 < role_choices.size(); ++index) { AppendMenuW(menu, MF_STRING, farmer_menu_id + index, role_choices[index + 1].title); } AppendMenuW(menu, MF_SEPARATOR, 0, nullptr); AppendMenuW(menu, MF_STRING, residents_button_id, L"Жители…\tC"); return menu; } void apply_resident_role(HWND owner) { const auto* resident = selected_agent(); if (!resident || !roster.pending_role || *roster.pending_role == resident->profession || !can_give_orders()) return; using settlement::CommandStatus; const auto result = submit_command(settlement::CommandKind::AssignProfession, {}, static_cast(*roster.pending_role), {}, resident->id); if (result == CommandStatus::Accepted) { roster.pending_role.reset(); SetWindowTextW(roster.notice, lan.is_guest() ? L"Назначение отправлено хозяину." : L"Профессия назначена. Житель закончит текущее поручение."); } else { SetWindowTextW(roster.notice, L"Не удалось назначить профессию."); } sync_resident_roster(); update_roster_details(); invalidate_scene(owner); } LRESULT CALLBACK resident_roster_proc(HWND window, UINT message, WPARAM wparam, LPARAM lparam) { const auto owner = GetWindow(window, GW_OWNER); switch (message) { case WM_CREATE: { const auto control = [&](const wchar_t* type, const wchar_t* text, int id, DWORD style, int x, int y, int width, int height, DWORD ex_style = 0) { const auto child = CreateWindowExW(ex_style, type, text, WS_CHILD | WS_VISIBLE | style, x, y, width, height, window, reinterpret_cast(static_cast(id)), GetModuleHandleW(nullptr), nullptr); SendMessageW(child, WM_SETFONT, reinterpret_cast(GetStockObject(DEFAULT_GUI_FONT)), FALSE); return child; }; roster.list = control(WC_LISTVIEWW, L"", resident_list_id, WS_TABSTOP | LVS_REPORT | LVS_OWNERDATA | LVS_SINGLESEL | LVS_SHOWSELALWAYS | LVS_NOSORTHEADER, 16, 16, 282, 311, WS_EX_CLIENTEDGE); ListView_SetExtendedListViewStyle(roster.list, LVS_EX_FULLROWSELECT | LVS_EX_DOUBLEBUFFER); wchar_t resident_header[] = L"Житель"; wchar_t profession_header[] = L"Профессия"; LVCOLUMNW column{}; column.mask = LVCF_TEXT | LVCF_WIDTH; column.cx = 102; column.pszText = resident_header; ListView_InsertColumn(roster.list, 0, &column); column.cx = 156; column.pszText = profession_header; ListView_InsertColumn(roster.list, 1, &column); roster.current_role = control(L"STATIC", L"", 0, SS_LEFT, 316, 16, 234, 22); for (std::size_t index = 0; index < role_choices.size(); ++index) { const auto title = std::wstring(role_choices[index].title) + L" (0)"; roster.roles[index] = control(L"BUTTON", title.c_str(), first_role_id + static_cast(index), WS_TABSTOP | BS_OWNERDRAW, 316, 43 + static_cast(index) * 34, 234, 30); } roster.apply = control(L"BUTTON", L"Назначить профессию", IDOK, WS_TABSTOP | BS_DEFPUSHBUTTON, 316, 218, 234, 30); roster.notice = control(L"STATIC", L"", 0, SS_LEFT, 316, 256, 234, 44); const auto close = control(L"BUTTON", L"Закрыть", IDCANCEL, WS_TABSTOP | BS_PUSHBUTTON, 447, 301, 103, 26); if (!roster.list || !roster.current_role || !roster.apply || !roster.notice || !close || std::find(roster.roles.begin(), roster.roles.end(), nullptr) != roster.roles.end()) return -1; return 0; } case WM_NOTIFY: { const auto* notification = reinterpret_cast(lparam); if (!notification || notification->hwndFrom != roster.list) break; if (notification->code == LVN_GETDISPINFOW) { auto& item = reinterpret_cast(lparam)->item; if ((item.mask & LVIF_TEXT) != 0 && item.pszText && item.cchTextMax > 0 && item.iItem >= 0 && static_cast(item.iItem) < roster.rows.size()) { const auto& row = roster.rows[static_cast(item.iItem)]; const auto name = item.iSubItem == 0 ? L"Житель №" + std::to_wstring(row.id) : std::wstring(profession_name(row.role)); lstrcpynW(item.pszText, name.c_str(), item.cchTextMax); } return 0; } if (notification->code == LVN_ITEMCHANGED && !roster.updating_selection) { const auto& change = *reinterpret_cast(lparam); if ((change.uChanged & LVIF_STATE) != 0 && ((change.uOldState ^ change.uNewState) & LVIS_SELECTED) != 0) { const int index = ListView_GetNextItem(roster.list, -1, LVNI_SELECTED); std::optional resident; if (index >= 0 && static_cast(index) < roster.rows.size()) { resident = roster.rows[static_cast(index)].id; } if (selected_resident != resident) { selected_resident = resident; sync_resident_roster(true); invalidate_scene(owner); } } } break; } case WM_DRAWITEM: { const auto* item = reinterpret_cast(lparam); if (item && item->CtlType == ODT_BUTTON && item->CtlID >= first_role_id && item->CtlID < first_role_id + role_choices.size()) { const auto& choice = role_choices[item->CtlID - first_role_id]; const auto* resident = selected_agent(); const bool active = resident && roster.pending_role.value_or(resident->profession) == choice.role; draw_icon_button(*item, choice.icon, active); return TRUE; } break; } case WM_COMMAND: if (HIWORD(wparam) != BN_CLICKED) break; if (LOWORD(wparam) == IDCANCEL) { DestroyWindow(window); return 0; } if (LOWORD(wparam) == IDOK) { apply_resident_role(owner); return 0; } if (LOWORD(wparam) >= first_role_id && LOWORD(wparam) < first_role_id + role_choices.size() && selected_agent() && can_give_orders()) { roster.pending_role = role_choices[LOWORD(wparam) - first_role_id].role; SetWindowTextW(roster.notice, L""); update_roster_details(); return 0; } break; case DM_GETDEFID: return MAKELONG(IDOK, DC_HASDEFID); case WM_DESTROY: roster = {}; InvalidateRect(residents_button, nullptr, FALSE); return 0; } return DefWindowProcW(window, message, wparam, lparam); } void show_resident_roster(HWND owner) { if (roster.window) { SetActiveWindow(roster.window); return; } const auto instance = GetModuleHandleW(nullptr); WNDCLASSW window_info{}; window_info.lpfnWndProc = resident_roster_proc; window_info.hInstance = instance; window_info.lpszClassName = resident_window_class; window_info.hCursor = LoadCursorW(nullptr, IDC_ARROW); window_info.hbrBackground = GetSysColorBrush(COLOR_BTNFACE); if (!RegisterClassW(&window_info) && GetLastError() != ERROR_CLASS_ALREADY_EXISTS) return; constexpr auto style = WS_POPUP | WS_CAPTION | WS_SYSMENU | WS_CLIPCHILDREN; constexpr auto ex_style = WS_EX_TOOLWINDOW | WS_EX_CONTROLPARENT; RECT area{0, 0, 566, 343}; AdjustWindowRectEx(&area, style, FALSE, ex_style); RECT owner_rect{}; GetWindowRect(owner, &owner_rect); const int width = area.right - area.left; const int height = area.bottom - area.top; const int x = (owner_rect.left + owner_rect.right - width) / 2; const int y = (owner_rect.top + owner_rect.bottom - height) / 2; roster.window = CreateWindowExW(ex_style, resident_window_class, L"Жители поселения", style, x, y, width, height, owner, nullptr, instance, nullptr); if (!roster.window) return; if (!selected_agent() && !world->agents().empty()) selected_resident = world->agents().front().id; sync_resident_roster(true); InvalidateRect(residents_button, nullptr, FALSE); invalidate_scene(owner); ShowWindow(roster.window, SW_SHOW); SetFocus(roster.list); } std::optional resident_at(HWND window, POINT point) { RECT client{}; GetClientRect(window, &client); if (!is_map_point(client, point)) return std::nullopt; const auto scene = camera.to_scene({static_cast(point.x), static_cast(point.y)}); std::optional picked; double closest = 65.0; for (const auto& agent : world->agents()) { const auto position = resident_anchor( iso_point(agent.position.x, agent.position.y, client.right / 2, map_origin_y), agent); const double dx = scene.x - position.x; const double dy = scene.y - (position.y + 2); if (std::abs(dx) > 8 || std::abs(dy) > 8) continue; const double distance = dx * dx + dy * dy; if (distance <= closest) { closest = distance; picked = agent.id; } } return picked; } std::wstring resident_details() { const auto* resident = selected_agent(); if (resident == nullptr) return L"Щёлкните по жителю, чтобы увидеть его состояние и назначить профессию."; using settlement::ItemType; 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"лён"} }; std::wstring cargo; for (const auto& [type, name] : items) { const auto count = resident->inventory.item_count(type); if (count == 0) continue; if (!cargo.empty()) cargo += L", "; cargo += std::wstring(name) + L" ×" + std::to_wstring(count); } const auto hunger = 100U * resident->hunger / settlement::max_hunger; std::wstring text = L"Житель №" + std::to_wstring(resident->id) + L" " + profession_name(resident->profession) + L" Голод " + std::to_wstring(hunger) + L"%"; if (resident->state == settlement::AgentState::GoingToEat) text += L" Идёт к кладовой"; else if (resident->state == settlement::AgentState::Eating) text += L" Ест"; else if (resident->resource_node_index != settlement::no_entity_index && resident->storage_index == settlement::no_entity_index) { const auto& site = world->resource_nodes()[resident->resource_node_index]; const bool trees = site.site == settlement::ResourceSite::TreePlot; if (resident->state == settlement::AgentState::Travelling) { text += trees ? L" Идёт на посадку деревьев" : L" Идёт засевать поле"; } else { text += trees ? L" Сажает деревья" : L" Засевает поле"; } } text += L" В сумке "; text += cargo.empty() ? L"пусто" : cargo; if (world->scenario_active()) { const auto* bed = world->assigned_bed(resident->id); const auto fatigue = 100U * resident->fatigue / settlement::max_fatigue; text += L" Усталость " + std::to_wstring(fatigue) + L"%"; if (resident->state == settlement::AgentState::GoingToSleep) { text += resident->resting_on_ground ? L" Идёт отдыхать" : L" Идёт к кровати"; } if (resident->state == settlement::AgentState::Sleeping) { text += resident->resting_on_ground ? L" Отдыхает на земле" : L" Спит в кровати"; } text += bed == nullptr ? L" Место ещё не назначено" : L" Место [" + std::to_wstring(bed->position.x + 1) + L", " + std::to_wstring(bed->position.y + 1) + L"]"; } return text; } void draw_map(HDC dc, int width) { const int origin_x = width / 2; const int origin_y = map_origin_y; for (int y = 0; y < map_size; ++y) { for (int x = 0; x < map_size; ++x) { const POINT center = iso_point(x, y, origin_x, origin_y); const bool walkable = world->is_walkable({x, y}); const COLORREF grass = ((x * 7 + y * 11) % 9 == 0) ? color(158, 183, 124) : color(171, 195, 135); draw_ground_tile(dc, center, walkable ? grass : color(118, 133, 118), color(149, 170, 130)); if (hover_cell && *hover_cell == settlement::GridPosition{x, y} && (!shows_bed_choices() || selected_bed_base.has_value())) { const bool valid = valid_edit_cell(*hover_cell); draw_ground_tile(dc, center, valid ? color(154, 207, 225) : color(216, 140, 126), valid ? color(53, 116, 141) : color(147, 70, 58)); } if (move_source == settlement::GridPosition{x, y}) { draw_ground_tile(dc, center, color(224, 197, 125), color(124, 98, 47)); } } } const HPEN trail_pen = CreatePen(PS_SOLID, 1, color(100, 82, 134)); const HPEN delivery_pen = CreatePen(PS_SOLID, 2, color(38, 122, 112)); const HPEN meal_pen = CreatePen(PS_SOLID, 2, color(168, 67, 109)); const HPEN sleep_pen = CreatePen(PS_SOLID, 2, color(76, 98, 142)); const HGDIOBJ original_pen = SelectObject(dc, trail_pen); for (const auto& agent : world->agents()) { using settlement::AgentState; if (agent.state != AgentState::Travelling && agent.state != AgentState::Hauling && agent.state != AgentState::FetchingMaterials && agent.state != AgentState::GoingToEat && agent.state != AgentState::GoingToSleep) continue; HPEN pen = trail_pen; if (agent.state == AgentState::GoingToEat) pen = meal_pen; else if (agent.state == AgentState::GoingToSleep) pen = sleep_pen; else if (agent.production_index != settlement::no_entity_index && agent.state == AgentState::Hauling) { pen = delivery_pen; } SelectObject(dc, pen); const POINT start = iso_point(agent.position.x, agent.position.y, origin_x, origin_y); MoveToEx(dc, start.x, start.y, nullptr); for (std::size_t i = agent.route_cursor; i < agent.route.size(); ++i) { const POINT point = iso_point(agent.route[i].x, agent.route[i].y, origin_x, origin_y); LineTo(dc, point.x, point.y); } } SelectObject(dc, original_pen); DeleteObject(trail_pen); DeleteObject(delivery_pen); DeleteObject(meal_pen); DeleteObject(sleep_pen); for (int depth = 0; depth <= (map_size - 1) * 2; ++depth) { const int min_x = std::max(0, depth - (map_size - 1)); const int max_x = std::min(map_size - 1, depth); for (int x = min_x; x <= max_x; ++x) { const int y = depth - x; const POINT center = iso_point(x, y, origin_x, origin_y); if (!world->is_walkable({x, y})) draw_rock(dc, center); for (const settlement::ResourceNode& node : world->resource_nodes()) { if (node.position.x == x && node.position.y == y && (node.quantity > 0 || node.type == settlement::ItemType::Berries || node.site != settlement::ResourceSite::Natural)) { if (node.type == settlement::ItemType::Berries && node.foraging_enabled) { draw_ground_tile(dc, center, color(169, 202, 120), color(57, 112, 65)); } draw_site(dc, center, node); } } for (const settlement::Storage& storage : world->storages()) { if (storage.position.x == x && storage.position.y == y) draw_storage(dc, center, storage.kind); } for (const settlement::ProductionOrder& order : world->production_orders()) { if (order.position.x != x || order.position.y != y) continue; draw_production(dc, center, order); break; } for (const settlement::WorkJob& job : world->jobs()) { if (job.position.x != x || job.position.y != y) continue; const COLORREF job_color = job.state == settlement::JobState::Available ? color(66, 143, 85) : job.state == settlement::JobState::InProgress ? color(220, 151, 53) : color(148, 151, 145); const POINT marker[] = { {center.x, center.y - 4}, {center.x + 4, center.y - 2}, {center.x, center.y}, {center.x - 4, center.y - 2} }; fill_polygon(dc, marker, 4, job_color, color(75, 83, 69)); } for (const settlement::Agent& agent : world->agents()) { if (agent.position.x != x || agent.position.y != y) continue; draw_resident(dc, center, agent); } } } } void draw_world(HDC dc, int width, int height) { RECT bounds{0, 0, width, height}; HBRUSH background = CreateSolidBrush(color(239, 235, 222)); FillRect(dc, &bounds, background); DeleteObject(background); if (!world) return; if (height > map_top + map_footer) { const int saved = SaveDC(dc); if (saved != 0) { IntersectClipRect(dc, 0, map_top, width, height - map_footer); const auto offset = camera.offset(); const auto scale = static_cast(camera.scale()); const XFORM transform{scale, 0.0F, 0.0F, scale, static_cast(offset.x), static_cast(offset.y)}; if (SetGraphicsMode(dc, GM_ADVANCED) != 0 && SetWorldTransform(dc, &transform)) { draw_map(dc, width); } RestoreDC(dc, saved); } } const RECT dock{0, height - map_footer, width, height}; const auto dock_brush = CreateSolidBrush(color(34, 46, 40)); FillRect(dc, &dock, dock_brush); DeleteObject(dock_brush); const RECT dock_edge{0, dock.top, width, dock.top + 2}; const auto edge_brush = CreateSolidBrush(color(142, 132, 92)); FillRect(dc, &dock_edge, edge_brush); DeleteObject(edge_brush); SetBkMode(dc, TRANSPARENT); SetTextColor(dc, color(231, 227, 205)); const wchar_t* hint = world->scenario_active() ? L"Колесо — масштаб Перетаскивание — сдвиг карты Home — общий план" : L"Голубой — очередь Бирюзовый — доставка Янтарный — строительство"; if (!placement_message.empty()) hint = placement_message.c_str(); else if (placement_mode == PlacementMode::Foraging) { hint = L"Щёлкните по ягодному кусту, чтобы включить или выключить сбор. Esc — отмена."; } else if (placement_mode == PlacementMode::BerryField) { hint = L"Поле ягод. Выберите свободную клетку. Фермер засеет поле и соберёт урожай."; } else if (placement_mode == PlacementMode::FlaxField) { hint = L"Поле льна. Выберите свободную клетку. Фермер сначала засеет поле, затем соберёт лён."; } else if (placement_mode == PlacementMode::TreePlot) { hint = L"Посадка деревьев. Выберите свободную клетку. Лесоруб высадит деревья."; } else if (placement_mode == PlacementMode::Mine) { hint = L"Шахта. Щёлкните по скале, к которой ведёт свободный проход."; } else if (placement_mode == PlacementMode::Loom) { hint = L"Ткацкий станок. Выберите свободную клетку. Строитель будет делать ткань из льна."; } else if (placement_mode == PlacementMode::Storage || placement_mode == PlacementMode::Pantry) { hint = L"Выберите свободную клетку для склада или кладовой."; } else if (placement_mode == PlacementMode::Move) { hint = move_source ? L"Выберите свободную клетку для переноса." : L"Выберите кровать, склад, станок или посаженный участок."; } else if (placement_mode == PlacementMode::Demolish) { hint = L"Щёлкните по объекту, чтобы снести его. Esc отменяет режим."; } else if (placement_mode == PlacementMode::Building) { if (world->staged_beds()) { hint = selected_bed_base ? L"Щёлкайте по свободным клеткам. Основу можно сменить под кнопкой «Спальное место»." : L"Выберите «Дерево» или «Камень» под кнопкой «Спальное место»."; } else if (world->scenario_active()) { hint = L"Щёлкайте по свободным клеткам. Одно место требует доску. Esc — выход."; } else { hint = L"Выберите свободную клетку. Домик стоит три доски и два блока. Esc — отмена."; } } RECT legend{24, height - 159, width - 24, height - 136}; DrawTextW(dc, hint, -1, &legend, DT_LEFT | DT_VCENTER | DT_SINGLELINE | DT_END_ELLIPSIS); const auto details = resident_details(); SetTextColor(dc, color(190, 201, 178)); RECT inspector{24, height - 135, width - 24, height - 113}; DrawTextW(dc, details.c_str(), -1, &inspector, DT_LEFT | DT_VCENTER | DT_SINGLELINE | DT_END_ELLIPSIS); } LRESULT CALLBACK window_proc(HWND window, UINT message, WPARAM wparam, LPARAM lparam) { switch (message) { case WM_GETMINMAXINFO: { auto& size = *reinterpret_cast(lparam); size.ptMinTrackSize.x = 775; size.ptMinTrackSize.y = 490; return 0; } case WM_CREATE: { constexpr auto minimum = static_cast(settlement::min_worker_count); const UINT hardware = std::max(static_cast(minimum), std::thread::hardware_concurrency()); const int max_workers = static_cast(std::min(hardware, 32U)); selected_workers = static_cast(std::min(max_workers, 8)); CreateWindowExW(0, L"STATIC", L"Число потоков:", WS_CHILD | WS_VISIBLE, 18, 14, 112, 25, window, nullptr, nullptr, nullptr); worker_combo = CreateWindowExW(0, WC_COMBOBOXW, L"", WS_CHILD | WS_VISIBLE | CBS_DROPDOWNLIST, 132, 10, 76, 280, window, reinterpret_cast(static_cast(worker_combo_id)), GetModuleHandleW(nullptr), nullptr); for (int count = minimum; count <= max_workers; ++count) { const std::wstring option = std::to_wstring(count); SendMessageW(worker_combo, CB_ADDSTRING, 0, reinterpret_cast(option.c_str())); } SendMessageW(worker_combo, CB_SETCURSEL, static_cast(selected_workers - settlement::min_worker_count), 0); apply_button = CreateWindowExW(0, L"BUTTON", L"Применить и начать заново", WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON, 220, 10, 190, 28, window, reinterpret_cast(static_cast(apply_button_id)), GetModuleHandleW(nullptr), nullptr); status_label = CreateWindowExW(0, L"STATIC", L"", WS_CHILD | WS_VISIBLE, 430, 14, 620, 24, window, reinterpret_cast(static_cast(status_label_id)), GetModuleHandleW(nullptr), nullptr); production_label = CreateWindowExW(0, L"STATIC", L"", WS_CHILD | WS_VISIBLE, 288, 47, 817, 24, window, nullptr, nullptr, nullptr); const auto button = [&](int id, int x, int width, const wchar_t* title, DWORD style = BS_PUSHBUTTON, int y = 41, int height = 28) { return CreateWindowExW(0, L"BUTTON", title, WS_CHILD | WS_VISIBLE | style, x, y, width, height, window, reinterpret_cast(static_cast(id)), GetModuleHandleW(nullptr), nullptr); }; priority_button = button(priority_button_id, 18, 142, L"Равный приоритет"); pause_button = button(pause_button_id, 168, 96, L"Пауза"); residents_button = button(residents_button_id, 0, 112, L"Жители", BS_OWNERDRAW, 0); for (std::size_t index = 0; index < dock_sections.size(); ++index) { dock_section_buttons[index] = button(first_dock_section_id + static_cast(index), 0, 112, dock_sections[index].title, BS_OWNERDRAW, 0); } wood_bed_button = button(wood_bed_button_id, 0, bed_choice_width, L"Дерево", BS_OWNERDRAW, 0); stone_bed_button = button(stone_bed_button_id, 0, bed_choice_width, L"Камень", BS_OWNERDRAW, 0); for (std::size_t index = 0; index < work_choice_buttons.size(); ++index) { work_choice_buttons[index] = button(first_work_choice_id + static_cast(index), 0, 100, L"", BS_OWNERDRAW, 0); ShowWindow(work_choice_buttons[index], SW_HIDE); } layout_command_dock(window); reset_world(window); refresh_lan_controls(window); SetTimer(window, timer_id, 60, nullptr); return 0; } case WM_DRAWITEM: if (const auto* item = reinterpret_cast(lparam); item && item->CtlType == ODT_BUTTON && draw_toolbar_button(*item)) return TRUE; break; case WM_COMMAND: if (LOWORD(wparam) == residents_button_id && HIWORD(wparam) == BN_CLICKED) { if (world) show_resident_roster(window); return 0; } if (LOWORD(wparam) >= farmer_menu_id && LOWORD(wparam) <= builder_menu_id && HIWORD(wparam) == BN_CLICKED) { const auto panel = static_cast(LOWORD(wparam) - farmer_menu_id); toggle_work_panel(window, panel); return 0; } if (LOWORD(wparam) >= first_dock_section_id && static_cast(LOWORD(wparam) - first_dock_section_id) < dock_sections.size() && HIWORD(wparam) == BN_CLICKED) { const auto panel = dock_sections[static_cast(LOWORD(wparam) - first_dock_section_id)].panel; toggle_work_panel(window, panel); return 0; } if (LOWORD(wparam) >= first_work_choice_id && static_cast(LOWORD(wparam) - first_work_choice_id) < work_choice_buttons.size() && HIWORD(wparam) == BN_CLICKED) { const auto choices = work_choices(); const auto index = static_cast(LOWORD(wparam) - first_work_choice_id); if (index >= choices.size() || (lan.is_guest() && lan.state() != LanState::GuestConnected)) return 0; SendMessageW(window, WM_COMMAND, static_cast(choices[index].command), 0); return 0; } if (LOWORD(wparam) >= lan_host_id && LOWORD(wparam) <= lan_leave_id) { handle_lan_menu(window, LOWORD(wparam)); return 0; } if (LOWORD(wparam) >= berry_field_id && LOWORD(wparam) <= demolish_id) { if (!world || (lan.is_guest() && lan.state() != LanState::GuestConnected)) return 0; constexpr PlacementMode modes[] = {PlacementMode::BerryField, PlacementMode::TreePlot, PlacementMode::Mine, PlacementMode::Storage, PlacementMode::Pantry, PlacementMode::Move, PlacementMode::Demolish}; set_placement_mode(window, modes[LOWORD(wparam) - berry_field_id]); SetFocus(window); return 0; } if ((LOWORD(wparam) == flax_field_id || LOWORD(wparam) == loom_id) && HIWORD(wparam) == BN_CLICKED) { if (!world || !can_give_orders()) return 0; set_placement_mode(window, LOWORD(wparam) == flax_field_id ? PlacementMode::FlaxField : PlacementMode::Loom); SetFocus(window); return 0; } if (LOWORD(wparam) == reset_camera_id) { camera = {}; hover_cell.reset(); invalidate_scene(window); return 0; } if (LOWORD(wparam) == save_menu_id || LOWORD(wparam) == load_menu_id) { handle_save_menu(window, LOWORD(wparam) == save_menu_id); return 0; } if (LOWORD(wparam) == apply_button_id) { if (lan.state() != LanState::Offline) return 0; const LRESULT selection = SendMessageW(worker_combo, CB_GETCURSEL, 0, 0); if (selection != CB_ERR) selected_workers = static_cast(selection) + settlement::min_worker_count; reset_world(window); return 0; } if (LOWORD(wparam) == cabin_button_id && HIWORD(wparam) == BN_CLICKED) { set_placement_mode(window, placement_mode == PlacementMode::Building ? PlacementMode::None : PlacementMode::Building); SetFocus(window); return 0; } if (HIWORD(wparam) == BN_CLICKED && shows_bed_choices() && (LOWORD(wparam) == wood_bed_button_id || LOWORD(wparam) == stone_bed_button_id)) { selected_bed_base = LOWORD(wparam) == wood_bed_button_id ? settlement::BedBase::Wood : settlement::BedBase::Stone; placement_message.clear(); update_bed_choices(); SetFocus(window); invalidate_scene(window); return 0; } if (LOWORD(wparam) == forage_action_id && HIWORD(wparam) == BN_CLICKED && world && (!lan.is_guest() || lan.state() == LanState::GuestConnected)) { set_placement_mode(window, placement_mode == PlacementMode::Foraging ? PlacementMode::None : PlacementMode::Foraging); SetFocus(window); return 0; } if (HIWORD(wparam) == BN_CLICKED && world && world->scenario_active()) { if (LOWORD(wparam) == priority_button_id) { const auto next = (static_cast(world->work_priority()) + 1U) % 3U; static_cast(send_command(settlement::CommandKind::SetPriority, {}, static_cast(next))); update_status(); return 0; } if (LOWORD(wparam) == pause_button_id) { static_cast(send_command(settlement::CommandKind::SetPaused, {}, static_cast(!world->paused()))); update_status(); return 0; } } break; case WM_MOUSEWHEEL: { POINT point = client_point(lparam); if (!ScreenToClient(window, &point)) break; RECT client{}; GetClientRect(window, &client); if (!is_map_point(client, point)) break; const double steps = static_cast(GET_WHEEL_DELTA_WPARAM(wparam)) / WHEEL_DELTA; camera.zoom_at({static_cast(point.x), static_cast(point.y)}, steps); update_map_hover(window, point); invalidate_scene(window); return 0; } case WM_MBUTTONDOWN: { RECT client{}; GetClientRect(window, &client); const POINT point = client_point(lparam); if (!is_map_point(client, point) || camera_drag) break; SetFocus(window); SetCapture(window); camera_drag = CameraDrag{point, false, false}; return 0; } case WM_MBUTTONUP: if (camera_drag && !camera_drag->left_button) { update_camera_drag(client_point(lparam)); camera_drag.reset(); if (GetCapture() == window) ReleaseCapture(); invalidate_scene(window); return 0; } break; case WM_CAPTURECHANGED: camera_drag.reset(); break; case WM_MOUSEMOVE: { const POINT point = client_point(lparam); if (camera_drag) { update_camera_drag(point); invalidate_scene(window); } update_map_hover(window, point); return 0; } case WM_MOUSELEAVE: hover_cell.reset(); invalidate_scene(window); return 0; case WM_LBUTTONDOWN: { RECT client{}; GetClientRect(window, &client); const POINT point = client_point(lparam); if (camera_drag || !is_map_point(client, point)) break; SetFocus(window); SetCapture(window); camera_drag = CameraDrag{point, true, false}; return 0; } case WM_LBUTTONUP: { if (!camera_drag || !camera_drag->left_button) break; const POINT point = client_point(lparam); update_camera_drag(point); const bool moved = camera_drag->moved; camera_drag.reset(); if (GetCapture() == window) ReleaseCapture(); if (moved) { update_map_hover(window, point); invalidate_scene(window); return 0; } RECT client{}; GetClientRect(window, &client); if (!is_map_point(client, point)) break; if (placement_mode == PlacementMode::Foraging && world) { const auto cell = map_cell(client, point); const auto* source = cell ? berry_source(*cell) : nullptr; if (source != nullptr) { static_cast(send_command(settlement::CommandKind::SetForaging, *cell, static_cast(!source->foraging_enabled))); } else { placement_message = L"Для сбора выберите ягодный куст."; } invalidate_scene(window); return 0; } if (placement_mode == PlacementMode::Building && world) { const auto cell = map_cell(client, point); if (world->scenario_active()) { if (!cell || !world->can_place_bed(*cell)) { placement_message = L"Для спального места нужна свободная клетка."; invalidate_scene(window); return 0; } if (shows_bed_choices() && !selected_bed_base) { placement_message = L"Сначала выберите основу под кнопкой «Спальное место»."; invalidate_scene(window); return 0; } const auto base = selected_bed_base.value_or(settlement::BedBase::Wood); if (send_command(settlement::CommandKind::PlaceBed, *cell, static_cast(base))) { hover_cell = cell; placement_message = lan.is_guest() ? L"Запрос на спальное место отправлен. Можно выбрать следующую клетку." : L"Спальное место заказано. Выберите следующую клетку или нажмите Esc."; update_status(); } else { placement_message = L"Для спального места нужна свободная клетка с проходом к мастерской."; } invalidate_scene(window); return 0; } if (!cell || !world->can_place_cabin(*cell)) { placement_message = L"Здесь нельзя поставить домик. Выберите свободную клетку."; invalidate_scene(window); return 0; } try { world->queue_cabin(*cell, sawmill, stonecutter); } catch (const std::invalid_argument&) { placement_message = L"К участку нет прохода от мастерских. Выберите другую клетку."; invalidate_scene(window); return 0; } set_placement_mode(window, PlacementMode::None, L"Чертёж поставлен. Материалы заказаны в мастерских."); update_status(); return 0; } if (world && placement_mode >= PlacementMode::BerryField) { if (const auto cell = map_cell(client, point)) edit_at_cell(window, *cell); return 0; } if (world) { selected_resident = resident_at(window, point); update_status(); sync_resident_roster(true); invalidate_scene(window); return 0; } break; } case WM_RBUTTONDOWN: if (placement_mode != PlacementMode::None || work_panel != WorkPanel::None) { set_placement_mode(window, PlacementMode::None); set_work_panel(window, WorkPanel::None); return 0; } break; case WM_KEYDOWN: if ((GetKeyState(VK_CONTROL) & 0x8000) == 0 && (wparam == 'H' || wparam == 'Z' || wparam == 'B')) { if ((lparam & (1L << 30)) == 0) { toggle_work_panel(window, wparam == 'H' ? WorkPanel::Gathering : wparam == 'Z' ? WorkPanel::Zones : WorkPanel::Construction); } return 0; } if (wparam == 'C' && (GetKeyState(VK_CONTROL) & 0x8000) == 0) { if (world) show_resident_roster(window); return 0; } if (wparam == VK_HOME) { SendMessageW(window, WM_COMMAND, reset_camera_id, 0); return 0; } if (wparam == VK_ESCAPE && (placement_mode != PlacementMode::None || work_panel != WorkPanel::None)) { set_placement_mode(window, PlacementMode::None); set_work_panel(window, WorkPanel::None); return 0; } break; case WM_TIMER: if (wparam == timer_id && world) { if (!file_dialog_active && !lan.is_guest()) world->step(); if (auto snapshot = lan.poll(*world)) world = std::move(snapshot); sync_resident_roster(); if (lan.state() != displayed_lan_state) refresh_lan_controls(window); if (const auto rejection = lan.take_rejection()) { placement_message = *rejection == settlement::CommandStatus::Busy ? L"Объект занят. Дождитесь окончания работы или сна." : L"Хозяин отклонил команду. Проверьте выбранную клетку."; } update_status(); invalidate_scene(window); return 0; } break; case WM_ERASEBKGND: return 1; case WM_SIZE: layout_command_dock(window); InvalidateRect(window, nullptr, FALSE); break; case WM_PAINT: { PAINTSTRUCT paint{}; HDC target = BeginPaint(window, &paint); RECT client{}; GetClientRect(window, &client); const int width = client.right - client.left; const int height = client.bottom - client.top; HDC buffer = CreateCompatibleDC(target); HBITMAP bitmap = CreateCompatibleBitmap(target, width, height); HGDIOBJ old_bitmap = SelectObject(buffer, bitmap); draw_world(buffer, width, height); const RECT& dirty = paint.rcPaint; BitBlt(target, dirty.left, dirty.top, dirty.right - dirty.left, dirty.bottom - dirty.top, buffer, dirty.left, dirty.top, SRCCOPY); SelectObject(buffer, old_bitmap); DeleteObject(bitmap); DeleteDC(buffer); EndPaint(window, &paint); return 0; } case WM_DESTROY: KillTimer(window, timer_id); lan.leave(); PostQuitMessage(0); return 0; } return DefWindowProcW(window, message, wparam, lparam); } } // namespace int WINAPI wWinMain(HINSTANCE instance, HINSTANCE, PWSTR, int show_command) { INITCOMMONCONTROLSEX controls{sizeof(controls), ICC_STANDARD_CLASSES | ICC_LISTVIEW_CLASSES}; InitCommonControlsEx(&controls); WNDCLASSEXW window_class_info{}; window_class_info.cbSize = sizeof(window_class_info); window_class_info.hInstance = instance; window_class_info.lpfnWndProc = window_proc; window_class_info.lpszClassName = window_class; window_class_info.hCursor = LoadCursorW(nullptr, IDC_ARROW); window_class_info.hbrBackground = reinterpret_cast(COLOR_WINDOW + 1); RegisterClassExW(&window_class_info); HMENU menu_bar = CreateMenu(); HMENU file_menu = CreatePopupMenu(); HMENU view_menu = CreatePopupMenu(); HMENU coop_menu = CreatePopupMenu(); HMENU work_menu = create_work_menu(); AppendMenuW(file_menu, MF_STRING, save_menu_id, L"Сохранить поселение…"); AppendMenuW(file_menu, MF_STRING, load_menu_id, L"Загрузить поселение…"); AppendMenuW(menu_bar, MF_POPUP, reinterpret_cast(file_menu), L"Поселение"); AppendMenuW(view_menu, MF_STRING, reset_camera_id, L"Общий план\tHome"); AppendMenuW(menu_bar, MF_POPUP, reinterpret_cast(view_menu), L"Вид"); if (work_menu != nullptr) { AppendMenuW(menu_bar, MF_POPUP, reinterpret_cast(work_menu), L"Работы"); } AppendMenuW(coop_menu, MF_STRING, lan_host_id, L"Открыть колонию для друга…"); AppendMenuW(coop_menu, MF_STRING, lan_join_id, L"Подключиться…"); AppendMenuW(coop_menu, MF_STRING, lan_info_id, L"Адрес и код партии…"); AppendMenuW(coop_menu, MF_STRING, lan_reconnect_id, L"Подключиться снова"); AppendMenuW(coop_menu, MF_SEPARATOR, 0, nullptr); AppendMenuW(coop_menu, MF_STRING, lan_leave_id, L"Выйти из сетевой игры"); AppendMenuW(menu_bar, MF_POPUP, reinterpret_cast(coop_menu), L"Кооператив"); HWND window = CreateWindowExW(0, window_class, L"Settlement — Первое поселение", WS_OVERLAPPEDWINDOW | WS_CLIPCHILDREN, CW_USEDEFAULT, CW_USEDEFAULT, 1120, 752, nullptr, menu_bar, instance, nullptr); if (!window) { DestroyMenu(menu_bar); return 1; } ShowWindow(window, show_command); UpdateWindow(window); MSG message{}; while (GetMessageW(&message, nullptr, 0, 0) > 0) { if (roster.window && IsDialogMessageW(roster.window, &message)) continue; TranslateMessage(&message); DispatchMessageW(&message); } return static_cast(message.wParam); }