diff --git a/CMakeLists.txt b/CMakeLists.txt index 9da6c35..7e74e26 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -35,16 +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) + 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() @@ -56,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 832e915..c6445fc 100644 --- a/PLAN.md +++ b/PLAN.md @@ -2,14 +2,14 @@ ## Цель -Самостоятельная C++-игра о поселении с повторяемой симуляцией, многопоточным расчётом и изометрическим клиентом. Это отдельный проект, не совместимый движок для Stonehearth. Код и игровые ресурсы Stonehearth не включаются. +Самостоятельная C++-игра о поселении с повторяемой симуляцией, многопоточным расчётом и 3D-клиентом. Это отдельный проект, не совместимый движок для Stonehearth. Код и игровые ресурсы Stonehearth не включаются. ## Этапы ### P0 — Инструменты и границы проекта - [x] Отдельный каталог, CMake, C++20, лицензия и базовая структура. -- [x] Portable-установщик CMake/LLVM-MinGW и скрипт сборки с CTest. +- [x] Portable-установщик MSYS2 UCRT64 с GCC 16 и сборка с CTest. - [ ] CI для Windows и Linux. - [x] Не включать код и ресурсы Stonehearth. @@ -39,17 +39,24 @@ - [x] Пул потоков для независимого выбора заданий, A* и продвижения жителей. - [x] Стабильное применение результатов в конце шага симуляции. - [x] Многопоточный режим с двумя и более рабочими потоками; проверка игровых результатов и загрузки. -- [x] Выбор числа потоков в командной версии и Windows-клиенте. +- [x] Автоматический выбор числа потоков в Windows-клиенте и параметр для командных бенчмарков. - [x] Повторный замер времени тика после расширения систем ресурсов. ### P4 — Игровой клиент -- [x] Изометрический Windows-просмотрщик карты, маршрутов и жителей. +- [x] Windows-клиент с отображением карты, маршрутов и жителей. - [x] Отображение источников ресурсов, складов и текущих запасов. - [x] Камера с перемещением и масштабированием относительно курсора. - [x] Нижняя панель с жителями, добычей, участками и строительством. -- [ ] Настоящий графический 3D-рендерер и объёмные модели. +- [x] Нижние кнопки «Работы» и приоритета с настраиваемым масштабом панели. +- [x] Главное меню со списком сохранений, продолжением партии и управлением кооперативом. +- [x] Меню Esc с паузой, сохранениями, выходом в главное меню и завершением игры. +- [x] Игровая карта на Direct3D 11 с глубиной и базовыми объёмными моделями. +- [ ] Расширение набора 3D-моделей и освещения. - [x] Постановка чертежа домика мышью в Windows-клиенте. +- [x] Редактируемая раскладка кроватей и станков с предпросмотром, списком материалов и подтверждением. +- [x] Прямоугольные чертежи комнат с полом, стенами, выбором стороны входа и поэтапной стройкой. +- [ ] Маршруты через дверные проёмы и настройка формы комнаты. - [ ] Интерфейс для остальных типов работ и зданий. ### P5 — Игровые системы и совместная игра 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 0000000..9bc0d00 Binary files /dev/null and b/app/art/doctor_house.ico differ diff --git a/app/art/miner_house.ico b/app/art/miner_house.ico new file mode 100644 index 0000000..6873e31 Binary files /dev/null and b/app/art/miner_house.ico differ diff --git a/app/art/weaver_house.ico b/app/art/weaver_house.ico new file mode 100644 index 0000000..f191e24 Binary files /dev/null and b/app/art/weaver_house.ico differ diff --git a/app/d3d_scene_win32.cpp b/app/d3d_scene_win32.cpp new file mode 100644 index 0000000..d7f4574 --- /dev/null +++ b/app/d3d_scene_win32.cpp @@ -0,0 +1,674 @@ +#define NOMINMAX +#include "d3d_scene_win32.hpp" + +#include +#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 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)); + 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 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 (furnishing_shape(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)); + 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()) { + 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)); + 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)); + 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 (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, 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 (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 + ? (fixture == RecipeId::BuildMedicineCabinet ? rgb(169, 214, 183) : rgb(153, 166, 172)) + : rgb(158, 202, 209); + 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, + 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::BuildBed) { + draw_blueprint(mesh, {order.position, order.recipe, order.bed_base}, false); + } else if (order.recipe == RecipeId::BuildCabin && order.state == JobState::Completed) { + 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); + mesh.box(x, y, .015f, .20f, .20f, .10f, + job.state == JobState::Available ? rgb(76, 134, 90) : rgb(208, 159, 77)); + } +} + +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; + 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 (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)); + } + } +} + +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, view.building_view); + for (std::size_t index = 0; index < view.room_blueprints.size(); ++index) { + if (view.moving_room == index) continue; + const auto& plan = view.room_blueprints[index]; + draw_room_plan(graphics.mesh, plan, false, world.can_place_room(plan)); + } + if (view.room_preview) draw_room_plan(graphics.mesh, *view.room_preview, true, view.valid_cursor); + for (const auto& part : view.blueprint) draw_blueprint(graphics.mesh, part, false); + if (view.preview) draw_blueprint(graphics.mesh, *view.preview, true); + 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..4b72d89 --- /dev/null +++ b/app/d3d_scene_win32.hpp @@ -0,0 +1,57 @@ +#pragma once + +#include + +#include "settlement/core/world.hpp" + +#include +#include +#include +#include +#include + +namespace settlement::viewer { + +enum class BuildingView { Full, NoRoofs, FloorsOnly }; + +struct BlueprintPart { + GridPosition cell; + RecipeId recipe; + BedBase base = BedBase::Wood; +}; + +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; + std::span blueprint; + std::optional preview; + std::span room_blueprints; + std::optional room_preview; + BuildingView building_view = BuildingView::Full; + std::optional moving_room; +}; + +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/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.hpp b/app/lan_session.hpp index 0ee6cef..74def74 100644 --- a/app/lan_session.hpp +++ b/app/lan_session.hpp @@ -12,6 +12,14 @@ 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; + GridPosition destination; +}; + class LanSession { public: LanSession(); @@ -30,7 +38,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..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 = 7; +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; @@ -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, awaiting_receipt->destination}; + } 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/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 new file mode 100644 index 0000000..9710681 --- /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_coop_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 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 { + 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)); + 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..02255fa 100644 --- a/app/viewer_win32.cpp +++ b/app/viewer_win32.cpp @@ -6,8 +6,11 @@ #include #include -#include "isometric_camera.hpp" +#include "d3d_scene_win32.hpp" +#include "house_icons.h" +#include "map_camera.hpp" #include "lan_session.hpp" +#include "title_screen_win32.hpp" #include "settlement/core/world.hpp" #include @@ -31,10 +34,10 @@ namespace { -constexpr wchar_t window_class[] = L"SettlementIsometricViewer"; +constexpr wchar_t window_class[] = L"SettlementViewer"; constexpr wchar_t resident_window_class[] = L"SettlementResidentRoster"; -constexpr int worker_combo_id = 1001; -constexpr int apply_button_id = 1002; +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; constexpr int save_menu_id = 1005; @@ -62,52 +65,90 @@ 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 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; 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; constexpr int timer_id = 1; constexpr int map_size = settlement::first_colony_map_size; constexpr int tile_width = 24; constexpr int tile_height = 14; constexpr int map_origin_y = 86; constexpr int map_top = 76; -constexpr int map_footer = 166; -constexpr int dock_sections_offset = 40; -constexpr int dock_actions_offset = 110; -constexpr int dock_materials_offset = 77; -constexpr int bed_choice_width = 78; -constexpr int bed_choice_height = 28; -constexpr int work_button_gap = 8; constexpr settlement::GridPosition sawmill{15, 14}; constexpr settlement::GridPosition stonecutter{17, 14}; -HWND worker_combo = nullptr; -HWND apply_button = nullptr; HWND status_label = nullptr; HWND production_label = nullptr; HWND wood_bed_button = nullptr; HWND stone_bed_button = nullptr; HWND priority_button = nullptr; -HWND pause_button = nullptr; +HWND 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 { + int height = 0; + int hint_top = 0; + int line_height = 0; + int scale = default_interface_scale; +}; +DockLayout dock_layout; 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; +bool enter_game_on_snapshot = false; +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; -std::size_t selected_workers = settlement::min_worker_count; -enum class PlacementMode { None, Building, Foraging, BerryField, FlaxField, TreePlot, Mine, Loom, Storage, Pantry, Move, Demolish }; +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 }; +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}, @@ -120,6 +161,15 @@ 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}, WorkChoice{loom_id, L"Ткацкий станок", WorkIcon::Loom, 149, PlacementMode::Loom}, @@ -127,13 +177,30 @@ 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}, + 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[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; @@ -156,6 +223,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; @@ -174,8 +242,19 @@ struct ResidentRoster { }; ResidentRoster roster; 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::IsometricCamera camera; +settlement::viewer::MapCamera camera; struct CameraDrag { POINT previous; bool left_button; @@ -187,6 +266,10 @@ std::optional hover_cell; std::optional selected_resident; std::wstring placement_message; +int dock_pixels(int pixels) { + return MulDiv(pixels, dock_layout.scale, 100); +} + COLORREF color(int red, int green, int blue) { return RGB(red, green, blue); } @@ -216,7 +299,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); @@ -225,7 +308,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); }; @@ -302,11 +389,24 @@ 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; + 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); } -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}; } @@ -315,8 +415,22 @@ 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 || + placement_mode == PlacementMode::Room; +} + +bool has_blueprint() { + return !blueprint.empty() || !room_blueprints.empty(); +} + +bool shows_blueprint_actions() { + return !showing_title && (is_blueprint_tool() || has_blueprint()); +} + 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 && graphics.ready() && point.x >= 0 && point.x < client.right && + point.y >= map_top && point.y < client.bottom - dock_layout.height; } POINT client_point(LPARAM coordinates) { @@ -328,6 +442,26 @@ void invalidate_scene(HWND window) { GetClientRect(window, &scene); scene.top = map_top; if (scene.bottom > scene.top) InvalidateRect(window, &scene, FALSE); + if (!showing_title && graphics.ready() && scene_window) { + InvalidateRect(scene_window, nullptr, FALSE); + } +} + +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) { @@ -364,174 +498,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}; @@ -549,42 +515,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; }); @@ -608,43 +538,149 @@ 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 {}; } -void layout_command_dock(HWND window) { - const auto choices = work_choices(); - RECT client{}; - GetClientRect(window, &client); - const auto width = static_cast(client.right); - const auto height = static_cast(client.bottom); - constexpr int section_widths[] = {112, 112, 112, 160}; - constexpr int sections_width = 112 * 3 + 160 + 3 * work_button_gap; - int section_x = std::max(16, (width - sections_width) / 2); - const auto place = [](HWND button, int x, int y, int w, int h) { - SetWindowPos(button, nullptr, x, y, w, h, SWP_NOZORDER | SWP_NOACTIVATE); +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 { + HWND control; + int width; + bool materials = false; }; - 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 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. + 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, 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 ? 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, 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, 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 = 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); + + if (shows_blueprint_actions()) { + const DockItem actions[] = {{build_blueprint_button, 182}, {clear_blueprint_button, 188}}; + layout_rows(actions, pixels(compact ? 31 : 37)); + } + const int line_height = pixels(compact ? 20 : 23); + const int hint_top = bottom - 2 * line_height; + return {height - hint_top + pixels(8), hint_top, line_height, 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)); + 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, 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); + 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); +} + +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 scale >= min_interface_scale && scale <= max_interface_scale ? scale : default_interface_scale; } void invalidate_work_choices() { @@ -668,17 +704,19 @@ 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, work_panel != WorkPanel::Carpenter || (world && world->scenario_active())); ShowWindow(button, SW_SHOWNA); } for (const auto button : dock_section_buttons) InvalidateRect(button, nullptr, FALSE); invalidate_work_choices(); RECT row{}; GetClientRect(window, &row); - row.top = row.bottom - map_footer; + 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, HICON artwork = nullptr) { const bool disabled = (item.itemState & ODS_DISABLED) != 0; const bool pressed = (item.itemState & ODS_SELECTED) != 0; const auto dc = item.hDC; @@ -707,11 +745,12 @@ 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); + 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); @@ -726,21 +765,36 @@ 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 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, 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)]; - draw_icon_button(item, section.icon, work_panel == section.panel, true); - return true; + 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)]; - draw_icon_button(item, choice.icon, placement_mode == choice.mode, true); - return true; + 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() { @@ -819,6 +873,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); @@ -827,13 +882,14 @@ 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(world->tick()) + - (lan.is_guest() ? L" Симуляция у хозяина" : L" Потоков: " + std::to_wstring(world->worker_count())); + L" Двери: " + std::to_wstring(doors) + + 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(); @@ -842,12 +898,12 @@ 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); + 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"Сначала стройка"; 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(), @@ -885,24 +941,45 @@ 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, has_blueprint() && can_give_orders() && !room_draft_move); + EnableWindow(clear_blueprint_button, has_blueprint()); + layout_command_dock(window); +} + void set_placement_mode(HWND window, PlacementMode mode, const wchar_t* message = L"") { placement_mode = mode; 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(); + update_blueprint_controls(window); invalidate_work_choices(); invalidate_scene(window); } +void clear_blueprints() { + blueprint.clear(); + room_blueprints.clear(); + room_anchor.reset(); + room_draft_move.reset(); +} + void toggle_work_panel(HWND window, WorkPanel panel) { if (!can_give_orders()) return; set_placement_mode(window, PlacementMode::None); @@ -910,13 +987,52 @@ 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) { + if (roster.window) DestroyWindow(roster.window); + set_work_panel(window, WorkPanel::None); + set_placement_mode(window, PlacementMode::None); + title_screen.reload_saves(); + update_title_controls(); + } else { + has_session = true; + 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; + 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); + RECT client{}; + GetClientRect(window, &client); + title_screen.layout(client.right, client.bottom); + update_blueprint_controls(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); + clear_blueprints(); 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 +1048,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 +1083,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 +1092,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 +1102,18 @@ 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); + clear_blueprints(); + 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()); @@ -1094,29 +1219,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; - EnableWindow(worker_combo, offline); - EnableWindow(apply_button, offline); - const auto menu = GetMenu(window); - const auto enable = [&](UINT command, bool enabled) { - EnableMenuItem(menu, command, MF_BYCOMMAND | (enabled ? MF_ENABLED : MF_GRAYED)); - }; - enable(lan_host_id, offline); - enable(lan_join_id, offline || disconnected); - enable(lan_info_id, hosting); - enable(lan_reconnect_id, disconnected); - enable(lan_leave_id, !offline); - enable(save_menu_id, !lan.is_guest()); - enable(load_menu_id, offline); const wchar_t* suffix = L""; switch (state) { case LanState::Offline: break; @@ -1126,34 +1236,51 @@ 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()); + enter_game_on_snapshot = false; + placement_message = showing_title ? L"Связь потеряна. Откройте «Кооператив», чтобы подключиться снова." : + L"Связь прервана. Переподключение — в разделе «Кооператив» главного меню."; } else if (state == LanState::GuestConnected) { placement_message = L"Подключено к колонии хозяина."; } - DrawMenuBar(window); if (roster.window) update_roster_details(); update_status(); + if (showing_title) { + 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->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); + clear_blueprints(); + 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())); + clear_blueprints(); + enter_game_on_snapshot = true; selected_resident.reset(); sync_resident_roster(true); set_work_panel(window, WorkPanel::None); @@ -1161,10 +1288,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"Сетевая игра завершена."); } @@ -1175,6 +1305,46 @@ 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 (command == title::title_coop_id && notification == BN_CLICKED) { + open_coop_menu(window); + return; + } + 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) || + (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 (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 (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; @@ -1214,11 +1384,214 @@ 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; } +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, 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 &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) { + 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; + if (world->can_place_room(room)) return room; + } + room.entrance = settlement::RoomSide::South; + } + return room; +} + +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_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 клеток."; + } 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 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)) { + *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(); + } + update_blueprint_controls(window); + invalidate_scene(window); +} + +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) && room_at(cell) == room_blueprints.end()) { + 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 || !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, + room.placement_value(), 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) && + 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(rooms_sent + objects_sent); + if (has_blueprint()) { + placement_message = L"Принято мест: " + count + L". Осталось в чертеже: " + + std::to_wstring(blueprint.size() + room_blueprints.size()) + + (lan.is_guest() ? L". Проверьте карту и отправьте оставшиеся места снова." : + L". Проверьте, свободны ли клетки и есть ли к ним проход."); + } 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); +} + void edit_at_cell(HWND window, settlement::GridPosition cell) { using settlement::CommandKind; using settlement::CommandStatus; @@ -1260,8 +1633,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 : @@ -1287,9 +1658,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; @@ -1327,7 +1700,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"Профессия"; @@ -1347,10 +1720,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; @@ -1441,7 +1814,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); @@ -1469,7 +1842,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; @@ -1490,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::Flax, L"лён"}, {ItemType::WoodenDoor, L"деревянная дверь"}, + {ItemType::MedicineCabinet, L"аптечный шкаф"}, {ItemType::MiningRack, L"стойка шахтёра"}, + {ItemType::Loom, L"ткацкий станок"} }; std::wstring cargo; for (const auto& [type, name] : items) { @@ -1504,6 +1879,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 && + 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) { const auto& site = world->resource_nodes()[resident->resource_node_index]; @@ -1533,102 +1913,48 @@ 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)); - } +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"каменные блоки"}, + {ItemType::WoodenDoor, L"готовые двери"}, {ItemType::MedicineCabinet, L"аптечные шкафы"}, + {ItemType::MiningRack, L"стойки шахтёра"}, {ItemType::Loom, L"ткацкие станки"}}; + std::array totals{}; + for (const auto& part : blueprint) { + 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; } } - - 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; + 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 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; + } } - 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); + if (const auto furnishings = room.furnishings()) { + for (const auto& part : *furnishings) { + 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; } } - 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); - } } } - + 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); + } + return text; } void draw_world(HDC dc, int width, int height) { @@ -1638,22 +1964,15 @@ void draw_world(HDC dc, int width, int height) { DeleteObject(background); if (!world) return; - if (height > map_top + map_footer) { - const int saved = SaveDC(dc); - if (saved != 0) { - IntersectClipRect(dc, 0, map_top, width, height - map_footer); - const auto offset = camera.offset(); - const auto scale = static_cast(camera.scale()); - const XFORM transform{scale, 0.0F, 0.0F, scale, - static_cast(offset.x), static_cast(offset.y)}; - if (SetGraphicsMode(dc, GM_ADVANCED) != 0 && SetWorldTransform(dc, &transform)) { - draw_map(dc, width); - } - RestoreDC(dc, saved); - } + 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); @@ -1664,11 +1983,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) { @@ -1677,32 +1996,334 @@ 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) { hint = move_source ? L"Выберите свободную клетку для переноса." : L"Выберите кровать, склад, станок или посаженный участок."; } else if (placement_mode == PlacementMode::Demolish) { - hint = L"Щёлкните по объекту, чтобы снести его. Esc отменяет режим."; - } else if (placement_mode == PlacementMode::Building) { - if (world->staged_beds()) { - hint = selected_bed_base - ? L"Щёлкайте по свободным клеткам. Основу можно сменить под кнопкой «Спальное место»." - : L"Выберите «Дерево» или «Камень» под кнопкой «Спальное место»."; - } else if (world->scenario_active()) { - hint = L"Щёлкайте по свободным клеткам. Одно место требует доску. Esc — выход."; + hint = L"Щёлкните по объекту, чтобы снести его. Правая кнопка — отмена."; + } else if (placement_mode == PlacementMode::Room) { + if (room_draft_move) { + hint = L"Щёлкните по новой площадке. R поворачивает дом, правый щелчок отменяет перенос."; + } else if (selected_room_template != settlement::RoomTemplate::Empty) { + hint = L"Выберите площадку 4×4. R поворачивает дом, Shift + щелчок переносит чертёж."; } else { - hint = L"Выберите свободную клетку. Домик стоит три доски и два блока. Esc — отмена."; + 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"Дверь и станок требуют по 2 дерева, шкаф — 1 дерево, стойка — по 1 дереву и камню."; + } + 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); + 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 settlement::is_carpentry_recipe(order.recipe) && order.state != settlement::JobState::Completed; + }); + 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" Назначьте плотника в списке «Жители»."; } } - RECT legend{24, height - 159, width - 24, height - 136}; - DrawTextW(dc, hint, -1, &legend, DT_LEFT | DT_VCENTER | DT_SINGLELINE | DT_END_ELLIPSIS); - const auto details = resident_details(); SetTextColor(dc, color(190, 201, 178)); - RECT inspector{24, height - 135, width - 24, height - 113}; + 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; + std::optional room_preview; + 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 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() && + 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, 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) { + 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() || + client.right <= 0 || client.bottom <= 0 || + graphics.render(*world, scene_view(client.right, client.bottom)); + EndPaint(window, &paint); + if (!drawn) { + graphics.reset(); + const auto parent = GetParent(window); + layout_scene(parent); + invalidate_scene(parent); + } + return 0; + } + return DefWindowProcW(window, message, wparam, lparam); +} + +struct MenuAction { + int id; + const wchar_t* caption; + bool enabled = true; +}; + +struct MenuDialog { + const wchar_t* title; + std::span actions; + HBRUSH background; +}; + +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); + SetWindowLongPtrW(dialog, DWLP_USER, lparam); + 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); + EnableWindow(child, action.enabled); + if (!first_enabled && action.enabled) first_enabled = child; + y += 25; + } + SetFocus(first_enabled); + return FALSE; + } + case WM_CTLCOLORDLG: + 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) { + 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; + 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; +} + +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 = 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, + menu_dialog_proc, reinterpret_cast(&menu)); + DeleteObject(menu.background); + return static_cast(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) { + 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); + } +} + +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"Выйти из игры"}, + }; + 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)); + } + break; + case save_menu_id: + 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); + break; + case exit_menu_id: + DestroyWindow(window); + break; + } + pause_menu_open = false; + 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) { @@ -1710,31 +2331,22 @@ 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: { - 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())); + 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); } - SendMessageW(worker_combo, CB_SETCURSEL, static_cast(selected_workers - settlement::min_worker_count), 0); - apply_button = CreateWindowExW(0, L"BUTTON", L"Применить и начать заново", WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON, - 220, 10, 190, 28, window, - reinterpret_cast(static_cast(apply_button_id)), - GetModuleHandleW(nullptr), nullptr); status_label = CreateWindowExW(0, L"STATIC", L"", WS_CHILD | WS_VISIBLE, - 430, 14, 620, 24, window, + 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, @@ -1746,40 +2358,106 @@ 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"Равный приоритет"); - pause_button = button(pause_button_id, 168, 96, L"Пауза"); + 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); + 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); ShowWindow(work_choice_buttons[index], SW_HIDE); } - layout_command_dock(window); - reset_world(window); + 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); 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) == 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_BOTTOMALIGN | TPM_RIGHTBUTTON, + bounds.left, bounds.top, 0, window, nullptr); + DestroyMenu(menu); + } + SetFocus(window); + return 0; + } if (LOWORD(wparam) == residents_button_id && HIWORD(wparam) == BN_CLICKED) { 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 && has_blueprint()) { + clear_blueprints(); + 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); return 0; } + if (LOWORD(wparam) == carpenter_menu_id && HIWORD(wparam) == BN_CLICKED) { + toggle_work_panel(window, WorkPanel::Carpenter); + update_status(); + return 0; + } + 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()) { + 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); + return 0; + } if (LOWORD(wparam) >= first_dock_section_id && static_cast(LOWORD(wparam) - first_dock_section_id) < dock_sections.size() && HIWORD(wparam) == BN_CLICKED) { @@ -1796,10 +2474,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, @@ -1821,15 +2495,12 @@ 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) == 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) == 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) { @@ -1838,6 +2509,37 @@ 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()) { + 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; + } 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; @@ -1854,19 +2556,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) { - 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: { @@ -1953,46 +2647,11 @@ 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 (world && is_blueprint_tool()) { + if (const auto cell = map_cell(client, point)) { + if (placement_mode == PlacementMode::Room) edit_room_blueprint(window, *cell, (wparam & MK_SHIFT) != 0); + else edit_blueprint(window, *cell); } - if (!cell || !world->can_place_cabin(*cell)) { - placement_message = L"Здесь нельзя поставить домик. Выберите свободную клетку."; - invalidate_scene(window); - return 0; - } - try { - world->queue_cabin(*cell, sawmill, stonecutter); - } catch (const std::invalid_argument&) { - placement_message = L"К участку нет прохода от мастерских. Выберите другую клетку."; - invalidate_scene(window); - return 0; - } - set_placement_mode(window, PlacementMode::None, L"Чертёж поставлен. Материалы заказаны в мастерских."); - update_status(); return 0; } if (world && placement_mode >= PlacementMode::BerryField) { @@ -2009,6 +2668,33 @@ LRESULT CALLBACK window_proc(HWND window, UINT message, WPARAM wparam, LPARAM lp break; } 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(); + 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); @@ -2016,6 +2702,12 @@ 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 : @@ -2031,22 +2723,52 @@ 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 (!file_dialog_active && !lan.is_guest()) world->step(); - if (auto snapshot = lan.poll(*world)) world = std::move(snapshot); + 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); + 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); 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 (rejection->kind == CommandKind::PlaceRoom) { + 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); + 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, + 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); @@ -2056,7 +2778,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 +2797,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 +2811,9 @@ LRESULT CALLBACK window_proc(HWND window, UINT message, WPARAM wparam, LPARAM lp case WM_DESTROY: KillTimer(window, timer_id); lan.leave(); + graphics.reset(); + if (dock_font) DeleteObject(std::exchange(dock_font, nullptr)); + scene_window = nullptr; PostQuitMessage(0); return 0; } @@ -2091,7 +2823,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); @@ -2102,39 +2834,22 @@ 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(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 — Первое поселение", + 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); MSG message{}; 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/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/roadmap-status.md b/docs/roadmap-status.md index cfd966c..587dec5 100644 --- a/docs/roadmap-status.md +++ b/docs/roadmap-status.md @@ -4,8 +4,8 @@ - Ядро симуляции с фиксированными тиками. - Пул потоков для выбора заданий, поиска маршрутов и продвижения жителей. -- Настройка числа потоков в командной версии и в Windows-просмотрщике. -- Изометрический прототип карты с жителями, заданиями и маршрутами. +- Автоматический выбор числа потоков в Windows-клиенте и параметр для командных бенчмарков. +- Объёмная карта с жителями, заданиями и маршрутами. - Базовый цикл ресурсов: источник дерева/камня → резервирование → добыча → перенос → склад. - Складской инвентарь со стеками `Wood` и `Stone` и учётом свободной вместимости. - Два рецепта превращают древесину в доски и камень в блоки. Домик строится из трёх досок и двух блоков. @@ -26,6 +26,9 @@ - Рост полей и посадок начинается после выполнения поручения фермером или лесорубом. После сбора участка выдаётся новое поручение. - Производительность ядра измерена на колониях с 50–500 жителями, полями, складами и ремеслом. Результаты и команда запуска описаны в [отчёте](../benchmarks/colony-performance.md). - Основные команды собраны в нижней панели «Жители», «Добыча», «Участки» и «Строительство». Меню «Работы» открывает те же команды по профессиям. +- Главное меню открывается при запуске. В нём можно начать новую колонию, выбрать сохранение или подключиться к другу. +- Esc открывает меню паузы и сохранений. Создание сетевой партии и подключение находятся в разделе «Кооператив» главного меню. +- Direct3D 11 рисует карту, жителей и постройки как объёмную геометрию с глубиной. - Поиск ресурсных работ отбирает подходящие поручения по профессиям. Повторные запросы путей используют кэш. - Движение, прогресс работ жителей и поиск маршрутов для общих заданий выполняются в пуле из двух и более потоков. Тесты проверяют игровые результаты, сохранения и команды кооператива. @@ -35,7 +38,7 @@ ## Ограничения прототипа -- Графика изометрическая и рисуется Win32/GDI; полноценного 3D-рендера пока нет. +- Камера поддерживает перемещение и масштабирование. Direct3D использует базовые модели и затенение граней. - Каждый поход добытчика доставляет одну единицу сырья. Строитель везёт весь комплект для одного домика за рейс с остановками у нужных складов. Мастерские пока используют складское сырьё напрямую. - Свободный житель сначала ищет еду, если проголодался. Если порции нет, он может снова взять работу. При голоде здоровье пока остаётся прежним. - Завершённое спальное место назначается одному жителю. Сейчас жители идут спать по усталости. diff --git a/docs/viewer.md b/docs/viewer.md index 2ca3d51..455b74f 100644 --- a/docs/viewer.md +++ b/docs/viewer.md @@ -1,4 +1,4 @@ -# Запуск изометрического прототипа +# Запуск игры на Windows Соберите проект командой: @@ -6,40 +6,60 @@ 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. -Колесо мыши приближает и отдаляет карту относительно курсора. Чтобы сдвинуть карту, перетащите её с зажатой левой или средней кнопкой мыши. Короткий щелчок левой кнопкой выбирает жителя или ставит чертёж. Home или «Вид → Общий план» возвращает исходный вид. +Колесо мыши приближает и отдаляет карту относительно курсора. Чтобы сдвинуть карту, перетащите её с зажатой левой или средней кнопкой мыши. Короткий щелчок левой кнопкой выбирает жителя или ставит чертёж. Home возвращает исходный вид. -В новой партии три поселенца. На нижней панели откройте «Строительство → Спальное место». Под кнопкой появятся «Дерево» слева и «Камень» справа. Выберите основу, затем щёлкайте по свободным клеткам. Выбранная основа применяется к следующим кроватям до выхода из режима или смены основы. Повторное нажатие «Спальное место», Esc или правый щелчок завершает размещение. +Карту, постройки и жителей рисует Direct3D 11. Игра сначала пробует использовать видеокарту. Если устройство недоступно, Direct3D 11 пробует создать программное устройство WARP. + +В новой партии три поселенца. На нижней панели откройте «Строительство → Спальное место». Под кнопкой появятся «Дерево» слева и «Камень» справа. Выберите основу и щёлкните по свободным клеткам. На карте появятся контуры чертежа, а под картой — количество объектов и список материалов. Выбранная основа применяется к следующим кроватям, пока вы её не смените. В режиме размещения повторный щелчок по контуру удаляет объект. В одном чертеже можно разместить кровати с разными основаниями и ткацкие станки. + +Нажмите «Начать стройку», чтобы отправить выбранные места в работу, или «Очистить чертёж», чтобы убрать всю раскладку. Чертёж остаётся доступным при смене инструмента и через Esc. Это локальная раскладка текущей партии. В сохранение и общую колонию попадают утверждённые постройки. Если хозяин отклоняет клетку в кооперативе, она возвращается в чертёж. + +В разделе «Строительство → Комната» укажите два противоположных угла прямоугольника от 3×3 до 12×12 клеток. По краям чертежа появятся стены, внутри — пол. Щёлкните по стороне, чтобы перенести вход в её середину. Правый щелчок по чертежу удаляет комнату. «Начать стройку» отправляет комнату в работу целиком. Поселенцы доставляют дерево для пола и стен. На готовый пол можно поставить мебель. В этой версии маршруты жителей проходят через стены. + +В нижней панели «Строительство → Готовые дома» выберите проект 4×4 по картинке. В доме врача есть деревянная кровать и аптечный шкаф, в доме шахтёра — каменная кровать и стойка с инструментами, в доме ткача — деревянная кровать и рабочий ткацкий станок. Укажите площадку одним щелчком. Щелчок по краю переносит вход и переставляет мебель к противоположной стене. Смета включает мебель, а строители собирают её после укладки пола под ней. Аптечный шкаф и стойка служат обстановкой. + +Когда пол, стены и вход готовы, у комнаты появляется крыша. Кнопка «Вид» в правом верхнем углу карты переключает полный вид, вид без крыш и вид без стен и крыш. Последний режим оставляет открытыми полы и мебель. Следующее нажатие возвращает полный вид. + +Клавиша R поворачивает вход и раскладку готового дома ещё до размещения. Клавиши «,» и «.» поворачивают в обе стороны. Чтобы перенести уже поставленный чертёж, щёлкните по нему с Shift, затем укажите новое место. Правый щелчок во время переноса возвращает чертёж на старое место. + +Новые комнаты и готовые дома требуют деревянную дверь как предмет. Если на складе нет свободной двери, «Начать стройку» автоматически ставит заказ в мастерскую. В списке «Жители» назначьте плотника. Он заберёт со склада две единицы дерева, сделает дверь за верстаком и отнесёт её на склад. Строитель или разнорабочий заберёт оттуда готовую дверь и установит её. Чтобы заготовить двери заранее, откройте «Работы → Плотник» и выберите «Изготовить дверь». + +Аптечный шкаф, стойка шахтёра и ткацкий станок для готовых домов также заказываются у плотника. Для шкафа нужно одно дерево, для стойки — дерево и камень, для станка — два дерева. Плотник доставляет готовый предмет на склад, а строитель забирает и устанавливает его после укладки пола. Подходящие предметы из запаса идут в работу без нового заказа. Изготовить мебель заранее можно в панели «Работы → Плотник». Отдельный станок из меню «Строительство» тоже требует готовый станок со склада. Если запаса нет, утверждение чертежа создаст заказ для плотника. Жители отдельно доставляют основу, ткань для настила и ткань для подушки. Каждая деталь появляется после завершения своего этапа. Камень и ткань доступны в стартовых запасах. Жители получают по одному готовому месту. Уставшие жители работают медленнее и после поручения идут к закреплённой кровати. На земле они отдыхают только при сильной усталости и восстанавливают меньше сил. Щелчок по жителю показывает усталость и состояние сна. -На нижней панели «Добыча» (H) открывает сбор с кустов и шахту. «Участки» (Z) открывают поля, посадки, склад и кладовую. «Строительство» (B) открывает спальное место, станок, перенос и снос. Выбор раздела показывает его инструменты над панелью. Те же действия сгруппированы по профессиям в верхнем меню «Работы». Разнорабочий берёт работу любой профессии. +На нижней панели «Добыча» (H) открывает сбор с кустов и шахту. «Участки» (Z) открывают поля, посадки, склад и кладовую. «Строительство» (B) открывает спальное место, станок, перенос и снос. Выбор раздела показывает его инструменты над панелью. Кнопка «Работы» открывает те же действия по профессиям. Разнорабочий берёт работу любой профессии. Откройте «Жители…» (клавиша C), выберите поселенца в списке, нажмите на нужную роль и подтвердите кнопкой «Назначить профессию». В списке видна текущая роль каждого жителя, а число рядом с названием профессии показывает, сколько жителей уже ею занимаются. Можно последовательно назначать роли всему поселению в одном окне. При смене профессии житель заканчивает текущее поручение. Фермер засевает поля ягод и льна, лесоруб высаживает деревья. Разметка участка создаёт поручение. Когда житель выходит на участок и заканчивает работу, начинается рост. После сбора последней порции участок снова нужно засадить. Разнорабочий тоже может взять это поручение. Шахтёру можно открыть шахту на скале с доступной стороны. -Чтобы получать ткань, поставьте «Участки → Поле льна» и «Строительство → Ткацкий станок» на свободных клетках. Созревший лён фермер относит на обычный склад. Строитель перерабатывает одну единицу льна в одну единицу ткани. Запасы льна и ткани видны над картой. Если обычные склады заполнены, постройте дополнительный склад. +Чтобы получать ткань, поставьте «Участки → Поле льна», затем добавьте «Строительство → Ткацкий станок» в чертёж и утвердите его. Созревший лён фермер относит на обычный склад. Строитель перерабатывает одну единицу льна в одну единицу ткани. Запасы льна и ткани видны над картой. Если обычные склады заполнены, постройте дополнительный склад. Для переноса выберите «Строительство → Перенести», щёлкните по кровати, складу, станку или посаженному участку и выберите новую клетку. Кровать сохраняет владельца, склад — содержимое. Там же находится «Снести». Снос склада с запасами требует подтверждения. Дождитесь освобождения занятого объекта перед переносом или сносом. -Нажмите «Добыча → Сбор ягод» и щёлкните по кусту, чтобы включить или отключить его сбор. Правый щелчок или Esc закрывает режим выбора. Кнопка приоритета переключает режимы «Равный приоритет», «Сначала еда» и «Сначала стройка». В паузе можно менять задания. Цель выполнена, когда каждому назначено место и в кладовой есть шесть свободных порций. +Нажмите «Добыча → Сбор ягод» и щёлкните по кусту, чтобы включить или отключить его сбор. Правый щелчок закрывает режим выбора. Кнопка приоритета переключает режимы «Равный приоритет», «Сначала еда» и «Сначала стройка». Цель выполнена, когда каждому назначено место и в кладовой есть шесть свободных порций. Кусты дают ягоды, которые жители несут в кладовую с розовой крышкой. Розовый маршрут ведёт к еде. Чтобы увидеть голод жителя и его груз, щёлкните по фигурке вне режима размещения чертежа. -В меню «Поселение» выберите «Сохранить поселение…» или «Загрузить поселение…». Время останавливается на время выбора файла. Файл `.settlement` хранит карту, текущий такт, голод, запасы, заказы и маршруты. При загрузке используются рабочие потоки текущего окна. Если файл повреждён или его версия не подходит, окно показывает ошибку и продолжает текущую партию. +Esc открывает меню игры из любого режима строительства и выбора. В одиночной партии симуляция останавливается, пока меню открыто. «Продолжить» или Esc закрывает меню. Выбранный на карте инструмент можно использовать дальше. В этом меню доступны сохранение, загрузка, главное меню и выход. Файл `.settlement` хранит карту, текущий такт, голод, запасы, заказы и маршруты. При ошибке загрузки текущая колония остаётся открытой. -Старые сохранения продолжаются со своими правилами стройки. Кнопка «Применить и начать заново» запускает партию с поэтапной сборкой и стартовым запасом ткани. +«Esc → Масштаб панели» открывает ползунок от 50% до 250% с предпросмотром. «Применить» сохраняет выбор между запусками, «Отмена» возвращает предыдущий масштаб. В маленьком окне панель подстраивается под доступное место, чтобы оставить видимой карту. По умолчанию используется 125%. + +В одиночной игре «Esc → Главное меню» возвращает на стартовый экран и останавливает симуляцию. «Продолжить» возвращает к текущей колонии. «Новая колония» запускает отдельную партию с поэтапной сборкой и стартовым запасом ткани. Старые сохранения продолжаются со своими правилами стройки. ## Кооператив по локальной сети 1. Запустите одинаковую версию игры на двух компьютерах в одной локальной сети. -2. Хозяин открывает свою колонию через «Кооператив → Открыть колонию для друга…» и передаёт гостю IPv4 и код партии. Порт игры — TCP 41727. -3. Гость выбирает «Кооператив → Подключиться…» и вводит эти данные. При обрыве связи можно выбрать «Подключиться снова», пока хозяин оставляет партию открытой. +2. Хозяин открывает «Кооператив…» в главном меню и создаёт сетевую колонию либо открывает для друга уже начатую. Он передаёт гостю IPv4 и код партии. Затем он нажимает «Продолжить». Порт игры — TCP 41727. +3. Гость выбирает «Кооператив → Подключиться к другу…» в главном меню и вводит эти данные. При обрыве связи в этом же разделе можно выбрать «Подключиться снова», пока хозяин держит партию открытой. -Оба игрока строят и меняют задания в общей колонии. Хозяин ставит симуляцию на паузу и сохраняет игру. После выхода гостя хозяин может продолжить партию. +Оба игрока строят и меняют задания в общей колонии. «Esc → Главное меню» позволяет открыть настройки кооператива и вернуться в колонию через «Продолжить». Хозяин сохраняет игру через Esc и может остановить симуляцию через «Кооператив → Пауза для всех» в главном меню. diff --git a/engine/include/settlement/core/world.hpp b/engine/include/settlement/core/world.hpp index 25393c6..fc70338 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,17 @@ enum class ItemType : std::uint8_t { StoneBlock, Berries, Cloth, - Flax + Flax, + WoodenDoor, + MedicineCabinet, + MiningRack, + Loom }; -inline constexpr std::size_t item_type_count = static_cast(ItemType::Flax); +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 }; @@ -74,21 +83,93 @@ enum class RecipeId : std::uint8_t { CutStoneBlock, BuildCabin, BuildBed, - WeaveCloth + WeaveCloth, + BuildFloor, + BuildWall, + BuildDoorAlongX, + BuildDoorAlongY, + BuildMedicineCabinet, + BuildMiningRack, + BuildLoom, + InstallDoorAlongX, + InstallDoorAlongY, + 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 }; -constexpr bool is_construction(RecipeId recipe) noexcept { - return recipe == RecipeId::BuildCabin || recipe == RecipeId::BuildBed; +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::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) || is_carpentry_recipe(recipe); +} + +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 + PlaceStorage = 9, AssignProfession = 10, PlaceFlaxField = 11, PlaceLoom = 12, PlaceRoom = 13, + CraftDoor = 14, CraftFurniture = 15 }; enum class CommandStatus : std::uint8_t { Accepted, Unavailable, Unauthorized, WrongSequence, InvalidTarget, Busy }; @@ -218,6 +299,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; @@ -273,6 +361,14 @@ 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; + [[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_; + } void queue_cabin(GridPosition position, GridPosition sawmill, GridPosition stonecutter); void start_scenario(GridPosition sawmill); [[nodiscard]] CommandReceipt apply_command(const PlayerCommand& command); @@ -330,6 +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_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 473365f..fcadab4 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,16 +66,61 @@ 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}; + 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}; + 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; 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; + 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; + 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(); @@ -124,6 +173,63 @@ 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; + 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 { + 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::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; @@ -220,8 +326,14 @@ void World::set_blocked(GridPosition position, bool blocked) { } } for (const Agent& agent : agents_) { + if (agent.production_index != no_entity_index && + 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) continue; + agent.state != AgentState::GoingToEat && agent.state != AgentState::GoingToSleep && + !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"); @@ -314,11 +426,14 @@ 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 (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"); } 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 +449,78 @@ 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() || (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}, + {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 { + 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{}; +} + +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::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 == 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(product); + } + } + for (const auto& storage : storages_) { + 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; } void World::queue_cabin(GridPosition position, GridPosition sawmill, GridPosition stonecutter) { @@ -408,6 +594,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 && 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) { @@ -428,6 +616,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; } @@ -442,7 +632,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; @@ -457,6 +647,10 @@ CommandStatus World::edit_object(GridPosition position, const GridPosition* dest if (storage != storages_.end()) { if (destination) storage->position = *destination; else { + 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); @@ -464,11 +658,29 @@ 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_) { + 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; } 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()); @@ -487,7 +699,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) { @@ -570,8 +783,65 @@ 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)) { + 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); + const auto furnishings = plan.furnishings(); + const bool legacy_bed = furnishings.has_value() && !staged_beds_; + 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 + 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 = 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)); + } + } + 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 = 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); + for (std::size_t i = 0; i < fixture_orders; ++i) { + queue_production(scenario_sawmill_, recipe_for_carpentry_item(fixture_item)); + } + break; + } case CommandKind::PlaceStorage: if (command.value > static_cast(StorageKind::Pantry) || !can_place_storage(command.cell) || !can_reach_object_cell(command.cell)) { @@ -587,7 +857,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, @@ -896,10 +1166,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 (;;) { @@ -991,7 +1262,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]; @@ -999,15 +1271,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 carpentry = is_carpentry_recipe(order.recipe); + 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) { @@ -1038,7 +1313,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, {}}); } @@ -1052,12 +1327,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 = 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 (carpentry) { + 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; @@ -1069,7 +1350,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; } @@ -1218,6 +1499,10 @@ void World::advance_construction_delivery(Agent& agent) { agent.inventory.add(material.type, material.count); } } + 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; agent.route = std::move(stop.route_to_next); agent.route_cursor = 0; @@ -1228,6 +1513,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 (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); + 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); @@ -1240,6 +1537,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 (furnishing_shape(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 8a73b39..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 = 9; +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 >= 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_); @@ -214,6 +215,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); @@ -255,6 +257,10 @@ 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."); + 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); @@ -361,9 +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::WeaveCloth && 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(!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)) && @@ -381,8 +388,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) { @@ -400,7 +407,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(), @@ -424,6 +431,30 @@ 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: + 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: + case RecipeId::BuildDoorAlongY: + case RecipeId::BuildMedicineCabinet: + case RecipeId::BuildMiningRack: + 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; + } + break; } invalid(ingredients == required); } @@ -441,7 +472,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; @@ -449,7 +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()); - invalid(agent.haul_route.empty() || has_source); + 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); @@ -468,7 +501,18 @@ 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 (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); + 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]); @@ -488,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::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/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 e5e13ba..e7de8ea 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,37 @@ 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(); + [[= Void::Testing::tag("construction")]] Test test_carpenter_makes_furnishings_for_rooms(); +}; + +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 +75,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 +116,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 +139,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 +163,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 +245,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 +268,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 +318,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 +337,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 +383,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 +416,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 +467,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 +483,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 +525,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 +579,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,17 +636,20 @@ 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}); 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) { @@ -617,13 +668,24 @@ void 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"); @@ -632,8 +694,8 @@ void 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); @@ -648,9 +710,13 @@ 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"); + 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 {}; } -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 +743,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 +765,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,38 +787,331 @@ 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 {}; +} + +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})); + 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)); + 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() == 20, "the furnished room did not queue construction and carpentry"); + require(place(1, plan.placement_value()) == CommandStatus::InvalidTarget && + 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) { + 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(furnishing_shape(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 {}; +} + +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() { - try { - test_rng_repeats_for_same_seed(); - test_work_jobs_complete(); - test_astar_route_uses_opening_in_wall(); - test_parallel_pathfinding_completes_the_jobs(); - test_single_worker_configuration_is_rejected(); - test_residents_gather_and_deliver_resources(); - test_production_reservations_and_construction(); - test_cabin_placement_queues_a_complete_order(); - test_hungry_resident_reserves_and_eats_a_berry(); - test_invalid_save_is_rejected(); - test_two_players_share_the_first_colony(); - test_bed_parts_are_delivered_separately(); - test_resident_uses_assigned_bed_and_sleep_survives_save(); - test_fatigue_slows_work_without_interrupting_it(); - test_ground_rest_never_uses_another_residents_bed(); - test_fields_mines_and_reindexing_active_hauls(); - test_specialists_take_their_own_jobs_and_finish_prior_assignments(); - test_flax_and_loom_supply_a_bed_without_starting_cloth(); - test_field_growth_requires_a_worker(); - test_opening_a_mine_invalidates_unreachable_routes(); - test_object_tools_work_in_an_older_demo_world(); - } catch (const std::exception& error) { - std::cerr << "Test failed: " << error.what() << '\n'; - return 1; - } - - std::cout << "All core checks passed.\n"; - return 0; +int main(int argc, char** argv) { + return CoreTests::run(argc, argv); } diff --git a/tests/lan_tests.cpp b/tests/lan_tests.cpp index 4cb2771..907d1df 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(); @@ -56,7 +64,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"); @@ -116,9 +129,11 @@ void 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(); } @@ -129,16 +144,40 @@ 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 + 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([&] { + 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 + 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