From 5cb3b9cec212d2da8ae15ac6987fb66b093515d6 Mon Sep 17 00:00:00 2001 From: Codex Date: Sun, 29 Nov 2026 18:34:15 +0300 Subject: [PATCH 1/7] Start the Windows game at a colony and save menu --- PLAN.md | 3 +- app/title_screen_win32.hpp | 241 +++++++++++++++++++++++++++++++++++++ app/viewer_win32.cpp | 198 +++++++++++++++++++++--------- docs/roadmap-status.md | 3 +- docs/viewer.md | 10 +- 5 files changed, 395 insertions(+), 60 deletions(-) create mode 100644 app/title_screen_win32.hpp diff --git a/PLAN.md b/PLAN.md index 832e915..5802f98 100644 --- a/PLAN.md +++ b/PLAN.md @@ -39,7 +39,7 @@ - [x] Пул потоков для независимого выбора заданий, A* и продвижения жителей. - [x] Стабильное применение результатов в конце шага симуляции. - [x] Многопоточный режим с двумя и более рабочими потоками; проверка игровых результатов и загрузки. -- [x] Выбор числа потоков в командной версии и Windows-клиенте. +- [x] Автоматический выбор числа потоков в Windows-клиенте и параметр для командных бенчмарков. - [x] Повторный замер времени тика после расширения систем ресурсов. ### P4 — Игровой клиент @@ -48,6 +48,7 @@ - [x] Отображение источников ресурсов, складов и текущих запасов. - [x] Камера с перемещением и масштабированием относительно курсора. - [x] Нижняя панель с жителями, добычей, участками и строительством. +- [x] Главное меню перед игрой со списком сохранений, продолжением партии и подключением к другу. - [ ] Настоящий графический 3D-рендерер и объёмные модели. - [x] Постановка чертежа домика мышью в Windows-клиенте. - [ ] Интерфейс для остальных типов работ и зданий. diff --git a/app/title_screen_win32.hpp b/app/title_screen_win32.hpp new file mode 100644 index 0000000..e00f37f --- /dev/null +++ b/app/title_screen_win32.hpp @@ -0,0 +1,241 @@ +#pragma once + +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace settlement::viewer { + +constexpr int title_continue_id = 1100; +constexpr int title_new_id = 1101; +constexpr int title_browse_id = 1102; +constexpr int title_join_id = 1103; +constexpr int title_exit_id = 1104; +constexpr int title_saves_id = 1105; +constexpr int title_open_id = 1106; + +inline std::filesystem::path saves_directory() { + const DWORD length = GetEnvironmentVariableW(L"LOCALAPPDATA", nullptr, 0); + if (length == 0) return {}; + std::wstring base(length, L'\0'); + const DWORD copied = GetEnvironmentVariableW(L"LOCALAPPDATA", base.data(), length); + if (copied == 0 || copied >= length) return {}; + base.resize(copied); + return std::filesystem::path(base) / L"Settlement" / L"Saves"; +} + +class TitleScreen { +public: + ~TitleScreen() { + if (list_background_) DeleteObject(list_background_); + if (font_) DeleteObject(font_); + } + + void create(HWND owner) { + constexpr const wchar_t* names[] = { + L"Продолжить", L"Новая колония", L"Открыть файл…", L"Подключиться к другу…", L"Выход" + }; + const auto instance = GetModuleHandleW(nullptr); + for (std::size_t i = 0; i < buttons_.size(); ++i) { + buttons_[i] = CreateWindowExW(0, L"BUTTON", names[i], WS_CHILD | WS_TABSTOP | BS_OWNERDRAW, + 0, 0, 0, 0, owner, id(title_continue_id + static_cast(i)), instance, nullptr); + } + saves_ = CreateWindowExW(WS_EX_CLIENTEDGE, L"LISTBOX", L"", + WS_CHILD | WS_TABSTOP | WS_VSCROLL | LBS_NOTIFY | LBS_NOINTEGRALHEIGHT, + 0, 0, 0, 0, owner, id(title_saves_id), instance, nullptr); + open_ = CreateWindowExW(0, L"BUTTON", L"Загрузить выбранное", WS_CHILD | WS_TABSTOP | BS_OWNERDRAW, + 0, 0, 0, 0, owner, id(title_open_id), instance, nullptr); + list_background_ = CreateSolidBrush(RGB(44, 63, 53)); + font_ = CreateFontW(-16, 0, 0, 0, FW_NORMAL, FALSE, FALSE, FALSE, DEFAULT_CHARSET, + OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS, CLEARTYPE_QUALITY, DEFAULT_PITCH | FF_SWISS, L"Segoe UI"); + const auto font = reinterpret_cast(font_ ? font_ : GetStockObject(DEFAULT_GUI_FONT)); + for (const auto button : buttons_) SendMessageW(button, WM_SETFONT, font, FALSE); + SendMessageW(saves_, WM_SETFONT, font, FALSE); + SendMessageW(open_, WM_SETFONT, font, FALSE); + } + + void reload_saves() { + const auto folder = saves_directory(); + saves.clear(); + SendMessageW(saves_, LB_RESETCONTENT, 0, 0); + if (folder.empty()) return; + std::error_code error; + for (auto entry = std::filesystem::directory_iterator(folder, error); + !error && entry != std::filesystem::directory_iterator{}; entry.increment(error)) { + std::error_code file_error; + if (!entry->is_regular_file(file_error)) continue; + if (_wcsicmp(entry->path().extension().c_str(), L".settlement") != 0) continue; + const auto written = entry->last_write_time(file_error); + if (!file_error) saves.push_back({entry->path(), written}); + } + std::sort(saves.begin(), saves.end(), [](const auto& a, const auto& b) { + if (a.written != b.written) return a.written > b.written; + return a.path < b.path; + }); + for (const auto& entry : saves) { + const auto name = entry.path.stem().wstring(); + SendMessageW(saves_, LB_ADDSTRING, 0, reinterpret_cast(name.c_str())); + } + if (!saves.empty()) SendMessageW(saves_, LB_SETCURSEL, 0, 0); + } + + void show(bool visible) const { + const int flags = visible ? SW_SHOWNA : SW_HIDE; + for (const auto button : buttons_) ShowWindow(button, flags); + ShowWindow(saves_, flags); + ShowWindow(open_, flags); + } + + void update(bool has_session, bool connecting) const { + EnableWindow(buttons_[0], !connecting && (has_session || !saves.empty())); + for (std::size_t i = 1; i < buttons_.size() - 1; ++i) EnableWindow(buttons_[i], !connecting); + EnableWindow(open_, !connecting && selected_index() < saves.size()); + EnableWindow(saves_, !connecting); + } + + HBRUSH paint_list_background(HWND control, HDC dc) const { + if (control != saves_ || !list_background_) return nullptr; + SetTextColor(dc, RGB(246, 237, 210)); + SetBkColor(dc, RGB(44, 63, 53)); + return list_background_; + } + + [[nodiscard]] std::optional selected_save() const { + const auto selected = selected_index(); + return selected < saves.size() ? std::optional{saves[selected].path} : std::nullopt; + } + + [[nodiscard]] std::optional latest_save() const { + return saves.empty() ? std::nullopt : std::optional{saves.front().path}; + } + + void layout(int width, int height) const { + const RECT panel = bounds(width, height); + for (std::size_t i = 0; i < buttons_.size(); ++i) { + position(buttons_[i], panel.left + 28, panel.top + 118 + static_cast(i) * 40, 252, 33); + } + position(saves_, panel.left + 318, panel.top + 146, panel.right - panel.left - 346, 118); + position(open_, panel.left + 318, panel.top + 274, panel.right - panel.left - 346, 33); + } + + void draw(HDC dc, int width, int height, const std::wstring& notice) const { + shade(dc, {0, 0, width, height}, RGB(24, 38, 34)); + // A simple isometric landscape with the same palette as the colony map. + const auto old_pen = SelectObject(dc, GetStockObject(NULL_PEN)); + const auto distant = CreateSolidBrush(RGB(32, 53, 44)); + const auto near_hills = CreateSolidBrush(RGB(41, 66, 50)); + const auto old_brush = SelectObject(dc, distant); + const POINT hills[] = {{0, height}, {0, height * 5 / 8}, {width / 4, height / 4}, + {width * 5 / 9, height * 5 / 8}, {width * 5 / 6, height / 4}, {width, height / 2}, {width, height}}; + Polygon(dc, hills, static_cast(std::size(hills))); + SelectObject(dc, near_hills); + const POINT foreground[] = {{0, height}, {0, height * 7 / 8}, {width / 3, height / 2}, + {width * 3 / 4, height * 7 / 8}, {width, height * 3 / 5}, {width, height}}; + Polygon(dc, foreground, static_cast(std::size(foreground))); + SelectObject(dc, old_brush); + SelectObject(dc, old_pen); + DeleteObject(near_hills); + DeleteObject(distant); + + const RECT panel = bounds(width, height); + shade(dc, panel, RGB(35, 50, 43)); + shade(dc, {panel.left, panel.top, panel.right, panel.top + 2}, RGB(179, 150, 92)); + const auto face = CreateFontW(-46, 0, 0, 0, FW_BOLD, FALSE, FALSE, FALSE, DEFAULT_CHARSET, + OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS, CLEARTYPE_QUALITY, DEFAULT_PITCH | FF_ROMAN, L"Georgia"); + const auto font = SelectObject(dc, face ? face : GetStockObject(DEFAULT_GUI_FONT)); + const auto mode = SetBkMode(dc, TRANSPARENT); + const auto ink = SetTextColor(dc, RGB(248, 235, 204)); + RECT heading{panel.left + 27, panel.top + 19, panel.right - 27, panel.top + 76}; + DrawTextW(dc, L"Settlement", -1, &heading, DT_SINGLELINE | DT_VCENTER); + SelectObject(dc, font_ ? font_ : GetStockObject(DEFAULT_GUI_FONT)); + RECT name{panel.left + 30, panel.top + 78, panel.right - 28, panel.top + 99}; + DrawTextW(dc, L"Первое поселение", -1, &name, DT_SINGLELINE | DT_VCENTER); + RECT saves_label{panel.left + 318, panel.top + 117, panel.right - 27, panel.top + 140}; + DrawTextW(dc, saves.empty() ? L"Сохранения · список пуст" : L"Сохранения", -1, + &saves_label, DT_SINGLELINE | DT_VCENTER); + if (!notice.empty()) { + RECT information{panel.left + 318, panel.top + 311, panel.right - 27, panel.bottom - 11}; + DrawTextW(dc, notice.c_str(), -1, &information, DT_WORDBREAK | DT_NOPREFIX); + } + SetTextColor(dc, ink); + SetBkMode(dc, mode); + SelectObject(dc, font); + if (face) DeleteObject(face); + } + + static bool draw_button(const DRAWITEMSTRUCT& item) { + if (item.CtlID < title_continue_id || item.CtlID > title_open_id || item.CtlID == title_saves_id) return false; + const bool disabled = (item.itemState & ODS_DISABLED) != 0; + const bool accented = (item.itemState & (ODS_SELECTED | ODS_FOCUS)) != 0; + const bool primary = item.CtlID == title_new_id && !disabled; + shade(item.hDC, item.rcItem, accented ? RGB(90, 105, 70) : + (primary ? RGB(69, 89, 60) : RGB(47, 65, 55))); + const auto edge = CreateSolidBrush(accented || primary ? RGB(186, 157, 100) : RGB(91, 110, 91)); + FrameRect(item.hDC, &item.rcItem, edge); + DeleteObject(edge); + RECT label = item.rcItem; + InflateRect(&label, -12, 0); + wchar_t text[96]{}; + GetWindowTextW(item.hwndItem, text, static_cast(std::size(text))); + const auto face = reinterpret_cast(SendMessageW(item.hwndItem, WM_GETFONT, 0, 0)); + const auto font = SelectObject(item.hDC, face ? face : GetStockObject(DEFAULT_GUI_FONT)); + const auto mode = SetBkMode(item.hDC, TRANSPARENT); + const auto ink = SetTextColor(item.hDC, disabled ? RGB(162, 173, 157) : RGB(248, 240, 217)); + DrawTextW(item.hDC, text, -1, &label, DT_LEFT | DT_VCENTER | DT_SINGLELINE | DT_END_ELLIPSIS); + SetTextColor(item.hDC, ink); + SetBkMode(item.hDC, mode); + SelectObject(item.hDC, font); + if ((item.itemState & ODS_FOCUS) != 0) { + RECT focus = item.rcItem; + InflateRect(&focus, -4, -4); + DrawFocusRect(item.hDC, &focus); + } + return true; + } + +private: + struct SaveFile { + std::filesystem::path path; + std::filesystem::file_time_type written; + }; + + static HMENU id(int value) { return reinterpret_cast(static_cast(value)); } + + static RECT bounds(int width, int height) { + constexpr int panel_width = 704; + constexpr int panel_height = 365; + const int left = (width - panel_width) / 2; + const int top = (height - panel_height) / 2; + return {left, top, left + panel_width, top + panel_height}; + } + + static void position(HWND control, int x, int y, int width, int height) { + SetWindowPos(control, nullptr, x, y, width, height, SWP_NOACTIVATE | SWP_NOZORDER); + } + + static void shade(HDC dc, RECT area, COLORREF color) { + const auto brush = CreateSolidBrush(color); + FillRect(dc, &area, brush); + DeleteObject(brush); + } + + [[nodiscard]] std::size_t selected_index() const { + const auto selection = SendMessageW(saves_, LB_GETCURSEL, 0, 0); + return selection == LB_ERR ? saves.size() : static_cast(selection); + } + + std::array buttons_{}; + HWND saves_ = nullptr; + HWND open_ = nullptr; + HBRUSH list_background_ = nullptr; + HFONT font_ = nullptr; + std::vector saves; +}; + +} // namespace settlement::viewer diff --git a/app/viewer_win32.cpp b/app/viewer_win32.cpp index 0d4c221..d4d4583 100644 --- a/app/viewer_win32.cpp +++ b/app/viewer_win32.cpp @@ -8,6 +8,7 @@ #include "isometric_camera.hpp" #include "lan_session.hpp" +#include "title_screen_win32.hpp" #include "settlement/core/world.hpp" #include @@ -33,8 +34,7 @@ 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 title_menu_id = 1002; constexpr int status_label_id = 1003; constexpr int cabin_button_id = 1004; constexpr int save_menu_id = 1005; @@ -82,8 +82,6 @@ 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; @@ -93,10 +91,16 @@ HWND pause_button = nullptr; HWND residents_button = nullptr; std::array dock_section_buttons{}; std::unique_ptr world; +namespace title = settlement::viewer; +title::TitleScreen title_screen; +bool showing_title = true; +bool has_session = false; +HMENU play_menu = nullptr; using settlement::viewer::LanState; settlement::viewer::LanSession lan; LanState displayed_lan_state = LanState::Offline; -std::size_t selected_workers = settlement::min_worker_count; +const auto local_worker_count = std::clamp( + std::thread::hardware_concurrency(), settlement::min_worker_count, 8); 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 }; @@ -316,7 +320,8 @@ bool shows_bed_choices() { } 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; + return !showing_title && point.x >= 0 && point.x < client.right && + point.y >= map_top && point.y < client.bottom - map_footer; } POINT client_point(LPARAM coordinates) { @@ -832,8 +837,7 @@ void update_status() { 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())); + L" Ход: " + std::to_wstring(world->tick()); SetWindowTextW(status_label, text.c_str()); const bool scenario = world->scenario_active(); const bool can_play = can_give_orders(); @@ -910,13 +914,41 @@ void toggle_work_panel(HWND window, WorkPanel panel) { SetFocus(window); } +void show_title_screen(HWND window, bool visible) { + showing_title = visible; + if (visible) { + if (roster.window) DestroyWindow(roster.window); + set_work_panel(window, WorkPanel::None); + set_placement_mode(window, PlacementMode::None); + title_screen.reload_saves(); + title_screen.update(has_session, lan.state() == LanState::Connecting); + } else { + has_session = true; + } + const int flags = visible ? SW_HIDE : SW_SHOWNA; + for (const auto control : {status_label, production_label, priority_button, pause_button, residents_button}) { + ShowWindow(control, flags); + } + for (const auto control : dock_section_buttons) ShowWindow(control, flags); + title_screen.show(visible); + SetMenu(window, visible ? nullptr : play_menu); + DrawMenuBar(window); + RECT client{}; + GetClientRect(window, &client); + title_screen.layout(client.right, client.bottom); + layout_command_dock(window); + SetFocus(window); + InvalidateRect(window, nullptr, FALSE); +} + void reset_world(HWND window) { - world = settlement::make_first_colony(selected_workers); + world = settlement::make_first_colony(local_worker_count); camera = {}; selected_resident.reset(); sync_resident_roster(true); set_work_panel(window, WorkPanel::None); set_placement_mode(window, PlacementMode::None); + show_title_screen(window, false); update_status(); invalidate_scene(window); } @@ -932,6 +964,12 @@ std::optional choose_save_file(HWND window, bool saving) dialog.lpstrFile = filename; dialog.nMaxFile = static_cast(std::size(filename)); dialog.lpstrDefExt = L"settlement"; + const auto folder = title::saves_directory(); + if (!folder.empty()) { + std::error_code error; + if (saving) std::filesystem::create_directories(folder, error); + if (std::filesystem::is_directory(folder, error)) dialog.lpstrInitialDir = folder.c_str(); + } dialog.Flags = OFN_EXPLORER | OFN_NOCHANGEDIR | OFN_PATHMUSTEXIST | (saving ? OFN_OVERWRITEPROMPT : OFN_FILEMUSTEXIST); const BOOL accepted = saving ? GetSaveFileNameW(&dialog) : GetOpenFileNameW(&dialog); @@ -961,8 +999,8 @@ void save_world_file(const std::filesystem::path& path) { } } -void handle_save_menu(HWND window, bool saving) { - if (file_dialog_active || !world) return; +void handle_save_menu(HWND window, bool saving, std::optional selected = std::nullopt) { + if (file_dialog_active || (saving && !world)) return; if (lan.is_guest() || (!saving && lan.state() != LanState::Offline)) return; file_dialog_active = true; struct RestoreTimer { @@ -970,7 +1008,7 @@ void handle_save_menu(HWND window, bool saving) { } restore_timer; try { - const auto path = choose_save_file(window, saving); + const auto path = selected ? std::move(selected) : choose_save_file(window, saving); if (!path) return; if (saving) { save_world_file(*path); @@ -980,15 +1018,17 @@ void handle_save_menu(HWND window, bool saving) { } 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); + auto loaded = settlement::World::read_save(stream, local_worker_count); 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); + camera = {}; selected_resident.reset(); sync_resident_roster(true); set_work_panel(window, WorkPanel::None); set_placement_mode(window, PlacementMode::None, L"Поселение загружено."); + show_title_screen(window, false); update_status(); } catch (const std::exception& error) { const std::string_view details(error.what()); @@ -1104,17 +1144,15 @@ void refresh_lan_controls(HWND window) { 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)); + if (play_menu) EnableMenuItem(play_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(title_menu_id, offline); enable(save_menu_id, !lan.is_guest()); enable(load_menu_id, offline); const wchar_t* suffix = L""; @@ -1126,24 +1164,29 @@ void refresh_lan_controls(HWND window) { 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()); + const auto caption = std::wstring(showing_title ? L"Settlement" : L"Settlement — Первое поселение") + suffix; + SetWindowTextW(window, caption.c_str()); if (disconnected) { set_placement_mode(window, PlacementMode::None); - placement_message = L"Связь прервана. «Кооператив → Подключиться снова». " + widen_ascii(lan.detail()); + placement_message = showing_title ? L"Не удалось подключиться. Проверьте адрес и код." : + L"Связь прервана. «Кооператив → Подключиться снова». " + widen_ascii(lan.detail()); } else if (state == LanState::GuestConnected) { placement_message = L"Подключено к колонии хозяина."; } DrawMenuBar(window); if (roster.window) update_roster_details(); update_status(); + if (showing_title) { + title_screen.update(has_session, state == LanState::Connecting); + InvalidateRect(window, nullptr, FALSE); + } 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()) { + if (!world || !world->scenario_active()) { throw std::runtime_error("Start the playable colony before hosting."); } lan.host(); @@ -1153,6 +1196,7 @@ void handle_lan_menu(HWND window, int command) { (lan.state() == LanState::Offline || lan.state() == LanState::GuestDisconnected)) { const auto request = ask_join_address(window); if (!request) return; + if (!world) world = settlement::make_first_colony(local_worker_count); lan.join(narrow_lan_input(request->address.data()), narrow_lan_input(request->code.data())); selected_resident.reset(); sync_resident_roster(true); @@ -1175,6 +1219,41 @@ void handle_lan_menu(HWND window, int command) { } } +void handle_title_command(HWND window, int command, int notification) { + if (command == title::title_exit_id && notification == BN_CLICKED) { + DestroyWindow(window); + return; + } + if (lan.state() == LanState::Connecting) return; + if (command == title::title_saves_id && notification == LBN_SELCHANGE) { + title_screen.update(has_session, false); + return; + } + if (command == title::title_join_id && notification == BN_CLICKED) { + handle_lan_menu(window, lan_join_id); + return; + } + const bool open_selected = (command == title::title_open_id && notification == BN_CLICKED) || + (command == title::title_saves_id && notification == LBN_DBLCLK); + if (!open_selected && (notification != BN_CLICKED || + (command != title::title_new_id && command != title::title_continue_id && command != title::title_browse_id))) { + return; + } + if (lan.state() == LanState::GuestDisconnected) lan.leave(); + if (open_selected) { + if (const auto path = title_screen.selected_save()) handle_save_menu(window, false, path); + } else if (command == title::title_new_id) { + reset_world(window); + } else if (command == title::title_browse_id) { + handle_save_menu(window, false); + } else if (has_session) { + show_title_screen(window, false); + } else if (const auto path = title_screen.latest_save()) { + handle_save_menu(window, false, path); + } + refresh_lan_controls(window); +} + 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; @@ -1714,27 +1793,9 @@ LRESULT CALLBACK window_proc(HWND window, UINT message, WPARAM wparam, LPARAM lp 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); + play_menu = GetMenu(window); status_label = CreateWindowExW(0, L"STATIC", L"", WS_CHILD | WS_VISIBLE, - 430, 14, 620, 24, window, + 18, 14, 735, 24, window, reinterpret_cast(static_cast(status_label_id)), GetModuleHandleW(nullptr), nullptr); production_label = CreateWindowExW(0, L"STATIC", L"", WS_CHILD | WS_VISIBLE, @@ -1760,17 +1821,29 @@ LRESULT CALLBACK window_proc(HWND window, UINT message, WPARAM wparam, LPARAM lp 0, 100, L"", BS_OWNERDRAW, 0); ShowWindow(work_choice_buttons[index], SW_HIDE); } - layout_command_dock(window); - reset_world(window); + title_screen.create(window); + show_title_screen(window, true); 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; + item && item->CtlType == ODT_BUTTON) { + if (showing_title ? title::TitleScreen::draw_button(*item) : draw_toolbar_button(*item)) return TRUE; + } + break; + case WM_CTLCOLORLISTBOX: + if (showing_title) { + if (const auto brush = title_screen.paint_list_background(reinterpret_cast(lparam), + reinterpret_cast(wparam))) return reinterpret_cast(brush); + } break; case WM_COMMAND: + if (showing_title) { + handle_title_command(window, LOWORD(wparam), HIWORD(wparam)); + return 0; + } if (LOWORD(wparam) == residents_button_id && HIWORD(wparam) == BN_CLICKED) { if (world) show_resident_roster(window); return 0; @@ -1825,11 +1898,11 @@ LRESULT CALLBACK window_proc(HWND window, UINT message, WPARAM wparam, LPARAM lp 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); + if (LOWORD(wparam) == title_menu_id) { + if (lan.state() == LanState::Offline) { + show_title_screen(window, true); + refresh_lan_controls(window); + } return 0; } if (LOWORD(wparam) == cabin_button_id && HIWORD(wparam) == BN_CLICKED) { @@ -2016,6 +2089,7 @@ LRESULT CALLBACK window_proc(HWND window, UINT message, WPARAM wparam, LPARAM lp } break; case WM_KEYDOWN: + if (showing_title) break; 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 : @@ -2039,8 +2113,12 @@ LRESULT CALLBACK window_proc(HWND window, UINT message, WPARAM wparam, LPARAM lp 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); + if (showing_title && lan.state() != LanState::Connecting) return 0; + if (!showing_title && !file_dialog_active && !lan.is_guest()) world->step(); + if (auto snapshot = lan.poll(*world)) { + world = std::move(snapshot); + if (showing_title) show_title_screen(window, false); + } sync_resident_roster(); if (lan.state() != displayed_lan_state) refresh_lan_controls(window); if (const auto rejection = lan.take_rejection()) { @@ -2056,7 +2134,13 @@ LRESULT CALLBACK window_proc(HWND window, UINT message, WPARAM wparam, LPARAM lp case WM_ERASEBKGND: return 1; case WM_SIZE: - layout_command_dock(window); + if (showing_title) { + RECT client{}; + GetClientRect(window, &client); + title_screen.layout(client.right, client.bottom); + } else { + layout_command_dock(window); + } InvalidateRect(window, nullptr, FALSE); break; case WM_PAINT: { @@ -2069,7 +2153,8 @@ LRESULT CALLBACK window_proc(HWND window, UINT message, WPARAM wparam, LPARAM lp HDC buffer = CreateCompatibleDC(target); HBITMAP bitmap = CreateCompatibleBitmap(target, width, height); HGDIOBJ old_bitmap = SelectObject(buffer, bitmap); - draw_world(buffer, width, height); + if (showing_title) title_screen.draw(buffer, width, height, placement_message); + else 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); @@ -2082,6 +2167,8 @@ LRESULT CALLBACK window_proc(HWND window, UINT message, WPARAM wparam, LPARAM lp case WM_DESTROY: KillTimer(window, timer_id); lan.leave(); + if (play_menu && GetMenu(window) != play_menu) DestroyMenu(play_menu); + play_menu = nullptr; PostQuitMessage(0); return 0; } @@ -2109,6 +2196,8 @@ int WINAPI wWinMain(HINSTANCE instance, HINSTANCE, PWSTR, int show_command) { 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(file_menu, MF_SEPARATOR, 0, nullptr); + AppendMenuW(file_menu, MF_STRING, title_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"Вид"); @@ -2122,7 +2211,7 @@ int WINAPI wWinMain(HINSTANCE instance, HINSTANCE, PWSTR, int show_command) { 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 — Первое поселение", + 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) { @@ -2135,6 +2224,7 @@ int WINAPI wWinMain(HINSTANCE instance, HINSTANCE, PWSTR, int show_command) { MSG message{}; while (GetMessageW(&message, nullptr, 0, 0) > 0) { if (roster.window && IsDialogMessageW(roster.window, &message)) continue; + if (showing_title && IsDialogMessageW(window, &message)) continue; TranslateMessage(&message); DispatchMessageW(&message); } diff --git a/docs/roadmap-status.md b/docs/roadmap-status.md index cfd966c..f87e70a 100644 --- a/docs/roadmap-status.md +++ b/docs/roadmap-status.md @@ -4,7 +4,7 @@ - Ядро симуляции с фиксированными тиками. - Пул потоков для выбора заданий, поиска маршрутов и продвижения жителей. -- Настройка числа потоков в командной версии и в Windows-просмотрщике. +- Автоматический выбор числа потоков в Windows-клиенте и параметр для командных бенчмарков. - Изометрический прототип карты с жителями, заданиями и маршрутами. - Базовый цикл ресурсов: источник дерева/камня → резервирование → добыча → перенос → склад. - Складской инвентарь со стеками `Wood` и `Stone` и учётом свободной вместимости. @@ -26,6 +26,7 @@ - Рост полей и посадок начинается после выполнения поручения фермером или лесорубом. После сбора участка выдаётся новое поручение. - Производительность ядра измерена на колониях с 50–500 жителями, полями, складами и ремеслом. Результаты и команда запуска описаны в [отчёте](../benchmarks/colony-performance.md). - Основные команды собраны в нижней панели «Жители», «Добыча», «Участки» и «Строительство». Меню «Работы» открывает те же команды по профессиям. +- Главное меню открывается при запуске. В нём можно начать новую колонию, выбрать сохранение или подключиться к другу. - Поиск ресурсных работ отбирает подходящие поручения по профессиям. Повторные запросы путей используют кэш. - Движение, прогресс работ жителей и поиск маршрутов для общих заданий выполняются в пуле из двух и более потоков. Тесты проверяют игровые результаты, сохранения и команды кооператива. diff --git a/docs/viewer.md b/docs/viewer.md index 2ca3d51..0ac37c8 100644 --- a/docs/viewer.md +++ b/docs/viewer.md @@ -6,7 +6,9 @@ powershell.exe -NoProfile -ExecutionPolicy Bypass -File .\build.ps1 ``` -После сборки запустите `build\settlement_viewer.exe`. В списке доступны от двух рабочих потоков до числа логических процессоров компьютера, максимум 32. Нажмите «Применить и начать заново», чтобы применить выбор и перезапустить демонстрационное поселение. +После сборки запустите `build\settlement_viewer.exe`. Откроется главное меню. Здесь можно начать новую колонию, продолжить текущую партию, загрузить сохранение или подключиться к другу по локальной сети. Игра автоматически выбирает от двух до восьми рабочих потоков с учётом числа логических процессоров. + +Список показывает файлы `.settlement` из папки `%LOCALAPPDATA%\Settlement\Saves`, начиная с самого свежего. Дважды щёлкните по сохранению или нажмите «Загрузить выбранное». «Открыть файл…» позволяет загрузить сохранение из любой папки. При первом запуске «Продолжить» открывает самое свежее сохранение из списка. При запуске без явного параметра командная версия выбирает от двух до восьми потоков с учётом числа логических процессоров. Для ручного выбора используйте `settlement_sim.exe --workers N`, где N от 2 до 32. @@ -32,14 +34,14 @@ powershell.exe -NoProfile -ExecutionPolicy Bypass -File .\build.ps1 Кусты дают ягоды, которые жители несут в кладовую с розовой крышкой. Розовый маршрут ведёт к еде. Чтобы увидеть голод жителя и его груз, щёлкните по фигурке вне режима размещения чертежа. -В меню «Поселение» выберите «Сохранить поселение…» или «Загрузить поселение…». Время останавливается на время выбора файла. Файл `.settlement` хранит карту, текущий такт, голод, запасы, заказы и маршруты. При загрузке используются рабочие потоки текущего окна. Если файл повреждён или его версия не подходит, окно показывает ошибку и продолжает текущую партию. +В меню «Поселение» выберите «Сохранить поселение…» или «Загрузить поселение…». Время останавливается на время выбора файла. Файл `.settlement` хранит карту, текущий такт, голод, запасы, заказы и маршруты. Если файл повреждён или его версия не подходит, окно показывает ошибку и продолжает текущую партию. -Старые сохранения продолжаются со своими правилами стройки. Кнопка «Применить и начать заново» запускает партию с поэтапной сборкой и стартовым запасом ткани. +В одиночной игре «Поселение → Главное меню» останавливает симуляцию. «Продолжить» возвращает к текущей колонии. «Новая колония» запускает отдельную партию с поэтапной сборкой и стартовым запасом ткани. Старые сохранения продолжаются со своими правилами стройки. ## Кооператив по локальной сети 1. Запустите одинаковую версию игры на двух компьютерах в одной локальной сети. 2. Хозяин открывает свою колонию через «Кооператив → Открыть колонию для друга…» и передаёт гостю IPv4 и код партии. Порт игры — TCP 41727. -3. Гость выбирает «Кооператив → Подключиться…» и вводит эти данные. При обрыве связи можно выбрать «Подключиться снова», пока хозяин оставляет партию открытой. +3. Гость выбирает «Подключиться к другу…» в главном меню или «Кооператив → Подключиться…» в игре и вводит эти данные. При обрыве связи можно выбрать «Подключиться снова», пока хозяин оставляет партию открытой. Оба игрока строят и меняют задания в общей колонии. Хозяин ставит симуляцию на паузу и сохраняет игру. После выхода гостя хозяин может продолжить партию. -- 2.54.0 From 1e5a1a63163b2e095d31ca4af40127b7eb3dfb1d Mon Sep 17 00:00:00 2001 From: Codex Date: Sun, 29 Nov 2026 18:50:11 +0300 Subject: [PATCH 2/7] Add the Escape menu and a Direct3D 11 colony viewport --- CMakeLists.txt | 4 +- PLAN.md | 4 +- app/d3d_scene_win32.cpp | 408 ++++++++++++++++++++++++++++++++++++++++ app/d3d_scene_win32.hpp | 42 +++++ app/viewer_win32.cpp | 310 +++++++++++++++++++++++------- docs/roadmap-status.md | 4 +- docs/viewer.md | 20 +- 7 files changed, 715 insertions(+), 77 deletions(-) create mode 100644 app/d3d_scene_win32.cpp create mode 100644 app/d3d_scene_win32.hpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 9da6c35..c57a419 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -36,10 +36,12 @@ target_link_libraries(settlement_colony_benchmark PRIVATE settlement_core) if(WIN32) add_executable(settlement_viewer WIN32 + app/d3d_scene_win32.cpp app/viewer_win32.cpp app/lan_session_win32.cpp ) - target_link_libraries(settlement_viewer PRIVATE settlement_core user32 gdi32 comctl32 comdlg32 ws2_32 bcrypt iphlpapi) + target_link_libraries(settlement_viewer PRIVATE settlement_core user32 gdi32 comctl32 comdlg32 ws2_32 bcrypt iphlpapi + d3d11 d3dcompiler) if(NOT MSVC) target_link_options(settlement_viewer PRIVATE -municode) target_compile_options(settlement_viewer PRIVATE -Wall -Wextra -Wpedantic -Wconversion -Wshadow) diff --git a/PLAN.md b/PLAN.md index 5802f98..edaef1d 100644 --- a/PLAN.md +++ b/PLAN.md @@ -49,7 +49,9 @@ - [x] Камера с перемещением и масштабированием относительно курсора. - [x] Нижняя панель с жителями, добычей, участками и строительством. - [x] Главное меню перед игрой со списком сохранений, продолжением партии и подключением к другу. -- [ ] Настоящий графический 3D-рендерер и объёмные модели. +- [x] Меню Esc с паузой, сохранениями, графикой и сетевыми действиями. +- [x] Игровая карта на Direct3D 11 с глубиной и базовыми объёмными моделями. +- [ ] Расширение набора 3D-моделей и освещения. - [x] Постановка чертежа домика мышью в Windows-клиенте. - [ ] Интерфейс для остальных типов работ и зданий. diff --git a/app/d3d_scene_win32.cpp b/app/d3d_scene_win32.cpp new file mode 100644 index 0000000..deb25cc --- /dev/null +++ b/app/d3d_scene_win32.cpp @@ -0,0 +1,408 @@ +#define NOMINMAX +#include "d3d_scene_win32.hpp" + +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +namespace settlement::viewer { +namespace { + +using Microsoft::WRL::ComPtr; + +struct Point { float x, y, z; }; +struct Color { float r, g, b; }; +struct Vertex { Point position; Color color; }; + +constexpr Color rgb(int r, int g, int b) { + return {static_cast(r) / 255.f, static_cast(g) / 255.f, static_cast(b) / 255.f}; +} + +constexpr Color shade(Color color, float amount) { + return {color.r * amount, color.g * amount, color.b * amount}; +} + +class Mesh { +public: + std::vector vertices; + + void quad(Point a, Point b, Point c, Point d, Color color) { + vertices.insert(vertices.end(), {{a, color}, {b, color}, {c, color}, {a, color}, {c, color}, {d, color}}); + } + + void flat(float a, float b, float c, float d, float z, Color color) { + quad({a, b, z}, {c, b, z}, {c, d, z}, {a, d, z}, color); + } + + void box(float x, float y, float z, float w, float d, float h, Color color) { + const float a = x - w / 2, b = y - d / 2, c = x + w / 2, e = y + d / 2, top = z + h; + flat(a, b, c, e, top, color); + quad({c, b, z}, {c, e, z}, {c, e, top}, {c, b, top}, shade(color, .76f)); + quad({a, e, z}, {c, e, z}, {c, e, top}, {a, e, top}, shade(color, .62f)); + } + + void track(GridPosition from, GridPosition to, Color color) { + const float x = static_cast(from.x), y = static_cast(from.y); + const float end_x = static_cast(to.x), end_y = static_cast(to.y); + constexpr float half = .035f; + flat(std::min(x, end_x) - half, std::min(y, end_y) - half, + std::max(x, end_x) + half, std::max(y, end_y) + half, .016f, color); + } +}; + +void terrain(Mesh& mesh, const World& world, const SceneView& view) { + mesh.box(static_cast(world.width() - 1) / 2.f, static_cast(world.height() - 1) / 2.f, -.65f, + static_cast(world.width()), static_cast(world.height()), .64f, rgb(133, 107, 71)); + for (int y = 0; y < world.height(); ++y) { + for (int x = 0; x < world.width(); ++x) { + const GridPosition cell{x, y}; + const float px = static_cast(x), py = static_cast(y); + const int variation = (x * 17 + y * 29 + x * y * 5) % 12; + const bool walkable = world.is_walkable(cell); + auto surface = walkable ? rgb(123 + variation, 157 + variation, 104 + variation) : rgb(103, 118, 106); + if (view.move_source == cell) surface = rgb(219, 189, 113); + if (view.cursor == cell) surface = view.valid_cursor ? rgb(150, 205, 219) : rgb(223, 139, 124); + mesh.flat(px - .50f, py - .50f, px + .50f, py + .50f, 0, shade(surface, .90f)); + mesh.flat(px - .48f, py - .48f, px + .48f, py + .48f, .004f, surface); + if (walkable) continue; + const float height = .50f + static_cast(variation % 4) * .10f; + mesh.box(px, py, .004f, .75f, .76f, height * .45f, rgb(114, 131, 119)); + mesh.box(px - .06f, py - .04f, height * .45f, .55f, .59f, height * .55f, rgb(146, 157, 143)); + } + } +} + +void resources(Mesh& mesh, const World& world) { + for (const auto& node : world.resource_nodes()) { + const float x = static_cast(node.position.x), y = static_cast(node.position.y); + if (node.site != ResourceSite::Natural) { + mesh.flat(x - .43f, y - .43f, x + .43f, y + .43f, .025f, rgb(133, 103, 70)); + } + if (node.site == ResourceSite::Mine) { + mesh.box(x, y, .025f, .74f, .76f, .09f, rgb(62, 67, 63)); + mesh.box(x - .28f, y, .05f, .12f, .65f, .46f, rgb(140, 102, 67)); + mesh.box(x + .28f, y, .05f, .12f, .65f, .46f, rgb(140, 102, 67)); + mesh.box(x, y, .51f, .76f, .65f, .11f, rgb(181, 141, 90)); + } else if (node.quantity == 0) { + if (node.growth_at != 0 || node.reserved_workers != 0) { + mesh.box(x, y, .025f, .16f, .14f, .15f, rgb(100, 150, 85)); + } + } else if (node.type == ItemType::Wood) { + mesh.box(x, y, .02f, .19f, .19f, .75f, rgb(117, 83, 57)); + mesh.box(x, y, .58f, .72f, .73f, .36f, rgb(67, 112, 72)); + mesh.box(x - .07f, y - .07f, .94f, .49f, .49f, .29f, rgb(91, 143, 85)); + } else if (node.type == ItemType::Berries || node.type == ItemType::Flax) { + const bool flax = node.type == ItemType::Flax; + if (node.type == ItemType::Berries && node.foraging_enabled) { + mesh.flat(x - .39f, y - .39f, x + .39f, y + .39f, .028f, rgb(159, 187, 102)); + } + for (int i = 0; i < 3; ++i) { + const float shift = static_cast(i - 1) * .19f; + mesh.box(x + shift, y - shift * .56f, .03f, flax ? .12f : .30f, flax ? .13f : .33f, + flax ? .34f : .24f, flax ? rgb(98, 143, 80) : rgb(78, 133, 75)); + mesh.box(x + shift, y - shift * .56f, flax ? .37f : .27f, .13f, .15f, .08f, + flax ? rgb(147, 175, 229) : rgb(207, 105, 135)); + } + } else { + mesh.box(x, y, .03f, .51f, .53f, .32f, rgb(151, 159, 150)); + } + } +} + +void construction(Mesh& mesh, const World& world) { + for (const auto& storage : world.storages()) { + const float x = static_cast(storage.position.x), y = static_cast(storage.position.y); + mesh.box(x, y, .02f, .66f, .62f, .44f, rgb(160, 110, 65)); + mesh.box(x, y, .46f, .72f, .67f, .10f, storage.kind == StorageKind::Pantry ? + rgb(187, 120, 148) : rgb(202, 155, 91)); + mesh.box(x + .34f, y, .30f, .052f, .13f, .13f, rgb(229, 195, 124)); + } + for (const auto& order : world.production_orders()) { + const float x = static_cast(order.position.x), y = static_cast(order.position.y); + if (!is_construction(order.recipe)) { + mesh.box(x, y, .025f, .71f, .58f, .34f, rgb(150, 110, 73)); + mesh.box(x, y, .37f, .77f, .62f, .10f, rgb(199, 156, 100)); + if (order.recipe == RecipeId::WeaveCloth) { + mesh.box(x, y - .12f, .46f, .62f, .12f, .37f, rgb(167, 124, 79)); + mesh.box(x, y - .15f, .79f, .48f, .15f, .10f, rgb(235, 225, 193)); + } + continue; + } + if (order.state != JobState::Completed) { + const auto marked = order.state == JobState::Available ? rgb(121, 178, 195) : rgb(214, 171, 99); + mesh.flat(x - .44f, y - .44f, x + .44f, y + .44f, .03f, marked); + } + 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, + order.bed_base == BedBase::Stone ? rgb(145, 155, 151) : rgb(156, 107, 66)); + if (order.bed_stage == BedStage::Pillow || order.state == JobState::Completed) { + mesh.box(x, y, .225f, .69f, .38f, .12f, rgb(115, 159, 185)); + } + if (order.state == JobState::Completed) { + mesh.box(x - .23f, y, .345f, .2f, .32f, .07f, rgb(243, 230, 194)); + } + } else if (order.recipe == RecipeId::BuildCabin && order.state == JobState::Completed) { + mesh.box(x, y, .03f, .83f, .82f, .65f, rgb(194, 151, 103)); + mesh.quad({x - .46f, y + .46f, .64f}, {x + .46f, y + .46f, .64f}, + {x + .46f, y, 1.03f}, {x - .46f, y, 1.03f}, rgb(158, 83, 62)); + mesh.quad({x - .46f, y, 1.03f}, {x + .46f, y, 1.03f}, + {x + .46f, y - .46f, .64f}, {x - .46f, y - .46f, .64f}, rgb(193, 113, 79)); + mesh.quad({x + .42f, y - .42f, .67f}, {x + .42f, y + .42f, .67f}, + {x + .42f, y, 1.01f}, {x + .42f, y, 1.01f}, rgb(174, 126, 80)); + } + } + for (const auto& job : world.jobs()) { + if (job.state == JobState::Completed) continue; + const float x = static_cast(job.position.x), y = static_cast(job.position.y); + mesh.box(x, y, .015f, .20f, .20f, .10f, + job.state == JobState::Available ? rgb(76, 134, 90) : rgb(208, 159, 77)); + } +} + +void residents(Mesh& mesh, const World& world, const SceneView& view) { + for (const auto& agent : world.agents()) { + using enum AgentState; + if (agent.state != Sleeping) { + auto position = agent.position; + const auto trail = agent.state == Hauling ? rgb(104, 164, 159) : rgb(137, 126, 167); + for (std::size_t i = agent.route_cursor; i < agent.route.size(); ++i) { + mesh.track(position, agent.route[i], trail); + position = agent.route[i]; + } + } + const float shift = static_cast(static_cast(agent.id % 5) - 2) / 12.f; + const float x = static_cast(agent.position.x) + shift; + const float y = static_cast(agent.position.y) - shift; + const auto clothes = agent.state == Working ? rgb(195, 98, 74) : + agent.state == Gathering ? rgb(196, 152, 74) : + agent.state == Hauling ? rgb(67, 146, 138) : rgb(89, 126, 172); + if (view.selected == agent.id) { + mesh.flat(x - .28f, y - .26f, x + .28f, y + .26f, .042f, rgb(247, 207, 114)); + } + if (agent.state == Sleeping) { + const float bed_height = agent.resting_on_ground ? .035f : .36f; + mesh.box(x, y, bed_height, .54f, .25f, .14f, clothes); + mesh.box(x - .23f, y, bed_height + .01f, .16f, .20f, .15f, rgb(234, 195, 149)); + continue; + } + mesh.box(x, y, .027f, .19f, .22f, .14f, rgb(75, 72, 71)); + 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.empty()) { + mesh.box(x - .11f, y - .12f, .14f, .19f, .18f, .24f, rgb(200, 156, 92)); + } + } +} + +constexpr char hlsl[] = R"( +cbuffer Camera : register(b0) { + float2 origin; + float2 halfTile; + float2 screen; + float scale; + float padding; +}; +struct Input { float3 position : POSITION; float3 color : COLOR; }; +struct Pixel { float4 position : SV_Position; float3 color : COLOR; }; +Pixel project(Input input) { + float3 p = input.position; + float2 screenPoint = origin + scale * float2((p.x - p.y) * halfTile.x, + (p.x + p.y) * halfTile.y - p.z * 16.0); + Pixel result; + result.position = float4(screenPoint.x * 2.0 / screen.x - 1.0, + 1.0 - screenPoint.y * 2.0 / screen.y, 0.96 - (p.x + p.y + p.z * 1.5) * 0.009, 1.0); + result.color = input.color; + return result; +} +float4 paint(Pixel input) : SV_Target { return float4(input.color, 1.0); } +)"; + +} // namespace + +struct D3DScene::Backend { + ComPtr device; + ComPtr context; + ComPtr swap_chain; + ComPtr target_texture; + ComPtr target_view; + ComPtr depth_view; + ComPtr vertex_shader; + ComPtr pixel_shader; + ComPtr layout; + ComPtr rasterizer; + ComPtr camera; + ComPtr geometry; + UINT buffer_bytes = 0; + int width = 0, height = 0; + Mesh mesh; + + bool resize(int w, int h) { + if (w == width && h == height && target_view && depth_view) return true; + context->OMSetRenderTargets(0, nullptr, nullptr); + target_texture.Reset(); + target_view.Reset(); + depth_view.Reset(); + D3D11_TEXTURE2D_DESC texture{}; + texture.Width = static_cast(w); + texture.Height = static_cast(h); + texture.MipLevels = texture.ArraySize = texture.SampleDesc.Count = 1; + texture.Format = DXGI_FORMAT_B8G8R8A8_UNORM; + texture.BindFlags = D3D11_BIND_RENDER_TARGET; + if (swap_chain) { + if (FAILED(swap_chain->ResizeBuffers(0, texture.Width, texture.Height, DXGI_FORMAT_UNKNOWN, 0)) || + FAILED(swap_chain->GetBuffer(0, IID_PPV_ARGS(target_texture.GetAddressOf())))) return false; + } else if (FAILED(device->CreateTexture2D(&texture, nullptr, &target_texture))) { + return false; + } + texture.Format = DXGI_FORMAT_D24_UNORM_S8_UINT; + texture.BindFlags = D3D11_BIND_DEPTH_STENCIL; + ComPtr depth; + if (FAILED(device->CreateRenderTargetView(target_texture.Get(), nullptr, &target_view)) || + FAILED(device->CreateTexture2D(&texture, nullptr, &depth)) || + FAILED(device->CreateDepthStencilView(depth.Get(), nullptr, &depth_view))) return false; + width = w; + height = h; + return true; + } + + bool upload_geometry() { + const auto bytes = mesh.vertices.size() * sizeof(Vertex); + if (bytes > std::numeric_limits::max()) return false; + if (bytes > buffer_bytes) { + D3D11_BUFFER_DESC desc{}; + desc.ByteWidth = static_cast(bytes); + desc.Usage = D3D11_USAGE_DYNAMIC; + desc.BindFlags = D3D11_BIND_VERTEX_BUFFER; + desc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; + if (FAILED(device->CreateBuffer(&desc, nullptr, geometry.ReleaseAndGetAddressOf()))) return false; + buffer_bytes = desc.ByteWidth; + } + D3D11_MAPPED_SUBRESOURCE mapped{}; + if (FAILED(context->Map(geometry.Get(), 0, D3D11_MAP_WRITE_DISCARD, 0, &mapped))) return false; + std::memcpy(mapped.pData, mesh.vertices.data(), bytes); + context->Unmap(geometry.Get(), 0); + return true; + } + + bool read_frame(std::vector& pixels) { + D3D11_TEXTURE2D_DESC desc{}; + target_texture->GetDesc(&desc); + desc.BindFlags = 0; + desc.Usage = D3D11_USAGE_STAGING; + desc.CPUAccessFlags = D3D11_CPU_ACCESS_READ; + ComPtr copy; + if (FAILED(device->CreateTexture2D(&desc, nullptr, ©))) return false; + context->CopyResource(copy.Get(), target_texture.Get()); + pixels.resize(static_cast(width) * static_cast(height)); + D3D11_MAPPED_SUBRESOURCE mapped{}; + if (FAILED(context->Map(copy.Get(), 0, D3D11_MAP_READ, 0, &mapped))) return false; + const auto* data = static_cast(mapped.pData); + for (int row = 0; row < height; ++row) { + std::memcpy(pixels.data() + static_cast(row) * static_cast(width), + data + static_cast(row) * mapped.RowPitch, + static_cast(width) * sizeof(std::uint32_t)); + } + context->Unmap(copy.Get(), 0); + return true; + } +}; + +D3DScene::D3DScene() = default; +D3DScene::~D3DScene() = default; + +bool D3DScene::initialize(HWND target, bool software) { + auto graphics = std::make_unique(); + const auto driver = software ? D3D_DRIVER_TYPE_WARP : D3D_DRIVER_TYPE_HARDWARE; + constexpr D3D_FEATURE_LEVEL levels[] = {D3D_FEATURE_LEVEL_11_0, D3D_FEATURE_LEVEL_10_1, D3D_FEATURE_LEVEL_10_0}; + constexpr UINT flags = D3D11_CREATE_DEVICE_BGRA_SUPPORT; + if (target) { + DXGI_SWAP_CHAIN_DESC swap{}; + swap.BufferDesc.Format = DXGI_FORMAT_B8G8R8A8_UNORM; + swap.SampleDesc.Count = 1; + swap.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; + swap.BufferCount = 2; + swap.OutputWindow = target; + swap.Windowed = TRUE; + swap.SwapEffect = DXGI_SWAP_EFFECT_DISCARD; + if (FAILED(D3D11CreateDeviceAndSwapChain(nullptr, driver, nullptr, flags, levels, std::size(levels), + D3D11_SDK_VERSION, &swap, &graphics->swap_chain, &graphics->device, nullptr, &graphics->context))) return false; + } else if (FAILED(D3D11CreateDevice(nullptr, driver, nullptr, flags, levels, std::size(levels), + D3D11_SDK_VERSION, &graphics->device, nullptr, &graphics->context))) return false; + + ComPtr vertex, pixel; + constexpr UINT compile_flags = D3DCOMPILE_ENABLE_STRICTNESS | D3DCOMPILE_OPTIMIZATION_LEVEL3; + if (FAILED(D3DCompile(hlsl, sizeof(hlsl) - 1, nullptr, nullptr, nullptr, "project", "vs_4_0", + compile_flags, 0, &vertex, nullptr)) || + FAILED(D3DCompile(hlsl, sizeof(hlsl) - 1, nullptr, nullptr, nullptr, "paint", "ps_4_0", + compile_flags, 0, &pixel, nullptr))) return false; + if (FAILED(graphics->device->CreateVertexShader(vertex->GetBufferPointer(), vertex->GetBufferSize(), + nullptr, &graphics->vertex_shader)) || + FAILED(graphics->device->CreatePixelShader(pixel->GetBufferPointer(), pixel->GetBufferSize(), + nullptr, &graphics->pixel_shader))) return false; + constexpr D3D11_INPUT_ELEMENT_DESC elements[] = { + {"POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0}, + {"COLOR", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, sizeof(Point), D3D11_INPUT_PER_VERTEX_DATA, 0} + }; + D3D11_RASTERIZER_DESC raster{}; + raster.FillMode = D3D11_FILL_SOLID; + raster.CullMode = D3D11_CULL_NONE; + raster.DepthClipEnable = TRUE; + D3D11_BUFFER_DESC constants{}; + constants.ByteWidth = 32; + constants.BindFlags = D3D11_BIND_CONSTANT_BUFFER; + if (FAILED(graphics->device->CreateInputLayout(elements, std::size(elements), vertex->GetBufferPointer(), + vertex->GetBufferSize(), &graphics->layout)) || + FAILED(graphics->device->CreateRasterizerState(&raster, &graphics->rasterizer)) || + FAILED(graphics->device->CreateBuffer(&constants, nullptr, &graphics->camera))) return false; + backend_ = std::move(graphics); + return true; +} + +bool D3DScene::ready() const noexcept { return backend_ != nullptr; } +void D3DScene::reset() noexcept { backend_.reset(); } + +bool D3DScene::render(const World& world, const SceneView& view, std::vector* capture) { + if (!backend_ || view.width <= 0 || view.height <= 0) return false; + auto& graphics = *backend_; + if (!graphics.resize(view.width, view.height)) return false; + graphics.mesh.vertices.clear(); + terrain(graphics.mesh, world, view); + resources(graphics.mesh, world); + construction(graphics.mesh, world); + residents(graphics.mesh, world, view); + if (!graphics.upload_geometry()) return false; + + auto* ctx = graphics.context.Get(); + constexpr float clear[] = {.83f, .87f, .79f, 1.f}; + ctx->ClearRenderTargetView(graphics.target_view.Get(), clear); + ctx->ClearDepthStencilView(graphics.depth_view.Get(), D3D11_CLEAR_DEPTH, 1.f, 0); + ctx->OMSetRenderTargets(1, graphics.target_view.GetAddressOf(), graphics.depth_view.Get()); + const D3D11_VIEWPORT viewport{0, 0, static_cast(view.width), static_cast(view.height), 0, 1}; + ctx->RSSetViewports(1, &viewport); + ctx->RSSetState(graphics.rasterizer.Get()); + const float constants[] = {view.origin_x, view.origin_y, view.tile_half_width, view.tile_half_height, + viewport.Width, viewport.Height, view.scale, 0}; + ctx->UpdateSubresource(graphics.camera.Get(), 0, nullptr, constants, 0, 0); + constexpr UINT stride = sizeof(Vertex); + constexpr UINT offset = 0; + ctx->IASetInputLayout(graphics.layout.Get()); + ctx->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST); + ctx->IASetVertexBuffers(0, 1, graphics.geometry.GetAddressOf(), &stride, &offset); + ctx->VSSetShader(graphics.vertex_shader.Get(), nullptr, 0); + ctx->VSSetConstantBuffers(0, 1, graphics.camera.GetAddressOf()); + ctx->PSSetShader(graphics.pixel_shader.Get(), nullptr, 0); + ctx->Draw(static_cast(graphics.mesh.vertices.size()), 0); + if (capture && !graphics.read_frame(*capture)) return false; + return !graphics.swap_chain || SUCCEEDED(graphics.swap_chain->Present(0, 0)); +} + +} // namespace settlement::viewer diff --git a/app/d3d_scene_win32.hpp b/app/d3d_scene_win32.hpp new file mode 100644 index 0000000..47c7fda --- /dev/null +++ b/app/d3d_scene_win32.hpp @@ -0,0 +1,42 @@ +#pragma once + +#include + +#include "settlement/core/world.hpp" + +#include +#include +#include +#include + +namespace settlement::viewer { + +struct SceneView { + int width; + int height; + float origin_x; + float origin_y; + float scale; + float tile_half_width; + float tile_half_height; + std::optional cursor; + bool valid_cursor; + std::optional move_source; + std::optional selected; +}; + +class D3DScene { +public: + D3DScene(); + ~D3DScene(); + bool initialize(HWND target, bool software = false); + [[nodiscard]] bool ready() const noexcept; + bool render(const World& world, const SceneView& view, std::vector* capture = nullptr); + void reset() noexcept; + +private: + struct Backend; + std::unique_ptr backend_; +}; + +} // namespace settlement::viewer diff --git a/app/viewer_win32.cpp b/app/viewer_win32.cpp index d4d4583..fa1f2f5 100644 --- a/app/viewer_win32.cpp +++ b/app/viewer_win32.cpp @@ -6,6 +6,7 @@ #include #include +#include "d3d_scene_win32.hpp" #include "isometric_camera.hpp" #include "lan_session.hpp" #include "title_screen_win32.hpp" @@ -34,6 +35,7 @@ namespace { constexpr wchar_t window_class[] = L"SettlementIsometricViewer"; constexpr wchar_t resident_window_class[] = L"SettlementResidentRoster"; +constexpr wchar_t scene_window_class[] = L"SettlementD3DViewport"; constexpr int title_menu_id = 1002; constexpr int status_label_id = 1003; constexpr int cabin_button_id = 1004; @@ -66,6 +68,9 @@ 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 work_list_button_id = 1083; +constexpr int graphics_menu_id = 1120; +constexpr int exit_menu_id = 1121; constexpr int timer_id = 1; constexpr int map_size = settlement::first_colony_map_size; constexpr int tile_width = 24; @@ -87,7 +92,7 @@ HWND production_label = nullptr; HWND wood_bed_button = nullptr; HWND stone_bed_button = nullptr; HWND priority_button = nullptr; -HWND pause_button = nullptr; +HWND work_list_button = nullptr; HWND residents_button = nullptr; std::array dock_section_buttons{}; std::unique_ptr world; @@ -95,7 +100,10 @@ namespace title = settlement::viewer; title::TitleScreen title_screen; bool showing_title = true; bool has_session = false; -HMENU play_menu = nullptr; +bool pause_menu_open = false; +HWND scene_window = nullptr; +settlement::viewer::D3DScene graphics; +bool prefer_direct3d = true; using settlement::viewer::LanState; settlement::viewer::LanSession lan; LanState displayed_lan_state = LanState::Offline; @@ -333,6 +341,21 @@ void invalidate_scene(HWND window) { GetClientRect(window, &scene); scene.top = map_top; if (scene.bottom > scene.top) InvalidateRect(window, &scene, FALSE); + if (!showing_title && prefer_direct3d && graphics.ready() && scene_window) { + InvalidateRect(scene_window, nullptr, FALSE); + } +} + +void layout_scene(HWND window) { + if (!scene_window) return; + if (showing_title || !prefer_direct3d || !graphics.ready()) { + ShowWindow(scene_window, SW_HIDE); + return; + } + RECT client{}; + GetClientRect(window, &client); + SetWindowPos(scene_window, HWND_BOTTOM, 0, map_top, client.right, + std::max(0, static_cast(client.bottom) - map_top - map_footer), SWP_NOACTIVATE | SWP_SHOWWINDOW); } void update_camera_drag(POINT point) { @@ -735,6 +758,7 @@ bool draw_toolbar_button(const DRAWITEMSTRUCT& item) { 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; + case work_list_button_id: draw_icon_button(item, WorkIcon::Hammer, false); 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)]; @@ -846,12 +870,11 @@ void update_status() { } for (const HWND button : dock_section_buttons) EnableWindow(button, can_play); EnableWindow(priority_button, scenario && can_play); - EnableWindow(pause_button, scenario && !lan.is_guest()); + EnableWindow(work_list_button, can_play); 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(), @@ -924,19 +947,21 @@ void show_title_screen(HWND window, bool visible) { title_screen.update(has_session, lan.state() == LanState::Connecting); } else { has_session = true; + if (prefer_direct3d && !graphics.ready() && (!scene_window || !graphics.initialize(scene_window))) { + prefer_direct3d = false; + } } const int flags = visible ? SW_HIDE : SW_SHOWNA; - for (const auto control : {status_label, production_label, priority_button, pause_button, residents_button}) { + for (const auto control : {status_label, production_label, priority_button, work_list_button, residents_button}) { ShowWindow(control, flags); } for (const auto control : dock_section_buttons) ShowWindow(control, flags); title_screen.show(visible); - SetMenu(window, visible ? nullptr : play_menu); - DrawMenuBar(window); RECT client{}; GetClientRect(window, &client); title_screen.layout(client.right, client.bottom); layout_command_dock(window); + layout_scene(window); SetFocus(window); InvalidateRect(window, nullptr, FALSE); } @@ -1134,27 +1159,14 @@ void show_lan_info(HWND window) { (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Друг в той же сети выбирает «Кооператив → Подключиться…»."; + 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; - const auto enable = [&](UINT command, bool enabled) { - if (play_menu) EnableMenuItem(play_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(title_menu_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; @@ -1169,11 +1181,10 @@ void refresh_lan_controls(HWND window) { if (disconnected) { set_placement_mode(window, PlacementMode::None); placement_message = showing_title ? L"Не удалось подключиться. Проверьте адрес и код." : - L"Связь прервана. «Кооператив → Подключиться снова». " + widen_ascii(lan.detail()); + L"Связь прервана. «Esc → Подключиться снова». " + widen_ascii(lan.detail()); } else if (state == LanState::GuestConnected) { placement_message = L"Подключено к колонии хозяина."; } - DrawMenuBar(window); if (roster.window) update_roster_details(); update_status(); if (showing_title) { @@ -1717,7 +1728,7 @@ void draw_world(HDC dc, int width, int height) { DeleteObject(background); if (!world) return; - if (height > map_top + map_footer) { + if ((!prefer_direct3d || !graphics.ready()) && height > map_top + map_footer) { const int saved = SaveDC(dc); if (saved != 0) { IntersectClipRect(dc, 0, map_top, width, height - map_footer); @@ -1743,11 +1754,11 @@ void draw_world(HDC dc, int width, int height) { SetBkMode(dc, TRANSPARENT); SetTextColor(dc, color(231, 227, 205)); const wchar_t* hint = world->scenario_active() ? - L"Колесо — масштаб Перетаскивание — сдвиг карты Home — общий план" : + L"Колесо — масштаб Перетаскивание — сдвиг карты Home — общий план Esc — меню" : L"Голубой — очередь Бирюзовый — доставка Янтарный — строительство"; if (!placement_message.empty()) hint = placement_message.c_str(); else if (placement_mode == PlacementMode::Foraging) { - hint = L"Щёлкните по ягодному кусту, чтобы включить или выключить сбор. Esc — отмена."; + hint = L"Щёлкните по ягодному кусту, чтобы включить или выключить сбор. Правая кнопка — отмена."; } else if (placement_mode == PlacementMode::BerryField) { hint = L"Поле ягод. Выберите свободную клетку. Фермер засеет поле и соберёт урожай."; } else if (placement_mode == PlacementMode::FlaxField) { @@ -1764,16 +1775,16 @@ void draw_world(HDC dc, int width, int height) { hint = move_source ? L"Выберите свободную клетку для переноса." : L"Выберите кровать, склад, станок или посаженный участок."; } else if (placement_mode == PlacementMode::Demolish) { - hint = L"Щёлкните по объекту, чтобы снести его. Esc отменяет режим."; + hint = L"Щёлкните по объекту, чтобы снести его. Правая кнопка — отмена."; } else if (placement_mode == PlacementMode::Building) { if (world->staged_beds()) { hint = selected_bed_base ? L"Щёлкайте по свободным клеткам. Основу можно сменить под кнопкой «Спальное место»." : L"Выберите «Дерево» или «Камень» под кнопкой «Спальное место»."; } else if (world->scenario_active()) { - hint = L"Щёлкайте по свободным клеткам. Одно место требует доску. Esc — выход."; + hint = L"Щёлкайте по свободным клеткам. Одно место требует доску. Правая кнопка — отмена."; } else { - hint = L"Выберите свободную клетку. Домик стоит три доски и два блока. Esc — отмена."; + hint = L"Выберите свободную клетку. Домик стоит три доски и два блока. Правая кнопка — отмена."; } } RECT legend{24, height - 159, width - 24, height - 136}; @@ -1784,6 +1795,166 @@ void draw_world(HDC dc, int width, int height) { DrawTextW(dc, details.c_str(), -1, &inspector, DT_LEFT | DT_VCENTER | DT_SINGLELINE | DT_END_ELLIPSIS); } +settlement::viewer::SceneView scene_view(int width, int height) { + const auto pan = camera.offset(); + const auto scale = camera.scale(); + const auto cursor = !shows_bed_choices() || selected_bed_base ? hover_cell : std::nullopt; + return {width, height, static_cast(width / 2 * scale + pan.x), + static_cast(map_origin_y * scale + pan.y - map_top), + static_cast(scale), tile_width / 2.f, tile_height / 2.f, + cursor, cursor && valid_edit_cell(*cursor), move_source, selected_resident}; +} + +LRESULT CALLBACK scene_window_proc(HWND window, UINT message, WPARAM wparam, LPARAM lparam) { + if (message == WM_NCHITTEST) return HTTRANSPARENT; + if (message == WM_ERASEBKGND) return 1; + if (message == WM_PAINT) { + PAINTSTRUCT paint{}; + BeginPaint(window, &paint); + RECT client{}; + GetClientRect(window, &client); + const bool drawn = !world || !graphics.ready() || !prefer_direct3d || + client.right <= 0 || client.bottom <= 0 || + graphics.render(*world, scene_view(client.right, client.bottom)); + EndPaint(window, &paint); + if (!drawn) { + graphics.reset(); + prefer_direct3d = false; + const auto parent = GetParent(window); + layout_scene(parent); + invalidate_scene(parent); + } + return 0; + } + return DefWindowProcW(window, message, wparam, lparam); +} + +void toggle_graphics(HWND window) { + if (prefer_direct3d && graphics.ready()) { + prefer_direct3d = false; + placement_message = L"Режим графики — изометрия GDI."; + } else { + prefer_direct3d = graphics.ready() || (scene_window && graphics.initialize(scene_window)); + placement_message = prefer_direct3d ? L"Режим графики — Direct3D 11." : + L"Direct3D 11 недоступен. Включена изометрия GDI."; + } + layout_scene(window); + invalidate_scene(window); +} + +struct PauseMenu { + LanState lan_state; + bool paused; + bool scenario; + bool direct3d; + HBRUSH background; +}; + +INT_PTR CALLBACK pause_menu_proc(HWND dialog, UINT message, WPARAM wparam, LPARAM lparam) { + switch (message) { + case WM_INITDIALOG: { + const auto& menu = *reinterpret_cast(lparam); + SetWindowLongPtrW(dialog, DWLP_USER, lparam); + const bool offline = menu.lan_state == LanState::Offline; + const bool host = menu.lan_state == LanState::Hosting || menu.lan_state == LanState::HostConnected; + const bool disconnected = menu.lan_state == LanState::GuestDisconnected; + SetWindowTextW(dialog, offline ? L"Меню паузы" : L"Меню игры"); + const auto control = [&](const wchar_t* type, const wchar_t* label, int id, DWORD flags, RECT rectangle) { + MapDialogRect(dialog, &rectangle); + const auto child = CreateWindowExW(0, type, label, WS_CHILD | WS_VISIBLE | flags, + rectangle.left, rectangle.top, rectangle.right - rectangle.left, rectangle.bottom - rectangle.top, + dialog, reinterpret_cast(static_cast(id)), GetModuleHandleW(nullptr), nullptr); + SendMessageW(child, WM_SETFONT, reinterpret_cast(GetStockObject(DEFAULT_GUI_FONT)), TRUE); + return child; + }; + const auto button = [&](int id, const wchar_t* label, int column, int row, bool enabled = true) { + const int x = column == 0 ? 13 : 184; + const int y = 27 + row * 25; + const auto child = control(L"BUTTON", label, id, WS_TABSTOP | BS_OWNERDRAW, + {x, y, x + 155, y + 20}); + EnableWindow(child, enabled); + }; + control(L"STATIC", L"Поселение", -1, 0, {13, 9, 167, 23}); + control(L"STATIC", L"Кооператив", -1, 0, {184, 9, 339, 23}); + button(IDOK, L"Продолжить", 0, 0); + button(save_menu_id, L"Сохранить поселение…", 0, 1, offline || host); + button(load_menu_id, L"Загрузить поселение…", 0, 2, offline); + button(title_menu_id, L"Главное меню", 0, 3, offline); + button(graphics_menu_id, menu.direct3d ? L"Графика · Direct3D 11" : L"Графика · Изометрия GDI", 0, 4); + button(exit_menu_id, L"Выйти из игры", 0, 5); + if (offline) { + button(lan_host_id, L"Открыть для друга…", 1, 0, menu.scenario); + button(lan_join_id, L"Подключиться к другу…", 1, 1); + } else if (host) { + button(lan_info_id, L"Адрес и код партии…", 1, 0); + button(pause_button_id, menu.paused ? L"Продолжить для всех" : L"Пауза для всех", 1, 1); + button(lan_leave_id, L"Закрыть сетевую игру", 1, 2); + } else { + if (disconnected) button(lan_reconnect_id, L"Подключиться снова", 1, 0); + button(lan_leave_id, L"Выйти из сетевой игры", 1, 1); + } + SetFocus(GetDlgItem(dialog, IDOK)); + return FALSE; + } + case WM_CTLCOLORDLG: + case WM_CTLCOLORSTATIC: + if (const auto* menu = reinterpret_cast(GetWindowLongPtrW(dialog, DWLP_USER))) { + const auto dc = reinterpret_cast(wparam); + SetTextColor(dc, color(236, 230, 205)); + SetBkMode(dc, TRANSPARENT); + return reinterpret_cast(menu->background); + } + break; + case WM_DRAWITEM: + if (const auto* item = reinterpret_cast(lparam); item && item->CtlType == ODT_BUTTON) { + WorkIcon icon = WorkIcon::Resident; + if (item->CtlID == graphics_menu_id) icon = WorkIcon::Stone; + else if (item->CtlID == save_menu_id || item->CtlID == load_menu_id) icon = WorkIcon::Crate; + draw_icon_button(*item, icon, item->CtlID == IDOK, true); + return TRUE; + } + break; + case WM_COMMAND: + if (HIWORD(wparam) == BN_CLICKED) { + EndDialog(dialog, LOWORD(wparam)); + return TRUE; + } + break; + case WM_CLOSE: + EndDialog(dialog, IDCANCEL); + return TRUE; + } + return FALSE; +} + +void open_pause_menu(HWND window) { + if (!world || showing_title || pause_menu_open) return; + camera_drag.reset(); + if (GetCapture() == window) ReleaseCapture(); + struct alignas(DWORD) EmptyDialog { + DLGTEMPLATE header{}; + WORD menu = 0, window_class = 0, title = 0; + } layout; + layout.header.style = WS_POPUP | WS_CAPTION | WS_SYSMENU | DS_MODALFRAME | DS_CENTER; + layout.header.cx = 352; + layout.header.cy = 184; + PauseMenu menu{lan.state(), world->paused(), world->scenario_active(), prefer_direct3d && graphics.ready(), + CreateSolidBrush(color(34, 46, 40))}; + pause_menu_open = true; + const auto action = DialogBoxIndirectParamW(GetModuleHandleW(nullptr), &layout.header, window, + pause_menu_proc, reinterpret_cast(&menu)); + if (action == IDOK) { + if (lan.state() == LanState::Offline && world->paused()) { + static_cast(send_command(settlement::CommandKind::SetPaused)); + } + } else if (action != IDCANCEL && action != -1) { + SendMessageW(window, WM_COMMAND, static_cast(action), 0); + } + pause_menu_open = false; + DeleteObject(menu.background); + if (IsWindow(window)) SetFocus(window); +} + LRESULT CALLBACK window_proc(HWND window, UINT message, WPARAM wparam, LPARAM lparam) { switch (message) { case WM_GETMINMAXINFO: { @@ -1793,7 +1964,16 @@ LRESULT CALLBACK window_proc(HWND window, UINT message, WPARAM wparam, LPARAM lp return 0; } case WM_CREATE: { - play_menu = GetMenu(window); + const auto instance = GetModuleHandleW(nullptr); + WNDCLASSW viewport{}; + viewport.lpfnWndProc = scene_window_proc; + viewport.hInstance = instance; + viewport.lpszClassName = scene_window_class; + viewport.hCursor = LoadCursorW(nullptr, IDC_ARROW); + if (RegisterClassW(&viewport) || GetLastError() == ERROR_CLASS_ALREADY_EXISTS) { + scene_window = CreateWindowExW(0, scene_window_class, L"", WS_CHILD, + 0, map_top, 1, 1, window, nullptr, instance, nullptr); + } status_label = CreateWindowExW(0, L"STATIC", L"", WS_CHILD | WS_VISIBLE, 18, 14, 735, 24, window, reinterpret_cast(static_cast(status_label_id)), @@ -1808,7 +1988,7 @@ LRESULT CALLBACK window_proc(HWND window, UINT message, WPARAM wparam, LPARAM lp GetModuleHandleW(nullptr), nullptr); }; priority_button = button(priority_button_id, 18, 142, L"Равный приоритет"); - pause_button = button(pause_button_id, 168, 96, L"Пауза"); + work_list_button = button(work_list_button_id, 168, 108, L"Работы", BS_OWNERDRAW); 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, @@ -1838,6 +2018,25 @@ LRESULT CALLBACK window_proc(HWND window, UINT message, WPARAM wparam, LPARAM lp if (const auto brush = title_screen.paint_list_background(reinterpret_cast(lparam), reinterpret_cast(wparam))) return reinterpret_cast(brush); } + if (LOWORD(wparam) == exit_menu_id && pause_menu_open) { + DestroyWindow(window); + return 0; + } + if (LOWORD(wparam) == graphics_menu_id && pause_menu_open) { + toggle_graphics(window); + return 0; + } + if (LOWORD(wparam) == work_list_button_id && HIWORD(wparam) == BN_CLICKED && can_give_orders()) { + if (const auto menu = create_work_menu()) { + RECT bounds{}; + GetWindowRect(work_list_button, &bounds); + TrackPopupMenu(menu, TPM_LEFTALIGN | TPM_TOPALIGN | TPM_RIGHTBUTTON, + bounds.left, bounds.bottom, 0, window, nullptr); + DestroyMenu(menu); + } + SetFocus(window); + return 0; + } break; case WM_COMMAND: if (showing_title) { @@ -1934,7 +2133,7 @@ LRESULT CALLBACK window_proc(HWND window, UINT message, WPARAM wparam, LPARAM lp update_status(); return 0; } - if (LOWORD(wparam) == pause_button_id) { + if (LOWORD(wparam) == pause_button_id && pause_menu_open && !lan.is_guest()) { static_cast(send_command(settlement::CommandKind::SetPaused, {}, static_cast(!world->paused()))); update_status(); @@ -2105,16 +2304,16 @@ LRESULT CALLBACK window_proc(HWND window, UINT message, WPARAM wparam, LPARAM lp 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); + if (wparam == VK_ESCAPE) { + if ((lparam & (1L << 30)) == 0) open_pause_menu(window); return 0; } break; case WM_TIMER: if (wparam == timer_id && world) { if (showing_title && lan.state() != LanState::Connecting) return 0; - if (!showing_title && !file_dialog_active && !lan.is_guest()) world->step(); + if (!showing_title && !file_dialog_active && !lan.is_guest() && + (!pause_menu_open || lan.state() != LanState::Offline)) world->step(); if (auto snapshot = lan.poll(*world)) { world = std::move(snapshot); if (showing_title) show_title_screen(window, false); @@ -2140,6 +2339,7 @@ LRESULT CALLBACK window_proc(HWND window, UINT message, WPARAM wparam, LPARAM lp title_screen.layout(client.right, client.bottom); } else { layout_command_dock(window); + layout_scene(window); } InvalidateRect(window, nullptr, FALSE); break; @@ -2167,8 +2367,8 @@ LRESULT CALLBACK window_proc(HWND window, UINT message, WPARAM wparam, LPARAM lp case WM_DESTROY: KillTimer(window, timer_id); lan.leave(); - if (play_menu && GetMenu(window) != play_menu) DestroyMenu(play_menu); - play_menu = nullptr; + graphics.reset(); + scene_window = nullptr; PostQuitMessage(0); return 0; } @@ -2189,35 +2389,10 @@ int WINAPI wWinMain(HINSTANCE instance, HINSTANCE, PWSTR, int show_command) { 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(file_menu, MF_SEPARATOR, 0, nullptr); - AppendMenuW(file_menu, MF_STRING, title_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; - } + nullptr, nullptr, instance, nullptr); + if (!window) return 1; ShowWindow(window, show_command); UpdateWindow(window); @@ -2225,6 +2400,11 @@ int WINAPI wWinMain(HINSTANCE instance, HINSTANCE, PWSTR, int show_command) { while (GetMessageW(&message, nullptr, 0, 0) > 0) { if (roster.window && IsDialogMessageW(roster.window, &message)) continue; if (showing_title && IsDialogMessageW(window, &message)) continue; + if (!showing_title && message.message == WM_KEYDOWN && message.wParam == VK_ESCAPE && + (message.hwnd == window || IsChild(window, message.hwnd))) { + SendMessageW(window, message.message, message.wParam, message.lParam); + continue; + } TranslateMessage(&message); DispatchMessageW(&message); } diff --git a/docs/roadmap-status.md b/docs/roadmap-status.md index f87e70a..4291c83 100644 --- a/docs/roadmap-status.md +++ b/docs/roadmap-status.md @@ -27,6 +27,8 @@ - Производительность ядра измерена на колониях с 50–500 жителями, полями, складами и ремеслом. Результаты и команда запуска описаны в [отчёте](../benchmarks/colony-performance.md). - Основные команды собраны в нижней панели «Жители», «Добыча», «Участки» и «Строительство». Меню «Работы» открывает те же команды по профессиям. - Главное меню открывается при запуске. В нём можно начать новую колонию, выбрать сохранение или подключиться к другу. +- Esc открывает меню паузы, сохранений, сетевых действий и графики. +- Direct3D 11 рисует карту, жителей и постройки как объёмную геометрию с глубиной. Изометрия GDI доступна через меню Esc. - Поиск ресурсных работ отбирает подходящие поручения по профессиям. Повторные запросы путей используют кэш. - Движение, прогресс работ жителей и поиск маршрутов для общих заданий выполняются в пуле из двух и более потоков. Тесты проверяют игровые результаты, сохранения и команды кооператива. @@ -36,7 +38,7 @@ ## Ограничения прототипа -- Графика изометрическая и рисуется Win32/GDI; полноценного 3D-рендера пока нет. +- Камера показывает карту в изометрической проекции. Direct3D использует базовые модели и затенение граней. - Каждый поход добытчика доставляет одну единицу сырья. Строитель везёт весь комплект для одного домика за рейс с остановками у нужных складов. Мастерские пока используют складское сырьё напрямую. - Свободный житель сначала ищет еду, если проголодался. Если порции нет, он может снова взять работу. При голоде здоровье пока остаётся прежним. - Завершённое спальное место назначается одному жителю. Сейчас жители идут спать по усталости. diff --git a/docs/viewer.md b/docs/viewer.md index 0ac37c8..3b12278 100644 --- a/docs/viewer.md +++ b/docs/viewer.md @@ -12,15 +12,17 @@ powershell.exe -NoProfile -ExecutionPolicy Bypass -File .\build.ps1 При запуске без явного параметра командная версия выбирает от двух до восьми потоков с учётом числа логических процессоров. Для ручного выбора используйте `settlement_sim.exe --workers N`, где N от 2 до 32. -Колесо мыши приближает и отдаляет карту относительно курсора. Чтобы сдвинуть карту, перетащите её с зажатой левой или средней кнопкой мыши. Короткий щелчок левой кнопкой выбирает жителя или ставит чертёж. Home или «Вид → Общий план» возвращает исходный вид. +Колесо мыши приближает и отдаляет карту относительно курсора. Чтобы сдвинуть карту, перетащите её с зажатой левой или средней кнопкой мыши. Короткий щелчок левой кнопкой выбирает жителя или ставит чертёж. Home возвращает исходный вид. -В новой партии три поселенца. На нижней панели откройте «Строительство → Спальное место». Под кнопкой появятся «Дерево» слева и «Камень» справа. Выберите основу, затем щёлкайте по свободным клеткам. Выбранная основа применяется к следующим кроватям до выхода из режима или смены основы. Повторное нажатие «Спальное место», Esc или правый щелчок завершает размещение. +Игра пробует включить Direct3D 11 при входе в колонию. Рендерер рисует объёмную карту с глубиной, постройки и жителей в изометрической проекции. Кнопка «Графика» в меню Esc переключает Direct3D и изометрию GDI. При ошибке устройства карта открывается в GDI. + +В новой партии три поселенца. На нижней панели откройте «Строительство → Спальное место». Под кнопкой появятся «Дерево» слева и «Камень» справа. Выберите основу, затем щёлкайте по свободным клеткам. Выбранная основа применяется к следующим кроватям до выхода из режима или смены основы. Повторное нажатие «Спальное место» или правый щелчок завершает размещение. Жители отдельно доставляют основу, ткань для настила и ткань для подушки. Каждая деталь появляется после завершения своего этапа. Камень и ткань доступны в стартовых запасах. Жители получают по одному готовому месту. Уставшие жители работают медленнее и после поручения идут к закреплённой кровати. На земле они отдыхают только при сильной усталости и восстанавливают меньше сил. Щелчок по жителю показывает усталость и состояние сна. -На нижней панели «Добыча» (H) открывает сбор с кустов и шахту. «Участки» (Z) открывают поля, посадки, склад и кладовую. «Строительство» (B) открывает спальное место, станок, перенос и снос. Выбор раздела показывает его инструменты над панелью. Те же действия сгруппированы по профессиям в верхнем меню «Работы». Разнорабочий берёт работу любой профессии. +На нижней панели «Добыча» (H) открывает сбор с кустов и шахту. «Участки» (Z) открывают поля, посадки, склад и кладовую. «Строительство» (B) открывает спальное место, станок, перенос и снос. Выбор раздела показывает его инструменты над панелью. Кнопка «Работы» открывает те же действия по профессиям. Разнорабочий берёт работу любой профессии. Откройте «Жители…» (клавиша C), выберите поселенца в списке, нажмите на нужную роль и подтвердите кнопкой «Назначить профессию». В списке видна текущая роль каждого жителя, а число рядом с названием профессии показывает, сколько жителей уже ею занимаются. Можно последовательно назначать роли всему поселению в одном окне. При смене профессии житель заканчивает текущее поручение. @@ -30,18 +32,18 @@ powershell.exe -NoProfile -ExecutionPolicy Bypass -File .\build.ps1 Для переноса выберите «Строительство → Перенести», щёлкните по кровати, складу, станку или посаженному участку и выберите новую клетку. Кровать сохраняет владельца, склад — содержимое. Там же находится «Снести». Снос склада с запасами требует подтверждения. Дождитесь освобождения занятого объекта перед переносом или сносом. -Нажмите «Добыча → Сбор ягод» и щёлкните по кусту, чтобы включить или отключить его сбор. Правый щелчок или Esc закрывает режим выбора. Кнопка приоритета переключает режимы «Равный приоритет», «Сначала еда» и «Сначала стройка». В паузе можно менять задания. Цель выполнена, когда каждому назначено место и в кладовой есть шесть свободных порций. +Нажмите «Добыча → Сбор ягод» и щёлкните по кусту, чтобы включить или отключить его сбор. Правый щелчок закрывает режим выбора. Кнопка приоритета переключает режимы «Равный приоритет», «Сначала еда» и «Сначала стройка». Цель выполнена, когда каждому назначено место и в кладовой есть шесть свободных порций. Кусты дают ягоды, которые жители несут в кладовую с розовой крышкой. Розовый маршрут ведёт к еде. Чтобы увидеть голод жителя и его груз, щёлкните по фигурке вне режима размещения чертежа. -В меню «Поселение» выберите «Сохранить поселение…» или «Загрузить поселение…». Время останавливается на время выбора файла. Файл `.settlement` хранит карту, текущий такт, голод, запасы, заказы и маршруты. Если файл повреждён или его версия не подходит, окно показывает ошибку и продолжает текущую партию. +Esc открывает меню игры из любого режима строительства и выбора. В одиночной партии симуляция останавливается, пока меню открыто. «Продолжить» или Esc закрывает меню. Выбранный на карте инструмент можно использовать дальше. В этом меню доступны сохранение, загрузка, главное меню и выход. Файл `.settlement` хранит карту, текущий такт, голод, запасы, заказы и маршруты. При ошибке загрузки текущая колония остаётся открытой. -В одиночной игре «Поселение → Главное меню» останавливает симуляцию. «Продолжить» возвращает к текущей колонии. «Новая колония» запускает отдельную партию с поэтапной сборкой и стартовым запасом ткани. Старые сохранения продолжаются со своими правилами стройки. +В одиночной игре «Esc → Главное меню» возвращает на стартовый экран и останавливает симуляцию. «Продолжить» возвращает к текущей колонии. «Новая колония» запускает отдельную партию с поэтапной сборкой и стартовым запасом ткани. Старые сохранения продолжаются со своими правилами стройки. ## Кооператив по локальной сети 1. Запустите одинаковую версию игры на двух компьютерах в одной локальной сети. -2. Хозяин открывает свою колонию через «Кооператив → Открыть колонию для друга…» и передаёт гостю IPv4 и код партии. Порт игры — TCP 41727. -3. Гость выбирает «Подключиться к другу…» в главном меню или «Кооператив → Подключиться…» в игре и вводит эти данные. При обрыве связи можно выбрать «Подключиться снова», пока хозяин оставляет партию открытой. +2. Хозяин открывает свою колонию через «Esc → Открыть для друга…» и передаёт гостю IPv4 и код партии. Порт игры — TCP 41727. +3. Гость выбирает «Подключиться к другу…» в главном меню или в меню Esc и вводит эти данные. При обрыве связи можно выбрать «Подключиться снова», пока хозяин оставляет партию открытой. -Оба игрока строят и меняют задания в общей колонии. Хозяин ставит симуляцию на паузу и сохраняет игру. После выхода гостя хозяин может продолжить партию. +Оба игрока строят и меняют задания в общей колонии. Меню Esc доступно каждому. Хозяин сохраняет игру и останавливает симуляцию кнопкой «Пауза для всех». После выхода гостя хозяин может продолжить партию. -- 2.54.0 From 73a91a066dc8ea9bd12fc4f2c661f4941863ef08 Mon Sep 17 00:00:00 2001 From: Codex Date: Sun, 29 Nov 2026 19:09:53 +0300 Subject: [PATCH 3/7] Use Direct3D 11 for the colony and move co-op to the title screen --- PLAN.md | 8 +- app/{isometric_camera.hpp => map_camera.hpp} | 2 +- app/title_screen_win32.hpp | 16 +- app/viewer_win32.cpp | 655 ++++++------------- docs/roadmap-status.md | 8 +- docs/viewer.md | 10 +- 6 files changed, 207 insertions(+), 492 deletions(-) rename app/{isometric_camera.hpp => map_camera.hpp} (97%) diff --git a/PLAN.md b/PLAN.md index edaef1d..8b82688 100644 --- a/PLAN.md +++ b/PLAN.md @@ -2,7 +2,7 @@ ## Цель -Самостоятельная C++-игра о поселении с повторяемой симуляцией, многопоточным расчётом и изометрическим клиентом. Это отдельный проект, не совместимый движок для Stonehearth. Код и игровые ресурсы Stonehearth не включаются. +Самостоятельная C++-игра о поселении с повторяемой симуляцией, многопоточным расчётом и 3D-клиентом. Это отдельный проект, не совместимый движок для Stonehearth. Код и игровые ресурсы Stonehearth не включаются. ## Этапы @@ -44,12 +44,12 @@ ### P4 — Игровой клиент -- [x] Изометрический Windows-просмотрщик карты, маршрутов и жителей. +- [x] Windows-клиент с отображением карты, маршрутов и жителей. - [x] Отображение источников ресурсов, складов и текущих запасов. - [x] Камера с перемещением и масштабированием относительно курсора. - [x] Нижняя панель с жителями, добычей, участками и строительством. -- [x] Главное меню перед игрой со списком сохранений, продолжением партии и подключением к другу. -- [x] Меню Esc с паузой, сохранениями, графикой и сетевыми действиями. +- [x] Главное меню со списком сохранений, продолжением партии и управлением кооперативом. +- [x] Меню Esc с паузой, сохранениями, выходом в главное меню и завершением игры. - [x] Игровая карта на Direct3D 11 с глубиной и базовыми объёмными моделями. - [ ] Расширение набора 3D-моделей и освещения. - [x] Постановка чертежа домика мышью в Windows-клиенте. diff --git a/app/isometric_camera.hpp b/app/map_camera.hpp similarity index 97% rename from app/isometric_camera.hpp rename to app/map_camera.hpp index 0bdf4ba..e885ec2 100644 --- a/app/isometric_camera.hpp +++ b/app/map_camera.hpp @@ -10,7 +10,7 @@ struct ScreenPoint { double y; }; -class IsometricCamera { +class MapCamera { public: [[nodiscard]] double scale() const noexcept { return scale_; } [[nodiscard]] ScreenPoint offset() const noexcept { return offset_; } diff --git a/app/title_screen_win32.hpp b/app/title_screen_win32.hpp index e00f37f..9710681 100644 --- a/app/title_screen_win32.hpp +++ b/app/title_screen_win32.hpp @@ -15,7 +15,7 @@ namespace settlement::viewer { constexpr int title_continue_id = 1100; constexpr int title_new_id = 1101; constexpr int title_browse_id = 1102; -constexpr int title_join_id = 1103; +constexpr int title_coop_id = 1103; constexpr int title_exit_id = 1104; constexpr int title_saves_id = 1105; constexpr int title_open_id = 1106; @@ -39,7 +39,7 @@ public: void create(HWND owner) { constexpr const wchar_t* names[] = { - L"Продолжить", L"Новая колония", L"Открыть файл…", L"Подключиться к другу…", L"Выход" + L"Продолжить", L"Новая колония", L"Открыть файл…", L"Кооператив…", L"Выход" }; const auto instance = GetModuleHandleW(nullptr); for (std::size_t i = 0; i < buttons_.size(); ++i) { @@ -92,11 +92,12 @@ public: ShowWindow(open_, flags); } - void update(bool has_session, bool connecting) const { - EnableWindow(buttons_[0], !connecting && (has_session || !saves.empty())); - for (std::size_t i = 1; i < buttons_.size() - 1; ++i) EnableWindow(buttons_[i], !connecting); - EnableWindow(open_, !connecting && selected_index() < saves.size()); - EnableWindow(saves_, !connecting); + void update(bool can_resume, bool offline) const { + EnableWindow(buttons_[0], can_resume || (offline && !saves.empty())); + EnableWindow(buttons_[title_new_id - title_continue_id], offline); + EnableWindow(buttons_[title_browse_id - title_continue_id], offline); + EnableWindow(open_, offline && selected_index() < saves.size()); + EnableWindow(saves_, offline); } HBRUSH paint_list_background(HWND control, HDC dc) const { @@ -126,7 +127,6 @@ public: void draw(HDC dc, int width, int height, const std::wstring& notice) const { shade(dc, {0, 0, width, height}, RGB(24, 38, 34)); - // A simple isometric landscape with the same palette as the colony map. const auto old_pen = SelectObject(dc, GetStockObject(NULL_PEN)); const auto distant = CreateSolidBrush(RGB(32, 53, 44)); const auto near_hills = CreateSolidBrush(RGB(41, 66, 50)); diff --git a/app/viewer_win32.cpp b/app/viewer_win32.cpp index fa1f2f5..538b1f2 100644 --- a/app/viewer_win32.cpp +++ b/app/viewer_win32.cpp @@ -7,7 +7,7 @@ #include #include "d3d_scene_win32.hpp" -#include "isometric_camera.hpp" +#include "map_camera.hpp" #include "lan_session.hpp" #include "title_screen_win32.hpp" #include "settlement/core/world.hpp" @@ -33,7 +33,7 @@ namespace { -constexpr wchar_t window_class[] = L"SettlementIsometricViewer"; +constexpr wchar_t window_class[] = L"SettlementViewer"; constexpr wchar_t resident_window_class[] = L"SettlementResidentRoster"; constexpr wchar_t scene_window_class[] = L"SettlementD3DViewport"; constexpr int title_menu_id = 1002; @@ -69,7 +69,6 @@ constexpr int resident_list_id = 1060; constexpr int first_role_id = 1070; constexpr int first_dock_section_id = 1080; constexpr int work_list_button_id = 1083; -constexpr int graphics_menu_id = 1120; constexpr int exit_menu_id = 1121; constexpr int timer_id = 1; constexpr int map_size = settlement::first_colony_map_size; @@ -100,10 +99,11 @@ namespace title = settlement::viewer; title::TitleScreen title_screen; bool showing_title = true; bool has_session = false; +bool enter_game_on_snapshot = false; +bool coop_menu_open = false; bool pause_menu_open = false; HWND scene_window = nullptr; settlement::viewer::D3DScene graphics; -bool prefer_direct3d = true; using settlement::viewer::LanState; settlement::viewer::LanSession lan; LanState displayed_lan_state = LanState::Offline; @@ -187,7 +187,7 @@ struct ResidentRoster { ResidentRoster roster; std::optional selected_bed_base; std::optional move_source; -settlement::viewer::IsometricCamera camera; +settlement::viewer::MapCamera camera; struct CameraDrag { POINT previous; bool left_button; @@ -318,7 +318,7 @@ void draw_work_icon(HDC dc, WorkIcon icon, int x, int y) { RestoreDC(dc, state); } -POINT iso_point(int x, int y, int origin_x, int origin_y) { +POINT map_projection(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}; } @@ -328,7 +328,7 @@ bool shows_bed_choices() { } bool is_map_point(const RECT& client, POINT point) { - return !showing_title && point.x >= 0 && point.x < client.right && + return !showing_title && graphics.ready() && point.x >= 0 && point.x < client.right && point.y >= map_top && point.y < client.bottom - map_footer; } @@ -341,14 +341,14 @@ void invalidate_scene(HWND window) { GetClientRect(window, &scene); scene.top = map_top; if (scene.bottom > scene.top) InvalidateRect(window, &scene, FALSE); - if (!showing_title && prefer_direct3d && graphics.ready() && scene_window) { + if (!showing_title && graphics.ready() && scene_window) { InvalidateRect(scene_window, nullptr, FALSE); } } void layout_scene(HWND window) { if (!scene_window) return; - if (showing_title || !prefer_direct3d || !graphics.ready()) { + if (showing_title || !graphics.ready()) { ShowWindow(scene_window, SW_HIDE); return; } @@ -392,174 +392,6 @@ void update_map_hover(HWND window, POINT point) { 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}; @@ -577,42 +409,6 @@ POINT resident_anchor(POINT center, const settlement::Agent& agent) { 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; }); @@ -937,6 +733,14 @@ void toggle_work_panel(HWND window, WorkPanel panel) { SetFocus(window); } +bool can_resume_session() { + return has_session && lan.state() != LanState::Connecting && lan.state() != LanState::GuestDisconnected; +} + +void update_title_controls() { + title_screen.update(can_resume_session(), lan.state() == LanState::Offline); +} + void show_title_screen(HWND window, bool visible) { showing_title = visible; if (visible) { @@ -944,11 +748,12 @@ void show_title_screen(HWND window, bool visible) { set_work_panel(window, WorkPanel::None); set_placement_mode(window, PlacementMode::None); title_screen.reload_saves(); - title_screen.update(has_session, lan.state() == LanState::Connecting); + update_title_controls(); } else { has_session = true; - if (prefer_direct3d && !graphics.ready() && (!scene_window || !graphics.initialize(scene_window))) { - prefer_direct3d = false; + enter_game_on_snapshot = false; + if (!graphics.ready() && scene_window && !graphics.initialize(scene_window)) { + graphics.initialize(scene_window, true); } } const int flags = visible ? SW_HIDE : SW_SHOWNA; @@ -1159,7 +964,7 @@ void show_lan_info(HWND window) { (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Друг в той же сети выбирает «Подключиться к другу…» в главном меню."; + L"\n\nДруг в той же сети выбирает «Кооператив → Подключиться к другу…» в главном меню."; MessageBoxW(window, text.c_str(), L"Кооператив по локальной сети", MB_OK | MB_ICONINFORMATION); } @@ -1180,35 +985,45 @@ void refresh_lan_controls(HWND window) { SetWindowTextW(window, caption.c_str()); if (disconnected) { set_placement_mode(window, PlacementMode::None); - placement_message = showing_title ? L"Не удалось подключиться. Проверьте адрес и код." : - L"Связь прервана. «Esc → Подключиться снова». " + widen_ascii(lan.detail()); + enter_game_on_snapshot = false; + placement_message = showing_title ? L"Связь потеряна. Откройте «Кооператив», чтобы подключиться снова." : + L"Связь прервана. Переподключение — в разделе «Кооператив» главного меню."; } else if (state == LanState::GuestConnected) { placement_message = L"Подключено к колонии хозяина."; } if (roster.window) update_roster_details(); update_status(); if (showing_title) { - title_screen.update(has_session, state == LanState::Connecting); + update_title_controls(); InvalidateRect(window, nullptr, FALSE); } invalidate_scene(window); } void handle_lan_menu(HWND window, int command) { + if (!showing_title) return; try { if (command == lan_host_id && lan.state() == LanState::Offline) { - if (!world || !world->scenario_active()) { - throw std::runtime_error("Start the playable colony before hosting."); - } + auto colony = !has_session || !world || !world->scenario_active() + ? settlement::make_first_colony(local_worker_count) : nullptr; lan.host(); + if (colony) { + world = std::move(colony); + camera = {}; + selected_resident.reset(); + } + has_session = true; + placement_message = L"Сетевая колония открыта. Нажмите «Продолжить», чтобы войти."; refresh_lan_controls(window); show_lan_info(window); + return; } else if (command == lan_join_id && (lan.state() == LanState::Offline || lan.state() == LanState::GuestDisconnected)) { const auto request = ask_join_address(window); if (!request) return; if (!world) world = settlement::make_first_colony(local_worker_count); lan.join(narrow_lan_input(request->address.data()), narrow_lan_input(request->code.data())); + enter_game_on_snapshot = true; selected_resident.reset(); sync_resident_roster(true); set_work_panel(window, WorkPanel::None); @@ -1216,10 +1031,13 @@ void handle_lan_menu(HWND window, int command) { } else if (command == lan_info_id && !lan.is_guest() && lan.state() != LanState::Offline) { show_lan_info(window); return; - } else if (command == lan_reconnect_id) { + } else if (command == lan_reconnect_id && lan.state() == LanState::GuestDisconnected) { lan.reconnect(); + enter_game_on_snapshot = true; + placement_message = L"Подключаемся к хозяину…"; } else if (command == lan_leave_id) { lan.leave(); + enter_game_on_snapshot = false; set_work_panel(window, WorkPanel::None); set_placement_mode(window, PlacementMode::None, L"Сетевая игра завершена."); } @@ -1230,18 +1048,26 @@ void handle_lan_menu(HWND window, int command) { } } +void open_coop_menu(HWND window); + void handle_title_command(HWND window, int command, int notification) { if (command == title::title_exit_id && notification == BN_CLICKED) { DestroyWindow(window); return; } - if (lan.state() == LanState::Connecting) return; - if (command == title::title_saves_id && notification == LBN_SELCHANGE) { - title_screen.update(has_session, false); + if (command == title::title_coop_id && notification == BN_CLICKED) { + open_coop_menu(window); return; } - if (command == title::title_join_id && notification == BN_CLICKED) { - handle_lan_menu(window, lan_join_id); + const bool offline = lan.state() == LanState::Offline; + if (command == title::title_continue_id && notification == BN_CLICKED && can_resume_session()) { + show_title_screen(window, false); + refresh_lan_controls(window); + return; + } + if (!offline) return; + if (command == title::title_saves_id && notification == LBN_SELCHANGE) { + update_title_controls(); return; } const bool open_selected = (command == title::title_open_id && notification == BN_CLICKED) || @@ -1250,15 +1076,12 @@ void handle_title_command(HWND window, int command, int notification) { (command != title::title_new_id && command != title::title_continue_id && command != title::title_browse_id))) { return; } - if (lan.state() == LanState::GuestDisconnected) lan.leave(); if (open_selected) { if (const auto path = title_screen.selected_save()) handle_save_menu(window, false, path); } else if (command == title::title_new_id) { reset_world(window); } else if (command == title::title_browse_id) { handle_save_menu(window, false); - } else if (has_session) { - show_title_screen(window, false); } else if (const auto path = title_screen.latest_save()) { handle_save_menu(window, false, path); } @@ -1559,7 +1382,7 @@ std::optional resident_at(HWND window, POINT point) { 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); + map_projection(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; @@ -1623,104 +1446,6 @@ std::wstring resident_details() { 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)); @@ -1728,19 +1453,12 @@ void draw_world(HDC dc, int width, int height) { DeleteObject(background); if (!world) return; - if ((!prefer_direct3d || !graphics.ready()) && 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); - } + if (!graphics.ready() && height > map_top + map_footer) { + RECT scene{16, map_top + 24, width - 16, height - map_footer}; + SetBkMode(dc, TRANSPARENT); + SetTextColor(dc, color(55, 68, 59)); + DrawTextW(dc, L"Не удалось запустить Direct3D 11. Откройте главное меню и войдите в колонию снова.", + -1, &scene, DT_CENTER | DT_WORDBREAK); } const RECT dock{0, height - map_footer, width, height}; @@ -1813,13 +1531,12 @@ LRESULT CALLBACK scene_window_proc(HWND window, UINT message, WPARAM wparam, LPA BeginPaint(window, &paint); RECT client{}; GetClientRect(window, &client); - const bool drawn = !world || !graphics.ready() || !prefer_direct3d || + const bool drawn = !world || !graphics.ready() || client.right <= 0 || client.bottom <= 0 || graphics.render(*world, scene_view(client.right, client.bottom)); EndPaint(window, &paint); if (!drawn) { graphics.reset(); - prefer_direct3d = false; const auto parent = GetParent(window); layout_scene(parent); invalidate_scene(parent); @@ -1829,88 +1546,50 @@ LRESULT CALLBACK scene_window_proc(HWND window, UINT message, WPARAM wparam, LPA return DefWindowProcW(window, message, wparam, lparam); } -void toggle_graphics(HWND window) { - if (prefer_direct3d && graphics.ready()) { - prefer_direct3d = false; - placement_message = L"Режим графики — изометрия GDI."; - } else { - prefer_direct3d = graphics.ready() || (scene_window && graphics.initialize(scene_window)); - placement_message = prefer_direct3d ? L"Режим графики — Direct3D 11." : - L"Direct3D 11 недоступен. Включена изометрия GDI."; - } - layout_scene(window); - invalidate_scene(window); -} +struct MenuAction { + int id; + const wchar_t* caption; + bool enabled = true; +}; -struct PauseMenu { - LanState lan_state; - bool paused; - bool scenario; - bool direct3d; +struct MenuDialog { + const wchar_t* title; + std::span actions; HBRUSH background; }; -INT_PTR CALLBACK pause_menu_proc(HWND dialog, UINT message, WPARAM wparam, LPARAM lparam) { +INT_PTR CALLBACK menu_dialog_proc(HWND dialog, UINT message, WPARAM wparam, LPARAM lparam) { switch (message) { case WM_INITDIALOG: { - const auto& menu = *reinterpret_cast(lparam); + const auto& menu = *reinterpret_cast(lparam); SetWindowLongPtrW(dialog, DWLP_USER, lparam); - const bool offline = menu.lan_state == LanState::Offline; - const bool host = menu.lan_state == LanState::Hosting || menu.lan_state == LanState::HostConnected; - const bool disconnected = menu.lan_state == LanState::GuestDisconnected; - SetWindowTextW(dialog, offline ? L"Меню паузы" : L"Меню игры"); - const auto control = [&](const wchar_t* type, const wchar_t* label, int id, DWORD flags, RECT rectangle) { - MapDialogRect(dialog, &rectangle); - const auto child = CreateWindowExW(0, type, label, WS_CHILD | WS_VISIBLE | flags, - rectangle.left, rectangle.top, rectangle.right - rectangle.left, rectangle.bottom - rectangle.top, - dialog, reinterpret_cast(static_cast(id)), GetModuleHandleW(nullptr), nullptr); + SetWindowTextW(dialog, menu.title); + HWND first_enabled = nullptr; + int y = 9; + for (const auto& action : menu.actions) { + RECT bounds{12, y, 218, y + 20}; + MapDialogRect(dialog, &bounds); + const auto child = CreateWindowExW(0, L"BUTTON", action.caption, + WS_CHILD | WS_VISIBLE | WS_TABSTOP | BS_OWNERDRAW, bounds.left, bounds.top, + bounds.right - bounds.left, bounds.bottom - bounds.top, dialog, + reinterpret_cast(static_cast(action.id)), GetModuleHandleW(nullptr), nullptr); SendMessageW(child, WM_SETFONT, reinterpret_cast(GetStockObject(DEFAULT_GUI_FONT)), TRUE); - return child; - }; - const auto button = [&](int id, const wchar_t* label, int column, int row, bool enabled = true) { - const int x = column == 0 ? 13 : 184; - const int y = 27 + row * 25; - const auto child = control(L"BUTTON", label, id, WS_TABSTOP | BS_OWNERDRAW, - {x, y, x + 155, y + 20}); - EnableWindow(child, enabled); - }; - control(L"STATIC", L"Поселение", -1, 0, {13, 9, 167, 23}); - control(L"STATIC", L"Кооператив", -1, 0, {184, 9, 339, 23}); - button(IDOK, L"Продолжить", 0, 0); - button(save_menu_id, L"Сохранить поселение…", 0, 1, offline || host); - button(load_menu_id, L"Загрузить поселение…", 0, 2, offline); - button(title_menu_id, L"Главное меню", 0, 3, offline); - button(graphics_menu_id, menu.direct3d ? L"Графика · Direct3D 11" : L"Графика · Изометрия GDI", 0, 4); - button(exit_menu_id, L"Выйти из игры", 0, 5); - if (offline) { - button(lan_host_id, L"Открыть для друга…", 1, 0, menu.scenario); - button(lan_join_id, L"Подключиться к другу…", 1, 1); - } else if (host) { - button(lan_info_id, L"Адрес и код партии…", 1, 0); - button(pause_button_id, menu.paused ? L"Продолжить для всех" : L"Пауза для всех", 1, 1); - button(lan_leave_id, L"Закрыть сетевую игру", 1, 2); - } else { - if (disconnected) button(lan_reconnect_id, L"Подключиться снова", 1, 0); - button(lan_leave_id, L"Выйти из сетевой игры", 1, 1); + EnableWindow(child, action.enabled); + if (!first_enabled && action.enabled) first_enabled = child; + y += 25; } - SetFocus(GetDlgItem(dialog, IDOK)); + SetFocus(first_enabled); return FALSE; } case WM_CTLCOLORDLG: - case WM_CTLCOLORSTATIC: - if (const auto* menu = reinterpret_cast(GetWindowLongPtrW(dialog, DWLP_USER))) { - const auto dc = reinterpret_cast(wparam); - SetTextColor(dc, color(236, 230, 205)); - SetBkMode(dc, TRANSPARENT); + if (const auto* menu = reinterpret_cast(GetWindowLongPtrW(dialog, DWLP_USER))) { return reinterpret_cast(menu->background); } break; case WM_DRAWITEM: if (const auto* item = reinterpret_cast(lparam); item && item->CtlType == ODT_BUTTON) { - WorkIcon icon = WorkIcon::Resident; - if (item->CtlID == graphics_menu_id) icon = WorkIcon::Stone; - else if (item->CtlID == save_menu_id || item->CtlID == load_menu_id) icon = WorkIcon::Crate; - draw_icon_button(*item, icon, item->CtlID == IDOK, true); + const bool storage = item->CtlID == save_menu_id || item->CtlID == load_menu_id; + draw_icon_button(*item, storage ? WorkIcon::Crate : WorkIcon::Resident, item->CtlID == IDOK, true); return TRUE; } break; @@ -1927,34 +1606,97 @@ INT_PTR CALLBACK pause_menu_proc(HWND dialog, UINT message, WPARAM wparam, LPARA return FALSE; } -void open_pause_menu(HWND window) { - if (!world || showing_title || pause_menu_open) return; - camera_drag.reset(); - if (GetCapture() == window) ReleaseCapture(); +int choose_menu_action(HWND window, const wchar_t* title, std::span actions) { struct alignas(DWORD) EmptyDialog { DLGTEMPLATE header{}; WORD menu = 0, window_class = 0, title = 0; } layout; layout.header.style = WS_POPUP | WS_CAPTION | WS_SYSMENU | DS_MODALFRAME | DS_CENTER; - layout.header.cx = 352; - layout.header.cy = 184; - PauseMenu menu{lan.state(), world->paused(), world->scenario_active(), prefer_direct3d && graphics.ready(), - CreateSolidBrush(color(34, 46, 40))}; - pause_menu_open = true; + layout.header.cx = 230; + layout.header.cy = static_cast(13 + 25 * actions.size()); + MenuDialog menu{title, actions, CreateSolidBrush(color(34, 46, 40))}; const auto action = DialogBoxIndirectParamW(GetModuleHandleW(nullptr), &layout.header, window, - pause_menu_proc, reinterpret_cast(&menu)); - if (action == IDOK) { - if (lan.state() == LanState::Offline && world->paused()) { + menu_dialog_proc, reinterpret_cast(&menu)); + DeleteObject(menu.background); + return static_cast(action); +} + +void open_pause_menu(HWND window) { + if (!world || showing_title || pause_menu_open) return; + camera_drag.reset(); + if (GetCapture() == window) ReleaseCapture(); + const bool offline = lan.state() == LanState::Offline; + const MenuAction actions[] = { + {IDOK, L"Продолжить"}, + {save_menu_id, L"Сохранить поселение…", !lan.is_guest()}, + {load_menu_id, L"Загрузить поселение…", offline}, + {title_menu_id, L"Главное меню"}, + {exit_menu_id, L"Выйти из игры"}, + }; + pause_menu_open = true; + const auto action = choose_menu_action(window, offline ? L"Меню паузы" : L"Меню игры", actions); + switch (action) { + case IDOK: + if (offline && world->paused()) { static_cast(send_command(settlement::CommandKind::SetPaused)); } - } else if (action != IDCANCEL && action != -1) { - SendMessageW(window, WM_COMMAND, static_cast(action), 0); + break; + case save_menu_id: + case load_menu_id: + handle_save_menu(window, action == save_menu_id); + break; + case title_menu_id: + show_title_screen(window, true); + refresh_lan_controls(window); + break; + case exit_menu_id: + DestroyWindow(window); + break; } pause_menu_open = false; - DeleteObject(menu.background); if (IsWindow(window)) SetFocus(window); } +void open_coop_menu(HWND window) { + std::vector actions; + switch (lan.state()) { + case LanState::Offline: + actions.push_back({lan_host_id, has_session && world && world->scenario_active() + ? L"Открыть текущую колонию для друга…" : L"Создать сетевую колонию…"}); + actions.push_back({lan_join_id, L"Подключиться к другу…"}); + break; + case LanState::Hosting: + case LanState::HostConnected: + actions.push_back({lan_info_id, L"Адрес и код партии…"}); + actions.push_back({pause_button_id, world->paused() ? L"Продолжить для всех" : L"Пауза для всех"}); + actions.push_back({lan_leave_id, L"Закрыть сетевую игру"}); + break; + case LanState::Connecting: + actions.push_back({lan_leave_id, L"Отменить подключение"}); + break; + case LanState::GuestDisconnected: + actions.push_back({lan_reconnect_id, L"Подключиться снова"}); + actions.push_back({lan_join_id, L"Подключиться к другу…"}); + [[fallthrough]]; + case LanState::GuestConnected: + actions.push_back({lan_leave_id, L"Выйти из сетевой игры"}); + break; + } + actions.push_back({IDCANCEL, L"Назад"}); + coop_menu_open = true; + const auto action = choose_menu_action(window, L"Кооператив", actions); + coop_menu_open = false; + if (action == pause_button_id && + (lan.state() == LanState::Hosting || lan.state() == LanState::HostConnected)) { + static_cast(send_command(settlement::CommandKind::SetPaused, {}, + static_cast(!world->paused()))); + placement_message = world->paused() ? L"Сетевая колония на паузе." : L"Сетевая колония продолжает работу."; + InvalidateRect(window, nullptr, FALSE); + } else if (action >= lan_host_id && action <= lan_leave_id) { + handle_lan_menu(window, action); + } +} + LRESULT CALLBACK window_proc(HWND window, UINT message, WPARAM wparam, LPARAM lparam) { switch (message) { case WM_GETMINMAXINFO: { @@ -2018,12 +1760,10 @@ LRESULT CALLBACK window_proc(HWND window, UINT message, WPARAM wparam, LPARAM lp if (const auto brush = title_screen.paint_list_background(reinterpret_cast(lparam), reinterpret_cast(wparam))) return reinterpret_cast(brush); } - if (LOWORD(wparam) == exit_menu_id && pause_menu_open) { - DestroyWindow(window); - return 0; - } - if (LOWORD(wparam) == graphics_menu_id && pause_menu_open) { - toggle_graphics(window); + break; + case WM_COMMAND: + if (showing_title) { + handle_title_command(window, LOWORD(wparam), HIWORD(wparam)); return 0; } if (LOWORD(wparam) == work_list_button_id && HIWORD(wparam) == BN_CLICKED && can_give_orders()) { @@ -2037,12 +1777,6 @@ LRESULT CALLBACK window_proc(HWND window, UINT message, WPARAM wparam, LPARAM lp SetFocus(window); return 0; } - break; - case WM_COMMAND: - if (showing_title) { - handle_title_command(window, LOWORD(wparam), HIWORD(wparam)); - return 0; - } if (LOWORD(wparam) == residents_button_id && HIWORD(wparam) == BN_CLICKED) { if (world) show_resident_roster(window); return 0; @@ -2068,10 +1802,6 @@ LRESULT CALLBACK window_proc(HWND window, UINT message, WPARAM wparam, LPARAM lp 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, @@ -2093,17 +1823,6 @@ LRESULT CALLBACK window_proc(HWND window, UINT message, WPARAM wparam, LPARAM lp 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) == title_menu_id) { - if (lan.state() == LanState::Offline) { - show_title_screen(window, true); - refresh_lan_controls(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); @@ -2126,19 +1845,11 @@ LRESULT CALLBACK window_proc(HWND window, UINT message, WPARAM wparam, LPARAM lp 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 && pause_menu_open && !lan.is_guest()) { - static_cast(send_command(settlement::CommandKind::SetPaused, {}, - static_cast(!world->paused()))); - update_status(); - return 0; - } + if (LOWORD(wparam) == priority_button_id && HIWORD(wparam) == BN_CLICKED && world && world->scenario_active()) { + const auto next = (static_cast(world->work_priority()) + 1U) % 3U; + static_cast(send_command(settlement::CommandKind::SetPriority, {}, static_cast(next))); + update_status(); + return 0; } break; case WM_MOUSEWHEEL: { @@ -2311,12 +2022,16 @@ LRESULT CALLBACK window_proc(HWND window, UINT message, WPARAM wparam, LPARAM lp break; case WM_TIMER: if (wparam == timer_id && world) { - if (showing_title && lan.state() != LanState::Connecting) return 0; - if (!showing_title && !file_dialog_active && !lan.is_guest() && - (!pause_menu_open || lan.state() != LanState::Offline)) world->step(); + const auto state = lan.state(); + if (showing_title && (state == LanState::Offline || state == LanState::GuestDisconnected)) return 0; + if (!file_dialog_active && !lan.is_guest() && + (state != LanState::Offline || (!showing_title && !pause_menu_open))) world->step(); if (auto snapshot = lan.poll(*world)) { world = std::move(snapshot); - if (showing_title) show_title_screen(window, false); + has_session = true; + } + if (showing_title && enter_game_on_snapshot && !coop_menu_open && lan.state() == LanState::GuestConnected) { + show_title_screen(window, false); } sync_resident_roster(); if (lan.state() != displayed_lan_state) refresh_lan_controls(window); diff --git a/docs/roadmap-status.md b/docs/roadmap-status.md index 4291c83..587dec5 100644 --- a/docs/roadmap-status.md +++ b/docs/roadmap-status.md @@ -5,7 +5,7 @@ - Ядро симуляции с фиксированными тиками. - Пул потоков для выбора заданий, поиска маршрутов и продвижения жителей. - Автоматический выбор числа потоков в Windows-клиенте и параметр для командных бенчмарков. -- Изометрический прототип карты с жителями, заданиями и маршрутами. +- Объёмная карта с жителями, заданиями и маршрутами. - Базовый цикл ресурсов: источник дерева/камня → резервирование → добыча → перенос → склад. - Складской инвентарь со стеками `Wood` и `Stone` и учётом свободной вместимости. - Два рецепта превращают древесину в доски и камень в блоки. Домик строится из трёх досок и двух блоков. @@ -27,8 +27,8 @@ - Производительность ядра измерена на колониях с 50–500 жителями, полями, складами и ремеслом. Результаты и команда запуска описаны в [отчёте](../benchmarks/colony-performance.md). - Основные команды собраны в нижней панели «Жители», «Добыча», «Участки» и «Строительство». Меню «Работы» открывает те же команды по профессиям. - Главное меню открывается при запуске. В нём можно начать новую колонию, выбрать сохранение или подключиться к другу. -- Esc открывает меню паузы, сохранений, сетевых действий и графики. -- Direct3D 11 рисует карту, жителей и постройки как объёмную геометрию с глубиной. Изометрия GDI доступна через меню Esc. +- Esc открывает меню паузы и сохранений. Создание сетевой партии и подключение находятся в разделе «Кооператив» главного меню. +- Direct3D 11 рисует карту, жителей и постройки как объёмную геометрию с глубиной. - Поиск ресурсных работ отбирает подходящие поручения по профессиям. Повторные запросы путей используют кэш. - Движение, прогресс работ жителей и поиск маршрутов для общих заданий выполняются в пуле из двух и более потоков. Тесты проверяют игровые результаты, сохранения и команды кооператива. @@ -38,7 +38,7 @@ ## Ограничения прототипа -- Камера показывает карту в изометрической проекции. Direct3D использует базовые модели и затенение граней. +- Камера поддерживает перемещение и масштабирование. Direct3D использует базовые модели и затенение граней. - Каждый поход добытчика доставляет одну единицу сырья. Строитель везёт весь комплект для одного домика за рейс с остановками у нужных складов. Мастерские пока используют складское сырьё напрямую. - Свободный житель сначала ищет еду, если проголодался. Если порции нет, он может снова взять работу. При голоде здоровье пока остаётся прежним. - Завершённое спальное место назначается одному жителю. Сейчас жители идут спать по усталости. diff --git a/docs/viewer.md b/docs/viewer.md index 3b12278..48a4dbb 100644 --- a/docs/viewer.md +++ b/docs/viewer.md @@ -1,4 +1,4 @@ -# Запуск изометрического прототипа +# Запуск игры на Windows Соберите проект командой: @@ -14,7 +14,7 @@ powershell.exe -NoProfile -ExecutionPolicy Bypass -File .\build.ps1 Колесо мыши приближает и отдаляет карту относительно курсора. Чтобы сдвинуть карту, перетащите её с зажатой левой или средней кнопкой мыши. Короткий щелчок левой кнопкой выбирает жителя или ставит чертёж. Home возвращает исходный вид. -Игра пробует включить Direct3D 11 при входе в колонию. Рендерер рисует объёмную карту с глубиной, постройки и жителей в изометрической проекции. Кнопка «Графика» в меню Esc переключает Direct3D и изометрию GDI. При ошибке устройства карта открывается в GDI. +Карту, постройки и жителей рисует Direct3D 11. Игра сначала пробует использовать видеокарту. Если устройство недоступно, Direct3D 11 пробует создать программное устройство WARP. В новой партии три поселенца. На нижней панели откройте «Строительство → Спальное место». Под кнопкой появятся «Дерево» слева и «Камень» справа. Выберите основу, затем щёлкайте по свободным клеткам. Выбранная основа применяется к следующим кроватям до выхода из режима или смены основы. Повторное нажатие «Спальное место» или правый щелчок завершает размещение. @@ -43,7 +43,7 @@ Esc открывает меню игры из любого режима стро ## Кооператив по локальной сети 1. Запустите одинаковую версию игры на двух компьютерах в одной локальной сети. -2. Хозяин открывает свою колонию через «Esc → Открыть для друга…» и передаёт гостю IPv4 и код партии. Порт игры — TCP 41727. -3. Гость выбирает «Подключиться к другу…» в главном меню или в меню Esc и вводит эти данные. При обрыве связи можно выбрать «Подключиться снова», пока хозяин оставляет партию открытой. +2. Хозяин открывает «Кооператив…» в главном меню и создаёт сетевую колонию либо открывает для друга уже начатую. Он передаёт гостю IPv4 и код партии. Затем он нажимает «Продолжить». Порт игры — TCP 41727. +3. Гость выбирает «Кооператив → Подключиться к другу…» в главном меню и вводит эти данные. При обрыве связи в этом же разделе можно выбрать «Подключиться снова», пока хозяин держит партию открытой. -Оба игрока строят и меняют задания в общей колонии. Меню Esc доступно каждому. Хозяин сохраняет игру и останавливает симуляцию кнопкой «Пауза для всех». После выхода гостя хозяин может продолжить партию. +Оба игрока строят и меняют задания в общей колонии. «Esc → Главное меню» позволяет открыть настройки кооператива и вернуться в колонию через «Продолжить». Хозяин сохраняет игру через Esc и может остановить симуляцию через «Кооператив → Пауза для всех» в главном меню. -- 2.54.0 From 2a71ed6242f19f9076bc6d8926ca875ca7d886be Mon Sep 17 00:00:00 2001 From: Codex Date: Sun, 29 Nov 2026 19:30:05 +0300 Subject: [PATCH 4/7] Scale the bottom controls and confirm editable construction plans --- PLAN.md | 3 + app/d3d_scene_win32.cpp | 27 ++ app/d3d_scene_win32.hpp | 9 + app/lan_session.hpp | 9 +- app/lan_session_win32.cpp | 22 +- app/viewer_win32.cpp | 477 +++++++++++++++++------ docs/viewer.md | 8 +- engine/include/settlement/core/world.hpp | 1 + engine/src/world.cpp | 8 + tests/lan_tests.cpp | 7 +- 10 files changed, 438 insertions(+), 133 deletions(-) diff --git a/PLAN.md b/PLAN.md index 8b82688..a3599a4 100644 --- a/PLAN.md +++ b/PLAN.md @@ -48,11 +48,14 @@ - [x] Отображение источников ресурсов, складов и текущих запасов. - [x] Камера с перемещением и масштабированием относительно курсора. - [x] Нижняя панель с жителями, добычей, участками и строительством. +- [x] Нижние кнопки «Работы» и приоритета с настраиваемым масштабом панели. - [x] Главное меню со списком сохранений, продолжением партии и управлением кооперативом. - [x] Меню Esc с паузой, сохранениями, выходом в главное меню и завершением игры. - [x] Игровая карта на Direct3D 11 с глубиной и базовыми объёмными моделями. - [ ] Расширение набора 3D-моделей и освещения. - [x] Постановка чертежа домика мышью в Windows-клиенте. +- [x] Редактируемая раскладка кроватей и станков с предпросмотром, списком материалов и подтверждением. +- [ ] Чертежи комнат с полом, стенами и проёмами. - [ ] Интерфейс для остальных типов работ и зданий. ### P5 — Игровые системы и совместная игра diff --git a/app/d3d_scene_win32.cpp b/app/d3d_scene_win32.cpp index deb25cc..7b72f5e 100644 --- a/app/d3d_scene_win32.cpp +++ b/app/d3d_scene_win32.cpp @@ -167,6 +167,31 @@ void construction(Mesh& mesh, const World& world) { } } +void draw_blueprint(Mesh& mesh, const BlueprintPart& part, bool preview) { + const float x = static_cast(part.cell.x), y = static_cast(part.cell.y); + const auto ink = preview ? rgb(168, 232, 243) : rgb(90, 189, 236); + const auto frame = part.recipe == RecipeId::BuildBed && part.base == BedBase::Stone + ? shade(ink, .70f) : ink; + constexpr float beam = .055f; + const auto outline = [&](float width, float depth, float z, Color color) { + for (float side : {-1.f, 1.f}) { + mesh.box(x, y + side * depth / 2, z, width + beam, beam, beam, color); + mesh.box(x + side * width / 2, y, z, beam, depth, beam, color); + } + }; + outline(.88f, .88f, .035f, ink); + const float width = part.recipe == RecipeId::BuildBed ? .72f : .70f; + const float depth = part.recipe == RecipeId::BuildBed ? .41f : .62f; + const float top = part.recipe == RecipeId::BuildBed ? .34f : .68f; + outline(width, depth, top, frame); + for (float side_x : {-1.f, 1.f}) { + for (float side_y : {-1.f, 1.f}) { + mesh.box(x + side_x * width / 2, y + side_y * depth / 2, .04f, beam, beam, top - .04f, frame); + } + } + if (part.recipe == RecipeId::WeaveCloth) mesh.box(x, y, .30f, width, beam, beam, ink); +} + void residents(Mesh& mesh, const World& world, const SceneView& view) { for (const auto& agent : world.agents()) { using enum AgentState; @@ -378,6 +403,8 @@ bool D3DScene::render(const World& world, const SceneView& view, std::vector #include #include +#include #include namespace settlement::viewer { +struct BlueprintPart { + GridPosition cell; + RecipeId recipe; + BedBase base = BedBase::Wood; +}; + struct SceneView { int width; int height; @@ -23,6 +30,8 @@ struct SceneView { bool valid_cursor; std::optional move_source; std::optional selected; + std::span blueprint; + std::optional preview; }; class D3DScene { diff --git a/app/lan_session.hpp b/app/lan_session.hpp index 0ee6cef..2beb091 100644 --- a/app/lan_session.hpp +++ b/app/lan_session.hpp @@ -12,6 +12,13 @@ namespace settlement::viewer { enum class LanState { Offline, Hosting, HostConnected, Connecting, GuestConnected, GuestDisconnected }; inline constexpr std::uint16_t colony_lan_port = 41727; +struct LanRejection { + CommandStatus status; + CommandKind kind; + GridPosition cell; + std::uint8_t value; +}; + class LanSession { public: LanSession(); @@ -30,7 +37,7 @@ public: [[nodiscard]] const std::string& detail() const noexcept; [[nodiscard]] bool submit(CommandKind kind, GridPosition cell, std::uint8_t value, GridPosition destination = {}, AgentId resident = 0); - [[nodiscard]] std::optional take_rejection() noexcept; + [[nodiscard]] std::optional take_rejection() noexcept; [[nodiscard]] std::unique_ptr poll(World& world); private: diff --git a/app/lan_session_win32.cpp b/app/lan_session_win32.cpp index 9688c9f..3eabfdf 100644 --- a/app/lan_session_win32.cpp +++ b/app/lan_session_win32.cpp @@ -192,13 +192,13 @@ struct LanSession::Impl { bool connecting = false; bool authenticated = false; bool reject_pending = false; - bool waiting_reply = false; + std::optional awaiting_receipt; std::uint16_t network_port = 0; std::uint64_t key = 0; std::string host_address; std::string notice; std::deque actions; - std::optional rejected_command; + std::optional rejected_command; std::uint64_t guest_sequence = 0; Clock::time_point last_ping{}; Clock::time_point last_snapshot{}; @@ -218,7 +218,8 @@ struct LanSession::Impl { void drop_peer() noexcept { peer = Channel{}; - connecting = authenticated = reject_pending = waiting_reply = false; + connecting = authenticated = reject_pending = false; + awaiting_receipt.reset(); guest_sequence = 0; actions.clear(); rejected_command.reset(); @@ -298,14 +299,17 @@ struct LanSession::Impl { notice.clear(); return; } - if (message != Message::Receipt || payload.size() != 9 || !waiting_reply) { + if (message != Message::Receipt || payload.size() != 9 || !awaiting_receipt) { throw std::runtime_error("Invalid message from the host."); } const auto status = static_cast(static_cast(payload[0])); if (status > CommandStatus::Busy) throw std::runtime_error("Invalid command result."); - if (status != CommandStatus::Accepted) rejected_command = status; + if (status != CommandStatus::Accepted) { + rejected_command = LanRejection{status, awaiting_receipt->kind, awaiting_receipt->cell, + awaiting_receipt->value}; + } guest_sequence = number(payload.substr(1)); - waiting_reply = false; + awaiting_receipt.reset(); } void send_snapshot(const World& world, Clock::time_point now) { @@ -326,7 +330,7 @@ struct LanSession::Impl { } void send_action() { - if (waiting_reply || actions.empty() || guest_sequence == 0 || peer.pending()) return; + if (awaiting_receipt || actions.empty() || guest_sequence == 0 || peer.pending()) return; const Action action = actions.front(); std::string payload; append_number(payload, guest_sequence, 8); @@ -339,7 +343,7 @@ struct LanSession::Impl { append_number(payload, action.resident, 8); peer.queue(Message::Command, payload); actions.pop_front(); - waiting_reply = true; + awaiting_receipt = action; } }; @@ -438,7 +442,7 @@ bool LanSession::submit(CommandKind kind, GridPosition cell, std::uint8_t value, return true; } -std::optional LanSession::take_rejection() noexcept { +std::optional LanSession::take_rejection() noexcept { return std::exchange(impl_->rejected_command, std::nullopt); } diff --git a/app/viewer_win32.cpp b/app/viewer_win32.cpp index 538b1f2..eb451a6 100644 --- a/app/viewer_win32.cpp +++ b/app/viewer_win32.cpp @@ -69,20 +69,19 @@ constexpr int resident_list_id = 1060; constexpr int first_role_id = 1070; constexpr int first_dock_section_id = 1080; constexpr int work_list_button_id = 1083; +constexpr int build_blueprint_id = 1084; +constexpr int clear_blueprint_id = 1085; constexpr int exit_menu_id = 1121; +constexpr int interface_scale_id = 1122; +constexpr int first_scale_id = 1130; +constexpr std::array interface_scales{100, 125, 150}; +constexpr int default_interface_scale = 125; 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}; @@ -93,6 +92,16 @@ HWND stone_bed_button = nullptr; HWND priority_button = nullptr; HWND work_list_button = nullptr; HWND residents_button = nullptr; +HWND build_blueprint_button = nullptr; +HWND clear_blueprint_button = nullptr; +HFONT dock_font = nullptr; +int interface_scale = default_interface_scale; +struct DockLayout { + int height = 0; + int hint_top = 0; + int line_height = 0; +}; +DockLayout dock_layout; std::array dock_section_buttons{}; std::unique_ptr world; namespace title = settlement::viewer; @@ -113,7 +122,7 @@ enum class PlacementMode { None, Building, Foraging, BerryField, FlaxField, Tree 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 }; +enum class WorkIcon { Berries, Field, Flax, Tree, Pickaxe, Hammer, Loom, Resident, Bed, Wood, Stone, Crate, Pantry, Move, Demolish, Priority }; struct WorkChoice { int command; const wchar_t* title; @@ -186,6 +195,7 @@ struct ResidentRoster { }; ResidentRoster roster; std::optional selected_bed_base; +std::vector blueprint; std::optional move_source; settlement::viewer::MapCamera camera; struct CameraDrag { @@ -199,6 +209,10 @@ std::optional hover_cell; std::optional selected_resident; std::wstring placement_message; +int dock_pixels(int pixels) { + return MulDiv(pixels, interface_scale, 100); +} + COLORREF color(int red, int green, int blue) { return RGB(red, green, blue); } @@ -228,7 +242,7 @@ void fill_ellipse(HDC dc, int left, int top, int right, int bottom, DeleteObject(pen); } -void draw_work_icon(HDC dc, WorkIcon icon, int x, int y) { +void draw_work_icon(HDC dc, WorkIcon icon, int x, int y, int extent = 17) { const auto ink = color(54, 61, 58); const auto wood = color(158, 101, 52); const auto leaf = color(76, 137, 74); @@ -237,7 +251,11 @@ void draw_work_icon(HDC dc, WorkIcon icon, int x, int y) { const auto blue = color(91, 136, 184); const int state = SaveDC(dc); if (state == 0) return; - OffsetViewportOrgEx(dc, x, y, nullptr); + const float scale = static_cast(extent) / 17.f; + const XFORM transform{scale, 0.f, 0.f, scale, static_cast(x), static_cast(y)}; + if (extent == 17 || !SetGraphicsMode(dc, GM_ADVANCED) || !SetWorldTransform(dc, &transform)) { + 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); }; @@ -314,6 +332,11 @@ void draw_work_icon(HDC dc, WorkIcon icon, int x, int y) { box(6, 2, 11, 5, metal); box(2, 5, 15, 7, metal); break; + case WorkIcon::Priority: + box(2, 3, 16, 6, metal); + box(2, 8, 12, 11, metal); + box(2, 13, 8, 16, metal); + break; } RestoreDC(dc, state); } @@ -327,9 +350,17 @@ bool shows_bed_choices() { return world && world->staged_beds() && placement_mode == PlacementMode::Building; } +bool is_blueprint_tool() { + return placement_mode == PlacementMode::Building || placement_mode == PlacementMode::Loom; +} + +bool shows_blueprint_actions() { + return !showing_title && (is_blueprint_tool() || !blueprint.empty()); +} + bool is_map_point(const RECT& client, POINT point) { return !showing_title && graphics.ready() && point.x >= 0 && point.x < client.right && - point.y >= map_top && point.y < client.bottom - map_footer; + point.y >= map_top && point.y < client.bottom - dock_layout.height; } POINT client_point(LPARAM coordinates) { @@ -355,7 +386,7 @@ void layout_scene(HWND window) { RECT client{}; GetClientRect(window, &client); SetWindowPos(scene_window, HWND_BOTTOM, 0, map_top, client.right, - std::max(0, static_cast(client.bottom) - map_top - map_footer), SWP_NOACTIVATE | SWP_SHOWWINDOW); + std::max(0, static_cast(client.bottom) - map_top - dock_layout.height), SWP_NOACTIVATE | SWP_SHOWWINDOW); } void update_camera_drag(POINT point) { @@ -438,37 +469,125 @@ std::span work_choices() { } 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); + SetWindowPos(status_label, nullptr, 16, 14, std::max(0, width - 32), 24, SWP_NOZORDER | SWP_NOACTIVATE); + SetWindowPos(production_label, nullptr, 16, 44, std::max(0, width - 32), 24, SWP_NOZORDER | SWP_NOACTIVATE); + const bool compact = height < map_top + dock_pixels(390); + const int margin = dock_pixels(compact ? 8 : 12); + const int gap = dock_pixels(compact ? 5 : 7); + const int available = std::max(1, width - margin * 2); + int bottom = height - margin; + struct DockItem { + HWND control; + int width; + bool materials = false; + }; 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); + const auto layout_rows = [&](std::span items, int button_height) { + // Pack from the end so rows near the bottom stay fixed as the window grows. + while (!items.empty()) { + int row_width = 0; + bool materials = false; + auto start = items.size(); + do { + const auto& item = items[start - 1]; + const int required = std::min(available, dock_pixels(item.width)) + (row_width ? gap : 0); + if (row_width + required > available) break; + row_width += required; + materials |= item.materials; + --start; + } while (start != 0); + const int material_height = materials ? dock_pixels(compact ? 28 : 34) + gap : 0; + int x = std::max(margin, (width - row_width) / 2); + const int y = bottom - material_height - button_height; + for (const auto& item : items.subspan(start)) { + const int w = std::min(available, dock_pixels(item.width)); + place(item.control, x, y, w, button_height); + if (item.materials) { + const int half = (w - gap) / 2; + const int material_y = y + button_height + gap; + place(wood_bed_button, x, material_y, half, material_height - gap); + place(stone_bed_button, x + half + gap, material_y, w - half - gap, material_height - gap); + } + x += w + gap; + } + bottom = y - gap; + items = items.first(start); + } + }; + const DockItem sections[] = { + {residents_button, 101}, {dock_section_buttons[0], 104}, {dock_section_buttons[1], 104}, + {dock_section_buttons[2], 163}, {work_list_button, 101}, {priority_button, 172}, + }; + layout_rows(sections, dock_pixels(compact ? 34 : 40)); + const auto choices = work_choices(); + std::array tools{}; 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; + const bool bed = choice.command == cabin_button_id; + tools[index] = {work_choice_buttons[index], choice.width + (bed ? 32 : 14), bed && shows_bed_choices()}; } + const int tool_height = dock_pixels(compact ? 30 : 36); + if (choices.empty()) bottom -= tool_height + gap; + else layout_rows(std::span(tools).first(choices.size()), tool_height); + + if (shows_blueprint_actions()) { + const DockItem actions[] = {{build_blueprint_button, 182}, {clear_blueprint_button, 188}}; + layout_rows(actions, dock_pixels(compact ? 31 : 37)); + } + const int line_height = dock_pixels(compact ? 20 : 23); + const int hint_top = bottom - 2 * line_height; + const int new_height = height - hint_top + dock_pixels(8); + if (new_height != dock_layout.height && !showing_title) { + RECT dirty{0, height - std::max(new_height, dock_layout.height), width, height}; + InvalidateRect(window, &dirty, FALSE); + } + dock_layout = {new_height, hint_top, line_height}; + layout_scene(window); +} + +std::filesystem::path interface_settings_file() { + const auto saves = title::saves_directory(); + return saves.empty() ? std::filesystem::path{} : saves.parent_path() / L"settings.ini"; +} + +void apply_interface_scale(HWND window, int scale) { + interface_scale = scale; + const auto font = CreateFontW(-dock_pixels(15), 0, 0, 0, FW_NORMAL, FALSE, FALSE, FALSE, DEFAULT_CHARSET, + OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS, CLEARTYPE_QUALITY, DEFAULT_PITCH | FF_SWISS, L"Segoe UI"); + const auto face = reinterpret_cast(font ? font : GetStockObject(DEFAULT_GUI_FONT)); + const auto set_font = [&](HWND button) { SendMessageW(button, WM_SETFONT, face, TRUE); }; + for (const auto button : {priority_button, work_list_button, residents_button, wood_bed_button, + stone_bed_button, build_blueprint_button, clear_blueprint_button}) set_font(button); + for (const auto button : dock_section_buttons) set_font(button); + for (const auto button : work_choice_buttons) set_font(button); + if (dock_font) DeleteObject(dock_font); + dock_font = font; + layout_command_dock(window); + InvalidateRect(window, nullptr, FALSE); +} + +bool save_interface_scale(int scale) { + const auto file = interface_settings_file(); + if (file.empty()) return false; + std::error_code error; + std::filesystem::create_directories(file.parent_path(), error); + if (error) return false; + const auto value = std::to_wstring(scale); + return WritePrivateProfileStringW(L"Interface", L"Scale", value.c_str(), file.c_str()) != FALSE; +} + +int read_interface_scale() { + const auto file = interface_settings_file(); + if (file.empty()) return default_interface_scale; + const auto scale = static_cast(GetPrivateProfileIntW(L"Interface", L"Scale", default_interface_scale, file.c_str())); + return std::find(interface_scales.begin(), interface_scales.end(), scale) != interface_scales.end() + ? scale : default_interface_scale; } void invalidate_work_choices() { @@ -498,11 +617,11 @@ void set_work_panel(HWND window, WorkPanel panel) { invalidate_work_choices(); RECT row{}; GetClientRect(window, &row); - row.top = row.bottom - map_footer; + row.top = row.bottom - dock_layout.height; InvalidateRect(window, &row, FALSE); } -void draw_icon_button(const DRAWITEMSTRUCT& item, WorkIcon icon, bool active, bool dock = false) { +void draw_icon_button(const DRAWITEMSTRUCT& item, WorkIcon icon, bool active, bool dock = false, int icon_width = 17) { const bool disabled = (item.itemState & ODS_DISABLED) != 0; const bool pressed = (item.itemState & ODS_SELECTED) != 0; const auto dc = item.hDC; @@ -531,11 +650,10 @@ void draw_icon_button(const DRAWITEMSTRUCT& item, WorkIcon icon, bool active, bo 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); + draw_work_icon(dc, icon, left + offset, (box.top + box.bottom - icon_width) / 2 + offset, icon_width); RECT caption_box{left + icon_width + gap + offset, box.top + offset, box.right - 1, box.bottom + offset}; const auto previous_mode = SetBkMode(dc, TRANSPARENT); @@ -550,22 +668,27 @@ void draw_icon_button(const DRAWITEMSTRUCT& item, WorkIcon icon, bool active, bo bool draw_toolbar_button(const DRAWITEMSTRUCT& item) { const auto id = static_cast(item.CtlID); + const auto draw = [&](WorkIcon icon, bool active = false) { + draw_icon_button(item, icon, active, true, dock_pixels(17)); + return true; + }; 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; - case work_list_button_id: draw_icon_button(item, WorkIcon::Hammer, false); return true; + case wood_bed_button_id: return draw(WorkIcon::Wood, selected_bed_base == settlement::BedBase::Wood); + case stone_bed_button_id: return draw(WorkIcon::Stone, selected_bed_base == settlement::BedBase::Stone); + case residents_button_id: return draw(WorkIcon::Resident, roster.window != nullptr); + case work_list_button_id: return draw(WorkIcon::Hammer); + case priority_button_id: return draw(WorkIcon::Priority); + case build_blueprint_id: return draw(WorkIcon::Hammer, !blueprint.empty()); + case clear_blueprint_id: return draw(WorkIcon::Demolish); } 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; + return draw(section.icon, work_panel == section.panel); } 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; + return draw(choice.icon, placement_mode == choice.mode); } bool can_give_orders() { @@ -667,6 +790,7 @@ void update_status() { for (const HWND button : dock_section_buttons) EnableWindow(button, can_play); EnableWindow(priority_button, scenario && can_play); EnableWindow(work_list_button, can_play); + EnableWindow(build_blueprint_button, !blueprint.empty() && can_play); const wchar_t* priority = L"Равный приоритет"; if (world->work_priority() == settlement::WorkPriority::FoodFirst) priority = L"Сначала еда"; else if (world->work_priority() == settlement::WorkPriority::BuildingFirst) priority = L"Сначала стройка"; @@ -708,13 +832,22 @@ void update_status() { } void update_bed_choices() { - const int visibility = shows_bed_choices() ? SW_SHOW : SW_HIDE; + const int visibility = !showing_title && shows_bed_choices() ? SW_SHOWNA : 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 update_blueprint_controls(HWND window) { + const int visibility = shows_blueprint_actions() ? SW_SHOWNA : SW_HIDE; + ShowWindow(build_blueprint_button, visibility); + ShowWindow(clear_blueprint_button, visibility); + EnableWindow(build_blueprint_button, !blueprint.empty() && can_give_orders()); + EnableWindow(clear_blueprint_button, !blueprint.empty()); + layout_command_dock(window); +} + void set_placement_mode(HWND window, PlacementMode mode, const wchar_t* message = L"") { placement_mode = mode; selected_bed_base.reset(); @@ -722,6 +855,7 @@ void set_placement_mode(HWND window, PlacementMode mode, const wchar_t* message hover_cell.reset(); placement_message = message; update_bed_choices(); + update_blueprint_controls(window); invalidate_work_choices(); invalidate_scene(window); } @@ -765,14 +899,14 @@ void show_title_screen(HWND window, bool visible) { RECT client{}; GetClientRect(window, &client); title_screen.layout(client.right, client.bottom); - layout_command_dock(window); - layout_scene(window); + update_blueprint_controls(window); SetFocus(window); InvalidateRect(window, nullptr, FALSE); } void reset_world(HWND window) { world = settlement::make_first_colony(local_worker_count); + blueprint.clear(); camera = {}; selected_resident.reset(); sync_resident_roster(true); @@ -853,6 +987,7 @@ void handle_save_menu(HWND window, bool saving, std::optionaladdress.data()), narrow_lan_input(request->code.data())); + blueprint.clear(); enter_game_on_snapshot = true; selected_resident.reset(); sync_resident_roster(true); @@ -1132,6 +1269,71 @@ bool valid_edit_cell(settlement::GridPosition cell) { return false; } +std::optional preview_blueprint(settlement::GridPosition cell) { + using settlement::RecipeId; + if (placement_mode == PlacementMode::Loom) { + return settlement::viewer::BlueprintPart{cell, RecipeId::WeaveCloth}; + } + if (placement_mode != PlacementMode::Building || (shows_bed_choices() && !selected_bed_base)) { + return std::nullopt; + } + return settlement::viewer::BlueprintPart{cell, + world->scenario_active() ? RecipeId::BuildBed : RecipeId::BuildCabin, + selected_bed_base.value_or(settlement::BedBase::Wood)}; +} + +void edit_blueprint(HWND window, settlement::GridPosition cell) { + if (!can_give_orders()) return; + if (std::erase_if(blueprint, [cell](const auto& part) { return part.cell == cell; }) != 0) { + placement_message = L"Объект убран из чертежа."; + } else if (const auto part = preview_blueprint(cell); part && valid_edit_cell(cell)) { + blueprint.push_back(*part); + placement_message.clear(); + } else { + placement_message = shows_bed_choices() && !selected_bed_base + ? L"Выберите основу под кнопкой «Спальное место»." + : L"Эта клетка занята или недоступна для чертежа."; + } + update_blueprint_controls(window); + invalidate_scene(window); +} + +void submit_blueprint(HWND window) { + if (!world || blueprint.empty() || !can_give_orders()) return; + using settlement::CommandKind; + using settlement::RecipeId; + const auto sent = std::erase_if(blueprint, [](const auto& part) { + switch (part.recipe) { + case RecipeId::BuildBed: + return world->can_place_bed(part.cell) && + send_command(CommandKind::PlaceBed, part.cell, static_cast(part.base)); + case RecipeId::WeaveCloth: + return world->can_place_storage(part.cell) && send_command(CommandKind::PlaceLoom, part.cell); + case RecipeId::BuildCabin: + try { + world->queue_cabin(part.cell, sawmill, stonecutter); + return true; + } catch (const std::invalid_argument&) { + return false; + } + default: + return false; + } + }); + const std::wstring count = std::to_wstring(sent); + if (!blueprint.empty()) { + placement_message = L"Принято мест: " + count + L". Осталось в чертеже: " + + std::to_wstring(blueprint.size()) + + (lan.is_guest() ? L". Проверьте карту и отправьте оставшиеся места снова." : + L". Проверьте, свободны ли клетки и есть ли к ним проход."); + } else { + placement_message = (lan.is_guest() ? L"Передано хозяину мест: " : L"Утверждено мест: ") + count + L"."; + } + update_blueprint_controls(window); + update_status(); + invalidate_scene(window); +} + void edit_at_cell(HWND window, settlement::GridPosition cell) { using settlement::CommandKind; using settlement::CommandStatus; @@ -1173,8 +1375,6 @@ void edit_at_cell(HWND window, settlement::GridPosition cell) { 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 : @@ -1446,6 +1646,28 @@ std::wstring resident_details() { return text; } +std::wstring blueprint_details() { + using settlement::ItemType; + struct Material { + ItemType type; + const wchar_t* name; + }; + constexpr Material materials[] = {{ItemType::Wood, L"дерево"}, {ItemType::Stone, L"камень"}, + {ItemType::Cloth, L"ткань"}, {ItemType::Plank, L"доски"}, {ItemType::StoneBlock, L"каменные блоки"}}; + std::array totals{}; + for (const auto& part : blueprint) { + for (const auto& material : world->construction_materials(part.recipe, part.base)) { + totals[static_cast(material.type)] += material.count; + } + } + std::wstring text = L"Чертёж · объектов " + std::to_wstring(blueprint.size()); + for (const auto& material : materials) { + const auto count = totals[static_cast(material.type)]; + if (count != 0) text += std::wstring(L" ") + material.name + L" " + std::to_wstring(count); + } + return text; +} + void draw_world(HDC dc, int width, int height) { RECT bounds{0, 0, width, height}; HBRUSH background = CreateSolidBrush(color(239, 235, 222)); @@ -1453,15 +1675,15 @@ void draw_world(HDC dc, int width, int height) { DeleteObject(background); if (!world) return; - if (!graphics.ready() && height > map_top + map_footer) { - RECT scene{16, map_top + 24, width - 16, height - map_footer}; + if (!graphics.ready() && height > map_top + dock_layout.height) { + RECT scene{16, map_top + 24, width - 16, height - dock_layout.height}; SetBkMode(dc, TRANSPARENT); SetTextColor(dc, color(55, 68, 59)); DrawTextW(dc, L"Не удалось запустить Direct3D 11. Откройте главное меню и войдите в колонию снова.", -1, &scene, DT_CENTER | DT_WORDBREAK); } - const RECT dock{0, height - map_footer, width, height}; + const RECT dock{0, height - dock_layout.height, width, height}; const auto dock_brush = CreateSolidBrush(color(34, 46, 40)); FillRect(dc, &dock, dock_brush); DeleteObject(dock_brush); @@ -1485,8 +1707,6 @@ void draw_world(HDC dc, int width, int height) { 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) { @@ -1494,33 +1714,34 @@ void draw_world(HDC dc, int width, int height) { L"Выберите кровать, склад, станок или посаженный участок."; } else if (placement_mode == PlacementMode::Demolish) { hint = L"Щёлкните по объекту, чтобы снести его. Правая кнопка — отмена."; - } else if (placement_mode == PlacementMode::Building) { - if (world->staged_beds()) { - hint = selected_bed_base - ? L"Щёлкайте по свободным клеткам. Основу можно сменить под кнопкой «Спальное место»." - : L"Выберите «Дерево» или «Камень» под кнопкой «Спальное место»."; - } else if (world->scenario_active()) { - hint = L"Щёлкайте по свободным клеткам. Одно место требует доску. Правая кнопка — отмена."; - } else { - hint = L"Выберите свободную клетку. Домик стоит три доски и два блока. Правая кнопка — отмена."; - } + } else if (is_blueprint_tool()) { + hint = shows_bed_choices() && !selected_bed_base + ? L"Выберите «Дерево» или «Камень» под кнопкой «Спальное место»." + : L"Щёлкните по клетке, чтобы добавить объект или убрать его из чертежа."; } - RECT legend{24, height - 159, width - 24, height - 136}; + const auto previous_font = dock_font ? SelectObject(dc, dock_font) : nullptr; + const int margin = dock_pixels(12); + RECT legend{margin, dock_layout.hint_top, width - margin, dock_layout.hint_top + dock_layout.line_height}; DrawTextW(dc, hint, -1, &legend, DT_LEFT | DT_VCENTER | DT_SINGLELINE | DT_END_ELLIPSIS); - const auto details = resident_details(); + const auto details = blueprint.empty() ? resident_details() : blueprint_details(); SetTextColor(dc, color(190, 201, 178)); - RECT inspector{24, height - 135, width - 24, height - 113}; + RECT inspector{margin, legend.bottom, width - margin, legend.bottom + dock_layout.line_height}; DrawTextW(dc, details.c_str(), -1, &inspector, DT_LEFT | DT_VCENTER | DT_SINGLELINE | DT_END_ELLIPSIS); + if (previous_font) SelectObject(dc, previous_font); } settlement::viewer::SceneView scene_view(int width, int height) { const auto pan = camera.offset(); const auto scale = camera.scale(); const auto cursor = !shows_bed_choices() || selected_bed_base ? hover_cell : std::nullopt; + const bool valid_cursor = cursor && valid_edit_cell(*cursor); + const auto preview = valid_cursor && is_blueprint_tool() && + std::none_of(blueprint.begin(), blueprint.end(), [&](const auto& part) { return part.cell == *cursor; }) + ? preview_blueprint(*cursor) : std::nullopt; return {width, height, static_cast(width / 2 * scale + pan.x), static_cast(map_origin_y * scale + pan.y - map_top), static_cast(scale), tile_width / 2.f, tile_height / 2.f, - cursor, cursor && valid_edit_cell(*cursor), move_source, selected_resident}; + cursor, valid_cursor, move_source, selected_resident, blueprint, preview}; } LRESULT CALLBACK scene_window_proc(HWND window, UINT message, WPARAM wparam, LPARAM lparam) { @@ -1621,15 +1842,37 @@ int choose_menu_action(HWND window, const wchar_t* title, std::span(action); } +void choose_interface_scale(HWND window) { + std::array captions; + std::array actions{}; + for (std::size_t index = 0; index < interface_scales.size(); ++index) { + const auto scale = interface_scales[index]; + captions[index] = std::to_wstring(scale) + L"%"; + if (scale == interface_scale) captions[index] += L" · текущий"; + actions[index] = {first_scale_id + static_cast(index), captions[index].c_str()}; + } + const int action = choose_menu_action(window, L"Масштаб нижней панели", actions); + if (action < first_scale_id || action >= first_scale_id + static_cast(interface_scales.size())) return; + const int scale = interface_scales[static_cast(action - first_scale_id)]; + if (scale == interface_scale) return; + const bool saved = save_interface_scale(scale); + const auto caption = std::to_wstring(scale) + L"%"; + placement_message = L"Масштаб нижней панели · " + caption + + (saved ? L"" : L". Настройку не удалось сохранить на диск."); + apply_interface_scale(window, scale); +} + void open_pause_menu(HWND window) { if (!world || showing_title || pause_menu_open) return; camera_drag.reset(); if (GetCapture() == window) ReleaseCapture(); const bool offline = lan.state() == LanState::Offline; + const auto interface_caption = L"Масштаб панели · " + std::to_wstring(interface_scale) + L"%…"; const MenuAction actions[] = { {IDOK, L"Продолжить"}, {save_menu_id, L"Сохранить поселение…", !lan.is_guest()}, {load_menu_id, L"Загрузить поселение…", offline}, + {interface_scale_id, interface_caption.c_str()}, {title_menu_id, L"Главное меню"}, {exit_menu_id, L"Выйти из игры"}, }; @@ -1645,6 +1888,9 @@ void open_pause_menu(HWND window) { case load_menu_id: handle_save_menu(window, action == save_menu_id); break; + case interface_scale_id: + choose_interface_scale(window); + break; case title_menu_id: show_title_screen(window, true); refresh_lan_controls(window); @@ -1702,7 +1948,7 @@ LRESULT CALLBACK window_proc(HWND window, UINT message, WPARAM wparam, LPARAM lp case WM_GETMINMAXINFO: { auto& size = *reinterpret_cast(lparam); size.ptMinTrackSize.x = 775; - size.ptMinTrackSize.y = 490; + size.ptMinTrackSize.y = 640; return 0; } case WM_CREATE: { @@ -1729,21 +1975,24 @@ LRESULT CALLBACK window_proc(HWND window, UINT message, WPARAM wparam, LPARAM lp reinterpret_cast(static_cast(id)), GetModuleHandleW(nullptr), nullptr); }; - priority_button = button(priority_button_id, 18, 142, L"Равный приоритет"); - work_list_button = button(work_list_button_id, 168, 108, L"Работы", BS_OWNERDRAW); + priority_button = button(priority_button_id, 0, 142, L"Равный приоритет", BS_OWNERDRAW, 0); + work_list_button = button(work_list_button_id, 0, 108, L"Работы", BS_OWNERDRAW, 0); 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); + wood_bed_button = button(wood_bed_button_id, 0, 90, L"Дерево", BS_OWNERDRAW, 0); + stone_bed_button = button(stone_bed_button_id, 0, 90, L"Камень", BS_OWNERDRAW, 0); + build_blueprint_button = button(build_blueprint_id, 0, 180, L"Начать стройку", BS_OWNERDRAW, 0); + clear_blueprint_button = button(clear_blueprint_id, 0, 180, 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); } title_screen.create(window); + apply_interface_scale(window, read_interface_scale()); show_title_screen(window, true); refresh_lan_controls(window); SetTimer(window, timer_id, 60, nullptr); @@ -1770,8 +2019,8 @@ LRESULT CALLBACK window_proc(HWND window, UINT message, WPARAM wparam, LPARAM lp if (const auto menu = create_work_menu()) { RECT bounds{}; GetWindowRect(work_list_button, &bounds); - TrackPopupMenu(menu, TPM_LEFTALIGN | TPM_TOPALIGN | TPM_RIGHTBUTTON, - bounds.left, bounds.bottom, 0, window, nullptr); + TrackPopupMenu(menu, TPM_LEFTALIGN | TPM_BOTTOMALIGN | TPM_RIGHTBUTTON, + bounds.left, bounds.top, 0, window, nullptr); DestroyMenu(menu); } SetFocus(window); @@ -1781,6 +2030,19 @@ LRESULT CALLBACK window_proc(HWND window, UINT message, WPARAM wparam, LPARAM lp if (world) show_resident_roster(window); return 0; } + if (HIWORD(wparam) == BN_CLICKED && LOWORD(wparam) == build_blueprint_id) { + submit_blueprint(window); + SetFocus(window); + return 0; + } + if (HIWORD(wparam) == BN_CLICKED && LOWORD(wparam) == clear_blueprint_id && !blueprint.empty()) { + blueprint.clear(); + placement_message = L"Чертёж очищен."; + update_blueprint_controls(window); + SetFocus(window); + invalidate_scene(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); @@ -1936,46 +2198,8 @@ LRESULT CALLBACK window_proc(HWND window, UINT message, WPARAM wparam, LPARAM lp 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(); + if (world && is_blueprint_tool()) { + if (const auto cell = map_cell(client, point)) edit_blueprint(window, *cell); return 0; } if (world && placement_mode >= PlacementMode::BerryField) { @@ -2036,9 +2260,22 @@ LRESULT CALLBACK window_proc(HWND window, UINT message, WPARAM wparam, LPARAM lp 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"Хозяин отклонил команду. Проверьте выбранную клетку."; + using settlement::CommandKind; + using settlement::RecipeId; + const bool bed = rejection->kind == CommandKind::PlaceBed; + if (bed || rejection->kind == CommandKind::PlaceLoom) { + if (std::none_of(blueprint.begin(), blueprint.end(), + [&](const auto& part) { return part.cell == rejection->cell; })) { + blueprint.push_back({rejection->cell, bed ? RecipeId::BuildBed : RecipeId::WeaveCloth, + static_cast(rejection->value)}); + update_blueprint_controls(window); + } + placement_message = L"Клетка отклонена хозяином и оставлена в чертеже."; + } else { + placement_message = rejection->status == settlement::CommandStatus::Busy + ? L"Объект занят. Дождитесь окончания работы или сна." + : L"Хозяин отклонил команду. Проверьте выбранную клетку."; + } } update_status(); invalidate_scene(window); @@ -2054,7 +2291,6 @@ LRESULT CALLBACK window_proc(HWND window, UINT message, WPARAM wparam, LPARAM lp title_screen.layout(client.right, client.bottom); } else { layout_command_dock(window); - layout_scene(window); } InvalidateRect(window, nullptr, FALSE); break; @@ -2083,6 +2319,7 @@ LRESULT CALLBACK window_proc(HWND window, UINT message, WPARAM wparam, LPARAM lp KillTimer(window, timer_id); lan.leave(); graphics.reset(); + if (dock_font) DeleteObject(std::exchange(dock_font, nullptr)); scene_window = nullptr; PostQuitMessage(0); return 0; diff --git a/docs/viewer.md b/docs/viewer.md index 48a4dbb..158a142 100644 --- a/docs/viewer.md +++ b/docs/viewer.md @@ -16,7 +16,9 @@ powershell.exe -NoProfile -ExecutionPolicy Bypass -File .\build.ps1 Карту, постройки и жителей рисует Direct3D 11. Игра сначала пробует использовать видеокарту. Если устройство недоступно, Direct3D 11 пробует создать программное устройство WARP. -В новой партии три поселенца. На нижней панели откройте «Строительство → Спальное место». Под кнопкой появятся «Дерево» слева и «Камень» справа. Выберите основу, затем щёлкайте по свободным клеткам. Выбранная основа применяется к следующим кроватям до выхода из режима или смены основы. Повторное нажатие «Спальное место» или правый щелчок завершает размещение. +В новой партии три поселенца. На нижней панели откройте «Строительство → Спальное место». Под кнопкой появятся «Дерево» слева и «Камень» справа. Выберите основу и щёлкните по свободным клеткам. На карте появятся контуры чертежа, а под картой — количество объектов и список материалов. Выбранная основа применяется к следующим кроватям, пока вы её не смените. В режиме размещения повторный щелчок по контуру удаляет объект. В одном чертеже можно разместить кровати с разными основаниями и ткацкие станки. + +Нажмите «Начать стройку», чтобы отправить выбранные места в работу, или «Очистить чертёж», чтобы убрать всю раскладку. Чертёж остаётся доступным при смене инструмента и через Esc. Это локальная раскладка текущей партии. В сохранение и общую колонию попадают утверждённые постройки. Если хозяин отклоняет клетку в кооперативе, она возвращается в чертёж. Жители отдельно доставляют основу, ткань для настила и ткань для подушки. Каждая деталь появляется после завершения своего этапа. Камень и ткань доступны в стартовых запасах. Жители получают по одному готовому месту. @@ -28,7 +30,7 @@ powershell.exe -NoProfile -ExecutionPolicy Bypass -File .\build.ps1 Фермер засевает поля ягод и льна, лесоруб высаживает деревья. Разметка участка создаёт поручение. Когда житель выходит на участок и заканчивает работу, начинается рост. После сбора последней порции участок снова нужно засадить. Разнорабочий тоже может взять это поручение. Шахтёру можно открыть шахту на скале с доступной стороны. -Чтобы получать ткань, поставьте «Участки → Поле льна» и «Строительство → Ткацкий станок» на свободных клетках. Созревший лён фермер относит на обычный склад. Строитель перерабатывает одну единицу льна в одну единицу ткани. Запасы льна и ткани видны над картой. Если обычные склады заполнены, постройте дополнительный склад. +Чтобы получать ткань, поставьте «Участки → Поле льна», затем добавьте «Строительство → Ткацкий станок» в чертёж и утвердите его. Созревший лён фермер относит на обычный склад. Строитель перерабатывает одну единицу льна в одну единицу ткани. Запасы льна и ткани видны над картой. Если обычные склады заполнены, постройте дополнительный склад. Для переноса выберите «Строительство → Перенести», щёлкните по кровати, складу, станку или посаженному участку и выберите новую клетку. Кровать сохраняет владельца, склад — содержимое. Там же находится «Снести». Снос склада с запасами требует подтверждения. Дождитесь освобождения занятого объекта перед переносом или сносом. @@ -38,6 +40,8 @@ powershell.exe -NoProfile -ExecutionPolicy Bypass -File .\build.ps1 Esc открывает меню игры из любого режима строительства и выбора. В одиночной партии симуляция останавливается, пока меню открыто. «Продолжить» или Esc закрывает меню. Выбранный на карте инструмент можно использовать дальше. В этом меню доступны сохранение, загрузка, главное меню и выход. Файл `.settlement` хранит карту, текущий такт, голод, запасы, заказы и маршруты. При ошибке загрузки текущая колония остаётся открытой. +«Esc → Масштаб панели» меняет размер кнопок, значков и текста внизу. Доступны 100%, 125% и 150%. По умолчанию используется 125%, выбранный масштаб запоминается между запусками. + В одиночной игре «Esc → Главное меню» возвращает на стартовый экран и останавливает симуляцию. «Продолжить» возвращает к текущей колонии. «Новая колония» запускает отдельную партию с поэтапной сборкой и стартовым запасом ткани. Старые сохранения продолжаются со своими правилами стройки. ## Кооператив по локальной сети diff --git a/engine/include/settlement/core/world.hpp b/engine/include/settlement/core/world.hpp index 25393c6..cc78cc1 100644 --- a/engine/include/settlement/core/world.hpp +++ b/engine/include/settlement/core/world.hpp @@ -273,6 +273,7 @@ public: void enable_hunger() noexcept; void queue_production(GridPosition position, RecipeId recipe); [[nodiscard]] bool can_place_cabin(GridPosition position) const noexcept; + [[nodiscard]] std::array construction_materials(RecipeId recipe, BedBase base) const; void queue_cabin(GridPosition position, GridPosition sawmill, GridPosition stonecutter); void start_scenario(GridPosition sawmill); [[nodiscard]] CommandReceipt apply_command(const PlayerCommand& command); diff --git a/engine/src/world.cpp b/engine/src/world.cpp index 473365f..beb1b8c 100644 --- a/engine/src/world.cpp +++ b/engine/src/world.cpp @@ -337,6 +337,14 @@ bool World::can_place_cabin(GridPosition position) const noexcept { std::none_of(production_orders_.begin(), production_orders_.end(), occupies_cell); } +std::array World::construction_materials(RecipeId recipe, BedBase base) const { + if (recipe == RecipeId::BuildBed && staged_beds_) { + return {ItemStack{base == BedBase::Stone ? ItemType::Stone : ItemType::Wood, 1}, + ItemStack{ItemType::Cloth, 2}}; + } + return is_construction(recipe) ? recipe_for(recipe).ingredients : std::array{}; +} + void World::queue_cabin(GridPosition position, GridPosition sawmill, GridPosition stonecutter) { if (!can_place_cabin(position) || position == sawmill || position == stonecutter || (scenario_active_ && position == scenario_sawmill_)) { diff --git a/tests/lan_tests.cpp b/tests/lan_tests.cpp index 4cb2771..6ea872a 100644 --- a/tests/lan_tests.cpp +++ b/tests/lan_tests.cpp @@ -56,7 +56,12 @@ void test_shared_colony_over_loopback() { require(authoritative->production_orders().front().bed_base == BedBase::Stone, "the guest's choice of bed material was lost"); require(guest.submit(CommandKind::PlaceBed, {16, 18}, 0), "the guest could not send a conflicting command"); - pump_until([&] { return guest.take_rejection() == CommandStatus::InvalidTarget; }, + pump_until([&] { + const auto rejected = guest.take_rejection(); + return rejected && rejected->status == CommandStatus::InvalidTarget && + rejected->kind == CommandKind::PlaceBed && rejected->cell == GridPosition{16, 18} && + rejected->value == 0; + }, "a conflicting guest command did not return a rejection"); require(authoritative->production_orders().size() == 1, "the same cell was claimed twice"); -- 2.54.0 From 85547b00b9a03fdc7831d9c0b2669564e8441d77 Mon Sep 17 00:00:00 2001 From: Codex Date: Sun, 29 Nov 2026 20:21:04 +0300 Subject: [PATCH 5/7] Add a live interface scale slider and room blueprints --- PLAN.md | 3 +- app/d3d_scene_win32.cpp | 48 ++- app/d3d_scene_win32.hpp | 2 + app/lan_session.hpp | 1 + app/lan_session_win32.cpp | 4 +- app/viewer_win32.cpp | 372 ++++++++++++++++++----- docs/viewer.md | 4 +- engine/include/settlement/core/world.hpp | 23 +- engine/src/world.cpp | 110 ++++++- engine/src/world_save.cpp | 13 +- tests/core_tests.cpp | 43 +++ tests/lan_tests.cpp | 26 ++ 12 files changed, 553 insertions(+), 96 deletions(-) diff --git a/PLAN.md b/PLAN.md index a3599a4..861d0cd 100644 --- a/PLAN.md +++ b/PLAN.md @@ -55,7 +55,8 @@ - [ ] Расширение набора 3D-моделей и освещения. - [x] Постановка чертежа домика мышью в Windows-клиенте. - [x] Редактируемая раскладка кроватей и станков с предпросмотром, списком материалов и подтверждением. -- [ ] Чертежи комнат с полом, стенами и проёмами. +- [x] Прямоугольные чертежи комнат с полом, стенами, выбором стороны входа и поэтапной стройкой. +- [ ] Маршруты через дверные проёмы и настройка формы комнаты. - [ ] Интерфейс для остальных типов работ и зданий. ### P5 — Игровые системы и совместная игра diff --git a/app/d3d_scene_win32.cpp b/app/d3d_scene_win32.cpp index 7b72f5e..fadeacc 100644 --- a/app/d3d_scene_win32.cpp +++ b/app/d3d_scene_win32.cpp @@ -116,6 +116,43 @@ void resources(Mesh& mesh, const World& world) { } } +void room_part(Mesh& mesh, GridPosition cell, RecipeId recipe, Color color, bool draft) { + const float x = static_cast(cell.x), y = static_cast(cell.y); + if (recipe == RecipeId::BuildFloor) { + mesh.flat(x - .495f, y - .495f, x + .495f, y + .495f, .013f, shade(color, .76f)); + for (int i = 0; i < 4; ++i) { + const auto strip = static_cast(i) * .24f; + mesh.flat(x - .49f, y - .48f + strip, x + .49f, y - .25f + strip, .015f, + shade(color, i % 2 ? 1.f : .93f)); + } + } else if (recipe == RecipeId::BuildWall) { + if (draft) { + mesh.box(x, y, .03f, .92f, .92f, .09f, shade(color, .69f)); + mesh.box(x, y, .12f, .91f, .91f, .16f, color); + } else { + mesh.box(x, y, .02f, 1.f, 1.f, .73f, color); + mesh.box(x, y, .75f, 1.f, 1.f, .10f, shade(color, 1.13f)); + } + } else { + const bool along_x = recipe == RecipeId::BuildDoorAlongX; + for (const float side : {-1.f, 1.f}) { + mesh.box(x + (along_x ? side * .40f : 0.f), y + (along_x ? 0.f : side * .40f), + .02f, along_x ? .20f : .62f, along_x ? .62f : .20f, .73f, color); + } + mesh.box(x, y, .75f, along_x ? 1.f : .62f, along_x ? .62f : 1.f, .10f, shade(color, 1.13f)); + } +} + +void draw_room_plan(Mesh& mesh, const RoomPlan& plan, bool preview, bool valid) { + for (int y = plan.first.y; y <= plan.last.y; ++y) { + for (int x = plan.first.x; x <= plan.last.x; ++x) { + const GridPosition cell{x, y}; + room_part(mesh, cell, plan.recipe_at(cell), !valid ? rgb(203, 113, 101) : + (preview ? rgb(169, 224, 232) : rgb(104, 176, 212)), true); + } + } +} + void construction(Mesh& mesh, const World& world) { for (const auto& storage : world.storages()) { const float x = static_cast(storage.position.x), y = static_cast(storage.position.y); @@ -139,7 +176,14 @@ void construction(Mesh& mesh, const World& world) { const auto marked = order.state == JobState::Available ? rgb(121, 178, 195) : rgb(214, 171, 99); mesh.flat(x - .44f, y - .44f, x + .44f, y + .44f, .03f, marked); } - if (order.recipe == RecipeId::BuildBed && + if (order.recipe >= RecipeId::BuildFloor) { + if (order.state == JobState::Completed) { + room_part(mesh, order.position, order.recipe, rgb(175, 123, 78), false); + } else if (order.recipe != RecipeId::BuildFloor) { + room_part(mesh, order.position, order.recipe, + order.state == JobState::Available ? rgb(121, 178, 195) : rgb(214, 171, 99), true); + } + } 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, order.bed_base == BedBase::Stone ? rgb(145, 155, 151) : rgb(156, 107, 66)); @@ -403,6 +447,8 @@ bool D3DScene::render(const World& world, const SceneView& view, std::vector selected; std::span blueprint; std::optional preview; + std::span room_blueprints; + std::optional room_preview; }; class D3DScene { diff --git a/app/lan_session.hpp b/app/lan_session.hpp index 2beb091..74def74 100644 --- a/app/lan_session.hpp +++ b/app/lan_session.hpp @@ -17,6 +17,7 @@ struct LanRejection { CommandKind kind; GridPosition cell; std::uint8_t value; + GridPosition destination; }; class LanSession { diff --git a/app/lan_session_win32.cpp b/app/lan_session_win32.cpp index 3eabfdf..49b1b3d 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 = 7; +constexpr std::uint32_t protocol_version = 8; constexpr std::size_t frame_limit = 4 * 1024 * 1024; constexpr auto poll_budget = 16; constexpr std::size_t command_queue_limit = 32; @@ -306,7 +306,7 @@ struct LanSession::Impl { if (status > CommandStatus::Busy) throw std::runtime_error("Invalid command result."); if (status != CommandStatus::Accepted) { rejected_command = LanRejection{status, awaiting_receipt->kind, awaiting_receipt->cell, - awaiting_receipt->value}; + awaiting_receipt->value, awaiting_receipt->destination}; } guest_sequence = number(payload.substr(1)); awaiting_receipt.reset(); diff --git a/app/viewer_win32.cpp b/app/viewer_win32.cpp index eb451a6..340a63b 100644 --- a/app/viewer_win32.cpp +++ b/app/viewer_win32.cpp @@ -64,6 +64,7 @@ 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 room_tool_id = 1044; constexpr int first_work_choice_id = 1050; constexpr int resident_list_id = 1060; constexpr int first_role_id = 1070; @@ -73,8 +74,10 @@ constexpr int build_blueprint_id = 1084; constexpr int clear_blueprint_id = 1085; constexpr int exit_menu_id = 1121; constexpr int interface_scale_id = 1122; -constexpr int first_scale_id = 1130; -constexpr std::array interface_scales{100, 125, 150}; +constexpr int scale_slider_id = 1130; +constexpr int scale_value_id = 1131; +constexpr int min_interface_scale = 50; +constexpr int max_interface_scale = 250; constexpr int default_interface_scale = 125; constexpr int timer_id = 1; constexpr int map_size = settlement::first_colony_map_size; @@ -100,6 +103,7 @@ struct DockLayout { int height = 0; int hint_top = 0; int line_height = 0; + int scale = default_interface_scale; }; DockLayout dock_layout; std::array dock_section_buttons{}; @@ -118,7 +122,7 @@ settlement::viewer::LanSession lan; LanState displayed_lan_state = LanState::Offline; const auto local_worker_count = std::clamp( std::thread::hardware_concurrency(), settlement::min_worker_count, 8); -enum class PlacementMode { None, Building, Foraging, BerryField, FlaxField, TreePlot, Mine, Loom, Storage, Pantry, Move, Demolish }; +enum class PlacementMode { None, Building, Foraging, BerryField, FlaxField, TreePlot, Mine, Loom, Storage, Pantry, Move, Demolish, Room }; PlacementMode placement_mode = PlacementMode::None; enum class WorkPanel { Farmer, Woodcutter, Miner, Builder, Gathering, Zones, Construction, None }; WorkPanel work_panel = WorkPanel::None; @@ -148,13 +152,14 @@ constexpr std::array builder_choices = { 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}, + WorkChoice{room_tool_id, L"Комната", WorkIcon::Hammer, 116, PlacementMode::Room}, }; 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]}; + builder_choices[6], builder_choices[4], builder_choices[5]}; struct DockSection { WorkPanel panel; const wchar_t* title; @@ -196,6 +201,8 @@ struct ResidentRoster { ResidentRoster roster; std::optional selected_bed_base; std::vector blueprint; +std::vector room_blueprints; +std::optional room_anchor; std::optional move_source; settlement::viewer::MapCamera camera; struct CameraDrag { @@ -210,7 +217,7 @@ std::optional selected_resident; std::wstring placement_message; int dock_pixels(int pixels) { - return MulDiv(pixels, interface_scale, 100); + return MulDiv(pixels, dock_layout.scale, 100); } COLORREF color(int red, int green, int blue) { @@ -351,11 +358,16 @@ bool shows_bed_choices() { } bool is_blueprint_tool() { - return placement_mode == PlacementMode::Building || placement_mode == PlacementMode::Loom; + return placement_mode == PlacementMode::Building || placement_mode == PlacementMode::Loom || + placement_mode == PlacementMode::Room; +} + +bool has_blueprint() { + return !blueprint.empty() || !room_blueprints.empty(); } bool shows_blueprint_actions() { - return !showing_title && (is_blueprint_tool() || !blueprint.empty()); + return !showing_title && (is_blueprint_tool() || has_blueprint()); } bool is_map_point(const RECT& client, POINT point) { @@ -468,16 +480,11 @@ std::span work_choices() { return {}; } -void layout_command_dock(HWND window) { - RECT client{}; - GetClientRect(window, &client); - const auto width = static_cast(client.right); - const auto height = static_cast(client.bottom); - SetWindowPos(status_label, nullptr, 16, 14, std::max(0, width - 32), 24, SWP_NOZORDER | SWP_NOACTIVATE); - SetWindowPos(production_label, nullptr, 16, 44, std::max(0, width - 32), 24, SWP_NOZORDER | SWP_NOACTIVATE); - const bool compact = height < map_top + dock_pixels(390); - const int margin = dock_pixels(compact ? 8 : 12); - const int gap = dock_pixels(compact ? 5 : 7); +DockLayout measure_command_dock(int width, int height, int scale, bool position_controls) { + const auto pixels = [scale](int amount) { return MulDiv(amount, scale, 100); }; + const bool compact = height < 760; + const int margin = pixels(compact ? 8 : 12); + const int gap = pixels(compact ? 5 : 7); const int available = std::max(1, width - margin * 2); int bottom = height - margin; struct DockItem { @@ -485,8 +492,8 @@ void layout_command_dock(HWND window) { int width; bool materials = false; }; - const auto place = [](HWND button, int x, int y, int w, int h) { - SetWindowPos(button, nullptr, x, y, w, h, SWP_NOZORDER | SWP_NOACTIVATE); + const auto place = [&](HWND button, int x, int y, int w, int h) { + if (position_controls) SetWindowPos(button, nullptr, x, y, w, h, SWP_NOZORDER | SWP_NOACTIVATE); }; const auto layout_rows = [&](std::span items, int button_height) { // Pack from the end so rows near the bottom stay fixed as the window grows. @@ -496,17 +503,17 @@ void layout_command_dock(HWND window) { auto start = items.size(); do { const auto& item = items[start - 1]; - const int required = std::min(available, dock_pixels(item.width)) + (row_width ? gap : 0); + const int required = std::min(available, pixels(item.width)) + (row_width ? gap : 0); if (row_width + required > available) break; row_width += required; materials |= item.materials; --start; } while (start != 0); - const int material_height = materials ? dock_pixels(compact ? 28 : 34) + gap : 0; + const int material_height = materials ? pixels(compact ? 28 : 34) + gap : 0; int x = std::max(margin, (width - row_width) / 2); const int y = bottom - material_height - button_height; for (const auto& item : items.subspan(start)) { - const int w = std::min(available, dock_pixels(item.width)); + const int w = std::min(available, pixels(item.width)); place(item.control, x, y, w, button_height); if (item.materials) { const int half = (w - gap) / 2; @@ -524,7 +531,7 @@ void layout_command_dock(HWND window) { {residents_button, 101}, {dock_section_buttons[0], 104}, {dock_section_buttons[1], 104}, {dock_section_buttons[2], 163}, {work_list_button, 101}, {priority_button, 172}, }; - layout_rows(sections, dock_pixels(compact ? 34 : 40)); + layout_rows(sections, pixels(compact ? 34 : 40)); const auto choices = work_choices(); std::array tools{}; for (std::size_t index = 0; index < choices.size(); ++index) { @@ -532,32 +539,20 @@ void layout_command_dock(HWND window) { const bool bed = choice.command == cabin_button_id; tools[index] = {work_choice_buttons[index], choice.width + (bed ? 32 : 14), bed && shows_bed_choices()}; } - const int tool_height = dock_pixels(compact ? 30 : 36); + const int tool_height = pixels(compact ? 30 : 36); if (choices.empty()) bottom -= tool_height + gap; else layout_rows(std::span(tools).first(choices.size()), tool_height); if (shows_blueprint_actions()) { const DockItem actions[] = {{build_blueprint_button, 182}, {clear_blueprint_button, 188}}; - layout_rows(actions, dock_pixels(compact ? 31 : 37)); + layout_rows(actions, pixels(compact ? 31 : 37)); } - const int line_height = dock_pixels(compact ? 20 : 23); + const int line_height = pixels(compact ? 20 : 23); const int hint_top = bottom - 2 * line_height; - const int new_height = height - hint_top + dock_pixels(8); - if (new_height != dock_layout.height && !showing_title) { - RECT dirty{0, height - std::max(new_height, dock_layout.height), width, height}; - InvalidateRect(window, &dirty, FALSE); - } - dock_layout = {new_height, hint_top, line_height}; - layout_scene(window); + return {height - hint_top + pixels(8), hint_top, line_height, scale}; } -std::filesystem::path interface_settings_file() { - const auto saves = title::saves_directory(); - return saves.empty() ? std::filesystem::path{} : saves.parent_path() / L"settings.ini"; -} - -void apply_interface_scale(HWND window, int scale) { - interface_scale = scale; +void update_dock_font() { const auto font = CreateFontW(-dock_pixels(15), 0, 0, 0, FW_NORMAL, FALSE, FALSE, FALSE, DEFAULT_CHARSET, OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS, CLEARTYPE_QUALITY, DEFAULT_PITCH | FF_SWISS, L"Segoe UI"); const auto face = reinterpret_cast(font ? font : GetStockObject(DEFAULT_GUI_FONT)); @@ -568,6 +563,40 @@ void apply_interface_scale(HWND window, int scale) { for (const auto button : work_choice_buttons) set_font(button); if (dock_font) DeleteObject(dock_font); dock_font = font; +} + +void layout_command_dock(HWND window) { + RECT client{}; + GetClientRect(window, &client); + const int width = client.right, height = client.bottom; + SetWindowPos(status_label, nullptr, 16, 14, std::max(0, width - 32), 24, SWP_NOZORDER | SWP_NOACTIVATE); + SetWindowPos(production_label, nullptr, 16, 44, std::max(0, width - 32), 24, SWP_NOZORDER | SWP_NOACTIVATE); + const int budget = std::max(0, height - map_top - 170); + int low = min_interface_scale, high = interface_scale; + while (low < high) { + const int scale = (low + high + 1) / 2; + if (measure_command_dock(width, height, scale, false).height <= budget) low = scale; + else high = scale - 1; + } + const auto next = measure_command_dock(width, height, low, true); + const auto new_height = next.height; + if (new_height != dock_layout.height && !showing_title) { + RECT dirty{0, height - std::max(new_height, dock_layout.height), width, height}; + InvalidateRect(window, &dirty, FALSE); + } + const bool font_changed = !dock_font || next.scale != dock_layout.scale; + dock_layout = next; + if (font_changed) update_dock_font(); + layout_scene(window); +} + +std::filesystem::path interface_settings_file() { + const auto saves = title::saves_directory(); + return saves.empty() ? std::filesystem::path{} : saves.parent_path() / L"settings.ini"; +} + +void apply_interface_scale(HWND window, int scale) { + interface_scale = std::clamp(scale, min_interface_scale, max_interface_scale); layout_command_dock(window); InvalidateRect(window, nullptr, FALSE); } @@ -586,8 +615,7 @@ int read_interface_scale() { const auto file = interface_settings_file(); if (file.empty()) return default_interface_scale; const auto scale = static_cast(GetPrivateProfileIntW(L"Interface", L"Scale", default_interface_scale, file.c_str())); - return std::find(interface_scales.begin(), interface_scales.end(), scale) != interface_scales.end() - ? scale : default_interface_scale; + return scale >= min_interface_scale && scale <= max_interface_scale ? scale : default_interface_scale; } void invalidate_work_choices() { @@ -678,7 +706,7 @@ bool draw_toolbar_button(const DRAWITEMSTRUCT& item) { case residents_button_id: return draw(WorkIcon::Resident, roster.window != nullptr); case work_list_button_id: return draw(WorkIcon::Hammer); case priority_button_id: return draw(WorkIcon::Priority); - case build_blueprint_id: return draw(WorkIcon::Hammer, !blueprint.empty()); + case build_blueprint_id: return draw(WorkIcon::Hammer, has_blueprint()); case clear_blueprint_id: return draw(WorkIcon::Demolish); } if (id >= first_dock_section_id && static_cast(id - first_dock_section_id) < dock_sections.size()) { @@ -790,7 +818,7 @@ void update_status() { for (const HWND button : dock_section_buttons) EnableWindow(button, can_play); EnableWindow(priority_button, scenario && can_play); EnableWindow(work_list_button, can_play); - EnableWindow(build_blueprint_button, !blueprint.empty() && can_play); + EnableWindow(build_blueprint_button, has_blueprint() && can_play); const wchar_t* priority = L"Равный приоритет"; if (world->work_priority() == settlement::WorkPriority::FoodFirst) priority = L"Сначала еда"; else if (world->work_priority() == settlement::WorkPriority::BuildingFirst) priority = L"Сначала стройка"; @@ -843,8 +871,8 @@ void update_blueprint_controls(HWND window) { const int visibility = shows_blueprint_actions() ? SW_SHOWNA : SW_HIDE; ShowWindow(build_blueprint_button, visibility); ShowWindow(clear_blueprint_button, visibility); - EnableWindow(build_blueprint_button, !blueprint.empty() && can_give_orders()); - EnableWindow(clear_blueprint_button, !blueprint.empty()); + EnableWindow(build_blueprint_button, has_blueprint() && can_give_orders()); + EnableWindow(clear_blueprint_button, has_blueprint()); layout_command_dock(window); } @@ -852,6 +880,7 @@ void set_placement_mode(HWND window, PlacementMode mode, const wchar_t* message placement_mode = mode; selected_bed_base.reset(); move_source.reset(); + room_anchor.reset(); hover_cell.reset(); placement_message = message; update_bed_choices(); @@ -860,6 +889,12 @@ void set_placement_mode(HWND window, PlacementMode mode, const wchar_t* message invalidate_scene(window); } +void clear_blueprints() { + blueprint.clear(); + room_blueprints.clear(); + room_anchor.reset(); +} + void toggle_work_panel(HWND window, WorkPanel panel) { if (!can_give_orders()) return; set_placement_mode(window, PlacementMode::None); @@ -906,7 +941,7 @@ void show_title_screen(HWND window, bool visible) { void reset_world(HWND window) { world = settlement::make_first_colony(local_worker_count); - blueprint.clear(); + clear_blueprints(); camera = {}; selected_resident.reset(); sync_resident_roster(true); @@ -987,7 +1022,7 @@ void handle_save_menu(HWND window, bool saving, std::optionaladdress.data()), narrow_lan_input(request->code.data())); - blueprint.clear(); + clear_blueprints(); enter_game_on_snapshot = true; selected_resident.reset(); sync_resident_roster(true); @@ -1264,11 +1299,77 @@ bool valid_edit_cell(settlement::GridPosition cell) { 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::Room: case PlacementMode::None: return false; } return false; } +auto room_at(settlement::GridPosition cell) { + return std::find_if(room_blueprints.begin(), room_blueprints.end(), + [cell](const auto& room) { return room.contains(cell); }); +} + +bool room_fits_blueprint(const settlement::RoomPlan& room) { + return std::none_of(blueprint.begin(), blueprint.end(), + [&](const auto& part) { return room.contains(part.cell); }) && + std::none_of(room_blueprints.begin(), room_blueprints.end(), [&](const auto& other) { + return room.first.x <= other.last.x && room.last.x >= other.first.x && + room.first.y <= other.last.y && room.last.y >= other.first.y; + }); +} + +settlement::RoomPlan preview_room(settlement::GridPosition cell) { + auto room = settlement::make_room_plan(*room_anchor, cell); + if (room.valid_size() && !world->can_place_room(room)) { + for (const auto side : {settlement::RoomSide::North, settlement::RoomSide::East, settlement::RoomSide::West}) { + room.entrance = side; + if (world->can_place_room(room)) return room; + } + room.entrance = settlement::RoomSide::South; + } + return room; +} + +void edit_room_blueprint(HWND window, settlement::GridPosition cell) { + if (!can_give_orders()) return; + using settlement::RoomSide; + if (room_anchor) { + const auto room = preview_room(cell); + if (!room.valid_size()) { + placement_message = L"Ширина и длина комнаты должны быть от 3 до 12 клеток."; + } else if (!world->can_place_room(room) || !room_fits_blueprint(room)) { + placement_message = L"Нужна свободная площадка и проход снаружи."; + } else { + room_blueprints.push_back(room); + room_anchor.reset(); + placement_message.clear(); + } + } else if (const auto room = room_at(cell); room != room_blueprints.end()) { + auto candidate = *room; + if (cell.y == room->first.y) candidate.entrance = RoomSide::North; + else if (cell.y == room->last.y) candidate.entrance = RoomSide::South; + else if (cell.x == room->first.x) candidate.entrance = RoomSide::West; + else if (cell.x == room->last.x) candidate.entrance = RoomSide::East; + else { + placement_message = L"Щёлкните по краю комнаты, чтобы перенести вход."; + invalidate_scene(window); + return; + } + if (world->can_place_room(candidate)) { + *room = candidate; + placement_message.clear(); + } else { + placement_message = L"С этой стороны нет свободного прохода."; + } + } else { + room_anchor = cell; + placement_message.clear(); + } + update_blueprint_controls(window); + invalidate_scene(window); +} + std::optional preview_blueprint(settlement::GridPosition cell) { using settlement::RecipeId; if (placement_mode == PlacementMode::Loom) { @@ -1286,7 +1387,8 @@ void edit_blueprint(HWND window, settlement::GridPosition cell) { if (!can_give_orders()) return; if (std::erase_if(blueprint, [cell](const auto& part) { return part.cell == cell; }) != 0) { placement_message = L"Объект убран из чертежа."; - } else if (const auto part = preview_blueprint(cell); part && valid_edit_cell(cell)) { + } else if (const auto part = preview_blueprint(cell); + part && valid_edit_cell(cell) && room_at(cell) == room_blueprints.end()) { blueprint.push_back(*part); placement_message.clear(); } else { @@ -1299,10 +1401,14 @@ void edit_blueprint(HWND window, settlement::GridPosition cell) { } void submit_blueprint(HWND window) { - if (!world || blueprint.empty() || !can_give_orders()) return; + if (!world || !has_blueprint() || !can_give_orders()) return; using settlement::CommandKind; using settlement::RecipeId; - const auto sent = std::erase_if(blueprint, [](const auto& part) { + const auto rooms_sent = std::erase_if(room_blueprints, [](const auto& room) { + return world->can_place_room(room) && submit_command(CommandKind::PlaceRoom, room.first, + static_cast(room.entrance), room.last) == settlement::CommandStatus::Accepted; + }); + const auto objects_sent = std::erase_if(blueprint, [](const auto& part) { switch (part.recipe) { case RecipeId::BuildBed: return world->can_place_bed(part.cell) && @@ -1320,10 +1426,10 @@ void submit_blueprint(HWND window) { return false; } }); - const std::wstring count = std::to_wstring(sent); - if (!blueprint.empty()) { + const std::wstring count = std::to_wstring(rooms_sent + objects_sent); + if (has_blueprint()) { placement_message = L"Принято мест: " + count + L". Осталось в чертеже: " + - std::to_wstring(blueprint.size()) + + std::to_wstring(blueprint.size() + room_blueprints.size()) + (lan.is_guest() ? L". Проверьте карту и отправьте оставшиеся места снова." : L". Проверьте, свободны ли клетки и есть ли к ним проход."); } else { @@ -1660,7 +1766,15 @@ std::wstring blueprint_details() { totals[static_cast(material.type)] += material.count; } } - std::wstring text = L"Чертёж · объектов " + std::to_wstring(blueprint.size()); + for (const auto& room : room_blueprints) { + for (int y = room.first.y; y <= room.last.y; ++y) { + for (int x = room.first.x; x <= room.last.x; ++x) { + const auto ingredients = world->construction_materials(room.recipe_at({x, y}), settlement::BedBase::Wood); + for (const auto& item : ingredients) totals[static_cast(item.type)] += item.count; + } + } + } + std::wstring text = L"Чертёж · объектов " + std::to_wstring(blueprint.size() + room_blueprints.size()); for (const auto& material : materials) { const auto count = totals[static_cast(material.type)]; if (count != 0) text += std::wstring(L" ") + material.name + L" " + std::to_wstring(count); @@ -1714,6 +1828,9 @@ void draw_world(HDC dc, int width, int height) { L"Выберите кровать, склад, станок или посаженный участок."; } else if (placement_mode == PlacementMode::Demolish) { hint = L"Щёлкните по объекту, чтобы снести его. Правая кнопка — отмена."; + } else if (placement_mode == PlacementMode::Room) { + hint = room_anchor ? L"Укажите противоположный угол комнаты." : + L"Укажите первый угол. Щелчок по краю чертежа меняет вход, правый щелчок удаляет комнату."; } else if (is_blueprint_tool()) { hint = shows_bed_choices() && !selected_bed_base ? L"Выберите «Дерево» или «Камень» под кнопкой «Спальное место»." @@ -1723,7 +1840,7 @@ void draw_world(HDC dc, int width, int height) { const int margin = dock_pixels(12); RECT legend{margin, dock_layout.hint_top, width - margin, dock_layout.hint_top + dock_layout.line_height}; DrawTextW(dc, hint, -1, &legend, DT_LEFT | DT_VCENTER | DT_SINGLELINE | DT_END_ELLIPSIS); - const auto details = blueprint.empty() ? resident_details() : blueprint_details(); + const auto details = has_blueprint() ? blueprint_details() : resident_details(); SetTextColor(dc, color(190, 201, 178)); RECT inspector{margin, legend.bottom, width - margin, legend.bottom + dock_layout.line_height}; DrawTextW(dc, details.c_str(), -1, &inspector, DT_LEFT | DT_VCENTER | DT_SINGLELINE | DT_END_ELLIPSIS); @@ -1734,14 +1851,21 @@ settlement::viewer::SceneView scene_view(int width, int height) { const auto pan = camera.offset(); const auto scale = camera.scale(); const auto cursor = !shows_bed_choices() || selected_bed_base ? hover_cell : std::nullopt; - const bool valid_cursor = cursor && valid_edit_cell(*cursor); + std::optional room_preview; + if (cursor && room_anchor && placement_mode == PlacementMode::Room) { + const auto room = preview_room(*cursor); + if (room.valid_size()) room_preview = room; + } + const bool valid_cursor = room_preview ? world->can_place_room(*room_preview) && room_fits_blueprint(*room_preview) + : cursor && (placement_mode == PlacementMode::Room ? !room_anchor : valid_edit_cell(*cursor)); const auto preview = valid_cursor && is_blueprint_tool() && + cursor && room_at(*cursor) == room_blueprints.end() && std::none_of(blueprint.begin(), blueprint.end(), [&](const auto& part) { return part.cell == *cursor; }) ? preview_blueprint(*cursor) : std::nullopt; return {width, height, static_cast(width / 2 * scale + pan.x), static_cast(map_origin_y * scale + pan.y - map_top), static_cast(scale), tile_width / 2.f, tile_height / 2.f, - cursor, valid_cursor, move_source, selected_resident, blueprint, preview}; + cursor, valid_cursor, move_source, selected_resident, blueprint, preview, room_blueprints, room_preview}; } LRESULT CALLBACK scene_window_proc(HWND window, UINT message, WPARAM wparam, LPARAM lparam) { @@ -1842,24 +1966,73 @@ int choose_menu_action(HWND window, const wchar_t* title, std::span(action); } +INT_PTR CALLBACK scale_dialog_proc(HWND dialog, UINT message, WPARAM wparam, LPARAM lparam) { + switch (message) { + case WM_INITDIALOG: { + SetWindowTextW(dialog, L"Масштаб нижней панели"); + const auto add = [&](const wchar_t* kind, const wchar_t* text, int id, DWORD style, RECT rect) { + MapDialogRect(dialog, &rect); + const auto child = CreateWindowExW(0, kind, text, WS_VISIBLE | WS_CHILD | style, + rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top, dialog, + reinterpret_cast(static_cast(id)), GetModuleHandleW(nullptr), nullptr); + SendMessageW(child, WM_SETFONT, reinterpret_cast(GetStockObject(DEFAULT_GUI_FONT)), FALSE); + return child; + }; + add(L"STATIC", L"", scale_value_id, SS_CENTER, {8, 6, 235, 21}); + const auto slider = add(TRACKBAR_CLASSW, L"Масштаб панели", scale_slider_id, + TBS_AUTOTICKS | WS_TABSTOP, {10, 24, 233, 46}); + SendMessageW(slider, TBM_SETRANGE, TRUE, MAKELONG(min_interface_scale, max_interface_scale)); + SendMessageW(slider, TBM_SETTICFREQ, 25, 0); + SendMessageW(slider, TBM_SETPAGESIZE, 0, 10); + SendMessageW(slider, TBM_SETPOS, TRUE, interface_scale); + add(L"STATIC", L"50%", -1, 0, {12, 46, 45, 59}); + add(L"STATIC", L"250%", -1, SS_RIGHT, {195, 46, 232, 59}); + add(L"BUTTON", L"Применить", IDOK, BS_DEFPUSHBUTTON | WS_TABSTOP, {91, 63, 157, 83}); + add(L"BUTTON", L"Отмена", IDCANCEL, BS_PUSHBUTTON | WS_TABSTOP, {164, 63, 230, 83}); + SendMessageW(dialog, WM_HSCROLL, 0, reinterpret_cast(slider)); + SetFocus(slider); + return FALSE; + } + case WM_HSCROLL: + if (reinterpret_cast(lparam) == GetDlgItem(dialog, scale_slider_id)) { + const auto scale = static_cast(SendMessageW(reinterpret_cast(lparam), TBM_GETPOS, 0, 0)); + if (scale != interface_scale) apply_interface_scale(GetWindow(dialog, GW_OWNER), scale); + auto value = std::to_wstring(interface_scale) + L"%"; + if (dock_layout.scale != interface_scale) { + value += L" · в этом окне " + std::to_wstring(dock_layout.scale) + L"%"; + } + SetDlgItemTextW(dialog, scale_value_id, value.c_str()); + return TRUE; + } + break; + case WM_COMMAND: + if (LOWORD(wparam) == IDOK || LOWORD(wparam) == IDCANCEL) { + EndDialog(dialog, LOWORD(wparam)); + return TRUE; + } + break; + case WM_CLOSE: + EndDialog(dialog, IDCANCEL); + return TRUE; + } + return FALSE; +} + void choose_interface_scale(HWND window) { - std::array captions; - std::array actions{}; - for (std::size_t index = 0; index < interface_scales.size(); ++index) { - const auto scale = interface_scales[index]; - captions[index] = std::to_wstring(scale) + L"%"; - if (scale == interface_scale) captions[index] += L" · текущий"; - actions[index] = {first_scale_id + static_cast(index), captions[index].c_str()}; + struct alignas(DWORD) EmptyDialog { + DLGTEMPLATE header{}; + WORD menu = 0, window_class = 0, title = 0; + } layout; + layout.header.style = WS_POPUP | WS_CAPTION | WS_SYSMENU | DS_MODALFRAME | DS_CENTER; + layout.header.cx = 243; + layout.header.cy = 91; + const int previous = interface_scale; + if (DialogBoxIndirectParamW(GetModuleHandleW(nullptr), &layout.header, window, scale_dialog_proc, 0) != IDOK) { + if (interface_scale != previous) apply_interface_scale(window, previous); + } else if (interface_scale != previous && !save_interface_scale(interface_scale)) { + placement_message = L"Не удалось сохранить масштаб панели на диск."; + invalidate_scene(window); } - const int action = choose_menu_action(window, L"Масштаб нижней панели", actions); - if (action < first_scale_id || action >= first_scale_id + static_cast(interface_scales.size())) return; - const int scale = interface_scales[static_cast(action - first_scale_id)]; - if (scale == interface_scale) return; - const bool saved = save_interface_scale(scale); - const auto caption = std::to_wstring(scale) + L"%"; - placement_message = L"Масштаб нижней панели · " + caption + - (saved ? L"" : L". Настройку не удалось сохранить на диск."); - apply_interface_scale(window, scale); } void open_pause_menu(HWND window) { @@ -2035,8 +2208,8 @@ LRESULT CALLBACK window_proc(HWND window, UINT message, WPARAM wparam, LPARAM lp SetFocus(window); return 0; } - if (HIWORD(wparam) == BN_CLICKED && LOWORD(wparam) == clear_blueprint_id && !blueprint.empty()) { - blueprint.clear(); + if (HIWORD(wparam) == BN_CLICKED && LOWORD(wparam) == clear_blueprint_id && has_blueprint()) { + clear_blueprints(); placement_message = L"Чертёж очищен."; update_blueprint_controls(window); SetFocus(window); @@ -2091,6 +2264,11 @@ LRESULT CALLBACK window_proc(HWND window, UINT message, WPARAM wparam, LPARAM lp SetFocus(window); return 0; } + if (LOWORD(wparam) == room_tool_id && HIWORD(wparam) == BN_CLICKED && world && can_give_orders()) { + set_placement_mode(window, placement_mode == PlacementMode::Room ? PlacementMode::None : PlacementMode::Room); + 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; @@ -2199,7 +2377,10 @@ LRESULT CALLBACK window_proc(HWND window, UINT message, WPARAM wparam, LPARAM lp return 0; } if (world && is_blueprint_tool()) { - if (const auto cell = map_cell(client, point)) edit_blueprint(window, *cell); + if (const auto cell = map_cell(client, point)) { + if (placement_mode == PlacementMode::Room) edit_room_blueprint(window, *cell); + else edit_blueprint(window, *cell); + } return 0; } if (world && placement_mode >= PlacementMode::BerryField) { @@ -2216,6 +2397,26 @@ LRESULT CALLBACK window_proc(HWND window, UINT message, WPARAM wparam, LPARAM lp break; } case WM_RBUTTONDOWN: + if (placement_mode == PlacementMode::Room) { + if (room_anchor) { + room_anchor.reset(); + placement_message.clear(); + invalidate_scene(window); + return 0; + } + RECT client{}; + GetClientRect(window, &client); + if (const auto cell = map_cell(client, client_point(lparam))) { + const auto room = room_at(*cell); + if (room != room_blueprints.end()) { + room_blueprints.erase(room); + placement_message = L"Комната убрана из чертежа."; + update_blueprint_controls(window); + invalidate_scene(window); + return 0; + } + } + } if (placement_mode != PlacementMode::None || work_panel != WorkPanel::None) { set_placement_mode(window, PlacementMode::None); set_work_panel(window, WorkPanel::None); @@ -2263,7 +2464,16 @@ LRESULT CALLBACK window_proc(HWND window, UINT message, WPARAM wparam, LPARAM lp using settlement::CommandKind; using settlement::RecipeId; const bool bed = rejection->kind == CommandKind::PlaceBed; - if (bed || rejection->kind == CommandKind::PlaceLoom) { + if (rejection->kind == CommandKind::PlaceRoom) { + const settlement::RoomPlan room{rejection->cell, rejection->destination, + static_cast(rejection->value)}; + if (room.valid_size() && std::none_of(room_blueprints.begin(), room_blueprints.end(), + [&](const auto& other) { return other.first == room.first && other.last == room.last; })) { + room_blueprints.push_back(room); + update_blueprint_controls(window); + } + placement_message = L"Хозяин отклонил площадку. Комната возвращена в чертёж."; + } else if (bed || rejection->kind == CommandKind::PlaceLoom) { if (std::none_of(blueprint.begin(), blueprint.end(), [&](const auto& part) { return part.cell == rejection->cell; })) { blueprint.push_back({rejection->cell, bed ? RecipeId::BuildBed : RecipeId::WeaveCloth, @@ -2330,7 +2540,7 @@ LRESULT CALLBACK window_proc(HWND window, UINT message, WPARAM wparam, LPARAM lp } // namespace int WINAPI wWinMain(HINSTANCE instance, HINSTANCE, PWSTR, int show_command) { - INITCOMMONCONTROLSEX controls{sizeof(controls), ICC_STANDARD_CLASSES | ICC_LISTVIEW_CLASSES}; + INITCOMMONCONTROLSEX controls{sizeof(controls), ICC_LISTVIEW_CLASSES | ICC_BAR_CLASSES}; InitCommonControlsEx(&controls); WNDCLASSEXW window_class_info{}; window_class_info.cbSize = sizeof(window_class_info); diff --git a/docs/viewer.md b/docs/viewer.md index 158a142..fcbc993 100644 --- a/docs/viewer.md +++ b/docs/viewer.md @@ -20,6 +20,8 @@ powershell.exe -NoProfile -ExecutionPolicy Bypass -File .\build.ps1 Нажмите «Начать стройку», чтобы отправить выбранные места в работу, или «Очистить чертёж», чтобы убрать всю раскладку. Чертёж остаётся доступным при смене инструмента и через Esc. Это локальная раскладка текущей партии. В сохранение и общую колонию попадают утверждённые постройки. Если хозяин отклоняет клетку в кооперативе, она возвращается в чертёж. +В разделе «Строительство → Комната» укажите два противоположных угла прямоугольника от 3×3 до 12×12 клеток. По краям чертежа появятся стены, внутри — пол. Щёлкните по стороне, чтобы перенести вход в её середину. Правый щелчок по чертежу удаляет комнату. «Начать стройку» отправляет комнату в работу целиком. Поселенцы доставляют дерево и собирают пол, стены и проём по частям. На готовый пол можно поставить мебель. В этой версии маршруты жителей проходят через стены. + Жители отдельно доставляют основу, ткань для настила и ткань для подушки. Каждая деталь появляется после завершения своего этапа. Камень и ткань доступны в стартовых запасах. Жители получают по одному готовому месту. Уставшие жители работают медленнее и после поручения идут к закреплённой кровати. На земле они отдыхают только при сильной усталости и восстанавливают меньше сил. Щелчок по жителю показывает усталость и состояние сна. @@ -40,7 +42,7 @@ powershell.exe -NoProfile -ExecutionPolicy Bypass -File .\build.ps1 Esc открывает меню игры из любого режима строительства и выбора. В одиночной партии симуляция останавливается, пока меню открыто. «Продолжить» или Esc закрывает меню. Выбранный на карте инструмент можно использовать дальше. В этом меню доступны сохранение, загрузка, главное меню и выход. Файл `.settlement` хранит карту, текущий такт, голод, запасы, заказы и маршруты. При ошибке загрузки текущая колония остаётся открытой. -«Esc → Масштаб панели» меняет размер кнопок, значков и текста внизу. Доступны 100%, 125% и 150%. По умолчанию используется 125%, выбранный масштаб запоминается между запусками. +«Esc → Масштаб панели» открывает ползунок от 50% до 250% с предпросмотром. «Применить» сохраняет выбор между запусками, «Отмена» возвращает предыдущий масштаб. В маленьком окне панель подстраивается под доступное место, чтобы оставить видимой карту. По умолчанию используется 125%. В одиночной игре «Esc → Главное меню» возвращает на стартовый экран и останавливает симуляцию. «Продолжить» возвращает к текущей колонии. «Новая колония» запускает отдельную партию с поэтапной сборкой и стартовым запасом ткани. Старые сохранения продолжаются со своими правилами стройки. diff --git a/engine/include/settlement/core/world.hpp b/engine/include/settlement/core/world.hpp index cc78cc1..6748972 100644 --- a/engine/include/settlement/core/world.hpp +++ b/engine/include/settlement/core/world.hpp @@ -74,21 +74,37 @@ enum class RecipeId : std::uint8_t { CutStoneBlock, BuildCabin, BuildBed, - WeaveCloth + WeaveCloth, + BuildFloor, + BuildWall, + BuildDoorAlongX, + BuildDoorAlongY }; enum class BedBase : std::uint8_t { Wood, Stone }; enum class BedStage : std::uint8_t { Legacy, Foundation, Bedding, Pillow }; constexpr bool is_construction(RecipeId recipe) noexcept { - return recipe == RecipeId::BuildCabin || recipe == RecipeId::BuildBed; + return recipe == RecipeId::BuildCabin || recipe == RecipeId::BuildBed || + (recipe >= RecipeId::BuildFloor && recipe <= RecipeId::BuildDoorAlongY); } +enum class RoomSide : std::uint8_t { North, East, South, West }; +struct RoomPlan { + GridPosition first; + GridPosition last; + RoomSide entrance = RoomSide::South; + [[nodiscard]] bool valid_size() const noexcept; + [[nodiscard]] bool contains(GridPosition cell) const noexcept; + [[nodiscard]] RecipeId recipe_at(GridPosition cell) const noexcept; +}; +[[nodiscard]] RoomPlan make_room_plan(GridPosition first, GridPosition last) noexcept; + enum class WorkPriority : std::uint8_t { Balanced, FoodFirst, BuildingFirst }; enum class Profession : std::uint8_t { Generalist = 0, Farmer, Woodcutter, Miner, Builder }; 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 + PlaceStorage = 9, AssignProfession = 10, PlaceFlaxField = 11, PlaceLoom = 12, PlaceRoom = 13 }; enum class CommandStatus : std::uint8_t { Accepted, Unavailable, Unauthorized, WrongSequence, InvalidTarget, Busy }; @@ -273,6 +289,7 @@ public: void enable_hunger() noexcept; void queue_production(GridPosition position, RecipeId recipe); [[nodiscard]] bool can_place_cabin(GridPosition position) const noexcept; + [[nodiscard]] bool can_place_room(const RoomPlan& plan) const noexcept; [[nodiscard]] std::array construction_materials(RecipeId recipe, BedBase base) const; void queue_cabin(GridPosition position, GridPosition sawmill, GridPosition stonecutter); void start_scenario(GridPosition sawmill); diff --git a/engine/src/world.cpp b/engine/src/world.cpp index beb1b8c..6458412 100644 --- a/engine/src/world.cpp +++ b/engine/src/world.cpp @@ -35,6 +35,10 @@ bool is_production_object(RecipeId recipe) noexcept { return is_construction(recipe) || recipe == RecipeId::WeaveCloth; } +bool is_finished_floor(const ProductionOrder& order) noexcept { + return order.recipe == RecipeId::BuildFloor && order.state == JobState::Completed; +} + bool can_take_work(const Agent& agent, Profession profession) noexcept { return agent.profession == Profession::Generalist || agent.profession == profession; } @@ -62,12 +66,19 @@ const Recipe& recipe_for(RecipeId id) { ItemType::None, 28}; static constexpr Recipe bed{{ItemStack{ItemType::Plank, 1}, {}}, ItemType::None, 14}; static constexpr Recipe weave{{ItemStack{ItemType::Flax, 1}, {}}, ItemType::Cloth, 12}; + static constexpr Recipe floor{{ItemStack{ItemType::Wood, 1}, {}}, ItemType::None, 6}; + static constexpr Recipe wall{{ItemStack{ItemType::Wood, 1}, {}}, ItemType::None, 9}; + static constexpr Recipe door{{ItemStack{ItemType::Wood, 2}, {}}, ItemType::None, 12}; switch (id) { case RecipeId::SawPlank: return saw; case RecipeId::CutStoneBlock: return cut; case RecipeId::BuildCabin: return cabin; case RecipeId::BuildBed: return bed; case RecipeId::WeaveCloth: return weave; + case RecipeId::BuildFloor: return floor; + case RecipeId::BuildWall: return wall; + case RecipeId::BuildDoorAlongX: + case RecipeId::BuildDoorAlongY: return door; } throw std::invalid_argument("unknown production recipe"); } @@ -124,6 +135,38 @@ struct OpenNodeLater { } // namespace +RoomPlan make_room_plan(GridPosition first, GridPosition last) noexcept { + return {{std::min(first.x, last.x), std::min(first.y, last.y)}, + {std::max(first.x, last.x), std::max(first.y, last.y)}}; +} + +bool RoomPlan::valid_size() const noexcept { + const auto width = static_cast(last.x) - first.x + 1; + const auto height = static_cast(last.y) - first.y + 1; + return width >= 3 && width <= 12 && height >= 3 && height <= 12 && entrance <= RoomSide::West; +} + +bool RoomPlan::contains(GridPosition cell) const noexcept { + return cell.x >= first.x && cell.x <= last.x && cell.y >= first.y && cell.y <= last.y; +} + +RecipeId RoomPlan::recipe_at(GridPosition cell) const noexcept { + const auto middle_x = std::midpoint(first.x, last.x), middle_y = std::midpoint(first.y, last.y); + if (cell.y == first.y || cell.y == last.y) { + if (cell.x == middle_x && (cell.y == first.y ? entrance == RoomSide::North : entrance == RoomSide::South)) { + return RecipeId::BuildDoorAlongX; + } + return RecipeId::BuildWall; + } + if (cell.x == first.x || cell.x == last.x) { + if (cell.y == middle_y && (cell.x == first.x ? entrance == RoomSide::West : entrance == RoomSide::East)) { + return RecipeId::BuildDoorAlongY; + } + return RecipeId::BuildWall; + } + return RecipeId::BuildFloor; +} + std::uint32_t Inventory::item_count(ItemType type) const noexcept { const auto index = static_cast(type); return index != 0 && index <= counts_.size() ? counts_[index - 1] : 0; @@ -318,7 +361,7 @@ void World::queue_production(GridPosition position, RecipeId recipe) { throw std::invalid_argument("the production site is occupied"); } for (const ProductionOrder& order : production_orders_) { - if (is_production_object(order.recipe) && order.position == position) { + if (is_production_object(order.recipe) && order.position == position && !is_finished_floor(order)) { throw std::invalid_argument("a building occupies the production site"); } } @@ -334,7 +377,32 @@ bool World::can_place_cabin(GridPosition position) const noexcept { return std::none_of(storages_.begin(), storages_.end(), occupies_cell) && std::none_of(resource_nodes_.begin(), resource_nodes_.end(), occupies_cell) && std::none_of(jobs_.begin(), jobs_.end(), occupies_cell) && - std::none_of(production_orders_.begin(), production_orders_.end(), occupies_cell); + std::none_of(production_orders_.begin(), production_orders_.end(), + [&](const auto& order) { return occupies_cell(order) && !is_finished_floor(order); }); +} + +bool World::can_place_room(const RoomPlan& plan) const noexcept { + if (!plan.valid_size() || !is_walkable(plan.first) || !is_walkable(plan.last)) return false; + const int middle_x = std::midpoint(plan.first.x, plan.last.x); + const int middle_y = std::midpoint(plan.first.y, plan.last.y); + const GridPosition exits[] = {{middle_x, plan.first.y - 1}, {plan.last.x + 1, middle_y}, + {middle_x, plan.last.y + 1}, {plan.first.x - 1, middle_y}}; + if (!is_walkable(exits[static_cast(plan.entrance)]) || + (scenario_active_ && plan.contains(scenario_sawmill_))) return false; + for (int y = plan.first.y; y <= plan.last.y; ++y) { + for (int x = plan.first.x; x <= plan.last.x; ++x) { + if (!is_walkable({x, y})) return false; + } + } + const auto inside = [&](const auto& entity) { return plan.contains(entity.position); }; + return std::none_of(production_orders_.begin(), production_orders_.end(), inside) && + std::none_of(resource_nodes_.begin(), resource_nodes_.end(), inside) && + std::none_of(storages_.begin(), storages_.end(), inside) && + std::none_of(jobs_.begin(), jobs_.end(), inside) && + std::none_of(agents_.begin(), agents_.end(), [&](const Agent& agent) { + return (agent.state == AgentState::Sleeping && inside(agent)) || + (agent.state == AgentState::GoingToSleep && !agent.route.empty() && plan.contains(agent.route.back())); + }); } std::array World::construction_materials(RecipeId recipe, BedBase base) const { @@ -416,6 +484,8 @@ CommandStatus World::object_status(GridPosition position, bool moving) const noe constexpr auto ready = CommandStatus::Accepted; for (const auto& order : production_orders_) { if (order.position != position || !is_production_object(order.recipe)) continue; + if (is_finished_floor(order)) continue; + if (moving && order.recipe >= RecipeId::BuildFloor) return CommandStatus::InvalidTarget; return order.state == JobState::InProgress || resting_at(position) ? busy : ready; } for (std::size_t i = 0; i < storages_.size(); ++i) { @@ -436,6 +506,8 @@ CommandStatus World::object_status(GridPosition position, bool moving) const noe } return node.reserved_workers != 0 ? busy : ready; } + if (!moving && !resting_at(position) && std::any_of(production_orders_.begin(), production_orders_.end(), + [position](const auto& order) { return order.position == position && is_finished_floor(order); })) return ready; return CommandStatus::InvalidTarget; } @@ -450,7 +522,7 @@ CommandStatus World::edit_object(GridPosition position, const GridPosition* dest if (index != no_entity_index && index > removed) --index; }; const auto order = std::find_if(production_orders_.begin(), production_orders_.end(), [&](const auto& entry) { - return is_production_object(entry.recipe) && at_position(entry); + return is_production_object(entry.recipe) && !is_finished_floor(entry) && at_position(entry); }); if (order != production_orders_.end()) { if (destination) order->position = *destination; @@ -476,7 +548,15 @@ CommandStatus World::edit_object(GridPosition position, const GridPosition* dest return CommandStatus::Accepted; } const auto source = std::find_if(resource_nodes_.begin(), resource_nodes_.end(), at_position); - if (source == resource_nodes_.end()) return CommandStatus::InvalidTarget; + if (source == resource_nodes_.end()) { + const auto floor = std::find_if(production_orders_.begin(), production_orders_.end(), + [&](const auto& entry) { return is_finished_floor(entry) && at_position(entry); }); + if (floor == production_orders_.end() || destination) return CommandStatus::InvalidTarget; + const auto removed = static_cast(floor - production_orders_.begin()); + production_orders_.erase(floor); + for (auto& agent : agents_) shift_index(agent.production_index, removed); + return CommandStatus::Accepted; + } if (destination) source->position = *destination; else { const auto removed = static_cast(source - resource_nodes_.begin()); @@ -495,7 +575,8 @@ std::uint64_t World::next_command_sequence(std::uint8_t player) const noexcept { CommandReceipt World::apply_command(const PlayerCommand& command) { const auto receipt = [&](CommandStatus status) { return CommandReceipt{status, tick_, command_revision_}; }; const bool object_command = (command.kind >= CommandKind::PlaceBerryField && command.kind <= CommandKind::PlaceStorage) || - command.kind == CommandKind::PlaceFlaxField || command.kind == CommandKind::PlaceLoom; + command.kind == CommandKind::PlaceFlaxField || command.kind == CommandKind::PlaceLoom || + command.kind == CommandKind::PlaceRoom; if (!scenario_active_ && !object_command && command.kind != CommandKind::AssignProfession && command.kind != CommandKind::SetForaging) return receipt(CommandStatus::Unavailable); if (command.player < colony_host || command.player > colony_player_slots) { @@ -580,6 +661,25 @@ CommandReceipt World::apply_command(const PlayerCommand& command) { } queue_production(command.cell, RecipeId::WeaveCloth); break; + case CommandKind::PlaceRoom: { + const RoomPlan plan{command.cell, command.destination, static_cast(command.value)}; + if (!can_place_room(plan) || !can_reach_object_cell(plan.first)) { + return receipt(CommandStatus::InvalidTarget); + } + const auto width = static_cast(plan.last.x - plan.first.x + 1); + const auto height = static_cast(plan.last.y - plan.first.y + 1); + production_orders_.reserve(production_orders_.size() + width * height); + for (int y = plan.first.y; y <= plan.last.y; ++y) { + for (int x = plan.first.x; x <= plan.last.x; ++x) { + const GridPosition cell{x, y}; + ProductionOrder order{}; + order.position = cell; + order.recipe = plan.recipe_at(cell); + production_orders_.push_back(std::move(order)); + } + } + break; + } case CommandKind::PlaceStorage: if (command.value > static_cast(StorageKind::Pantry) || !can_place_storage(command.cell) || !can_reach_object_cell(command.cell)) { diff --git a/engine/src/world_save.cpp b/engine/src/world_save.cpp index 8a73b39..26e9cdc 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 = 9; +constexpr std::uint32_t save_version = 10; 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; @@ -255,6 +255,7 @@ struct WorldSaveCodec { archive.field(order.recipe); require_save(version >= 2 || order.recipe <= RecipeId::BuildCabin, "Unknown recipe for save version."); require_save(version >= 7 || order.recipe <= RecipeId::BuildBed, "Unknown recipe for save version."); + require_save(version >= 10 || order.recipe <= RecipeId::WeaveCloth, "Unknown recipe for save version."); archive.field(order.state); sequence(archive, order.materials, item_types, [&](auto& material) { index(archive, material.storage_index); @@ -361,7 +362,7 @@ 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::WeaveCloth && order.state <= JobState::Completed && + invalid(order.recipe <= RecipeId::BuildDoorAlongY && order.state <= JobState::Completed && world.is_walkable(order.position) && (order.recipe != RecipeId::WeaveCloth || order.state != JobState::Completed)); invalid(order.bed_base <= BedBase::Stone && order.bed_stage <= BedStage::Pillow && @@ -424,6 +425,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::BuildFloor: + case RecipeId::BuildWall: + case RecipeId::BuildDoorAlongX: + case RecipeId::BuildDoorAlongY: + for (const auto& item : world.construction_materials(order.recipe, order.bed_base)) { + if (item.count) required[item_index(item.type)] = item.count; + } + break; } invalid(ingredients == required); } diff --git a/tests/core_tests.cpp b/tests/core_tests.cpp index e5e13ba..bffadee 100644 --- a/tests/core_tests.cpp +++ b/tests/core_tests.cpp @@ -721,6 +721,48 @@ void test_object_tools_work_in_an_older_demo_world() { static_cast(save_roundtrip(*world)); } +void test_room_builds_and_saves_as_separate_parts() { + using namespace settlement; + World world(61, 16, 16); + static_cast(world.spawn_agent({3, 3})); + const auto storage = world.add_storage({2, 2}, 32); + world.stock_storage(storage, ItemType::Wood, 32); + auto room = make_room_plan({9, 8}, {6, 5}); + room.entrance = RoomSide::East; + const auto place = [&](const RoomPlan& plan) { + return world.apply_command({1, world.next_command_sequence(1), CommandKind::PlaceRoom, plan.first, + static_cast(plan.entrance), plan.last}).status; + }; + require(room.recipe_at({9, 6}) == RecipeId::BuildDoorAlongY, "room lost its entrance"); + world.set_blocked({10, 6}, true); + require(place(room) == CommandStatus::InvalidTarget && world.production_orders().empty(), + "a room with a blocked entrance was partially scheduled"); + world.set_blocked({10, 6}, false); + require(place(room) == CommandStatus::Accepted && world.production_orders().size() == 16, + "room did not queue floor, walls and entrance together"); + require(place(room) == CommandStatus::InvalidTarget && world.production_orders().size() == 16, + "duplicate room placement altered its construction orders"); + world.step(); + require(world.production_orders().front().state == JobState::InProgress, "builders did not start the room"); + auto resumed = save_roundtrip(world); + for (int i = 0; i < 850; ++i) resumed->step(); + for (const auto& order : resumed->production_orders()) { + require(order.state == JobState::Completed && order.recipe == room.recipe_at(order.position), + "room component did not survive delivery and construction after load"); + } + require(resumed->storages().front().item_count(ItemType::Wood) == 15, "room used incorrect materials"); + const auto apply = [&](CommandKind command, GridPosition cell) { + return resumed->apply_command({1, resumed->next_command_sequence(1), command, cell}).status; + }; + const GridPosition floor{7, 6}; + require(apply(CommandKind::PlaceLoom, floor) == CommandStatus::Accepted, + "finished floor could not hold furniture"); + require(apply(CommandKind::DemolishObject, floor) == CommandStatus::Accepted && + resumed->production_orders().size() == 16 && resumed->can_place_storage(floor), + "demolition removed the floor instead of the furniture"); + static_cast(save_roundtrip(*resumed)); +} + } // namespace int main() { @@ -746,6 +788,7 @@ int main() { test_field_growth_requires_a_worker(); test_opening_a_mine_invalidates_unreachable_routes(); test_object_tools_work_in_an_older_demo_world(); + test_room_builds_and_saves_as_separate_parts(); } catch (const std::exception& error) { std::cerr << "Test failed: " << error.what() << '\n'; return 1; diff --git a/tests/lan_tests.cpp b/tests/lan_tests.cpp index 6ea872a..da8b32d 100644 --- a/tests/lan_tests.cpp +++ b/tests/lan_tests.cpp @@ -134,6 +134,32 @@ void test_shared_colony_over_loopback() { client_view->resource_nodes().back().needs_tending() && client_view->resource_nodes().back().reserved_workers == 1; }, "a snapshot lost the resident's sowing assignment"); + RoomPlan room{}; + bool found_room = false; + for (int y = 2; y < 29 && !found_room; ++y) { + for (int x = 2; x < 29 && !found_room; ++x) { + const auto candidate = make_room_plan({x, y}, {x + 2, y + 2}); + if (!authoritative->can_place_room(candidate)) continue; + room = candidate; + found_room = true; + } + } + require(found_room, "could not find a test plot for a room"); + const auto entrance = static_cast(room.entrance); + const auto previous_size = authoritative->production_orders().size(); + require(guest.submit(CommandKind::PlaceRoom, room.first, entrance, room.last), + "guest could not send the room"); + pump_until([&] { return client_view->production_orders().size() == previous_size + 9; }, + "snapshot did not carry all room components"); + require(guest.submit(CommandKind::PlaceRoom, room.first, entrance, room.last), + "guest could not send the conflicting room"); + pump_until([&] { + const auto rejected = guest.take_rejection(); + return rejected && rejected->kind == CommandKind::PlaceRoom && rejected->cell == room.first && + rejected->destination == room.last && rejected->value == entrance && + rejected->status == CommandStatus::InvalidTarget; + }, "room rejection lost the geometry needed to restore the draft"); + require(authoritative->production_orders().size() == previous_size + 9, "room conflict scheduled extra work"); std::cout << "Loopback LAN checks passed.\n"; } -- 2.54.0 From 8bb448cc49e3d76a5fdd52e490bd423138cca5f7 Mon Sep 17 00:00:00 2001 From: Codex Date: Tue, 1 Dec 2026 11:51:48 +0300 Subject: [PATCH 6/7] Add furnished houses, roof views, carpentry, and GCC 16 tests --- CMakeLists.txt | 12 +- PLAN.md | 2 +- README.md | 8 +- app/art/doctor_house.ico | Bin 0 -> 18890 bytes app/art/miner_house.ico | Bin 0 -> 18510 bytes app/art/weaver_house.ico | Bin 0 -> 19644 bytes app/d3d_scene_win32.cpp | 248 ++++++++++++++-- app/d3d_scene_win32.hpp | 4 + app/house_icons.h | 8 + app/house_icons.rc | 5 + app/lan_session_win32.cpp | 2 +- app/viewer_win32.cpp | 344 ++++++++++++++++++++--- build.ps1 | 90 +++--- docs/viewer.md | 10 +- engine/include/settlement/core/world.hpp | 62 +++- engine/src/world.cpp | 168 +++++++++-- engine/src/world_save.cpp | 38 ++- setup-toolchain.ps1 | 144 +++------- tests/core_tests.cpp | 299 ++++++++++++++++---- tests/lan_tests.cpp | 28 +- tests/testing.hpp | 115 ++++++++ 21 files changed, 1256 insertions(+), 331 deletions(-) create mode 100644 app/art/doctor_house.ico create mode 100644 app/art/miner_house.ico create mode 100644 app/art/weaver_house.ico create mode 100644 app/house_icons.h create mode 100644 app/house_icons.rc create mode 100644 tests/testing.hpp diff --git a/CMakeLists.txt b/CMakeLists.txt index c57a419..7e74e26 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -35,18 +35,21 @@ add_executable(settlement_colony_benchmark benchmarks/colony.cpp) target_link_libraries(settlement_colony_benchmark PRIVATE settlement_core) if(WIN32) + enable_language(RC) add_executable(settlement_viewer WIN32 app/d3d_scene_win32.cpp app/viewer_win32.cpp app/lan_session_win32.cpp + app/house_icons.rc ) target_link_libraries(settlement_viewer PRIVATE settlement_core user32 gdi32 comctl32 comdlg32 ws2_32 bcrypt iphlpapi d3d11 d3dcompiler) if(NOT MSVC) target_link_options(settlement_viewer PRIVATE -municode) - target_compile_options(settlement_viewer PRIVATE -Wall -Wextra -Wpedantic -Wconversion -Wshadow) + target_compile_options(settlement_viewer PRIVATE + $<$:-Wall;-Wextra;-Wpedantic;-Wconversion;-Wshadow>) else() - target_compile_options(settlement_viewer PRIVATE /W4 /permissive-) + target_compile_options(settlement_viewer PRIVATE $<$:/W4;/permissive->) endif() endif() @@ -58,13 +61,18 @@ endif() include(CTest) if(BUILD_TESTING) + if(NOT CMAKE_CXX_COMPILER_ID STREQUAL "GNU" OR CMAKE_CXX_COMPILER_VERSION VERSION_LESS 16) + message(FATAL_ERROR "The reflection test suites need GCC 16 or later. Set BUILD_TESTING=OFF to build the game alone.") + endif() add_executable(settlement_core_tests tests/core_tests.cpp ) + target_compile_options(settlement_core_tests PRIVATE -std=c++26 -freflection) target_link_libraries(settlement_core_tests PRIVATE settlement_core) add_test(NAME settlement_core_tests COMMAND settlement_core_tests) if(WIN32) add_executable(settlement_lan_tests tests/lan_tests.cpp app/lan_session_win32.cpp) + target_compile_options(settlement_lan_tests PRIVATE -std=c++26 -freflection) target_include_directories(settlement_lan_tests PRIVATE app) target_link_libraries(settlement_lan_tests PRIVATE settlement_core ws2_32 bcrypt iphlpapi) add_test(NAME settlement_lan_tests COMMAND settlement_lan_tests) diff --git a/PLAN.md b/PLAN.md index 861d0cd..c6445fc 100644 --- a/PLAN.md +++ b/PLAN.md @@ -9,7 +9,7 @@ ### P0 — Инструменты и границы проекта - [x] Отдельный каталог, CMake, C++20, лицензия и базовая структура. -- [x] Portable-установщик CMake/LLVM-MinGW и скрипт сборки с CTest. +- [x] Portable-установщик MSYS2 UCRT64 с GCC 16 и сборка с CTest. - [ ] CI для Windows и Linux. - [x] Не включать код и ресурсы Stonehearth. diff --git a/README.md b/README.md index a3e093a..344f8e8 100644 --- a/README.md +++ b/README.md @@ -42,16 +42,18 @@ powershell.exe -NoProfile -ExecutionPolicy Bypass -File .\tools\render-svg-to-pn По умолчанию он читает `build/workload.svg` и создаёт `build/workload.png`. -## Portable toolchain и сборка +## Сборка Windows на MSYS2 UCRT64 -Требуется 64-битная Windows с доступом к GitHub. Toolchain устанавливается локально в `.tools/`, не меняет системный PATH и не требует администратора. Скрипт загружает CMake и LLVM-MinGW с официальных релизов и проверяет доступные SHA-256 digests. +Требуется 64-битная Windows. Скрипт установки разворачивает MSYS2 в `.tools/toolchain/msys64`, проверяет SHA-256 архива и устанавливает GCC 16, CMake и Ninja через UCRT64. Если MSYS2 уже установлен, передайте его каталог обоим скриптам через `-Msys2Root` или задайте `SETTLEMENT_MSYS2_ROOT`. ```powershell powershell.exe -NoProfile -ExecutionPolicy Bypass -File .\setup-toolchain.ps1 powershell.exe -NoProfile -ExecutionPolicy Bypass -File .\build.ps1 ``` -Сборка запускает CTest и копирует runtime-библиотеки LLVM рядом с исполняемыми файлами, чтобы их можно было запускать без глобального PATH. +Сборка запускает CTest и помещает проверенные исполняемые файлы и библиотеки GCC в `build/`. Просмотрщик запускается из `build/settlement_viewer.exe`. + +Тесты используют C++26 и `-freflection`. `Void::Testing::Suite` находит методы с возвращаемым типом `Test`. Необязательный `setup()` выполняется перед каждым запускаемым тестом. Метки задаются через `[[= Void::Testing::tag("construction")]]`, а `[[= Void::Testing::skip("причина")]]` пропускает тест с пояснением. Чтобы запустить только тесты строительства, выполните `build/settlement_core_tests.exe --tag construction`. Для сборки игры на другом компиляторе через CMake есть `-DBUILD_TESTING=OFF`. ## Структура diff --git a/app/art/doctor_house.ico b/app/art/doctor_house.ico new file mode 100644 index 0000000000000000000000000000000000000000..9bc0d003c5881ac1201f6735df62a19446a27f35 GIT binary patch literal 18890 zcmV)+K#0Ep009620AOGM0096X0JKQ}02TlM0EtjeM-2)Z3IG5A4M|8uQUCw|U;qFB zUXl*nO{M2fa$OIDyMQKr1IcWud}c|W{8 z?+v9r#_l<`#A%w^<#*113R7M4fOqfz-|*dgUw!C9zs9fe_ryOr{>HEIYy29&#y@f# zhU-6e{Jme}KI1T4&%2nY?!TO}&L`{T=rny+1mR-ZZ-scpXCYdCrQ^S{OifQLQR z4_=H~JFg^dPu(7}|LD$019LH6%Pe#onA81M=8>TW=GIUHb17N(gR_yEkMH+arA`N{ zB*(Awj~0(VE-Suqr()#VE%A*DSBre-56gxQZdn$`KD;kVAOHLZf$zW4|B)v~ z8(dchYHl7TYyS9J+Q!@%tY;Rw^^Dt63cH*~mF0P8)fd5ARfbHHf_XSt$s7*Ym`kZT z=4`C?znqKJe08PQ6hD6Le{^{GbnzRH-;*$pKUKjza<_uHaYw>jxmCd|uN5)bv7*13 zUNo&vEE~-qWVpHEHy>OburYUr?abY5BlGBpPZ8fj8cx2XiC(mXUM1xPf= zvFtYET)dVpr|an;Zo{(I!i>2zjK8Y<>&LJCj|Nw6mRN7x;Mtbegzv8HikS7C5;}je z1eXuRn3)qG5H2Kdu$UR2H8XQ7=A+qV%lBrMETJJ~k-romVr{d|UHZ3#V zuA>#V38(t1a5-+nQ@JL*IMs^hr&@8CtjD#120S;}hQ~)+a5h?poJ&Lgs&eWwh^g09 z#&nrVzi|B8{{Vbo8|!}xo121?Yu8IZ_xKZKM~^-xI@&uc{Oh^3QmpNWX>m4|$%Iyh5A1A|2v%IUGVQHz!B zdMvEjFt=QTnI$V`m#tV>t6^qWtjyS)g$c%#jH5|3cKmnzkC1W7K0e*9VpwxC>{KD! zqDHPojmb7GCR`d!xYStpn2>ALz*ANF{<4;#yRwv30(B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^ataC z+5L&&SNdGFU$XNl!b&11ms`%v;SbkNJ>F=n_1bR*nhF!lsK32}m&J|;7 zlus?rJPJj5SXdO%>5ZbF&1L!I_ZCpI>m<|Olh1fVJjT^g@V2jtFOD~qPmDH||ISRS zgqd|onUxO3(MUrD8@qF6B~mSZJyKgX6Sa#Qd=2;EAxr;XK!5*-@&_^{|NG2*DKk7= z#5A=OFupLK$xVuwshMIX7UMJBULMov%KtwcEqUK{brn3}Y%lz~?;mELjM#m3|B{~Grnznt&o{WX4# dU*kUE{{mo@{DIy@gscDn002ovPDHLkV1keP%JKjJ literal 0 HcmV?d00001 diff --git a/app/art/miner_house.ico b/app/art/miner_house.ico new file mode 100644 index 0000000000000000000000000000000000000000..6873e316c71ca766d3956beb9f034e4c3af85b48 GIT binary patch literal 18510 zcmV)=K!m>l009620AOGM0096X060hh02TlM0EtjeM-2)Z3IG5A4M|8uQUCw|U;qFB zU!!Gxw=BD{Qri( zD-KvHTHkZ7Yz|+o*&e#yYyHNR9`mo9FB?vttr|TSx()kwfB*lD*zJI~#Sxcl7R!}h z+qLThj^DjC>}0O>*_f4>iaFJ7WNr@HnHvLk=5nv)TW8D0XU>+4mCcN?efKr~k3p_? zvAKKnh+$yh#6K1S{=UI~EC)P17EoWS+1IYrtY2XberwpltR=Nfx2Y3W{y`{P_QE4= zq@=cuYBoN$vO4B^zm>UMvoYr?=D$2&F}<}MRd?^c?oTBQhVh?I_bmns!-pR$4zGT@ zdvu*C4zGQ!FuZ;%Ke!anWCr%{{+S;K>lwq`m0m0J=$MOnXw1dj8gcGi8?e%9LPh-! zA^GJ^P_^xYOL7Q3HUXAnYFwyV==y-2&i7cclGHI{9to4sw*B(%YyVWCGIqq$J-U9b zIK28>#o<+^GO@vQj~!w1BkMceBS)C>#4)BcvB{LjkN#nKV&m1yWE$paUK_5}?0DZ)0FRFOaG_$wY*;}h zGoQlB778hvnV_QS@69#9L z(OUiJvW3X(Nl`F6fb!%q^sijP@cK0jtzJR@@&ybYK2L)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D>QJ-FUS?>#pmK^-pdR+?qm9#`^NsEMgEQ9^i;Y1@=~>O zWwHA7wdLv`+*++M4{r=I4;~$0Zmjk(4;<;Iv8J% zm&lUIV5CqmLTighu(q&H{gnYqgcC4z8DQ2Mq1Wo5QK_L;X`vQ2GZDqRclu5DQNQsX zTJ-Fpt=IuNm8_%H=pmZ*9oU)j?qzx`_kOc%zV9FVuWtW!o~ZlJ!Nt||p6e?;?n?{R z%_|GlPhFZX|M|m52bh`e0F&@qnc2P^&DJtB*O$XwUmnZDCEA>EkImKNlu6{!rP08k)j_3DLN1j;ES8eIv*Ej5(Yu(U{$8eRxQ7|A-pdSG?q%k^ zdzqE+L1xUopQ+jRzQ1a?kDHVFsm7U!MC-N1a^HB)bEcB?zp*e>VrKjD%ydtNnX0BS z+n1%4VYbSOk>8>tn@$O%O3YmA)iI9_bf0iIfrZJ5RX;@A8Kg z_lzYq_ngS--t%P1aL=cDP51onh;!d>_d52Lc7KllBk=g@>Yj<7%*bdt{lS5J>|3MV zab}8jL{Ek($9;^?q-E@S6=P6IzMeC*{??GajhXiGnT)!Tu?Y@*%j5C<9D5z7#Wv)y z*?-+`u`*7pov|3rjML`Y2{?TecKN81E0M)$C52Q$60sOEsg#k+WQ<5GVFW_q7llHh za`(TDg+lQTHpjjFkEQvyh)l+_zm{WJc=+sKF8bwS)cb9ZQS(8UL7id8B^&R3M}xLy z&tuxQy}#uV*ZrwOT(`38693L>u$s+A<0*qy_p3IOl?i!+Owi+JLY}~mPTj>QP)cfbEL{0u+C&+vZ<{s-Gn+TDBE6f^(; N002ovPDHLkV1ick;70%e literal 0 HcmV?d00001 diff --git a/app/art/weaver_house.ico b/app/art/weaver_house.ico new file mode 100644 index 0000000000000000000000000000000000000000..f191e2478e023ddbb278da32c092a62202e6fa91 GIT binary patch literal 19644 zcmV*8KykkS009620AOGM0096X0H#a;02TlM0EtjeM-2)Z3IG5A4M|8uQUCw|U;qFB zUOCMHNuwoJ0m8 zfe;`eP!>W2389>`)G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#W z#fEdW@sXU*82Y(aA9TiT4CX<=|C6;i6hS>%B4clssI1>5SwG;CT5mSxMh-V6zPoHFWhN_pm%b-*%No>v8}oc;X&Bdt2q@N~CR zZ0XOEb}e&D&-7-AKI+dBbE~~FuGSXC<;R45;4_7o2PXZ`=e@)85* zwmF2hu2fNXr7gTN(-8Wl{T}-NyOm`4&u3S()g?w%H75(7S&%Gzr!GP8&uPk_a}H%- z>RRr|jHWiMtx1E(0=00000NkvXXu0mjf Ddc-Ro literal 0 HcmV?d00001 diff --git a/app/d3d_scene_win32.cpp b/app/d3d_scene_win32.cpp index fadeacc..0eb447b 100644 --- a/app/d3d_scene_win32.cpp +++ b/app/d3d_scene_win32.cpp @@ -6,6 +6,7 @@ #include #include +#include #include #include #include @@ -140,20 +141,191 @@ void room_part(Mesh& mesh, GridPosition cell, RecipeId recipe, Color color, bool .02f, along_x ? .20f : .62f, along_x ? .62f : .20f, .73f, color); } mesh.box(x, y, .75f, along_x ? 1.f : .62f, along_x ? .62f : 1.f, .10f, shade(color, 1.13f)); - } -} - -void draw_room_plan(Mesh& mesh, const RoomPlan& plan, bool preview, bool valid) { - for (int y = plan.first.y; y <= plan.last.y; ++y) { - for (int x = plan.first.x; x <= plan.last.x; ++x) { - const GridPosition cell{x, y}; - room_part(mesh, cell, plan.recipe_at(cell), !valid ? rgb(203, 113, 101) : - (preview ? rgb(169, 224, 232) : rgb(104, 176, 212)), true); + if (!draft) { + const auto leaf = [x, y, along_x](float side, float inward, float height) { + return along_x ? Point{x + side, y + inward, height} : Point{x + inward, y + side, height}; + }; + mesh.quad(leaf(-.28f, 0.f, .04f), leaf(-.06f, .40f, .04f), leaf(-.06f, .40f, .66f), + leaf(-.28f, 0.f, .66f), shade(color, .75f)); + const auto handle = leaf(-.09f, .32f, .37f); + mesh.box(handle.x, handle.y, handle.z, .06f, .06f, .06f, rgb(215, 183, 107)); } } } -void construction(Mesh& mesh, const World& world) { +void draw_blueprint(Mesh& mesh, const BlueprintPart& part, bool preview); + +void draw_furnishing(Mesh& mesh, GridPosition cell, RecipeId recipe, Color wood, Color detail) { + const float x = static_cast(cell.x), y = static_cast(cell.y); + if (recipe == RecipeId::BuildMedicineCabinet) { + mesh.box(x, y + .10f, .03f, .64f, .35f, .61f, wood); + for (const float offset : {-.22f, 0.f, .22f}) { + mesh.box(x + offset, y - .13f, .34f, .15f, .15f, .22f, detail); + mesh.box(x + offset, y - .13f, .56f, .10f, .10f, .056f, shade(detail, .73f)); + } + } else if (recipe == RecipeId::BuildMiningRack) { + mesh.box(x, y, .03f, .74f, .45f, .12f, wood); + for (const float offset : {-.25f, .25f}) { + mesh.box(x + offset, y + .1f, .15f, .09f, .10f, .62f, wood); + } + mesh.box(x, y + .1f, .64f, .64f, .10f, .11f, wood); + for (const float offset : {-.15f, .15f}) { + mesh.box(x + offset, y - .04f, .22f, .045f, .05f, .39f, shade(wood, 1.25f)); + mesh.box(x + offset, y - .04f, .59f, .23f, .08f, .07f, detail); + } + } else { + mesh.box(x, y, .025f, .71f, .58f, .34f, shade(wood, .82f)); + mesh.box(x, y, .37f, .77f, .62f, .10f, wood); + mesh.box(x, y - .12f, .46f, .62f, .12f, .37f, wood); + mesh.box(x, y - .15f, .79f, .48f, .15f, .10f, detail); + } +} + +void draw_room_plan(Mesh& mesh, const RoomPlan& plan, bool preview, bool valid) { + const auto ink = !valid ? rgb(203, 113, 101) : + (preview ? rgb(169, 224, 232) : rgb(104, 176, 212)); + for (int y = plan.first.y; y <= plan.last.y; ++y) { + for (int x = plan.first.x; x <= plan.last.x; ++x) { + const GridPosition cell{x, y}; + room_part(mesh, cell, plan.recipe_at(cell), ink, true); + } + } + if (const auto furnishings = plan.furnishings()) { + for (const auto& part : *furnishings) { + if (part.recipe == RecipeId::BuildBed) { + draw_blueprint(mesh, {part.position, part.recipe, part.bed_base}, preview); + } else { + draw_furnishing(mesh, part.position, part.recipe, ink, shade(ink, .73f)); + } + } + } +} + +void draw_gabled_roof(Mesh& mesh, float left, float top, float right, float bottom, float eaves, + float ridge, bool along_x, Color tiles, Color gable) { + if (!along_x) { + std::swap(left, top); + std::swap(right, bottom); + } + const auto point = [along_x](float x, float y, float z) { + return along_x ? Point{x, y, z} : Point{y, x, z}; + }; + const float middle = (top + bottom) / 2.f; + constexpr float overhang = .12f; + for (const float edge : {left, right}) { + const auto peak = point(edge, middle, ridge); + mesh.quad(point(edge, top, eaves), point(edge, bottom, eaves), peak, peak, gable); + } + left -= overhang; + right += overhang; + const auto slope = [&](float edge, float light) { + constexpr std::array shades{.90f, 1.03f, .95f, 1.08f}; + for (std::size_t i = 0; i < shades.size(); ++i) { + const float a = static_cast(i) / static_cast(shades.size()); + const float b = static_cast(i + 1) / static_cast(shades.size()); + const float y1 = std::lerp(edge, middle, a), y2 = std::lerp(edge, middle, b); + const float z1 = std::lerp(eaves, ridge, a), z2 = std::lerp(eaves, ridge, b); + mesh.quad(point(left, y1, z1), point(right, y1, z1), point(right, y2, z2), + point(left, y2, z2), shade(tiles, light * shades[i])); + } + }; + slope(top - overhang, .93f); + slope(bottom + overhang, 1.12f); + mesh.quad(point(left, middle - .035f, ridge + .02f), point(right, middle - .035f, ridge + .02f), + point(right, middle + .035f, ridge + .02f), point(left, middle + .035f, ridge + .02f), + shade(tiles, .72f)); +} + +void draw_room_roofs(Mesh& mesh, const World& world) { + struct Tile { + RecipeId structure = RecipeId::SawPlank; + RoomTemplate furnishing = RoomTemplate::Empty; + bool visited = false; + }; + const auto width = static_cast(world.width()); + std::vector map(width * static_cast(world.height())); + const auto tile = [&](GridPosition cell) -> Tile& { + return map[static_cast(cell.y) * width + static_cast(cell.x)]; + }; + for (const auto& order : world.production_orders()) { + auto& cell = tile(order.position); + if (is_room_part(order.recipe) && order.state == JobState::Completed) { + cell.structure = room_part_shape(order.recipe); + } + switch (order.recipe) { + case RecipeId::BuildMedicineCabinet: cell.furnishing = RoomTemplate::Doctor; break; + case RecipeId::BuildMiningRack: cell.furnishing = RoomTemplate::Miner; break; + case RecipeId::BuildLoom: + case RecipeId::WeaveCloth: cell.furnishing = RoomTemplate::Weaver; break; + default: break; + } + } + const auto in_bounds = [&](GridPosition cell) { + return cell.x >= 0 && cell.y >= 0 && cell.x < world.width() && cell.y < world.height(); + }; + const GridPosition neighbors[] = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}}; + const auto intact = [&](const RoomPlan& plan) { + for (int y = plan.first.y; y <= plan.last.y; ++y) { + for (int x = plan.first.x; x <= plan.last.x; ++x) { + const GridPosition cell{x, y}; + if (tile(cell).structure != plan.recipe_at(cell)) return false; + } + } + return true; + }; + constexpr Color finishes[] = {rgb(146, 94, 66), rgb(107, 136, 76), rgb(86, 116, 136), rgb(169, 91, 65)}; + std::vector floor; + const auto visit = [&](GridPosition cell) { + if (!in_bounds(cell)) return; + auto& entry = tile(cell); + if (entry.visited || entry.structure != RecipeId::BuildFloor) return; + entry.visited = true; + floor.push_back(cell); + }; + for (int y = 0; y < world.height(); ++y) { + for (int x = 0; x < world.width(); ++x) { + floor.clear(); + visit({x, y}); + if (floor.empty()) continue; + GridPosition first{x, y}, last{x, y}; + auto finish = RoomTemplate::Empty; + for (std::size_t i = 0; i < floor.size(); ++i) { + const auto from = floor[i]; + first.x = std::min(first.x, from.x); + first.y = std::min(first.y, from.y); + last.x = std::max(last.x, from.x); + last.y = std::max(last.y, from.y); + if (tile(from).furnishing != RoomTemplate::Empty) finish = tile(from).furnishing; + for (const auto offset : neighbors) visit({from.x + offset.x, from.y + offset.y}); + } + RoomPlan plan{{first.x - 1, first.y - 1}, {last.x + 1, last.y + 1}}; + if (!plan.valid_size() || !in_bounds(plan.first) || !in_bounds(plan.last)) continue; + // A room from an older save has the same completed floor and perimeter as a new room. + for (const auto side : {RoomSide::North, RoomSide::East, RoomSide::South, RoomSide::West}) { + plan.entrance = side; + if (!intact(plan)) continue; + const bool along_x = side == RoomSide::East || side == RoomSide::West; + const int span = along_x ? plan.last.y - plan.first.y : plan.last.x - plan.first.x; + draw_gabled_roof(mesh, static_cast(plan.first.x) - .5f, static_cast(plan.first.y) - .5f, + static_cast(plan.last.x) + .5f, static_cast(plan.last.y) + .5f, .85f, + .85f + std::min(.24f * static_cast(span + 1), 1.65f), along_x, + finishes[static_cast(finish)], rgb(176, 127, 82)); + break; + } + } + } +} + +void construction(Mesh& mesh, const World& world, BuildingView building_view) { + const auto workshop = world.carpenter_workshop(); + if (workshop) { + const auto x = static_cast(workshop->x); + const auto y = static_cast(workshop->y); + mesh.box(x, y, .02f, .87f, .74f, .36f, rgb(142, 95, 59)); + mesh.box(x, y, .38f, .92f, .77f, .12f, rgb(209, 161, 104)); + mesh.box(x, y - .12f, .50f, .59f, .12f, .08f, rgb(180, 190, 191)); + mesh.box(x - .29f, y - .12f, .52f, .16f, .17f, .12f, rgb(123, 68, 46)); + } for (const auto& storage : world.storages()) { const float x = static_cast(storage.position.x), y = static_cast(storage.position.y); mesh.box(x, y, .02f, .66f, .62f, .44f, rgb(160, 110, 65)); @@ -162,27 +334,39 @@ void construction(Mesh& mesh, const World& world) { 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 || + (order.recipe == RecipeId::SawPlank && workshop == order.position)) continue; 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)); + continue; + } if (!is_construction(order.recipe)) { mesh.box(x, y, .025f, .71f, .58f, .34f, rgb(150, 110, 73)); mesh.box(x, y, .37f, .77f, .62f, .10f, rgb(199, 156, 100)); - if (order.recipe == RecipeId::WeaveCloth) { - mesh.box(x, y - .12f, .46f, .62f, .12f, .37f, rgb(167, 124, 79)); - mesh.box(x, y - .15f, .79f, .48f, .15f, .10f, rgb(235, 225, 193)); - } continue; } if (order.state != JobState::Completed) { const auto marked = order.state == JobState::Available ? rgb(121, 178, 195) : rgb(214, 171, 99); mesh.flat(x - .44f, y - .44f, x + .44f, y + .44f, .03f, marked); } - if (order.recipe >= RecipeId::BuildFloor) { + if (is_room_part(order.recipe)) { + const auto shape = room_part_shape(order.recipe); + if (building_view == BuildingView::FloorsOnly && shape != RecipeId::BuildFloor) continue; if (order.state == JobState::Completed) { - room_part(mesh, order.position, order.recipe, rgb(175, 123, 78), false); - } else if (order.recipe != RecipeId::BuildFloor) { - room_part(mesh, order.position, order.recipe, + room_part(mesh, order.position, shape, rgb(175, 123, 78), false); + } else if (shape != RecipeId::BuildFloor) { + 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) { + 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)) + : rgb(158, 202, 209); + draw_furnishing(mesh, order.position, order.recipe, 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, @@ -193,16 +377,18 @@ void construction(Mesh& mesh, const World& world) { if (order.state == JobState::Completed) { mesh.box(x - .23f, y, .345f, .2f, .32f, .07f, rgb(243, 230, 194)); } + } else if (order.recipe == RecipeId::BuildBed) { + draw_blueprint(mesh, {order.position, order.recipe, order.bed_base}, false); } else if (order.recipe == RecipeId::BuildCabin && order.state == JobState::Completed) { - mesh.box(x, y, .03f, .83f, .82f, .65f, rgb(194, 151, 103)); - mesh.quad({x - .46f, y + .46f, .64f}, {x + .46f, y + .46f, .64f}, - {x + .46f, y, 1.03f}, {x - .46f, y, 1.03f}, rgb(158, 83, 62)); - mesh.quad({x - .46f, y, 1.03f}, {x + .46f, y, 1.03f}, - {x + .46f, y - .46f, .64f}, {x - .46f, y - .46f, .64f}, rgb(193, 113, 79)); - mesh.quad({x + .42f, y - .42f, .67f}, {x + .42f, y + .42f, .67f}, - {x + .42f, y, 1.01f}, {x + .42f, y, 1.01f}, rgb(174, 126, 80)); + const float walls = building_view == BuildingView::FloorsOnly ? .07f : .65f; + mesh.box(x, y, .03f, .83f, .82f, walls, rgb(194, 151, 103)); + if (building_view == BuildingView::Full) { + draw_gabled_roof(mesh, x - .415f, y - .41f, x + .415f, y + .41f, + .68f, 1.03f, true, rgb(159, 90, 66), rgb(174, 126, 80)); + } } } + if (building_view == BuildingView::Full) draw_room_roofs(mesh, world); for (const auto& job : world.jobs()) { if (job.state == JobState::Completed) continue; const float x = static_cast(job.position.x), y = static_cast(job.position.y); @@ -266,7 +452,9 @@ 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.empty()) { + if (agent.inventory.item_count(ItemType::WoodenDoor) != 0) { + 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)); } } @@ -446,8 +634,12 @@ bool D3DScene::render(const World& world, const SceneView& view, std::vector preview; std::span room_blueprints; std::optional room_preview; + BuildingView building_view = BuildingView::Full; + std::optional moving_room; }; class D3DScene { diff --git a/app/house_icons.h b/app/house_icons.h new file mode 100644 index 0000000..47891e3 --- /dev/null +++ b/app/house_icons.h @@ -0,0 +1,8 @@ +#ifndef SETTLEMENT_HOUSE_ICONS_H +#define SETTLEMENT_HOUSE_ICONS_H + +#define IDI_DOCTOR_HOUSE 201 +#define IDI_MINER_HOUSE 202 +#define IDI_WEAVER_HOUSE 203 + +#endif diff --git a/app/house_icons.rc b/app/house_icons.rc new file mode 100644 index 0000000..93ca12b --- /dev/null +++ b/app/house_icons.rc @@ -0,0 +1,5 @@ +#include "house_icons.h" + +IDI_DOCTOR_HOUSE ICON "art/doctor_house.ico" +IDI_MINER_HOUSE ICON "art/miner_house.ico" +IDI_WEAVER_HOUSE ICON "art/weaver_house.ico" diff --git a/app/lan_session_win32.cpp b/app/lan_session_win32.cpp index 49b1b3d..c24e5c6 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 = 8; +constexpr std::uint32_t protocol_version = 10; 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 340a63b..abeded6 100644 --- a/app/viewer_win32.cpp +++ b/app/viewer_win32.cpp @@ -7,6 +7,7 @@ #include #include "d3d_scene_win32.hpp" +#include "house_icons.h" #include "map_camera.hpp" #include "lan_session.hpp" #include "title_screen_win32.hpp" @@ -65,6 +66,10 @@ constexpr int loom_id = 1039; constexpr int farmer_menu_id = 1040; constexpr int builder_menu_id = 1043; constexpr int room_tool_id = 1044; +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_work_choice_id = 1050; constexpr int resident_list_id = 1060; constexpr int first_role_id = 1070; @@ -72,10 +77,12 @@ constexpr int first_dock_section_id = 1080; constexpr int work_list_button_id = 1083; constexpr int build_blueprint_id = 1084; constexpr int clear_blueprint_id = 1085; +constexpr int building_view_id = 1086; constexpr int exit_menu_id = 1121; constexpr int interface_scale_id = 1122; constexpr int scale_slider_id = 1130; constexpr int scale_value_id = 1131; +constexpr int first_house_tool_id = 1140; constexpr int min_interface_scale = 50; constexpr int max_interface_scale = 250; constexpr int default_interface_scale = 125; @@ -97,6 +104,7 @@ HWND work_list_button = nullptr; HWND residents_button = nullptr; HWND build_blueprint_button = nullptr; HWND clear_blueprint_button = nullptr; +HWND building_view_button = nullptr; HFONT dock_font = nullptr; int interface_scale = default_interface_scale; struct DockLayout { @@ -117,6 +125,11 @@ bool coop_menu_open = false; bool pause_menu_open = false; HWND scene_window = nullptr; settlement::viewer::D3DScene graphics; +using settlement::viewer::BuildingView; +BuildingView building_view = BuildingView::Full; +constexpr const wchar_t* building_view_labels[] = { + L"Вид: полный", L"Вид: без крыш", L"Вид: без стен и крыш", +}; using settlement::viewer::LanState; settlement::viewer::LanSession lan; LanState displayed_lan_state = LanState::Offline; @@ -124,15 +137,17 @@ const auto local_worker_count = std::clamp( std::thread::hardware_concurrency(), settlement::min_worker_count, 8); enum class PlacementMode { None, Building, Foraging, BerryField, FlaxField, TreePlot, Mine, Loom, Storage, Pantry, Move, Demolish, Room }; PlacementMode placement_mode = PlacementMode::None; -enum class WorkPanel { Farmer, Woodcutter, Miner, Builder, Gathering, Zones, Construction, None }; +enum class WorkPanel { Farmer, Woodcutter, Miner, Builder, Gathering, Zones, Construction, Houses, Carpenter, None }; WorkPanel work_panel = WorkPanel::None; -enum class WorkIcon { Berries, Field, Flax, Tree, Pickaxe, Hammer, Loom, Resident, Bed, Wood, Stone, Crate, Pantry, Move, Demolish, Priority }; +WorkPanel house_list_parent = WorkPanel::Construction; +enum class WorkIcon { Berries, Field, Flax, Tree, Pickaxe, Hammer, Loom, Resident, Bed, Wood, Stone, Crate, Pantry, Move, Demolish, Priority, House, Back }; struct WorkChoice { int command; const wchar_t* title; WorkIcon icon; int width; PlacementMode mode = PlacementMode::None; + settlement::RoomTemplate layout = settlement::RoomTemplate::Empty; }; constexpr std::array farmer_choices = { WorkChoice{forage_action_id, L"Сбор ягод", WorkIcon::Berries, 113, PlacementMode::Foraging}, @@ -145,6 +160,9 @@ constexpr std::array woodcutter_choices = { constexpr std::array miner_choices = { WorkChoice{mine_id, L"Шахта", WorkIcon::Pickaxe, 98, PlacementMode::Mine}, }; +constexpr std::array carpenter_choices = { + WorkChoice{craft_door_id, L"Изготовить дверь", WorkIcon::Wood, 190}, +}; constexpr std::array builder_choices = { WorkChoice{cabin_button_id, L"Спальное место", WorkIcon::Bed, 153, PlacementMode::Building}, WorkChoice{loom_id, L"Ткацкий станок", WorkIcon::Loom, 149, PlacementMode::Loom}, @@ -153,13 +171,29 @@ constexpr std::array builder_choices = { WorkChoice{move_id, L"Перенести", WorkIcon::Move, 108, PlacementMode::Move}, WorkChoice{demolish_id, L"Снести", WorkIcon::Demolish, 90, PlacementMode::Demolish}, WorkChoice{room_tool_id, L"Комната", WorkIcon::Hammer, 116, PlacementMode::Room}, + WorkChoice{furnished_room_tool_id, L"Готовые дома", WorkIcon::House, 158}, }; 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[6], builder_choices[4], builder_choices[5]}; + builder_choices[6], builder_choices[7], builder_choices[4], builder_choices[5]}; +constexpr std::array house_choices = { + WorkChoice{house_list_back_id, L"Назад", WorkIcon::Back, 93}, + WorkChoice{first_house_tool_id, L"Дом врача", WorkIcon::House, 155, + PlacementMode::Room, settlement::RoomTemplate::Doctor}, + WorkChoice{first_house_tool_id + 1, L"Дом шахтёра", WorkIcon::House, 175, + PlacementMode::Room, settlement::RoomTemplate::Miner}, + WorkChoice{first_house_tool_id + 2, L"Дом ткача", WorkIcon::House, 155, + PlacementMode::Room, settlement::RoomTemplate::Weaver}, +}; +constexpr const wchar_t* house_contents[] = { + L"Деревянная кровать и аптечный шкаф", + L"Каменная кровать и стойка с инструментами", + L"Деревянная кровать и ткацкий станок", +}; +std::array house_artwork{}; struct DockSection { WorkPanel panel; const wchar_t* title; @@ -182,6 +216,7 @@ constexpr std::array role_choices = { RoleChoice{Profession::Woodcutter, L"Лесоруб", WorkIcon::Tree}, RoleChoice{Profession::Miner, L"Шахтёр", WorkIcon::Pickaxe}, RoleChoice{Profession::Builder, L"Строитель", WorkIcon::Hammer}, + RoleChoice{Profession::Carpenter, L"Плотник", WorkIcon::Wood}, }; struct ResidentRow { settlement::AgentId id; @@ -203,6 +238,14 @@ std::optional selected_bed_base; std::vector blueprint; std::vector room_blueprints; std::optional room_anchor; +settlement::RoomTemplate selected_room_template = settlement::RoomTemplate::Empty; +std::optional preferred_room_entrance; +struct RoomDraftMove { + std::size_t index; + settlement::GridPosition grabbed_cell; + settlement::RoomSide entrance; +}; +std::optional room_draft_move; std::optional move_source; settlement::viewer::MapCamera camera; struct CameraDrag { @@ -344,6 +387,14 @@ void draw_work_icon(HDC dc, WorkIcon icon, int x, int y, int extent = 17) { box(2, 8, 12, 11, metal); box(2, 13, 8, 16, metal); break; + case WorkIcon::House: + box(4, 8, 14, 16, wood); + shape({{1, 9}, {9, 2}, {17, 9}}, berry); + box(7, 10, 11, 16, metal); + break; + case WorkIcon::Back: + shape({{1, 9}, {7, 3}, {7, 7}, {16, 7}, {16, 11}, {7, 11}, {7, 15}}, metal); + break; } RestoreDC(dc, state); } @@ -393,12 +444,17 @@ void layout_scene(HWND window) { if (!scene_window) return; if (showing_title || !graphics.ready()) { ShowWindow(scene_window, SW_HIDE); + ShowWindow(building_view_button, SW_HIDE); return; } RECT client{}; GetClientRect(window, &client); SetWindowPos(scene_window, HWND_BOTTOM, 0, map_top, client.right, std::max(0, static_cast(client.bottom) - map_top - dock_layout.height), SWP_NOACTIVATE | SWP_SHOWWINDOW); + const int margin = dock_pixels(10); + const int width = dock_pixels(184); + SetWindowPos(building_view_button, HWND_TOP, client.right - width - margin, map_top + margin, + width, dock_pixels(32), SWP_NOACTIVATE | SWP_SHOWWINDOW); } void update_camera_drag(POINT point) { @@ -475,6 +531,8 @@ std::span work_choices() { case WorkPanel::Gathering: return gathering_choices; case WorkPanel::Zones: return zones_choices; case WorkPanel::Construction: return construction_choices; + case WorkPanel::Houses: return house_choices; + case WorkPanel::Carpenter: return carpenter_choices; case WorkPanel::None: return {}; } return {}; @@ -539,7 +597,7 @@ DockLayout measure_command_dock(int width, int height, int scale, bool position_ const bool bed = choice.command == cabin_button_id; tools[index] = {work_choice_buttons[index], choice.width + (bed ? 32 : 14), bed && shows_bed_choices()}; } - const int tool_height = pixels(compact ? 30 : 36); + const int tool_height = pixels(work_panel == WorkPanel::Houses ? 44 : (compact ? 30 : 36)); if (choices.empty()) bottom -= tool_height + gap; else layout_rows(std::span(tools).first(choices.size()), tool_height); @@ -558,7 +616,7 @@ void update_dock_font() { const auto face = reinterpret_cast(font ? font : GetStockObject(DEFAULT_GUI_FONT)); const auto set_font = [&](HWND button) { SendMessageW(button, WM_SETFONT, face, TRUE); }; for (const auto button : {priority_button, work_list_button, residents_button, wood_bed_button, - stone_bed_button, build_blueprint_button, clear_blueprint_button}) set_font(button); + stone_bed_button, build_blueprint_button, clear_blueprint_button, building_view_button}) set_font(button); for (const auto button : dock_section_buttons) set_font(button); for (const auto button : work_choice_buttons) set_font(button); if (dock_font) DeleteObject(dock_font); @@ -639,6 +697,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())); ShowWindow(button, SW_SHOWNA); } for (const auto button : dock_section_buttons) InvalidateRect(button, nullptr, FALSE); @@ -649,7 +708,8 @@ void set_work_panel(HWND window, WorkPanel panel) { InvalidateRect(window, &row, FALSE); } -void draw_icon_button(const DRAWITEMSTRUCT& item, WorkIcon icon, bool active, bool dock = false, int icon_width = 17) { +void draw_icon_button(const DRAWITEMSTRUCT& item, WorkIcon icon, bool active, bool dock = false, + int icon_width = 17, HICON artwork = nullptr) { const bool disabled = (item.itemState & ODS_DISABLED) != 0; const bool pressed = (item.itemState & ODS_SELECTED) != 0; const auto dc = item.hDC; @@ -681,7 +741,9 @@ void draw_icon_button(const DRAWITEMSTRUCT& item, WorkIcon icon, bool active, bo 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, icon_width); + const int icon_x = left + offset, icon_y = (box.top + box.bottom - icon_width) / 2 + offset; + if (artwork) DrawIconEx(dc, icon_x, icon_y, artwork, icon_width, icon_width, 0, nullptr, DI_NORMAL); + else draw_work_icon(dc, icon, icon_x, icon_y, icon_width); RECT caption_box{left + icon_width + gap + offset, box.top + offset, box.right - 1, box.bottom + offset}; const auto previous_mode = SetBkMode(dc, TRANSPARENT); @@ -708,15 +770,24 @@ bool draw_toolbar_button(const DRAWITEMSTRUCT& item) { case priority_button_id: return draw(WorkIcon::Priority); case build_blueprint_id: return draw(WorkIcon::Hammer, has_blueprint()); case clear_blueprint_id: return draw(WorkIcon::Demolish); + case building_view_id: return draw(WorkIcon::House, building_view != BuildingView::Full); } 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)]; - return draw(section.icon, work_panel == section.panel); + return draw(section.icon, work_panel == section.panel || + (work_panel == WorkPanel::Houses && section.panel == WorkPanel::Construction)); } 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)]; - return draw(choice.icon, placement_mode == choice.mode); + const bool active = choice.mode != PlacementMode::None && placement_mode == choice.mode && + (choice.mode != PlacementMode::Room || selected_room_template == choice.layout); + if (choice.layout != settlement::RoomTemplate::Empty) { + const auto artwork = house_artwork[static_cast(choice.layout) - 1]; + draw_icon_button(item, choice.icon, active, true, dock_pixels(34), artwork); + return true; + } + return draw(choice.icon, active); } bool can_give_orders() { @@ -795,6 +866,7 @@ void update_status() { std::uint64_t berries = 0; std::uint64_t cloth = 0; std::uint64_t flax = 0; + std::uint64_t doors = 0; for (const settlement::Storage& storage : world->storages()) { wood += storage.item_count(settlement::ItemType::Wood); stone += storage.item_count(settlement::ItemType::Stone); @@ -803,11 +875,13 @@ void update_status() { berries += storage.item_count(settlement::ItemType::Berries); cloth += storage.item_count(settlement::ItemType::Cloth); flax += storage.item_count(settlement::ItemType::Flax); + doors += storage.available_item_count(settlement::ItemType::WoodenDoor); } 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(doors) + L" Ход: " + std::to_wstring(world->tick()); SetWindowTextW(status_label, text.c_str()); const bool scenario = world->scenario_active(); @@ -818,7 +892,7 @@ void update_status() { for (const HWND button : dock_section_buttons) EnableWindow(button, can_play); EnableWindow(priority_button, scenario && can_play); EnableWindow(work_list_button, can_play); - EnableWindow(build_blueprint_button, has_blueprint() && can_play); + EnableWindow(build_blueprint_button, has_blueprint() && can_play && !room_draft_move); const wchar_t* priority = L"Равный приоритет"; if (world->work_priority() == settlement::WorkPriority::FoodFirst) priority = L"Сначала еда"; else if (world->work_priority() == settlement::WorkPriority::BuildingFirst) priority = L"Сначала стройка"; @@ -871,7 +945,7 @@ void update_blueprint_controls(HWND window) { const int visibility = shows_blueprint_actions() ? SW_SHOWNA : SW_HIDE; ShowWindow(build_blueprint_button, visibility); ShowWindow(clear_blueprint_button, visibility); - EnableWindow(build_blueprint_button, has_blueprint() && can_give_orders()); + EnableWindow(build_blueprint_button, has_blueprint() && can_give_orders() && !room_draft_move); EnableWindow(clear_blueprint_button, has_blueprint()); layout_command_dock(window); } @@ -881,6 +955,9 @@ void set_placement_mode(HWND window, PlacementMode mode, const wchar_t* message selected_bed_base.reset(); move_source.reset(); room_anchor.reset(); + room_draft_move.reset(); + preferred_room_entrance.reset(); + selected_room_template = settlement::RoomTemplate::Empty; hover_cell.reset(); placement_message = message; update_bed_choices(); @@ -893,6 +970,7 @@ void clear_blueprints() { blueprint.clear(); room_blueprints.clear(); room_anchor.reset(); + room_draft_move.reset(); } void toggle_work_panel(HWND window, WorkPanel panel) { @@ -1305,22 +1383,43 @@ bool valid_edit_cell(settlement::GridPosition cell) { return false; } +bool has_carpenter() { + return std::any_of(world->agents().begin(), world->agents().end(), + [](const auto& agent) { return agent.profession == Profession::Carpenter; }); +} + auto room_at(settlement::GridPosition cell) { return std::find_if(room_blueprints.begin(), room_blueprints.end(), [cell](const auto& room) { return room.contains(cell); }); } -bool room_fits_blueprint(const settlement::RoomPlan& room) { +bool room_fits_blueprint(const settlement::RoomPlan& room, const settlement::RoomPlan* ignored = nullptr) { return std::none_of(blueprint.begin(), blueprint.end(), [&](const auto& part) { return room.contains(part.cell); }) && std::none_of(room_blueprints.begin(), room_blueprints.end(), [&](const auto& other) { - return room.first.x <= other.last.x && room.last.x >= other.first.x && + return &other != ignored && room.first.x <= other.last.x && room.last.x >= other.first.x && room.first.y <= other.last.y && room.last.y >= other.first.y; }); } settlement::RoomPlan preview_room(settlement::GridPosition cell) { - auto room = settlement::make_room_plan(*room_anchor, cell); + if (room_draft_move) { + auto room = room_blueprints[room_draft_move->index]; + const int x = cell.x - room_draft_move->grabbed_cell.x; + const int y = cell.y - room_draft_move->grabbed_cell.y; + room.first = {room.first.x + x, room.first.y + y}; + room.last = {room.last.x + x, room.last.y + y}; + room.entrance = room_draft_move->entrance; + return room; + } + constexpr int edge = settlement::furnished_room_size - 1; + auto room = room_anchor ? settlement::make_room_plan(*room_anchor, cell) : + settlement::RoomPlan{cell, {cell.x + edge, cell.y + edge}}; + room.layout = selected_room_template; + if (preferred_room_entrance) { + room.entrance = *preferred_room_entrance; + return room; + } if (room.valid_size() && !world->can_place_room(room)) { for (const auto side : {settlement::RoomSide::North, settlement::RoomSide::East, settlement::RoomSide::West}) { room.entrance = side; @@ -1331,10 +1430,36 @@ settlement::RoomPlan preview_room(settlement::GridPosition cell) { return room; } -void edit_room_blueprint(HWND window, settlement::GridPosition cell) { +void rotate_room_preview(HWND window, int direction) { + using settlement::RoomSide; + const auto next = [direction](RoomSide side) { + return static_cast((static_cast(side) + direction + 4) % 4); + }; + if (room_draft_move) { + room_draft_move->entrance = next(room_draft_move->entrance); + } else { + const auto side = hover_cell ? preview_room(*hover_cell).entrance : + preferred_room_entrance.value_or(RoomSide::South); + preferred_room_entrance = next(side); + } + placement_message.clear(); + invalidate_scene(window); +} + +void edit_room_blueprint(HWND window, settlement::GridPosition cell, bool shift) { if (!can_give_orders()) return; using settlement::RoomSide; - if (room_anchor) { + if (room_draft_move) { + auto& original = room_blueprints[room_draft_move->index]; + const auto room = preview_room(cell); + if (world->can_place_room(room) && room_fits_blueprint(room, &original)) { + original = room; + room_draft_move.reset(); + placement_message.clear(); + } else { + placement_message = L"Здесь дом не помещается. Выберите другую площадку или отмените перенос."; + } + } else if (room_anchor) { const auto room = preview_room(cell); if (!room.valid_size()) { placement_message = L"Ширина и длина комнаты должны быть от 3 до 12 клеток."; @@ -1345,23 +1470,40 @@ void edit_room_blueprint(HWND window, settlement::GridPosition cell) { room_anchor.reset(); placement_message.clear(); } - } else if (const auto room = room_at(cell); room != room_blueprints.end()) { - auto candidate = *room; - if (cell.y == room->first.y) candidate.entrance = RoomSide::North; - else if (cell.y == room->last.y) candidate.entrance = RoomSide::South; - else if (cell.x == room->first.x) candidate.entrance = RoomSide::West; - else if (cell.x == room->last.x) candidate.entrance = RoomSide::East; + } else if (const auto draft = room_at(cell); draft != room_blueprints.end()) { + if (shift) { + room_draft_move = RoomDraftMove{static_cast(draft - room_blueprints.begin()), + cell, draft->entrance}; + hover_cell = cell; + placement_message.clear(); + update_blueprint_controls(window); + invalidate_scene(window); + return; + } + auto candidate = *draft; + if (cell.y == draft->first.y) candidate.entrance = RoomSide::North; + else if (cell.y == draft->last.y) candidate.entrance = RoomSide::South; + else if (cell.x == draft->first.x) candidate.entrance = RoomSide::West; + else if (cell.x == draft->last.x) candidate.entrance = RoomSide::East; else { placement_message = L"Щёлкните по краю комнаты, чтобы перенести вход."; invalidate_scene(window); return; } if (world->can_place_room(candidate)) { - *room = candidate; + *draft = candidate; placement_message.clear(); } else { placement_message = L"С этой стороны нет свободного прохода."; } + } else if (selected_room_template != settlement::RoomTemplate::Empty) { + const auto room = preview_room(cell); + if (world->can_place_room(room) && room_fits_blueprint(room)) { + room_blueprints.push_back(room); + placement_message.clear(); + } else { + placement_message = L"Для дома нужна свободная площадка 4×4 и проход снаружи."; + } } else { room_anchor = cell; placement_message.clear(); @@ -1401,12 +1543,12 @@ void edit_blueprint(HWND window, settlement::GridPosition cell) { } void submit_blueprint(HWND window) { - if (!world || !has_blueprint() || !can_give_orders()) return; + if (!world || !has_blueprint() || room_draft_move || !can_give_orders()) return; using settlement::CommandKind; using settlement::RecipeId; const auto rooms_sent = std::erase_if(room_blueprints, [](const auto& room) { return world->can_place_room(room) && submit_command(CommandKind::PlaceRoom, room.first, - static_cast(room.entrance), room.last) == settlement::CommandStatus::Accepted; + room.placement_value(), room.last) == settlement::CommandStatus::Accepted; }); const auto objects_sent = std::erase_if(blueprint, [](const auto& part) { switch (part.recipe) { @@ -1435,6 +1577,9 @@ void submit_blueprint(HWND window) { } else { placement_message = (lan.is_guest() ? L"Передано хозяину мест: " : L"Утверждено мест: ") + count + L"."; } + if (rooms_sent != 0 && world->scenario_active() && !has_carpenter()) { + placement_message += L" Деревянные двери изготавливает плотник. Его можно назначить в списке «Жители»."; + } update_blueprint_controls(window); update_status(); invalidate_scene(window); @@ -1506,9 +1651,11 @@ void edit_at_cell(HWND window, settlement::GridPosition cell) { 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); + for (int id = farmer_menu_id; id <= builder_menu_id; ++id) { + AppendMenuW(menu, MF_STRING, static_cast(id), + role_choices[static_cast(id - farmer_menu_id + 1)].title); } + AppendMenuW(menu, MF_STRING, carpenter_menu_id, L"Плотник"); AppendMenuW(menu, MF_SEPARATOR, 0, nullptr); AppendMenuW(menu, MF_STRING, residents_button_id, L"Жители…\tC"); return menu; @@ -1546,7 +1693,7 @@ LRESULT CALLBACK resident_roster_proc(HWND window, UINT message, WPARAM wparam, }; 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); + 16, 16, 282, 345, WS_EX_CLIENTEDGE); ListView_SetExtendedListViewStyle(roster.list, LVS_EX_FULLROWSELECT | LVS_EX_DOUBLEBUFFER); wchar_t resident_header[] = L"Житель"; wchar_t profession_header[] = L"Профессия"; @@ -1566,10 +1713,10 @@ LRESULT CALLBACK resident_roster_proc(HWND window, UINT message, WPARAM wparam, 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); + 316, 252, 234, 30); + roster.notice = control(L"STATIC", L"", 0, SS_LEFT, 316, 290, 234, 44); const auto close = control(L"BUTTON", L"Закрыть", IDCANCEL, WS_TABSTOP | BS_PUSHBUTTON, - 447, 301, 103, 26); + 447, 335, 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; @@ -1660,7 +1807,7 @@ void show_resident_roster(HWND owner) { 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}; + RECT area{0, 0, 566, 377}; AdjustWindowRectEx(&area, style, FALSE, ex_style); RECT owner_rect{}; GetWindowRect(owner, &owner_rect); @@ -1709,7 +1856,7 @@ 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::Flax, L"лён"}, {ItemType::WoodenDoor, L"деревянная дверь"} }; std::wstring cargo; for (const auto& [type, name] : items) { @@ -1723,6 +1870,11 @@ std::wstring resident_details() { 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->production_index != settlement::no_entity_index && + world->production_orders()[resident->production_index].recipe == settlement::RecipeId::CraftWoodenDoor) { + 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) { const auto& site = world->resource_nodes()[resident->resource_node_index]; @@ -1759,7 +1911,8 @@ std::wstring blueprint_details() { const wchar_t* name; }; constexpr Material materials[] = {{ItemType::Wood, L"дерево"}, {ItemType::Stone, L"камень"}, - {ItemType::Cloth, L"ткань"}, {ItemType::Plank, L"доски"}, {ItemType::StoneBlock, L"каменные блоки"}}; + {ItemType::Cloth, L"ткань"}, {ItemType::Plank, L"доски"}, {ItemType::StoneBlock, L"каменные блоки"}, + {ItemType::WoodenDoor, L"готовые двери"}}; std::array totals{}; for (const auto& part : blueprint) { for (const auto& material : world->construction_materials(part.recipe, part.base)) { @@ -1769,10 +1922,18 @@ std::wstring blueprint_details() { for (const auto& room : room_blueprints) { for (int y = room.first.y; y <= room.last.y; ++y) { for (int x = room.first.x; x <= room.last.x; ++x) { - const auto ingredients = world->construction_materials(room.recipe_at({x, y}), settlement::BedBase::Wood); + const auto recipe = world->room_construction_recipe(room.recipe_at({x, y})); + const auto ingredients = world->construction_materials(recipe, settlement::BedBase::Wood); for (const auto& item : ingredients) totals[static_cast(item.type)] += item.count; } } + if (const auto furnishings = room.furnishings()) { + for (const auto& part : *furnishings) { + for (const auto& item : world->construction_materials(part.recipe, part.bed_base)) { + totals[static_cast(item.type)] += item.count; + } + } + } } std::wstring text = L"Чертёж · объектов " + std::to_wstring(blueprint.size() + room_blueprints.size()); for (const auto& material : materials) { @@ -1829,18 +1990,41 @@ void draw_world(HDC dc, int width, int height) { } else if (placement_mode == PlacementMode::Demolish) { hint = L"Щёлкните по объекту, чтобы снести его. Правая кнопка — отмена."; } else if (placement_mode == PlacementMode::Room) { - hint = room_anchor ? L"Укажите противоположный угол комнаты." : - L"Укажите первый угол. Щелчок по краю чертежа меняет вход, правый щелчок удаляет комнату."; + if (room_draft_move) { + hint = L"Щёлкните по новой площадке. R поворачивает дом, правый щелчок отменяет перенос."; + } else if (selected_room_template != settlement::RoomTemplate::Empty) { + hint = L"Выберите площадку 4×4. R поворачивает дом, Shift + щелчок переносит чертёж."; + } else { + hint = room_anchor ? L"Укажите противоположный угол комнаты. R меняет сторону входа." : + L"Укажите первый угол. Щелчок по краю меняет вход, Shift + щелчок переносит чертёж."; + } } else if (is_blueprint_tool()) { hint = shows_bed_choices() && !selected_bed_base ? L"Выберите «Дерево» или «Камень» под кнопкой «Спальное место»." : L"Щёлкните по клетке, чтобы добавить объект или убрать его из чертежа."; + } else if (work_panel == WorkPanel::Houses) { + hint = L"Выберите проект дома для площадки 4×4."; + } else if (work_panel == WorkPanel::Carpenter) { + hint = L"Плотник делает дверь из двух единиц дерева. При подтверждении дома заказ создаётся автоматически."; } const auto previous_font = dock_font ? SelectObject(dc, dock_font) : nullptr; const int margin = dock_pixels(12); RECT legend{margin, dock_layout.hint_top, width - margin, dock_layout.hint_top + dock_layout.line_height}; DrawTextW(dc, hint, -1, &legend, DT_LEFT | DT_VCENTER | DT_SINGLELINE | DT_END_ELLIPSIS); - const auto details = has_blueprint() ? blueprint_details() : resident_details(); + auto details = has_blueprint() ? blueprint_details() : + selected_room_template != settlement::RoomTemplate::Empty + ? std::wstring(house_contents[static_cast(selected_room_template) - 1]) + : resident_details(); + 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; + }); + details = L"Заказов на двери " + std::to_wstring(orders); + if (!has_carpenter()) { + details += L" Назначьте плотника в списке «Жители»."; + } + } SetTextColor(dc, color(190, 201, 178)); RECT inspector{margin, legend.bottom, width - margin, legend.bottom + dock_layout.line_height}; DrawTextW(dc, details.c_str(), -1, &inspector, DT_LEFT | DT_VCENTER | DT_SINGLELINE | DT_END_ELLIPSIS); @@ -1852,11 +2036,14 @@ settlement::viewer::SceneView scene_view(int width, int height) { const auto scale = camera.scale(); const auto cursor = !shows_bed_choices() || selected_bed_base ? hover_cell : std::nullopt; std::optional room_preview; - if (cursor && room_anchor && placement_mode == PlacementMode::Room) { + if (cursor && placement_mode == PlacementMode::Room && + (room_draft_move || room_anchor || (selected_room_template != settlement::RoomTemplate::Empty && + room_at(*cursor) == room_blueprints.end()))) { const auto room = preview_room(*cursor); if (room.valid_size()) room_preview = room; } - const bool valid_cursor = room_preview ? world->can_place_room(*room_preview) && room_fits_blueprint(*room_preview) + const auto ignore = room_draft_move ? &room_blueprints[room_draft_move->index] : nullptr; + const bool valid_cursor = room_preview ? world->can_place_room(*room_preview) && room_fits_blueprint(*room_preview, ignore) : cursor && (placement_mode == PlacementMode::Room ? !room_anchor : valid_edit_cell(*cursor)); const auto preview = valid_cursor && is_blueprint_tool() && cursor && room_at(*cursor) == room_blueprints.end() && @@ -1865,7 +2052,8 @@ settlement::viewer::SceneView scene_view(int width, int height) { return {width, height, static_cast(width / 2 * scale + pan.x), static_cast(map_origin_y * scale + pan.y - map_top), static_cast(scale), tile_width / 2.f, tile_height / 2.f, - cursor, valid_cursor, move_source, selected_resident, blueprint, preview, room_blueprints, room_preview}; + cursor, valid_cursor, move_source, selected_resident, blueprint, preview, room_blueprints, room_preview, + building_view, room_draft_move ? std::optional(room_draft_move->index) : std::nullopt}; } LRESULT CALLBACK scene_window_proc(HWND window, UINT message, WPARAM wparam, LPARAM lparam) { @@ -2159,6 +2347,12 @@ LRESULT CALLBACK window_proc(HWND window, UINT message, WPARAM wparam, LPARAM lp stone_bed_button = button(stone_bed_button_id, 0, 90, L"Камень", BS_OWNERDRAW, 0); build_blueprint_button = button(build_blueprint_id, 0, 180, L"Начать стройку", BS_OWNERDRAW, 0); clear_blueprint_button = button(clear_blueprint_id, 0, 180, L"Очистить чертёж", BS_OWNERDRAW, 0); + building_view_button = button(building_view_id, 0, 184, building_view_labels[0], BS_OWNERDRAW); + constexpr int icons[] = {IDI_DOCTOR_HOUSE, IDI_MINER_HOUSE, IDI_WEAVER_HOUSE}; + for (std::size_t index = 0; index < house_artwork.size(); ++index) { + house_artwork[index] = reinterpret_cast(LoadImageW(instance, MAKEINTRESOURCEW(icons[index]), + IMAGE_ICON, 0, 0, LR_SHARED)); + } 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); @@ -2221,6 +2415,20 @@ LRESULT CALLBACK window_proc(HWND window, UINT message, WPARAM wparam, LPARAM lp toggle_work_panel(window, panel); return 0; } + if (LOWORD(wparam) == carpenter_menu_id && HIWORD(wparam) == BN_CLICKED) { + toggle_work_panel(window, WorkPanel::Carpenter); + update_status(); + return 0; + } + if (LOWORD(wparam) == craft_door_id && HIWORD(wparam) == BN_CLICKED && + world && world->carpenter_workshop() && can_give_orders()) { + if (send_command(settlement::CommandKind::CraftDoor)) { + placement_message = lan.is_guest() ? L"Заказ на дверь отправлен." : L"Дверь заказана в мастерской."; + } + SetFocus(window); + invalidate_scene(window); + return 0; + } if (LOWORD(wparam) >= first_dock_section_id && static_cast(LOWORD(wparam) - first_dock_section_id) < dock_sections.size() && HIWORD(wparam) == BN_CLICKED) { @@ -2258,6 +2466,14 @@ LRESULT CALLBACK window_proc(HWND window, UINT message, WPARAM wparam, LPARAM lp invalidate_scene(window); return 0; } + if (LOWORD(wparam) == building_view_id && HIWORD(wparam) == BN_CLICKED) { + const auto index = (static_cast(building_view) + 1) % std::size(building_view_labels); + building_view = static_cast(index); + SetWindowTextW(building_view_button, building_view_labels[index]); + SetFocus(window); + invalidate_scene(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); @@ -2265,7 +2481,33 @@ LRESULT CALLBACK window_proc(HWND window, UINT message, WPARAM wparam, LPARAM lp return 0; } if (LOWORD(wparam) == room_tool_id && HIWORD(wparam) == BN_CLICKED && world && can_give_orders()) { - set_placement_mode(window, placement_mode == PlacementMode::Room ? PlacementMode::None : PlacementMode::Room); + const bool editing_empty_room = placement_mode == PlacementMode::Room && + selected_room_template == settlement::RoomTemplate::Empty; + set_placement_mode(window, editing_empty_room ? PlacementMode::None : PlacementMode::Room); + SetFocus(window); + return 0; + } + if (LOWORD(wparam) == furnished_room_tool_id && HIWORD(wparam) == BN_CLICKED && + world && world->scenario_active() && can_give_orders()) { + house_list_parent = work_panel; + set_placement_mode(window, PlacementMode::None); + set_work_panel(window, WorkPanel::Houses); + SetFocus(window); + return 0; + } + if (LOWORD(wparam) == house_list_back_id && HIWORD(wparam) == BN_CLICKED && work_panel == WorkPanel::Houses) { + set_placement_mode(window, PlacementMode::None); + set_work_panel(window, house_list_parent); + SetFocus(window); + return 0; + } + if (LOWORD(wparam) >= first_house_tool_id && LOWORD(wparam) < first_house_tool_id + house_artwork.size() && + HIWORD(wparam) == BN_CLICKED && work_panel == WorkPanel::Houses && can_give_orders()) { + const auto layout = house_choices[LOWORD(wparam) - first_house_tool_id + 1].layout; + const bool already_selected = placement_mode == PlacementMode::Room && selected_room_template == layout; + set_placement_mode(window, already_selected ? PlacementMode::None : PlacementMode::Room); + if (!already_selected) selected_room_template = layout; + invalidate_work_choices(); SetFocus(window); return 0; } @@ -2378,7 +2620,7 @@ LRESULT CALLBACK window_proc(HWND window, UINT message, WPARAM wparam, LPARAM lp } if (world && is_blueprint_tool()) { if (const auto cell = map_cell(client, point)) { - if (placement_mode == PlacementMode::Room) edit_room_blueprint(window, *cell); + if (placement_mode == PlacementMode::Room) edit_room_blueprint(window, *cell, (wparam & MK_SHIFT) != 0); else edit_blueprint(window, *cell); } return 0; @@ -2398,6 +2640,13 @@ LRESULT CALLBACK window_proc(HWND window, UINT message, WPARAM wparam, LPARAM lp } case WM_RBUTTONDOWN: if (placement_mode == PlacementMode::Room) { + if (room_draft_move) { + room_draft_move.reset(); + placement_message.clear(); + update_blueprint_controls(window); + invalidate_scene(window); + return 0; + } if (room_anchor) { room_anchor.reset(); placement_message.clear(); @@ -2425,6 +2674,11 @@ LRESULT CALLBACK window_proc(HWND window, UINT message, WPARAM wparam, LPARAM lp break; case WM_KEYDOWN: if (showing_title) break; + if (placement_mode == PlacementMode::Room && + (wparam == 'R' || wparam == VK_OEM_COMMA || wparam == VK_OEM_PERIOD)) { + if ((lparam & (1L << 30)) == 0) rotate_room_preview(window, wparam == VK_OEM_COMMA ? -1 : 1); + return 0; + } 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 : @@ -2465,8 +2719,8 @@ LRESULT CALLBACK window_proc(HWND window, UINT message, WPARAM wparam, LPARAM lp using settlement::RecipeId; const bool bed = rejection->kind == CommandKind::PlaceBed; if (rejection->kind == CommandKind::PlaceRoom) { - const settlement::RoomPlan room{rejection->cell, rejection->destination, - static_cast(rejection->value)}; + const auto room = settlement::RoomPlan::from_placement( + rejection->cell, rejection->destination, rejection->value); if (room.valid_size() && std::none_of(room_blueprints.begin(), room_blueprints.end(), [&](const auto& other) { return other.first == room.first && other.last == room.last; })) { room_blueprints.push_back(room); diff --git a/build.ps1 b/build.ps1 index f27b088..7422c22 100644 --- a/build.ps1 +++ b/build.ps1 @@ -1,59 +1,49 @@ param( [ValidateSet('Debug', 'Release', 'RelWithDebInfo')] - [string]$Configuration = 'Release' + [string]$Configuration = 'Release', + [string]$Msys2Root = $env:SETTLEMENT_MSYS2_ROOT ) $ErrorActionPreference = 'Stop' -$projectRoot = Split-Path -Parent $MyInvocation.MyCommand.Path -$toolRoot = Join-Path $projectRoot '.tools\toolchain' - -if (-not (Test-Path -LiteralPath $toolRoot -PathType Container)) { - throw 'Portable tools are missing. Run .\setup-toolchain.ps1 first.' -} - -$cmakeExe = Get-ChildItem -LiteralPath (Join-Path $toolRoot 'cmake') -Filter 'cmake.exe' -File -Recurse -ErrorAction SilentlyContinue | Select-Object -First 1 -$clangxxExe = Get-ChildItem -LiteralPath (Join-Path $toolRoot 'llvm-mingw') -Filter 'clang++.exe' -File -Recurse -ErrorAction SilentlyContinue | Select-Object -First 1 -$ninjaExe = Get-ChildItem -LiteralPath (Join-Path $toolRoot 'llvm-mingw') -Filter 'ninja.exe' -File -Recurse -ErrorAction SilentlyContinue | Select-Object -First 1 -$makeExe = Get-ChildItem -LiteralPath (Join-Path $toolRoot 'llvm-mingw') -Filter 'mingw32-make.exe' -File -Recurse -ErrorAction SilentlyContinue | Select-Object -First 1 - -if ($null -eq $cmakeExe -or $null -eq $clangxxExe) { - throw 'CMake or Clang is missing. Run .\setup-toolchain.ps1 again.' -} - -$compilerBin = Split-Path -Parent $clangxxExe.FullName -$cmakeBin = Split-Path -Parent $cmakeExe.FullName -$env:Path = "$compilerBin;$cmakeBin;$env:Path" -$buildDirectory = Join-Path $projectRoot 'build' -$generatorArguments = @() -if ($null -ne $ninjaExe) { - $generatorArguments = @('-G', 'Ninja', "-DCMAKE_MAKE_PROGRAM=$($ninjaExe.FullName)") -} elseif ($null -ne $makeExe) { - $generatorArguments = @('-G', 'MinGW Makefiles', "-DCMAKE_MAKE_PROGRAM=$($makeExe.FullName)") -} else { - throw 'The LLVM-MinGW archive contains neither Ninja nor mingw32-make.' -} - -& $cmakeExe.FullName -S $projectRoot -B $buildDirectory @generatorArguments -U CMAKE_C_COMPILER ` - "-DCMAKE_CXX_COMPILER=$($clangxxExe.FullName)" ` - "-DCMAKE_BUILD_TYPE=$Configuration" -if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } - -& $cmakeExe.FullName --build $buildDirectory --parallel --config $Configuration -if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } - -# LLVM-MinGW links libc++ dynamically. Copy its runtime beside the executables -# so they can be launched from Explorer without editing the system PATH. -foreach ($runtimeName in @('libc++.dll', 'libunwind.dll')) { - $runtimeSource = Join-Path $compilerBin $runtimeName - if (-not (Test-Path -LiteralPath $runtimeSource -PathType Leaf)) { - throw "Required LLVM-MinGW runtime was not found: $runtimeSource" +$projectRoot = $PSScriptRoot +if (-not $Msys2Root) { $Msys2Root = Join-Path $projectRoot '.tools\toolchain\msys64' } +$bin = Join-Path $Msys2Root 'ucrt64\bin' +foreach ($tool in @('g++.exe', 'cmake.exe', 'ctest.exe', 'ninja.exe', 'windres.exe')) { + if (-not (Test-Path -LiteralPath (Join-Path $bin $tool) -PathType Leaf)) { + throw "MSYS2 UCRT64 tool missing: $tool. Run .\setup-toolchain.ps1." } - Copy-Item -LiteralPath $runtimeSource -Destination $buildDirectory -Force } +$bin = (Get-Item -LiteralPath $bin).FullName.Replace('\', '/') +$buildRoot = Join-Path $projectRoot 'build' +$buildDirectory = Join-Path $buildRoot 'msys2-ucrt64' +$previousPath = $env:Path +try { + $env:Path = "$bin;$previousPath" + $version = & (Join-Path $bin 'g++.exe') -dumpfullversion + if ($LASTEXITCODE -ne 0 -or $version -notmatch '^16(\.|$)') { + throw "MSYS2 UCRT64 GCC 16 is required. Found: $version" + } + Write-Output "Building with MSYS2 UCRT64 GCC $version" + $cmake = Join-Path $bin 'cmake.exe' + $options = @('-S', $projectRoot, '-B', $buildDirectory, '-G', 'Ninja', + "-DCMAKE_CXX_COMPILER=$bin/g++.exe", + "-DCMAKE_RC_COMPILER=$bin/windres.exe", + "-DCMAKE_MAKE_PROGRAM=$bin/ninja.exe", + "-DCMAKE_BUILD_TYPE=$Configuration", '-DBUILD_TESTING=ON') + & $cmake @options + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } + & $cmake --build $buildDirectory --parallel + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } + & (Join-Path $bin 'ctest.exe') --test-dir $buildDirectory --output-on-failure + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } -$ctestExe = Join-Path $cmakeBin 'ctest.exe' -if (-not (Test-Path -LiteralPath $ctestExe -PathType Leaf)) { - throw 'CTest was not found beside CMake.' + foreach ($runtime in @('libstdc++-6.dll', 'libgcc_s_seh-1.dll', 'libwinpthread-1.dll')) { + Copy-Item -LiteralPath (Join-Path $bin $runtime) -Destination $buildRoot -Force + } + foreach ($program in @('settlement_viewer', 'settlement_sim', 'settlement_colony_benchmark', + 'settlement_core_tests', 'settlement_lan_tests')) { + Copy-Item -LiteralPath (Join-Path $buildDirectory "$program.exe") -Destination $buildRoot -Force + } +} finally { + $env:Path = $previousPath } -& $ctestExe --test-dir $buildDirectory -C $Configuration --output-on-failure -exit $LASTEXITCODE diff --git a/docs/viewer.md b/docs/viewer.md index fcbc993..38815eb 100644 --- a/docs/viewer.md +++ b/docs/viewer.md @@ -20,7 +20,15 @@ powershell.exe -NoProfile -ExecutionPolicy Bypass -File .\build.ps1 Нажмите «Начать стройку», чтобы отправить выбранные места в работу, или «Очистить чертёж», чтобы убрать всю раскладку. Чертёж остаётся доступным при смене инструмента и через Esc. Это локальная раскладка текущей партии. В сохранение и общую колонию попадают утверждённые постройки. Если хозяин отклоняет клетку в кооперативе, она возвращается в чертёж. -В разделе «Строительство → Комната» укажите два противоположных угла прямоугольника от 3×3 до 12×12 клеток. По краям чертежа появятся стены, внутри — пол. Щёлкните по стороне, чтобы перенести вход в её середину. Правый щелчок по чертежу удаляет комнату. «Начать стройку» отправляет комнату в работу целиком. Поселенцы доставляют дерево и собирают пол, стены и проём по частям. На готовый пол можно поставить мебель. В этой версии маршруты жителей проходят через стены. +В разделе «Строительство → Комната» укажите два противоположных угла прямоугольника от 3×3 до 12×12 клеток. По краям чертежа появятся стены, внутри — пол. Щёлкните по стороне, чтобы перенести вход в её середину. Правый щелчок по чертежу удаляет комнату. «Начать стройку» отправляет комнату в работу целиком. Поселенцы доставляют дерево для пола и стен. На готовый пол можно поставить мебель. В этой версии маршруты жителей проходят через стены. + +В нижней панели «Строительство → Готовые дома» выберите проект 4×4 по картинке. В доме врача есть деревянная кровать и аптечный шкаф, в доме шахтёра — каменная кровать и стойка с инструментами, в доме ткача — деревянная кровать и рабочий ткацкий станок. Укажите площадку одним щелчком. Щелчок по краю переносит вход и переставляет мебель к противоположной стене. Смета включает мебель, а строители собирают её после укладки пола под ней. Аптечный шкаф и стойка служат обстановкой. + +Когда пол, стены и вход готовы, у комнаты появляется крыша. Кнопка «Вид» в правом верхнем углу карты переключает полный вид, вид без крыш и вид без стен и крыш. Последний режим оставляет открытыми полы и мебель. Следующее нажатие возвращает полный вид. + +Клавиша R поворачивает вход и раскладку готового дома ещё до размещения. Клавиши «,» и «.» поворачивают в обе стороны. Чтобы перенести уже поставленный чертёж, щёлкните по нему с Shift, затем укажите новое место. Правый щелчок во время переноса возвращает чертёж на старое место. + +Новые комнаты и готовые дома требуют деревянную дверь как предмет. Если на складе нет свободной двери, «Начать стройку» автоматически ставит заказ в мастерскую. В списке «Жители» назначьте плотника. Он заберёт со склада две единицы дерева, сделает дверь за верстаком и отнесёт её на склад. Строитель или разнорабочий заберёт оттуда готовую дверь и установит её. Чтобы заготовить двери заранее, откройте «Работы → Плотник» и выберите «Изготовить дверь». Жители отдельно доставляют основу, ткань для настила и ткань для подушки. Каждая деталь появляется после завершения своего этапа. Камень и ткань доступны в стартовых запасах. Жители получают по одному готовому месту. diff --git a/engine/include/settlement/core/world.hpp b/engine/include/settlement/core/world.hpp index 6748972..eb81080 100644 --- a/engine/include/settlement/core/world.hpp +++ b/engine/include/settlement/core/world.hpp @@ -6,6 +6,7 @@ #include #include #include +#include #include #include #include @@ -51,9 +52,10 @@ enum class ItemType : std::uint8_t { StoneBlock, Berries, Cloth, - Flax + Flax, + WoodenDoor }; -inline constexpr std::size_t item_type_count = static_cast(ItemType::Flax); +inline constexpr std::size_t item_type_count = static_cast(ItemType::WoodenDoor); enum class StorageKind : std::uint8_t { Materials, Pantry }; enum class ResourceSite : std::uint8_t { Natural, BerryField, TreePlot, Mine, FlaxField }; @@ -78,33 +80,68 @@ enum class RecipeId : std::uint8_t { BuildFloor, BuildWall, BuildDoorAlongX, - BuildDoorAlongY + BuildDoorAlongY, + BuildMedicineCabinet, + BuildMiningRack, + BuildLoom, + InstallDoorAlongX, + InstallDoorAlongY, + CraftWoodenDoor }; enum class BedBase : std::uint8_t { Wood, Stone }; enum class BedStage : std::uint8_t { Legacy, Foundation, Bedding, Pillow }; +constexpr RecipeId room_part_shape(RecipeId recipe) noexcept { + if (recipe == RecipeId::InstallDoorAlongX) return RecipeId::BuildDoorAlongX; + if (recipe == RecipeId::InstallDoorAlongY) return RecipeId::BuildDoorAlongY; + return recipe; +} + +constexpr bool is_room_part(RecipeId recipe) noexcept { + recipe = room_part_shape(recipe); + return recipe >= RecipeId::BuildFloor && recipe <= RecipeId::BuildDoorAlongY; +} + constexpr bool is_construction(RecipeId recipe) noexcept { return recipe == RecipeId::BuildCabin || recipe == RecipeId::BuildBed || - (recipe >= RecipeId::BuildFloor && recipe <= RecipeId::BuildDoorAlongY); + (recipe >= RecipeId::BuildFloor && recipe <= RecipeId::InstallDoorAlongY); +} + +constexpr bool delivers_materials(RecipeId recipe) noexcept { + return is_construction(recipe) || recipe == RecipeId::CraftWoodenDoor; } enum class RoomSide : std::uint8_t { North, East, South, West }; +enum class RoomTemplate : std::uint8_t { Empty, Doctor, Miner, Weaver }; +inline constexpr int furnished_room_size = 4; + +struct RoomFurnishing { + GridPosition position; + RecipeId recipe; + BedBase bed_base = BedBase::Wood; +}; + struct RoomPlan { GridPosition first; GridPosition last; RoomSide entrance = RoomSide::South; + RoomTemplate layout = RoomTemplate::Empty; [[nodiscard]] bool valid_size() const noexcept; [[nodiscard]] bool contains(GridPosition cell) const noexcept; [[nodiscard]] RecipeId recipe_at(GridPosition cell) const noexcept; + [[nodiscard]] std::optional> furnishings() const noexcept; + [[nodiscard]] std::uint8_t placement_value() const noexcept; + [[nodiscard]] static RoomPlan from_placement(GridPosition first, GridPosition last, std::uint8_t value) noexcept; }; [[nodiscard]] RoomPlan make_room_plan(GridPosition first, GridPosition last) noexcept; enum class WorkPriority : std::uint8_t { Balanced, FoodFirst, BuildingFirst }; -enum class Profession : std::uint8_t { Generalist = 0, Farmer, Woodcutter, Miner, Builder }; +enum class Profession : std::uint8_t { Generalist = 0, Farmer, Woodcutter, Miner, Builder, Carpenter }; 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 + PlaceStorage = 9, AssignProfession = 10, PlaceFlaxField = 11, PlaceLoom = 12, PlaceRoom = 13, + CraftDoor = 14 }; enum class CommandStatus : std::uint8_t { Accepted, Unavailable, Unauthorized, WrongSequence, InvalidTarget, Busy }; @@ -234,6 +271,13 @@ struct Storage { return 0; } + [[nodiscard]] std::uint32_t available_item_count(ItemType type) const noexcept { + for (const ItemStack& stack : items) { + if (stack.type == type) return stack.count - stack.reserved; + } + return 0; + } + [[nodiscard]] std::uint64_t total_items() const noexcept { std::uint64_t total = 0; for (const ItemStack& stack : items) total += stack.count; @@ -291,6 +335,11 @@ public: [[nodiscard]] bool can_place_cabin(GridPosition position) const noexcept; [[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::optional carpenter_workshop() const noexcept { + if (!scenario_active_) return std::nullopt; + return scenario_sawmill_; + } void queue_cabin(GridPosition position, GridPosition sawmill, GridPosition stonecutter); void start_scenario(GridPosition sawmill); [[nodiscard]] CommandReceipt apply_command(const PlayerCommand& command); @@ -348,6 +397,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; 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 6458412..10b05e2 100644 --- a/engine/src/world.cpp +++ b/engine/src/world.cpp @@ -69,6 +69,12 @@ const Recipe& recipe_for(RecipeId id) { static constexpr Recipe floor{{ItemStack{ItemType::Wood, 1}, {}}, ItemType::None, 6}; static constexpr Recipe wall{{ItemStack{ItemType::Wood, 1}, {}}, ItemType::None, 9}; static constexpr Recipe door{{ItemStack{ItemType::Wood, 2}, {}}, ItemType::None, 12}; + static constexpr Recipe cabinet{{ItemStack{ItemType::Wood, 1}, {}}, ItemType::None, 10}; + static constexpr Recipe mining_rack{{ItemStack{ItemType::Wood, 1}, ItemStack{ItemType::Stone, 1}}, + ItemType::None, 10}; + static constexpr Recipe loom{{ItemStack{ItemType::Wood, 2}, {}}, ItemType::None, 12}; + static constexpr Recipe install_door{{ItemStack{ItemType::WoodenDoor, 1}, {}}, ItemType::None, 8}; + static constexpr Recipe craft_door{{ItemStack{ItemType::Wood, 2}, {}}, ItemType::WoodenDoor, 14}; switch (id) { case RecipeId::SawPlank: return saw; case RecipeId::CutStoneBlock: return cut; @@ -79,6 +85,12 @@ const Recipe& recipe_for(RecipeId id) { case RecipeId::BuildWall: return wall; case RecipeId::BuildDoorAlongX: case RecipeId::BuildDoorAlongY: return door; + case RecipeId::BuildMedicineCabinet: return cabinet; + case RecipeId::BuildMiningRack: return mining_rack; + case RecipeId::BuildLoom: return loom; + case RecipeId::InstallDoorAlongX: + case RecipeId::InstallDoorAlongY: return install_door; + case RecipeId::CraftWoodenDoor: return craft_door; } throw std::invalid_argument("unknown production recipe"); } @@ -143,7 +155,9 @@ RoomPlan make_room_plan(GridPosition first, GridPosition last) noexcept { bool RoomPlan::valid_size() const noexcept { const auto width = static_cast(last.x) - first.x + 1; const auto height = static_cast(last.y) - first.y + 1; - return width >= 3 && width <= 12 && height >= 3 && height <= 12 && entrance <= RoomSide::West; + if (entrance > RoomSide::West || layout > RoomTemplate::Weaver) return false; + if (layout == RoomTemplate::Empty) return width >= 3 && width <= 12 && height >= 3 && height <= 12; + return width == furnished_room_size && height == furnished_room_size; } bool RoomPlan::contains(GridPosition cell) const noexcept { @@ -167,6 +181,29 @@ RecipeId RoomPlan::recipe_at(GridPosition cell) const noexcept { return RecipeId::BuildFloor; } +std::optional> RoomPlan::furnishings() const noexcept { + if (layout == RoomTemplate::Empty || !valid_size()) return std::nullopt; + // Keep the entry aisle clear by placing both pieces against the back wall. + const GridPosition bed_offsets[] = {{1, 2}, {1, 1}, {1, 1}, {2, 1}}; + const GridPosition fixture_offsets[] = {{2, 2}, {1, 2}, {2, 1}, {2, 2}}; + const RecipeId fixtures[] = {RecipeId::BuildMedicineCabinet, RecipeId::BuildMiningRack, RecipeId::BuildLoom}; + const auto side = static_cast(entrance); + const auto bed = bed_offsets[side]; + const auto fixture = fixture_offsets[side]; + return std::array{RoomFurnishing{{first.x + bed.x, first.y + bed.y}, RecipeId::BuildBed, + layout == RoomTemplate::Miner ? BedBase::Stone : BedBase::Wood}, + RoomFurnishing{{first.x + fixture.x, first.y + fixture.y}, + fixtures[static_cast(layout) - 1]}}; +} + +std::uint8_t RoomPlan::placement_value() const noexcept { + return static_cast((static_cast(layout) << 2) | static_cast(entrance)); +} + +RoomPlan RoomPlan::from_placement(GridPosition first, GridPosition last, std::uint8_t value) noexcept { + return {first, last, static_cast(value & 3U), static_cast(value >> 2)}; +} + std::uint32_t Inventory::item_count(ItemType type) const noexcept { const auto index = static_cast(type); return index != 0 && index <= counts_.size() ? counts_[index - 1] : 0; @@ -263,8 +300,14 @@ 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 && + 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) continue; + agent.state != AgentState::GoingToEat && agent.state != AgentState::GoingToSleep && + agent.inventory.item_count(ItemType::WoodenDoor) == 0) 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"); @@ -357,6 +400,9 @@ 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_production_object(recipe) && !can_place_storage(position)) { throw std::invalid_argument("the production site is occupied"); } @@ -382,7 +428,8 @@ bool World::can_place_cabin(GridPosition position) const noexcept { } bool World::can_place_room(const RoomPlan& plan) const noexcept { - if (!plan.valid_size() || !is_walkable(plan.first) || !is_walkable(plan.last)) return false; + if (!plan.valid_size() || (plan.layout != RoomTemplate::Empty && !scenario_active_) || + !is_walkable(plan.first) || !is_walkable(plan.last)) return false; const int middle_x = std::midpoint(plan.first.x, plan.last.x); const int middle_y = std::midpoint(plan.first.y, plan.last.y); const GridPosition exits[] = {{middle_x, plan.first.y - 1}, {plan.last.x + 1, middle_y}, @@ -413,6 +460,35 @@ std::array World::construction_materials(RecipeId recipe, BedBase return is_construction(recipe) ? recipe_for(recipe).ingredients : std::array{}; } +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; + } + return part; +} + +std::size_t World::missing_door_orders(std::size_t new_installations) const { + 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)) { + ++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); + } + } + for (const auto& storage : storages_) { + const auto available = storage.available_item_count(ItemType::WoodenDoor); + if (available != 0 && find_path(scenario_sawmill_, storage.position).reachable) supply += available; + } + return waiting_installations > supply ? static_cast(waiting_installations - supply) : 0; +} + void World::queue_cabin(GridPosition position, GridPosition sawmill, GridPosition stonecutter) { if (!can_place_cabin(position) || position == sawmill || position == stonecutter || (scenario_active_ && position == scenario_sawmill_)) { @@ -485,7 +561,7 @@ CommandStatus World::object_status(GridPosition position, bool moving) const noe for (const auto& order : production_orders_) { if (order.position != position || !is_production_object(order.recipe)) continue; if (is_finished_floor(order)) continue; - if (moving && order.recipe >= RecipeId::BuildFloor) return CommandStatus::InvalidTarget; + if (moving && is_room_part(order.recipe)) return CommandStatus::InvalidTarget; return order.state == JobState::InProgress || resting_at(position) ? busy : ready; } for (std::size_t i = 0; i < storages_.size(); ++i) { @@ -537,6 +613,7 @@ 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; const auto removed = static_cast(storage - storages_.begin()); storages_.erase(storage); for (auto& agent : agents_) shift_index(agent.storage_index, removed); @@ -544,6 +621,10 @@ 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); + } } return CommandStatus::Accepted; } @@ -661,23 +742,42 @@ CommandReceipt World::apply_command(const PlayerCommand& command) { } queue_production(command.cell, RecipeId::WeaveCloth); break; + case CommandKind::CraftDoor: + queue_production(scenario_sawmill_, RecipeId::CraftWoodenDoor); + break; case CommandKind::PlaceRoom: { - const RoomPlan plan{command.cell, command.destination, static_cast(command.value)}; + const auto plan = RoomPlan::from_placement(command.cell, command.destination, command.value); if (!can_place_room(plan) || !can_reach_object_cell(plan.first)) { return receipt(CommandStatus::InvalidTarget); } const auto width = static_cast(plan.last.x - plan.first.x + 1); const auto height = static_cast(plan.last.y - plan.first.y + 1); - production_orders_.reserve(production_orders_.size() + width * height); + 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; + production_orders_.reserve(production_orders_.size() + width * height + + (furnishings ? furnishings->size() : 0) + (legacy_bed ? 1U : 0U) + door_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.bed_base = part.bed_base; + if (order.recipe == RecipeId::BuildBed && staged_beds_) order.bed_stage = BedStage::Foundation; + production_orders_.push_back(std::move(order)); + } + } for (int y = plan.first.y; y <= plan.last.y; ++y) { for (int x = plan.first.x; x <= plan.last.x; ++x) { const GridPosition cell{x, y}; ProductionOrder order{}; order.position = cell; - order.recipe = plan.recipe_at(cell); + order.recipe = room_construction_recipe(plan.recipe_at(cell)); production_orders_.push_back(std::move(order)); } } + for (std::size_t i = 0; i < door_orders; ++i) queue_production(scenario_sawmill_, RecipeId::CraftWoodenDoor); break; } case CommandKind::PlaceStorage: @@ -695,7 +795,7 @@ CommandReceipt World::apply_command(const PlayerCommand& command) { break; } case CommandKind::AssignProfession: { - if (command.value > static_cast(Profession::Builder) || command.resident == 0) { + if (command.value > static_cast(Profession::Carpenter) || command.resident == 0) { return receipt(CommandStatus::InvalidTarget); } const auto resident = std::lower_bound(agents_.begin(), agents_.end(), command.resident, @@ -1004,10 +1104,11 @@ void World::assign_resource_tasks(ResourceFocus focus) { } for (Agent& agent : agents_) { if (open_pantry_count == 0 && open_material_store_count == 0 && untended_sites == 0) break; - if (agent.profession == Profession::Builder || agent.state != AgentState::Idle || agent.current_job != 0 || + const auto profession = static_cast(agent.profession); + if (profession >= available.size() || agent.state != AgentState::Idle || agent.current_job != 0 || !agent.inventory.empty()) continue; - const auto& candidates = available[static_cast(agent.profession)]; + const auto& candidates = available[profession]; if (candidates.empty()) continue; std::vector tried_nodes(candidates.size(), 0); for (;;) { @@ -1099,7 +1200,8 @@ void World::assign_production_tasks(bool weaving) { if (production_orders_.empty() || storages_.empty() || std::none_of(agents_.begin(), agents_.end(), [](const Agent& agent) { - return agent.state == AgentState::Idle && can_take_work(agent, Profession::Builder); + return agent.state == AgentState::Idle && + (can_take_work(agent, Profession::Builder) || agent.profession == Profession::Carpenter); })) return; for (std::size_t index = 0; index < production_orders_.size(); ++index) { ProductionOrder& order = production_orders_[index]; @@ -1107,15 +1209,18 @@ void World::assign_production_tasks(bool weaving) { const bool site_busy = std::any_of(production_orders_.begin(), production_orders_.end(), [&order](const ProductionOrder& other) { - return other.state == JobState::InProgress && - other.position.x == order.position.x && other.position.y == order.position.y; + return other.position == order.position && + (other.state == JobState::InProgress || + (order.recipe != RecipeId::BuildFloor && other.recipe == RecipeId::BuildFloor && + other.state != JobState::Completed)); }); if (site_busy) continue; const Recipe recipe = recipe_for(order); - const bool construction = is_construction(order.recipe); + const bool door_craft = order.recipe == RecipeId::CraftWoodenDoor; + const bool deliver_ingredients = delivers_materials(order.recipe); enum class Access { Unknown, Reachable, Unreachable }; - std::vector storage_access(construction || weaving ? storages_.size() : 0, Access::Unknown); + std::vector storage_access(deliver_ingredients || weaving ? storages_.size() : 0, Access::Unknown); std::vector materials; bool supplied = true; for (const ItemStack& ingredient : recipe.ingredients) { @@ -1146,7 +1251,7 @@ void World::assign_production_tasks(bool weaving) { if (!supplied) continue; std::vector stops; - if (construction) { + if (deliver_ingredients) { for (std::size_t s = 0; s < storage_access.size(); ++s) { if (storage_access[s] == Access::Reachable) stops.push_back({s, {}}); } @@ -1160,12 +1265,18 @@ void World::assign_production_tasks(bool weaving) { stops[i].route_to_next = std::move(path.positions); } } - const GridPosition destination = construction + const GridPosition destination = deliver_ingredients ? storages_[stops.front().storage_index].position : order.position; for (Agent& agent : agents_) { - if (agent.state != AgentState::Idle || !can_take_work(agent, Profession::Builder)) continue; + const bool can_craft = agent.profession == Profession::Carpenter; + const bool eligible = door_craft ? 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) { + agent.haul_route = assignment_path(order.position, storages_[materials.front().storage_index].position).positions; + } for (const auto& material : materials) { stack_position(storages_[material.storage_index], material.type)->reserved += material.count; @@ -1177,7 +1288,7 @@ void World::assign_production_tasks(bool weaving) { agent.route = std::move(path.positions); agent.route_cursor = 0; agent.work_remaining = recipe.ticks; - agent.state = construction ? AgentState::FetchingMaterials : + agent.state = deliver_ingredients ? AgentState::FetchingMaterials : (agent.route.empty() ? AgentState::Working : AgentState::Travelling); break; } @@ -1326,6 +1437,10 @@ 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. + ++storages_[stop.storage_index].reserved_slots; + } ++order.collected_stops; agent.route = std::move(stop.route_to_next); agent.route_cursor = 0; @@ -1336,6 +1451,18 @@ 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) { + agent.inventory.add(recipe.output); + agent.storage_index = order.materials.front().storage_index; + agent.route = std::move(agent.haul_route); + agent.haul_route.clear(); + agent.route_cursor = 0; + agent.production_index = no_entity_index; + agent.state = AgentState::Hauling; + order.materials.clear(); + order.state = JobState::Completed; + return; + } if (recipe.output != ItemType::None) { for (const auto& material : order.materials) { take_reserved_material(storages_[material.storage_index], material); @@ -1348,6 +1475,9 @@ 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) { + order.recipe = RecipeId::WeaveCloth; + order.state = JobState::Available; } else if (order.recipe == RecipeId::WeaveCloth) { order.state = JobState::Available; } else { diff --git a/engine/src/world_save.cpp b/engine/src/world_save.cpp index 26e9cdc..f723d46 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 = 10; +constexpr std::uint32_t save_version = 12; 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,7 @@ 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 >= 7 ? ItemType::Flax : ItemType::Cloth; + const auto max_item = 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_); @@ -214,6 +214,7 @@ struct WorldSaveCodec { if (version >= 4) archive.field(agent.fatigue); if (version >= 5) flag(archive, agent.resting_on_ground); if (version >= 6) archive.field(agent.profession); + require_save(version >= 12 || agent.profession <= Profession::Builder, "Unknown profession for save version."); }); sequence(archive, world.jobs_, max_records, [&](auto& job) { archive.field(job.id); @@ -256,6 +257,8 @@ struct WorldSaveCodec { require_save(version >= 2 || order.recipe <= RecipeId::BuildCabin, "Unknown recipe for save version."); require_save(version >= 7 || order.recipe <= RecipeId::BuildBed, "Unknown recipe for save version."); 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."); archive.field(order.state); sequence(archive, order.materials, item_types, [&](auto& material) { index(archive, material.storage_index); @@ -362,9 +365,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::BuildDoorAlongY && order.state <= JobState::Completed && + invalid(order.recipe <= RecipeId::CraftWoodenDoor && 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(order.bed_base <= BedBase::Stone && order.bed_stage <= BedStage::Pillow && (order.bed_stage == BedStage::Legacy || (world.staged_beds_ && order.recipe == RecipeId::BuildBed)) && @@ -382,8 +386,8 @@ void WorldSaveCodec::validate(const World& world) { continue; } - const bool construction = is_construction(order.recipe); - invalid(order.collected_stops <= order.delivery_stops.size() && (construction || order.delivery_stops.empty())); + const bool delivery = delivers_materials(order.recipe); + invalid(order.collected_stops <= order.delivery_stops.size() && (delivery || order.delivery_stops.empty())); std::size_t last_storage = 0; bool first_stop = true; for (const auto& stop : order.delivery_stops) { @@ -401,7 +405,7 @@ void WorldSaveCodec::validate(const World& world) { invalid(material.storage_index < world.storages_.size() && material.count > 0 && world.storages_[material.storage_index].kind == StorageKind::Materials); ingredients[type] += material.count; - if (!construction) { + if (!delivery) { reserved_items[material.storage_index][type] += material.count; } else if (!order.delivery_stops.empty()) { const auto stop = std::find_if(order.delivery_stops.begin(), order.delivery_stops.end(), @@ -425,10 +429,16 @@ 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::BuildFloor: case RecipeId::BuildWall: case RecipeId::BuildDoorAlongX: case RecipeId::BuildDoorAlongY: + case RecipeId::BuildMedicineCabinet: + case RecipeId::BuildMiningRack: + case RecipeId::BuildLoom: + case RecipeId::InstallDoorAlongX: + case RecipeId::InstallDoorAlongY: for (const auto& item : world.construction_materials(order.recipe, order.bed_base)) { if (item.count) required[item_index(item.type)] = item.count; } @@ -450,7 +460,7 @@ void WorldSaveCodec::validate(const World& world) { (world.hunger_enabled_ || agent.hunger == 0) && agent.fatigue <= max_fatigue && (world.scenario_active_ || agent.fatigue == 0)); invalid(!agent.resting_on_ground || agent.state == Sleeping || agent.state == GoingToSleep); - invalid(agent.profession <= Profession::Builder); + invalid(agent.profession <= Profession::Carpenter); valid_route(agent.route); valid_route(agent.haul_route); const bool has_job = agent.current_job != 0; @@ -458,7 +468,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()); - invalid(agent.haul_route.empty() || has_source); + 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); if (has_job) { invalid(!has_order && !has_storage && !has_source && agent.inventory.empty() && (agent.state == Travelling || agent.state == Working) && agent.work_remaining > 0); @@ -477,7 +489,13 @@ void WorldSaveCodec::validate(const World& world) { if (!order.delivery_stops.empty()) { invalid(agent.state == (order.collected_stops == 0 ? FetchingMaterials : Hauling)); } else { - invalid(agent.state == Working || (agent.state == Travelling && !is_construction(order.recipe))); + invalid(agent.state == Working || (agent.state == Travelling && !delivers_materials(order.recipe))); + } + if (door_craft) { + 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]; } 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]); @@ -497,7 +515,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::Berries || cargo == ItemType::Flax || cargo == ItemType::WoodenDoor) && 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/setup-toolchain.ps1 b/setup-toolchain.ps1 index cdf0930..42d1039 100644 --- a/setup-toolchain.ps1 +++ b/setup-toolchain.ps1 @@ -1,111 +1,57 @@ -param() +param([string]$Msys2Root = $env:SETTLEMENT_MSYS2_ROOT) $ErrorActionPreference = 'Stop' -[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 - -$projectRoot = Split-Path -Parent $MyInvocation.MyCommand.Path -$toolRoot = Join-Path $projectRoot '.tools\toolchain' -$downloadRoot = Join-Path $projectRoot '.tools\downloads' -$cmakeVersion = '4.5.1' -$llvmVersion = '20261117' -$cmakeArchiveName = "cmake-$cmakeVersion-windows-x86_64.zip" -$cmakeHashName = "cmake-$cmakeVersion-SHA-256.txt" -$llvmArchiveName = "llvm-mingw-$llvmVersion-ucrt-x86_64.zip" - if (-not [Environment]::Is64BitOperatingSystem) { - throw 'This portable toolchain setup requires 64-bit Windows.' + throw 'MSYS2 UCRT64 requires 64-bit Windows.' } - -New-Item -ItemType Directory -Path $downloadRoot -Force | Out-Null -New-Item -ItemType Directory -Path $toolRoot -Force | Out-Null - -function Get-Download { - param( - [Parameter(Mandatory = $true)][string]$Uri, - [Parameter(Mandatory = $true)][string]$Destination - ) - - if (-not (Test-Path -LiteralPath $Destination -PathType Leaf)) { - Write-Host "Downloading $([System.IO.Path]::GetFileName($Destination))" - Invoke-WebRequest -Uri $Uri -OutFile $Destination -UseBasicParsing +$toolRoot = Join-Path $PSScriptRoot '.tools\toolchain' +$portableRoot = Join-Path $toolRoot 'msys64' +if (-not $Msys2Root) { $Msys2Root = $portableRoot } +$bash = Join-Path $Msys2Root 'usr\bin\bash.exe' +$bin = Join-Path $Msys2Root 'ucrt64\bin' +$compiler = Join-Path $bin 'g++.exe' +if ((Test-Path -LiteralPath $compiler -PathType Leaf) -and + (Test-Path -LiteralPath (Join-Path $bin 'cmake.exe') -PathType Leaf) -and + (Test-Path -LiteralPath (Join-Path $bin 'ninja.exe') -PathType Leaf)) { + $version = & $compiler -dumpfullversion + if ($LASTEXITCODE -eq 0 -and $version -match '^16(\.|$)') { + Write-Output "MSYS2 UCRT64 GCC $version is ready." + return } } - -function Expand-IfMissing { - param( - [Parameter(Mandatory = $true)][string]$Archive, - [Parameter(Mandatory = $true)][string]$Destination, - [Parameter(Mandatory = $true)][string]$ExpectedExecutable - ) - - $existingExecutable = Get-ChildItem -LiteralPath $Destination -Filter $ExpectedExecutable -File -Recurse -ErrorAction SilentlyContinue | Select-Object -First 1 - if ($null -eq $existingExecutable) { - New-Item -ItemType Directory -Path $Destination -Force | Out-Null - Expand-Archive -LiteralPath $Archive -DestinationPath $Destination -Force +if (-not (Test-Path -LiteralPath $bash -PathType Leaf)) { + if ([IO.Path]::GetFullPath($Msys2Root) -ne [IO.Path]::GetFullPath($portableRoot)) { + throw "MSYS2 was not found at $Msys2Root." } -} - -$cmakeArchive = Join-Path $downloadRoot $cmakeArchiveName -$cmakeHashFile = Join-Path $downloadRoot $cmakeHashName -$cmakeBase = "https://github.com/Kitware/CMake/releases/download/v$cmakeVersion" -Get-Download -Uri "$cmakeBase/$cmakeArchiveName" -Destination $cmakeArchive -Get-Download -Uri "$cmakeBase/$cmakeHashName" -Destination $cmakeHashFile - -$escapedCmakeName = [regex]::Escape($cmakeArchiveName) -$hashText = Get-Content -LiteralPath $cmakeHashFile -Raw -$hashPatterns = @( - "(?im)^\s*([0-9a-f]{64})\s+\*?$escapedCmakeName\s*$", - "(?im)^\s*SHA-?256\s*\(\s*$escapedCmakeName\s*\)\s*[:=]\s*([0-9a-f]{64})\s*$", - "(?im)^\s*$escapedCmakeName\s*[: ]+\s*([0-9a-f]{64})\s*$" -) -$expectedCmakeHash = $null -foreach ($pattern in $hashPatterns) { - $match = [regex]::Match($hashText, $pattern) - if ($match.Success) { - $expectedCmakeHash = $match.Groups[1].Value.ToLowerInvariant() - break + $downloadRoot = Join-Path $PSScriptRoot '.tools\downloads' + New-Item -ItemType Directory -Path $downloadRoot, $toolRoot -Force | Out-Null + $name = 'msys2-base-x86_64-20261120.tar.zst' + $archive = Join-Path $downloadRoot $name + $expected = 'adde59fcb53760bd0fd2aa3c3e8da516f03159b771dc62b77c340e4ac187fcdd' + if (-not (Test-Path -LiteralPath $archive -PathType Leaf) -or + (Get-FileHash -LiteralPath $archive -Algorithm SHA256).Hash -ne $expected) { + Invoke-WebRequest -Uri "https://repo.msys2.org/distrib/x86_64/$name" -OutFile $archive -UseBasicParsing } -} -if (-not $expectedCmakeHash) { - throw "Could not read the official SHA-256 for $cmakeArchiveName. The archive was not extracted." -} -$actualCmakeHash = (Get-FileHash -LiteralPath $cmakeArchive -Algorithm SHA256).Hash.ToLowerInvariant() -if ($actualCmakeHash -ne $expectedCmakeHash) { - throw "CMake archive SHA-256 mismatch. Expected $expectedCmakeHash, got $actualCmakeHash." -} - -$llvmArchive = Join-Path $downloadRoot $llvmArchiveName -$llvmReleaseUri = "https://api.github.com/repos/mstorsjo/llvm-mingw/releases/tags/$llvmVersion" -$llvmRelease = Invoke-RestMethod -Uri $llvmReleaseUri -Headers @{ 'User-Agent' = 'stonehearth-sim-toolchain-setup' } -$llvmAsset = $llvmRelease.assets | Where-Object { $_.name -eq $llvmArchiveName } | Select-Object -First 1 -if ($null -eq $llvmAsset) { - throw "The official llvm-mingw release $llvmVersion does not contain $llvmArchiveName." -} -Get-Download -Uri $llvmAsset.browser_download_url -Destination $llvmArchive - -if ($llvmAsset.digest -and $llvmAsset.digest -match '^sha256:([0-9a-fA-F]{64})$') { - $expectedLlvmHash = $Matches[1].ToLowerInvariant() - $actualLlvmHash = (Get-FileHash -LiteralPath $llvmArchive -Algorithm SHA256).Hash.ToLowerInvariant() - if ($actualLlvmHash -ne $expectedLlvmHash) { - throw "LLVM-MinGW archive SHA-256 mismatch. Expected $expectedLlvmHash, got $actualLlvmHash." + if ((Get-FileHash -LiteralPath $archive -Algorithm SHA256).Hash -ne $expected) { + throw 'MSYS2 archive hash does not match the release.' } -} else { - Write-Warning 'GitHub did not publish a SHA-256 digest for this LLVM-MinGW asset; download is from the official release over HTTPS.' + & tar.exe -xf $archive -C $toolRoot + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } } -$cmakeInstall = Join-Path $toolRoot 'cmake' -$llvmInstall = Join-Path $toolRoot 'llvm-mingw' -Expand-IfMissing -Archive $cmakeArchive -Destination $cmakeInstall -ExpectedExecutable 'cmake.exe' -Expand-IfMissing -Archive $llvmArchive -Destination $llvmInstall -ExpectedExecutable 'clang++.exe' - -$cmakeExe = Get-ChildItem -LiteralPath $cmakeInstall -Filter 'cmake.exe' -File -Recurse | Select-Object -First 1 -$clangxxExe = Get-ChildItem -LiteralPath $llvmInstall -Filter 'clang++.exe' -File -Recurse | Select-Object -First 1 -if ($null -eq $cmakeExe -or $null -eq $clangxxExe) { - throw 'Extraction completed, but CMake or Clang++ was not found in the toolchain folders.' +$previousMsysSystem = $env:MSYSTEM +try { + $env:MSYSTEM = 'UCRT64' + # An MSYS2 runtime upgrade can close the first shell. Start a fresh shell for the remaining packages. + & $bash --login -c 'pacman -Syu --noconfirm' + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } + & $bash --login -c 'pacman -Syu --needed --noconfirm mingw-w64-ucrt-x86_64-gcc mingw-w64-ucrt-x86_64-cmake mingw-w64-ucrt-x86_64-ninja' + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } +} finally { + $env:MSYSTEM = $previousMsysSystem } - -Write-Host "CMake: $($cmakeExe.FullName)" -& $cmakeExe.FullName --version | Select-Object -First 1 -Write-Host "C++ compiler: $($clangxxExe.FullName)" -& $clangxxExe.FullName --version | Select-Object -First 1 -Write-Host 'Portable toolchain is ready. Run .\build.ps1 to configure, build, and run CTest.' +$version = & $compiler -dumpfullversion +if ($LASTEXITCODE -ne 0 -or $version -notmatch '^16(\.|$)') { + throw "Expected GCC 16 in MSYS2 UCRT64. Found: $version" +} +Write-Output "MSYS2 UCRT64 GCC $version is ready." diff --git a/tests/core_tests.cpp b/tests/core_tests.cpp index bffadee..3ef6b6c 100644 --- a/tests/core_tests.cpp +++ b/tests/core_tests.cpp @@ -1,6 +1,9 @@ +#include "testing.hpp" + #include "settlement/core/deterministic_rng.hpp" #include "settlement/core/world.hpp" +#include #include #include #include @@ -30,7 +33,36 @@ std::unique_ptr save_roundtrip(const settlement::World& world return restored; } -void test_parallel_pathfinding_completes_the_jobs() { +using Void::Testing::Test; + +struct CoreTests : Void::Testing::Suite { + Test test_parallel_pathfinding_completes_the_jobs(); + Test test_single_worker_configuration_is_rejected(); + Test test_rng_repeats_for_same_seed(); + Test test_work_jobs_complete(); + Test test_astar_route_uses_opening_in_wall(); + Test test_residents_gather_and_deliver_resources(); + [[= Void::Testing::tag("construction")]] Test test_production_reservations_and_construction(); + [[= Void::Testing::tag("construction")]] Test test_cabin_placement_queues_a_complete_order(); + Test test_hungry_resident_reserves_and_eats_a_berry(); + Test test_invalid_save_is_rejected(); + Test test_two_players_share_the_first_colony(); + Test test_bed_parts_are_delivered_separately(); + Test test_resident_uses_assigned_bed_and_sleep_survives_save(); + Test test_fatigue_slows_work_without_interrupting_it(); + Test test_ground_rest_never_uses_another_residents_bed(); + Test test_fields_mines_and_reindexing_active_hauls(); + Test test_specialists_take_their_own_jobs_and_finish_prior_assignments(); + Test test_flax_and_loom_supply_a_bed_without_starting_cloth(); + Test test_field_growth_requires_a_worker(); + Test test_opening_a_mine_invalidates_unreachable_routes(); + Test test_object_tools_work_in_an_older_demo_world(); + [[= 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(); +}; + +Test CoreTests::test_parallel_pathfinding_completes_the_jobs() { settlement::World world(123, 48, 48, 6); for (std::int32_t y = 0; y < 48; ++y) { if (y != 31) world.set_blocked({24, y}); @@ -42,26 +74,28 @@ void test_parallel_pathfinding_completes_the_jobs() { } for (int tick = 0; tick < 120; ++tick) world.step(); require(world.jobs_completed() == 24, "parallel pathfinding did not finish every job"); + return {}; } -void test_single_worker_configuration_is_rejected() { +Test CoreTests::test_single_worker_configuration_is_rejected() { try { settlement::World world(8, 8, 8, 1); } catch (const std::invalid_argument&) { - return; + return {}; } throw std::runtime_error("world accepted a single worker"); } -void test_rng_repeats_for_same_seed() { +Test CoreTests::test_rng_repeats_for_same_seed() { settlement::DeterministicRng left(12345); settlement::DeterministicRng right(12345); for (int index = 0; index < 1000; ++index) { - require(left.next_u64() == right.next_u64(), "RNG diverged for matching seeds"); + expect_eq(left.next_u64(), right.next_u64()); } + return {}; } -void test_work_jobs_complete() { +Test CoreTests::test_work_jobs_complete() { settlement::World world(1, 10, 10); const settlement::AgentId agent_id = world.spawn_agent({1, 1}); const settlement::JobId job_id = world.add_job({3, 1}, 2); @@ -81,9 +115,10 @@ void test_work_jobs_complete() { "completed job retained an active state"); require(world.agents().front().state == settlement::AgentState::Idle, "worker did not return to idle after completing a job"); + return {}; } -void test_astar_route_uses_opening_in_wall() { +Test CoreTests::test_astar_route_uses_opening_in_wall() { settlement::World world(2, 10, 10); for (std::int32_t y = 0; y < 10; ++y) { if (y != 8) { @@ -103,9 +138,10 @@ void test_astar_route_uses_opening_in_wall() { } require(world.path_searches() > 0, "path search counter was not updated"); require(world.path_nodes_visited() > 0, "A* did not report expanded nodes"); + return {}; } -void test_residents_gather_and_deliver_resources() { +Test CoreTests::test_residents_gather_and_deliver_resources() { settlement::World world(51, 16, 16, 4); static_cast(world.add_storage({1, 1}, 10)); static_cast(world.spawn_agent({1, 2})); @@ -126,9 +162,10 @@ void test_residents_gather_and_deliver_resources() { "storage retained reservations after deliveries completed"); require(world.resource_nodes()[0].quantity == 0 && world.resource_nodes()[1].quantity == 0, "resource nodes retained units after deliveries completed"); + return {}; } -void test_production_reservations_and_construction() { +Test CoreTests::test_production_reservations_and_construction() { using settlement::ItemType; using settlement::JobState; using settlement::RecipeId; @@ -207,9 +244,10 @@ void test_production_reservations_and_construction() { require(world.storages()[0].items.empty() && world.storages()[1].items.empty(), "building did not consume the crafted materials from both stores"); + return {}; } -void test_cabin_placement_queues_a_complete_order() { +Test CoreTests::test_cabin_placement_queues_a_complete_order() { using settlement::RecipeId; settlement::World world(1, 10, 10); world.set_blocked({1, 1}); @@ -229,9 +267,10 @@ void test_cabin_placement_queues_a_complete_order() { } catch (const std::invalid_argument&) { require(orders.size() == 6, "invalid placement partially queued new orders"); } + return {}; } -void test_hungry_resident_reserves_and_eats_a_berry() { +Test CoreTests::test_hungry_resident_reserves_and_eats_a_berry() { using settlement::AgentState; using settlement::ItemType; const settlement::GridPosition pantry{1, 1}; @@ -278,9 +317,10 @@ void test_hungry_resident_reserves_and_eats_a_berry() { static_cast(world.add_job(pantry, 1)); world.step(); require(world.jobs_completed() == 2, "the resident did not resume work after eating"); + return {}; } -void test_invalid_save_is_rejected() { +Test CoreTests::test_invalid_save_is_rejected() { const settlement::World world(5, 5, 5); auto bytes = save_contents(world); const auto rejected = [](const std::string& save) { @@ -296,9 +336,10 @@ void test_invalid_save_is_rejected() { require(rejected(bytes + 'x'), "save with trailing data was accepted"); bytes[8] = 127; require(rejected(bytes), "unknown save version was accepted"); + return {}; } -void test_two_players_share_the_first_colony() { +Test CoreTests::test_two_players_share_the_first_colony() { using settlement::CommandKind; using settlement::CommandStatus; auto world = settlement::make_first_colony(2); @@ -341,9 +382,10 @@ void test_two_players_share_the_first_colony() { "the shared colony could not feed its residents and complete the objective"); auto replay = save_roundtrip(*world); require(replay->scenario_progress().completed, "completion was lost after loading"); + return {}; } -void test_bed_parts_are_delivered_separately() { +Test CoreTests::test_bed_parts_are_delivered_separately() { using namespace settlement; auto world = make_first_colony(2); const GridPosition wood_bed{16, 18}; @@ -373,9 +415,10 @@ void test_bed_parts_are_delivered_separately() { "the beds were not completed through three separate deliveries"); require(world->storages().back().item_count(ItemType::Cloth) == 8, "two beds must consume four pieces of cloth"); + return {}; } -void test_resident_uses_assigned_bed_and_sleep_survives_save() { +Test CoreTests::test_resident_uses_assigned_bed_and_sleep_survives_save() { using namespace settlement; World world(4, 16, 16, 2); const auto owner = world.spawn_agent({1, 2}); @@ -423,9 +466,10 @@ void test_resident_uses_assigned_bed_and_sleep_survives_save() { } require(from_route && woke_rested && rested_on_ground, "sleep and recovery phases were not observed"); require(world.jobs_completed() == 2, "residents did not finish their existing work"); + return {}; } -void test_fatigue_slows_work_without_interrupting_it() { +Test CoreTests::test_fatigue_slows_work_without_interrupting_it() { using namespace settlement; World world(6, 10, 10); static_cast(world.spawn_agent({2, 2})); @@ -438,9 +482,10 @@ void test_fatigue_slows_work_without_interrupting_it() { const auto before = resident.work_remaining; for (int i = 0; i < 6; ++i) world.step(); require(before - resident.work_remaining == 2, "hunger and fatigue did not slow the ongoing work"); + return {}; } -void test_ground_rest_never_uses_another_residents_bed() { +Test CoreTests::test_ground_rest_never_uses_another_residents_bed() { using namespace settlement; World world(15, 14, 14); const GridPosition cell{7, 6}; @@ -479,9 +524,10 @@ void test_ground_rest_never_uses_another_residents_bed() { require(world.assigned_bed(owner)->position == new_cell, "moving a bed lost its owner"); require(world.apply_command({1, 3, CommandKind::DemolishObject, new_cell}).status == CommandStatus::Accepted && world.assigned_bed(owner) == nullptr, "demolishing a bed left a stale assignment"); + return {}; } -void test_fields_mines_and_reindexing_active_hauls() { +Test CoreTests::test_fields_mines_and_reindexing_active_hauls() { using namespace settlement; World world(22, 18, 18, 2); const GridPosition rock{9, 5}; @@ -532,9 +578,10 @@ void test_fields_mines_and_reindexing_active_hauls() { "growing, regrowing, or mining did not deliver resources"); require(apply(CommandKind::PlaceStorage, {11, 7}) == CommandStatus::Accepted, "a new storage could not be placed"); + return {}; } -void test_specialists_take_their_own_jobs_and_finish_prior_assignments() { +Test CoreTests::test_specialists_take_their_own_jobs_and_finish_prior_assignments() { using namespace settlement; World world(54, 14, 14, 2); const auto farmer = world.spawn_agent({2, 2}); @@ -588,9 +635,10 @@ void test_specialists_take_their_own_jobs_and_finish_prior_assignments() { } require(delivered_stone && later_cut_wood, "the reassigned miner did not finish mining and then cut wood"); require(world.scenario_progress().assigned_beds == 1, "the builder did not complete the bed"); + return {}; } -void test_flax_and_loom_supply_a_bed_without_starting_cloth() { +Test CoreTests::test_flax_and_loom_supply_a_bed_without_starting_cloth() { using namespace settlement; World world(92, 12, 12, 3); const auto farmer = world.spawn_agent({2, 3}); @@ -648,9 +696,10 @@ void 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"); + return {}; } -void test_field_growth_requires_a_worker() { +Test CoreTests::test_field_growth_requires_a_worker() { using namespace settlement; World world(58, 14, 14); const auto resident = world.spawn_agent({2, 2}); @@ -677,9 +726,10 @@ void test_field_growth_requires_a_worker() { require(save_contents(world) == save_contents(*restored), "sowing did not resume after loading"); } require(world.resource_nodes().front().quantity > 0, "planting without a storage did not grow flax"); + return {}; } -void test_opening_a_mine_invalidates_unreachable_routes() { +Test CoreTests::test_opening_a_mine_invalidates_unreachable_routes() { using namespace settlement; World world(44, 8, 8); const auto resident = world.spawn_agent({1, 4}); @@ -698,9 +748,10 @@ void test_opening_a_mine_invalidates_unreachable_routes() { world.step(); require(world.agents().front().resource_node_index == 0 && world.agents().front().state == AgentState::Travelling, "terrain edit left a stale route in the cache"); + return {}; } -void test_object_tools_work_in_an_older_demo_world() { +Test CoreTests::test_object_tools_work_in_an_older_demo_world() { using namespace settlement; World legacy(12, 12, 12); static_cast(legacy.spawn_agent({4, 4})); @@ -719,9 +770,10 @@ void test_object_tools_work_in_an_older_demo_world() { require(edit(CommandKind::DemolishObject, {4, 5}) == CommandStatus::Accepted, "a field in a demonstration could not be demolished"); static_cast(save_roundtrip(*world)); + return {}; } -void test_room_builds_and_saves_as_separate_parts() { +Test CoreTests::test_room_builds_and_saves_as_separate_parts() { using namespace settlement; World world(61, 16, 16); static_cast(world.spawn_agent({3, 3})); @@ -761,39 +813,176 @@ void test_room_builds_and_saves_as_separate_parts() { resumed->production_orders().size() == 16 && resumed->can_place_storage(floor), "demolition removed the floor instead of the furniture"); static_cast(save_roundtrip(*resumed)); + return {}; +} + +Test CoreTests::test_furnished_rooms_queue_and_build_their_contents() { + using namespace settlement; + using enum RecipeId; + const std::pair variants[] = {{RoomTemplate::Doctor, BuildMedicineCabinet}, + {RoomTemplate::Miner, BuildMiningRack}, {RoomTemplate::Weaver, BuildLoom}}; + for (const auto& [layout, fixture] : variants) { + World world(62, 16, 16); + static_cast(world.spawn_agent({3, 3})); + const auto carpenter = world.spawn_agent({4, 3}); + const auto storage = world.add_storage({3, 2}, 48); + world.stock_storage(storage, ItemType::Wood, 32); + world.stock_storage(storage, ItemType::Stone, 3); + world.stock_storage(storage, ItemType::Cloth, 2); + world.stock_storage(storage, ItemType::Flax, 1); + world.start_scenario({2, 3}); + require(world.apply_command({1, world.next_command_sequence(1), CommandKind::AssignProfession, + {}, static_cast(Profession::Carpenter), {}, carpenter}).status == CommandStatus::Accepted, + "could not assign a carpenter for the furnished room"); + RoomPlan plan{{6, 5}, {9, 8}, RoomSide::East, layout}; + for (const auto side : {RoomSide::North, RoomSide::East, RoomSide::South, RoomSide::West}) { + plan.entrance = side; + const auto decoded = RoomPlan::from_placement(plan.first, plan.last, plan.placement_value()); + const auto parts = decoded.furnishings(); + require(decoded.entrance == side && decoded.layout == layout && parts.has_value(), + "room command lost the direction or furnishings"); + require((*parts)[0].recipe == BuildBed && (*parts)[1].recipe == fixture && + (*parts)[0].position != (*parts)[1].position && + plan.recipe_at((*parts)[0].position) == BuildFloor && + plan.recipe_at((*parts)[1].position) == BuildFloor, + "the furnishings must occupy two distinct interior cells"); + } + const auto parts = *plan.furnishings(); + const auto place = [&](std::uint8_t player, std::uint8_t value) { + return world.apply_command({player, world.next_command_sequence(player), CommandKind::PlaceRoom, + plan.first, value, plan.last}).status; + }; + 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"); + require(place(1, plan.placement_value()) == CommandStatus::InvalidTarget && + world.production_orders().size() == 19, "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) { + return order.position == cell && order.recipe == BuildFloor && order.state == JobState::Completed; + }); + }; + world.step(); + auto resumed = save_roundtrip(world); + for (int tick = 0; tick < 850; ++tick) { + resumed->step(); + for (std::size_t i = 0; i < parts.size(); ++i) { + const auto& order = resumed->production_orders()[i]; + if (order.state != JobState::Available || order.recipe == WeaveCloth) { + require(floor_is_done(*resumed, parts[i].position), "a furnishing started before its floor"); + } + } + } + const auto& bed = resumed->production_orders()[0]; + const auto& furniture = resumed->production_orders()[1]; + require(bed.recipe == BuildBed && bed.position == parts[0].position && bed.state == JobState::Completed && + bed.bed_owner != 0 && bed.bed_base == (layout == RoomTemplate::Miner ? BedBase::Stone : BedBase::Wood), + "the room's bed did not become usable"); + require(furniture.position == parts[1].position, "the furnishing moved during construction"); + if (fixture == BuildLoom) { + 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, + "the themed furnishing did not finish"); + } + static_cast(save_roundtrip(*resumed)); + } + return {}; +} + +Test CoreTests::test_carpenter_delivers_the_door_before_installation() { + using namespace settlement; + auto world = std::make_unique(63, 16, 16); + const auto builder = world->spawn_agent({5, 3}); + const auto carpenter = world->spawn_agent({3, 3}); + const auto first_storage = world->add_storage({2, 3}, 9); + const auto second_storage = world->add_storage({3, 4}, 20); + world->stock_storage(first_storage, ItemType::Wood, 9); + world->stock_storage(second_storage, ItemType::Wood, 20); + constexpr GridPosition workshop{4, 3}; + world->start_scenario(workshop); + const auto assign = [&](AgentId resident, Profession role) { + return world->apply_command({1, world->next_command_sequence(1), CommandKind::AssignProfession, + {}, static_cast(role), {}, resident}).status; + }; + const auto place = [&](const RoomPlan& plan) { + return world->apply_command({1, world->next_command_sequence(1), CommandKind::PlaceRoom, + plan.first, plan.placement_value(), plan.last}).status; + }; + const auto order = [&](RecipeId recipe) -> const ProductionOrder& { + const auto& orders = world->production_orders(); + const auto found = std::find_if(orders.begin(), orders.end(), + [recipe](const auto& entry) { return entry.recipe == recipe; }); + require(found != orders.end(), "expected production order was missing"); + return *found; + }; + const auto crafted_orders = [&] { + return std::count_if(world->production_orders().begin(), world->production_orders().end(), + [](const auto& entry) { return entry.recipe == RecipeId::CraftWoodenDoor; }); + }; + require(assign(builder, Profession::Builder) == CommandStatus::Accepted && + place({{6, 5}, {8, 7}, RoomSide::South}) == CommandStatus::Accepted, + "could not place the room"); + for (int tick = 0; tick < 400; ++tick) world->step(); + require(order(RecipeId::CraftWoodenDoor).state == JobState::Available && + order(RecipeId::InstallDoorAlongX).state == JobState::Available && + world->storages()[0].item_count(ItemType::Wood) == 1, + "a builder or generalist bypassed the carpenter or failed to build the shell"); + require(assign(carpenter, Profession::Carpenter) == CommandStatus::Accepted, "could not promote the carpenter"); + + bool fetched_wood = false, crafted_at_bench = false, delivered_door = false, installed_from_cargo = false; + for (int tick = 0; tick < 400 && order(RecipeId::InstallDoorAlongX).state != JobState::Completed; ++tick) { + world->step(); + const auto& resident = world->agents()[1]; + if (!fetched_wood && resident.inventory.item_count(ItemType::Wood) == 1) { + fetched_wood = true; + require(world->storages()[0].reserved_slots == 1, "no space reserved for the product"); + world = save_roundtrip(*world); + continue; + } + if (!crafted_at_bench && order(RecipeId::CraftWoodenDoor).state == JobState::InProgress && + resident.state == AgentState::Working && resident.position == workshop) { + crafted_at_bench = true; + world = save_roundtrip(*world); + continue; + } + if (!delivered_door && resident.inventory.item_count(ItemType::WoodenDoor) == 1) { + delivered_door = true; + require(resident.state == AgentState::Hauling && resident.storage_index == 0 && + world->storages()[0].item_count(ItemType::WoodenDoor) == 0, + "the finished door appeared on the store before being delivered"); + world = save_roundtrip(*world); + continue; + } + if (!installed_from_cargo && world->agents()[0].inventory.item_count(ItemType::WoodenDoor) == 1) { + installed_from_cargo = true; + world = save_roundtrip(*world); + } + } + require(fetched_wood && crafted_at_bench && delivered_door && installed_from_cargo && + order(RecipeId::InstallDoorAlongX).state == JobState::Completed && crafted_orders() == 1 && + world->storages()[0].reserved_slots == 0 && world->storages()[1].item_count(ItemType::Wood) == 19, + "the complete carpenter and builder workflow did not run"); + + require(world->apply_command({1, world->next_command_sequence(1), CommandKind::CraftDoor}).status == + CommandStatus::Accepted, "an independent door order was rejected"); + for (int tick = 0; tick < 300 && world->storages()[1].item_count(ItemType::WoodenDoor) == 0; ++tick) world->step(); + require(world->storages()[1].item_count(ItemType::WoodenDoor) == 1 && crafted_orders() == 2, + "the independent order did not produce a spare door"); + require(place({{10, 5}, {12, 7}, RoomSide::South}) == CommandStatus::Accepted && crafted_orders() == 2, + "a new room did not use the spare door"); + require(world->apply_command({1, world->next_command_sequence(1), CommandKind::DemolishObject, + world->storages()[1].position}).status == CommandStatus::Accepted && crafted_orders() == 3, + "losing the stock did not queue a replacement for the waiting room"); + static_cast(save_roundtrip(*world)); + return {}; } } // namespace -int main() { - try { - test_rng_repeats_for_same_seed(); - test_work_jobs_complete(); - test_astar_route_uses_opening_in_wall(); - test_parallel_pathfinding_completes_the_jobs(); - test_single_worker_configuration_is_rejected(); - test_residents_gather_and_deliver_resources(); - test_production_reservations_and_construction(); - test_cabin_placement_queues_a_complete_order(); - test_hungry_resident_reserves_and_eats_a_berry(); - test_invalid_save_is_rejected(); - test_two_players_share_the_first_colony(); - test_bed_parts_are_delivered_separately(); - test_resident_uses_assigned_bed_and_sleep_survives_save(); - test_fatigue_slows_work_without_interrupting_it(); - test_ground_rest_never_uses_another_residents_bed(); - test_fields_mines_and_reindexing_active_hauls(); - test_specialists_take_their_own_jobs_and_finish_prior_assignments(); - test_flax_and_loom_supply_a_bed_without_starting_cloth(); - test_field_growth_requires_a_worker(); - test_opening_a_mine_invalidates_unreachable_routes(); - test_object_tools_work_in_an_older_demo_world(); - test_room_builds_and_saves_as_separate_parts(); - } catch (const std::exception& error) { - std::cerr << "Test failed: " << error.what() << '\n'; - return 1; - } - - std::cout << "All core checks passed.\n"; - return 0; +int main(int argc, char** argv) { + return CoreTests::run(argc, argv); } diff --git a/tests/lan_tests.cpp b/tests/lan_tests.cpp index da8b32d..d3e64a9 100644 --- a/tests/lan_tests.cpp +++ b/tests/lan_tests.cpp @@ -1,3 +1,5 @@ +#include "testing.hpp" + #include "lan_session.hpp" #include @@ -15,7 +17,13 @@ void require(bool condition, const char* message) { if (!condition) throw std::runtime_error(message); } -void test_shared_colony_over_loopback() { +using Void::Testing::Test; + +struct LanTests : Void::Testing::Suite { + [[= Void::Testing::tag("lan")]] Test test_shared_colony_over_loopback(); +}; + +Test LanTests::test_shared_colony_over_loopback() { auto authoritative = make_first_colony(4); auto client_view = make_first_colony(4); for (int i = 0; i < 25; ++i) authoritative->step(); @@ -149,8 +157,10 @@ void test_shared_colony_over_loopback() { const auto previous_size = authoritative->production_orders().size(); require(guest.submit(CommandKind::PlaceRoom, room.first, entrance, room.last), "guest could not send the room"); - pump_until([&] { return client_view->production_orders().size() == previous_size + 9; }, - "snapshot did not carry all room components"); + pump_until([&] { + return client_view->production_orders().size() == previous_size + 10 && + client_view->production_orders().back().recipe == RecipeId::CraftWoodenDoor; + }, "snapshot did not carry the room and carpenter's order"); require(guest.submit(CommandKind::PlaceRoom, room.first, entrance, room.last), "guest could not send the conflicting room"); pump_until([&] { @@ -159,17 +169,13 @@ void test_shared_colony_over_loopback() { rejected->destination == room.last && rejected->value == entrance && rejected->status == CommandStatus::InvalidTarget; }, "room rejection lost the geometry needed to restore the draft"); - require(authoritative->production_orders().size() == previous_size + 9, "room conflict scheduled extra work"); + require(authoritative->production_orders().size() == previous_size + 10, "room conflict scheduled extra work"); std::cout << "Loopback LAN checks passed.\n"; + return {}; } } // namespace -int main() { - try { - test_shared_colony_over_loopback(); - } catch (const std::exception& error) { - std::cerr << error.what() << '\n'; - return 1; - } +int main(int argc, char** argv) { + return LanTests::run(argc, argv); } diff --git a/tests/testing.hpp b/tests/testing.hpp new file mode 100644 index 0000000..4805f03 --- /dev/null +++ b/tests/testing.hpp @@ -0,0 +1,115 @@ +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace Void::Testing { + +struct Test {}; + +struct AnnotationText { + char text[96]{}; + + consteval AnnotationText(std::string_view value) { + if (value.size() >= sizeof(text)) throw "Test annotation is too long"; + value.copy(text, value.size()); + } + + constexpr std::string_view view() const noexcept { return text; } +}; + +struct Tag { AnnotationText value; }; +struct Skip { AnnotationText value; }; + +consteval Tag tag(std::string_view value) { return {value}; } +consteval Skip skip(std::string_view reason) { return {reason}; } + +namespace detail { + +namespace meta = std::meta; + +template +std::vector annotation_values() { + std::vector values; + template for (constexpr auto a : std::define_static_array(meta::annotations_of_with_type(Member, ^^Annotation))) { + constexpr auto annotation = meta::extract(a); + values.emplace_back(annotation.value.view()); + } + return values; +} + +consteval bool is_test(meta::info member) { + return meta::is_function(member) && !meta::is_static_member(member) && + !meta::is_constructor(member) && !meta::is_destructor(member) && + meta::parameters_of(member).empty() && meta::return_type_of(member) == ^^Test; +} + +} // namespace detail + +template +struct Suite { + template + static void expect_eq(const Actual& actual, const Expected& expected, + std::source_location at = std::source_location::current()) { + if (!(actual == expected)) { + throw std::runtime_error(std::string(at.file_name()) + ":" + std::to_string(at.line()) + + ": expected equal values"); + } + } + + static int run(int argc, char** argv) { + std::string_view selected_tag; + if (argc == 3 && std::string_view(argv[1]) == "--tag" && argv[2][0] != '\0') { + selected_tag = argv[2]; + } else if (argc != 1) { + std::cerr << "Usage: " << argv[0] << " [--tag NAME]\n"; + return 1; + } + namespace meta = std::meta; + int matched = 0, failed = 0, skipped = 0; + template for (constexpr auto member : std::define_static_array(meta::members_of(^^Derived, + meta::access_context::current()))) { + if constexpr (detail::is_test(member)) { + const auto tags = detail::annotation_values(); + if (selected_tag.empty() || std::ranges::find(tags, selected_tag) != tags.end()) { + ++matched; + constexpr auto name = meta::identifier_of(member); + const auto reasons = detail::annotation_values(); + if (!reasons.empty()) { + ++skipped; + std::cout << "[SKIP] " << name << " (" << reasons.front() << ")\n"; + } else { + try { + Derived suite{}; + if constexpr (requires { suite.setup(); }) suite.setup(); + suite.[:member:](); + std::cout << "[PASS] " << name << '\n'; + } catch (const std::exception& error) { + ++failed; + std::cerr << "[FAIL] " << name << ": " << error.what() << '\n'; + } catch (...) { + ++failed; + std::cerr << "[FAIL] " << name << ": unexpected exception\n"; + } + } + } + } + } + if (matched == 0) { + std::cerr << "No tests matched"; + if (!selected_tag.empty()) std::cerr << " tag " << selected_tag; + std::cerr << '\n'; + return 1; + } + std::cout << matched - failed - skipped << " passed, " << failed << " failed, " << skipped << " skipped\n"; + return failed == 0 ? 0 : 1; + } +}; + +} // namespace Void::Testing -- 2.54.0 From 803433bc9433778c838b9cdea6c0e859f639b236 Mon Sep 17 00:00:00 2001 From: Codex Date: Tue, 1 Dec 2026 11:54:01 +0300 Subject: [PATCH 7/7] Apply furniture and standalone loom crafting to the Windows game --- app/d3d_scene_win32.cpp | 15 +-- app/lan_session_win32.cpp | 2 +- app/viewer_win32.cpp | 57 ++++++--- docs/viewer.md | 2 + engine/include/settlement/core/world.hpp | 43 +++++-- engine/src/world.cpp | 112 ++++++++++++++---- engine/src/world_save.cpp | 39 +++++-- tests/core_tests.cpp | 141 ++++++++++++++++++++++- tests/lan_tests.cpp | 8 +- 9 files changed, 345 insertions(+), 74 deletions(-) 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(); } -- 2.54.0