Add furnished houses, roof views, carpentry, and GCC 16 tests

This commit is contained in:
Codex committed 2026-12-01 11:52:03 +03:00
1 parent 85547b00b9
commit 8bb448cc49
21 files changed
+1256 -331

No files matched your search

+10 -2
View File
@@ -35,18 +35,21 @@ add_executable(settlement_colony_benchmark benchmarks/colony.cpp)
target_link_libraries(settlement_colony_benchmark PRIVATE settlement_core) target_link_libraries(settlement_colony_benchmark PRIVATE settlement_core)
if(WIN32) if(WIN32)
enable_language(RC)
add_executable(settlement_viewer WIN32 add_executable(settlement_viewer WIN32
app/d3d_scene_win32.cpp app/d3d_scene_win32.cpp
app/viewer_win32.cpp app/viewer_win32.cpp
app/lan_session_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) d3d11 d3dcompiler)
if(NOT MSVC) if(NOT MSVC)
target_link_options(settlement_viewer PRIVATE -municode) target_link_options(settlement_viewer PRIVATE -municode)
target_compile_options(settlement_viewer PRIVATE -Wall -Wextra -Wpedantic -Wconversion -Wshadow) target_compile_options(settlement_viewer PRIVATE
$<$<COMPILE_LANGUAGE:CXX>:-Wall;-Wextra;-Wpedantic;-Wconversion;-Wshadow>)
else() else()
target_compile_options(settlement_viewer PRIVATE /W4 /permissive-) target_compile_options(settlement_viewer PRIVATE $<$<COMPILE_LANGUAGE:CXX>:/W4;/permissive->)
endif() endif()
endif() endif()
@@ -58,13 +61,18 @@ endif()
include(CTest) include(CTest)
if(BUILD_TESTING) 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 add_executable(settlement_core_tests
tests/core_tests.cpp tests/core_tests.cpp
) )
target_compile_options(settlement_core_tests PRIVATE -std=c++26 -freflection)
target_link_libraries(settlement_core_tests PRIVATE settlement_core) target_link_libraries(settlement_core_tests PRIVATE settlement_core)
add_test(NAME settlement_core_tests COMMAND settlement_core_tests) add_test(NAME settlement_core_tests COMMAND settlement_core_tests)
if(WIN32) if(WIN32)
add_executable(settlement_lan_tests tests/lan_tests.cpp app/lan_session_win32.cpp) 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_include_directories(settlement_lan_tests PRIVATE app)
target_link_libraries(settlement_lan_tests PRIVATE settlement_core ws2_32 bcrypt iphlpapi) target_link_libraries(settlement_lan_tests PRIVATE settlement_core ws2_32 bcrypt iphlpapi)
add_test(NAME settlement_lan_tests COMMAND settlement_lan_tests) add_test(NAME settlement_lan_tests COMMAND settlement_lan_tests)
+1 -1
View File
@@ -9,7 +9,7 @@
### P0 — Инструменты и границы проекта ### P0 — Инструменты и границы проекта
- [x] Отдельный каталог, CMake, C++20, лицензия и базовая структура. - [x] Отдельный каталог, CMake, C++20, лицензия и базовая структура.
- [x] Portable-установщик CMake/LLVM-MinGW и скрипт сборки с CTest. - [x] Portable-установщик MSYS2 UCRT64 с GCC 16 и сборка с CTest.
- [ ] CI для Windows и Linux. - [ ] CI для Windows и Linux.
- [x] Не включать код и ресурсы Stonehearth. - [x] Не включать код и ресурсы Stonehearth.
+5 -3
View File
@@ -42,16 +42,18 @@ powershell.exe -NoProfile -ExecutionPolicy Bypass -File .\tools\render-svg-to-pn
По умолчанию он читает `build/workload.svg` и создаёт `build/workload.png`. По умолчанию он читает `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
powershell.exe -NoProfile -ExecutionPolicy Bypass -File .\setup-toolchain.ps1 powershell.exe -NoProfile -ExecutionPolicy Bypass -File .\setup-toolchain.ps1
powershell.exe -NoProfile -ExecutionPolicy Bypass -File .\build.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<T>` находит методы с возвращаемым типом `Test`. Необязательный `setup()` выполняется перед каждым запускаемым тестом. Метки задаются через `[[= Void::Testing::tag("construction")]]`, а `[[= Void::Testing::skip("причина")]]` пропускает тест с пояснением. Чтобы запустить только тесты строительства, выполните `build/settlement_core_tests.exe --tag construction`. Для сборки игры на другом компиляторе через CMake есть `-DBUILD_TESTING=OFF`.
## Структура ## Структура
Binary file not shown.

After

Width:  |  Height:  |  Size: 18 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 18 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 19 KiB

+220 -28
View File
@@ -6,6 +6,7 @@
#include <wrl/client.h> #include <wrl/client.h>
#include <algorithm> #include <algorithm>
#include <array>
#include <cmath> #include <cmath>
#include <cstring> #include <cstring>
#include <iterator> #include <iterator>
@@ -140,20 +141,191 @@ void room_part(Mesh& mesh, GridPosition cell, RecipeId recipe, Color color, bool
.02f, along_x ? .20f : .62f, along_x ? .62f : .20f, .73f, color); .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)); 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};
void draw_room_plan(Mesh& mesh, const RoomPlan& plan, bool preview, bool valid) { };
for (int y = plan.first.y; y <= plan.last.y; ++y) { mesh.quad(leaf(-.28f, 0.f, .04f), leaf(-.06f, .40f, .04f), leaf(-.06f, .40f, .66f),
for (int x = plan.first.x; x <= plan.last.x; ++x) { leaf(-.28f, 0.f, .66f), shade(color, .75f));
const GridPosition cell{x, y}; const auto handle = leaf(-.09f, .32f, .37f);
room_part(mesh, cell, plan.recipe_at(cell), !valid ? rgb(203, 113, 101) : mesh.box(handle.x, handle.y, handle.z, .06f, .06f, .06f, rgb(215, 183, 107));
(preview ? rgb(169, 224, 232) : rgb(104, 176, 212)), true);
} }
} }
} }
void construction(Mesh& mesh, const World& world) { void draw_blueprint(Mesh& mesh, const BlueprintPart& part, bool preview);
void draw_furnishing(Mesh& mesh, GridPosition cell, RecipeId recipe, Color wood, Color detail) {
const float x = static_cast<float>(cell.x), y = static_cast<float>(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<float>(i) / static_cast<float>(shades.size());
const float b = static_cast<float>(i + 1) / static_cast<float>(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<std::size_t>(world.width());
std::vector<Tile> map(width * static_cast<std::size_t>(world.height()));
const auto tile = [&](GridPosition cell) -> Tile& {
return map[static_cast<std::size_t>(cell.y) * width + static_cast<std::size_t>(cell.x)];
};
for (const auto& order : world.production_orders()) {
auto& cell = tile(order.position);
if (is_room_part(order.recipe) && order.state == JobState::Completed) {
cell.structure = room_part_shape(order.recipe);
}
switch (order.recipe) {
case RecipeId::BuildMedicineCabinet: cell.furnishing = RoomTemplate::Doctor; break;
case RecipeId::BuildMiningRack: cell.furnishing = RoomTemplate::Miner; break;
case RecipeId::BuildLoom:
case RecipeId::WeaveCloth: cell.furnishing = RoomTemplate::Weaver; break;
default: break;
}
}
const auto in_bounds = [&](GridPosition cell) {
return cell.x >= 0 && cell.y >= 0 && cell.x < world.width() && cell.y < world.height();
};
const GridPosition neighbors[] = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
const auto intact = [&](const RoomPlan& plan) {
for (int y = plan.first.y; y <= plan.last.y; ++y) {
for (int x = plan.first.x; x <= plan.last.x; ++x) {
const GridPosition cell{x, y};
if (tile(cell).structure != plan.recipe_at(cell)) return false;
}
}
return true;
};
constexpr Color finishes[] = {rgb(146, 94, 66), rgb(107, 136, 76), rgb(86, 116, 136), rgb(169, 91, 65)};
std::vector<GridPosition> 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<float>(plan.first.x) - .5f, static_cast<float>(plan.first.y) - .5f,
static_cast<float>(plan.last.x) + .5f, static_cast<float>(plan.last.y) + .5f, .85f,
.85f + std::min(.24f * static_cast<float>(span + 1), 1.65f), along_x,
finishes[static_cast<std::size_t>(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<float>(workshop->x);
const auto y = static_cast<float>(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()) { for (const auto& storage : world.storages()) {
const float x = static_cast<float>(storage.position.x), y = static_cast<float>(storage.position.y); const float x = static_cast<float>(storage.position.x), y = static_cast<float>(storage.position.y);
mesh.box(x, y, .02f, .66f, .62f, .44f, rgb(160, 110, 65)); mesh.box(x, y, .02f, .66f, .62f, .44f, rgb(160, 110, 65));
@@ -162,27 +334,39 @@ void construction(Mesh& mesh, const World& world) {
mesh.box(x + .34f, y, .30f, .052f, .13f, .13f, rgb(229, 195, 124)); mesh.box(x + .34f, y, .30f, .052f, .13f, .13f, rgb(229, 195, 124));
} }
for (const auto& order : world.production_orders()) { for (const auto& order : world.production_orders()) {
if (order.recipe == RecipeId::CraftWoodenDoor ||
(order.recipe == RecipeId::SawPlank && workshop == order.position)) continue;
const float x = static_cast<float>(order.position.x), y = static_cast<float>(order.position.y); const float x = static_cast<float>(order.position.x), y = static_cast<float>(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)) { if (!is_construction(order.recipe)) {
mesh.box(x, y, .025f, .71f, .58f, .34f, rgb(150, 110, 73)); mesh.box(x, y, .025f, .71f, .58f, .34f, rgb(150, 110, 73));
mesh.box(x, y, .37f, .77f, .62f, .10f, rgb(199, 156, 100)); mesh.box(x, y, .37f, .77f, .62f, .10f, rgb(199, 156, 100));
if (order.recipe == RecipeId::WeaveCloth) {
mesh.box(x, y - .12f, .46f, .62f, .12f, .37f, rgb(167, 124, 79));
mesh.box(x, y - .15f, .79f, .48f, .15f, .10f, rgb(235, 225, 193));
}
continue; continue;
} }
if (order.state != JobState::Completed) { if (order.state != JobState::Completed) {
const auto marked = order.state == JobState::Available ? rgb(121, 178, 195) : rgb(214, 171, 99); 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); mesh.flat(x - .44f, y - .44f, x + .44f, y + .44f, .03f, marked);
} }
if (order.recipe >= RecipeId::BuildFloor) { if (is_room_part(order.recipe)) {
const auto shape = room_part_shape(order.recipe);
if (building_view == BuildingView::FloorsOnly && shape != RecipeId::BuildFloor) continue;
if (order.state == JobState::Completed) { if (order.state == JobState::Completed) {
room_part(mesh, order.position, order.recipe, rgb(175, 123, 78), false); room_part(mesh, order.position, shape, rgb(175, 123, 78), false);
} else if (order.recipe != RecipeId::BuildFloor) { } else if (shape != RecipeId::BuildFloor) {
room_part(mesh, order.position, order.recipe, room_part(mesh, order.position, shape,
order.state == JobState::Available ? rgb(121, 178, 195) : rgb(214, 171, 99), true); order.state == JobState::Available ? rgb(121, 178, 195) : rgb(214, 171, 99), true);
} }
} else if (order.recipe == RecipeId::BuildMedicineCabinet || order.recipe == RecipeId::BuildMiningRack ||
order.recipe == RecipeId::BuildLoom) {
const bool finished = order.state == JobState::Completed;
const auto wood = finished ? rgb(175, 123, 78) : rgb(117, 168, 181);
const auto detail = finished
? (order.recipe == RecipeId::BuildMedicineCabinet ? rgb(169, 214, 183) : rgb(153, 166, 172))
: rgb(158, 202, 209);
draw_furnishing(mesh, order.position, order.recipe, wood, detail);
} else if (order.recipe == RecipeId::BuildBed && } else if (order.recipe == RecipeId::BuildBed &&
(order.state == JobState::Completed || order.bed_stage == BedStage::Bedding || order.bed_stage == BedStage::Pillow)) { (order.state == JobState::Completed || order.bed_stage == BedStage::Bedding || order.bed_stage == BedStage::Pillow)) {
mesh.box(x, y, .045f, .77f, .43f, .18f, mesh.box(x, y, .045f, .77f, .43f, .18f,
@@ -193,16 +377,18 @@ void construction(Mesh& mesh, const World& world) {
if (order.state == JobState::Completed) { if (order.state == JobState::Completed) {
mesh.box(x - .23f, y, .345f, .2f, .32f, .07f, rgb(243, 230, 194)); 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) { } else if (order.recipe == RecipeId::BuildCabin && order.state == JobState::Completed) {
mesh.box(x, y, .03f, .83f, .82f, .65f, rgb(194, 151, 103)); const float walls = building_view == BuildingView::FloorsOnly ? .07f : .65f;
mesh.quad({x - .46f, y + .46f, .64f}, {x + .46f, y + .46f, .64f}, mesh.box(x, y, .03f, .83f, .82f, walls, rgb(194, 151, 103));
{x + .46f, y, 1.03f}, {x - .46f, y, 1.03f}, rgb(158, 83, 62)); if (building_view == BuildingView::Full) {
mesh.quad({x - .46f, y, 1.03f}, {x + .46f, y, 1.03f}, draw_gabled_roof(mesh, x - .415f, y - .41f, x + .415f, y + .41f,
{x + .46f, y - .46f, .64f}, {x - .46f, y - .46f, .64f}, rgb(193, 113, 79)); .68f, 1.03f, true, rgb(159, 90, 66), rgb(174, 126, 80));
mesh.quad({x + .42f, y - .42f, .67f}, {x + .42f, y + .42f, .67f}, }
{x + .42f, y, 1.01f}, {x + .42f, y, 1.01f}, rgb(174, 126, 80));
} }
} }
if (building_view == BuildingView::Full) draw_room_roofs(mesh, world);
for (const auto& job : world.jobs()) { for (const auto& job : world.jobs()) {
if (job.state == JobState::Completed) continue; if (job.state == JobState::Completed) continue;
const float x = static_cast<float>(job.position.x), y = static_cast<float>(job.position.y); const float x = static_cast<float>(job.position.x), y = static_cast<float>(job.position.y);
@@ -266,7 +452,9 @@ void residents(Mesh& mesh, const World& world, const SceneView& view) {
mesh.box(x, y, .167f, .27f, .22f, .22f, clothes); mesh.box(x, y, .167f, .27f, .22f, .22f, clothes);
mesh.box(x, y, .387f, .25f, .24f, .23f, rgb(232, 191, 144)); 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)); mesh.box(x - .025f, y - .02f, .59f, .27f, .25f, .065f, rgb(92, 73, 56));
if (!agent.inventory.empty()) { if (agent.inventory.item_count(ItemType::WoodenDoor) != 0) {
mesh.box(x - .14f, y - .12f, .09f, .13f, .30f, .39f, rgb(177, 116, 70));
} else if (!agent.inventory.empty()) {
mesh.box(x - .11f, y - .12f, .14f, .19f, .18f, .24f, rgb(200, 156, 92)); mesh.box(x - .11f, y - .12f, .14f, .19f, .18f, .24f, rgb(200, 156, 92));
} }
} }
@@ -446,8 +634,12 @@ bool D3DScene::render(const World& world, const SceneView& view, std::vector<std
graphics.mesh.vertices.clear(); graphics.mesh.vertices.clear();
terrain(graphics.mesh, world, view); terrain(graphics.mesh, world, view);
resources(graphics.mesh, world); resources(graphics.mesh, world);
construction(graphics.mesh, world); construction(graphics.mesh, world, view.building_view);
for (const auto& plan : view.room_blueprints) draw_room_plan(graphics.mesh, plan, false, world.can_place_room(plan)); 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); 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); for (const auto& part : view.blueprint) draw_blueprint(graphics.mesh, part, false);
if (view.preview) draw_blueprint(graphics.mesh, *view.preview, true); if (view.preview) draw_blueprint(graphics.mesh, *view.preview, true);
+4
View File
@@ -12,6 +12,8 @@
namespace settlement::viewer { namespace settlement::viewer {
enum class BuildingView { Full, NoRoofs, FloorsOnly };
struct BlueprintPart { struct BlueprintPart {
GridPosition cell; GridPosition cell;
RecipeId recipe; RecipeId recipe;
@@ -34,6 +36,8 @@ struct SceneView {
std::optional<BlueprintPart> preview; std::optional<BlueprintPart> preview;
std::span<const RoomPlan> room_blueprints; std::span<const RoomPlan> room_blueprints;
std::optional<RoomPlan> room_preview; std::optional<RoomPlan> room_preview;
BuildingView building_view = BuildingView::Full;
std::optional<std::size_t> moving_room;
}; };
class D3DScene { class D3DScene {
+8
View File
@@ -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
+5
View File
@@ -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"
+1 -1
View File
@@ -24,7 +24,7 @@ namespace {
using Clock = std::chrono::steady_clock; using Clock = std::chrono::steady_clock;
using namespace std::chrono_literals; using namespace std::chrono_literals;
constexpr std::uint32_t protocol_version = 8; constexpr std::uint32_t protocol_version = 10;
constexpr std::size_t frame_limit = 4 * 1024 * 1024; constexpr std::size_t frame_limit = 4 * 1024 * 1024;
constexpr auto poll_budget = 16; constexpr auto poll_budget = 16;
constexpr std::size_t command_queue_limit = 32; constexpr std::size_t command_queue_limit = 32;
+299 -45
View File
@@ -7,6 +7,7 @@
#include <windowsx.h> #include <windowsx.h>
#include "d3d_scene_win32.hpp" #include "d3d_scene_win32.hpp"
#include "house_icons.h"
#include "map_camera.hpp" #include "map_camera.hpp"
#include "lan_session.hpp" #include "lan_session.hpp"
#include "title_screen_win32.hpp" #include "title_screen_win32.hpp"
@@ -65,6 +66,10 @@ constexpr int loom_id = 1039;
constexpr int farmer_menu_id = 1040; constexpr int farmer_menu_id = 1040;
constexpr int builder_menu_id = 1043; constexpr int builder_menu_id = 1043;
constexpr int room_tool_id = 1044; constexpr int room_tool_id = 1044;
constexpr int furnished_room_tool_id = 1045;
constexpr int house_list_back_id = 1046;
constexpr int carpenter_menu_id = 1047;
constexpr int craft_door_id = 1048;
constexpr int first_work_choice_id = 1050; constexpr int first_work_choice_id = 1050;
constexpr int resident_list_id = 1060; constexpr int resident_list_id = 1060;
constexpr int first_role_id = 1070; constexpr int first_role_id = 1070;
@@ -72,10 +77,12 @@ constexpr int first_dock_section_id = 1080;
constexpr int work_list_button_id = 1083; constexpr int work_list_button_id = 1083;
constexpr int build_blueprint_id = 1084; constexpr int build_blueprint_id = 1084;
constexpr int clear_blueprint_id = 1085; constexpr int clear_blueprint_id = 1085;
constexpr int building_view_id = 1086;
constexpr int exit_menu_id = 1121; constexpr int exit_menu_id = 1121;
constexpr int interface_scale_id = 1122; constexpr int interface_scale_id = 1122;
constexpr int scale_slider_id = 1130; constexpr int scale_slider_id = 1130;
constexpr int scale_value_id = 1131; constexpr int scale_value_id = 1131;
constexpr int first_house_tool_id = 1140;
constexpr int min_interface_scale = 50; constexpr int min_interface_scale = 50;
constexpr int max_interface_scale = 250; constexpr int max_interface_scale = 250;
constexpr int default_interface_scale = 125; constexpr int default_interface_scale = 125;
@@ -97,6 +104,7 @@ HWND work_list_button = nullptr;
HWND residents_button = nullptr; HWND residents_button = nullptr;
HWND build_blueprint_button = nullptr; HWND build_blueprint_button = nullptr;
HWND clear_blueprint_button = nullptr; HWND clear_blueprint_button = nullptr;
HWND building_view_button = nullptr;
HFONT dock_font = nullptr; HFONT dock_font = nullptr;
int interface_scale = default_interface_scale; int interface_scale = default_interface_scale;
struct DockLayout { struct DockLayout {
@@ -117,6 +125,11 @@ bool coop_menu_open = false;
bool pause_menu_open = false; bool pause_menu_open = false;
HWND scene_window = nullptr; HWND scene_window = nullptr;
settlement::viewer::D3DScene graphics; 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; using settlement::viewer::LanState;
settlement::viewer::LanSession lan; settlement::viewer::LanSession lan;
LanState displayed_lan_state = LanState::Offline; LanState displayed_lan_state = LanState::Offline;
@@ -124,15 +137,17 @@ const auto local_worker_count = std::clamp<std::size_t>(
std::thread::hardware_concurrency(), settlement::min_worker_count, 8); 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 }; enum class PlacementMode { None, Building, Foraging, BerryField, FlaxField, TreePlot, Mine, Loom, Storage, Pantry, Move, Demolish, Room };
PlacementMode placement_mode = PlacementMode::None; 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; WorkPanel work_panel = WorkPanel::None;
enum class WorkIcon { Berries, Field, Flax, Tree, Pickaxe, Hammer, Loom, Resident, Bed, Wood, Stone, Crate, Pantry, Move, Demolish, Priority }; WorkPanel house_list_parent = WorkPanel::Construction;
enum class WorkIcon { Berries, Field, Flax, Tree, Pickaxe, Hammer, Loom, Resident, Bed, Wood, Stone, Crate, Pantry, Move, Demolish, Priority, House, Back };
struct WorkChoice { struct WorkChoice {
int command; int command;
const wchar_t* title; const wchar_t* title;
WorkIcon icon; WorkIcon icon;
int width; int width;
PlacementMode mode = PlacementMode::None; PlacementMode mode = PlacementMode::None;
settlement::RoomTemplate layout = settlement::RoomTemplate::Empty;
}; };
constexpr std::array farmer_choices = { constexpr std::array farmer_choices = {
WorkChoice{forage_action_id, L"Сбор ягод", WorkIcon::Berries, 113, PlacementMode::Foraging}, WorkChoice{forage_action_id, L"Сбор ягод", WorkIcon::Berries, 113, PlacementMode::Foraging},
@@ -145,6 +160,9 @@ constexpr std::array woodcutter_choices = {
constexpr std::array miner_choices = { constexpr std::array miner_choices = {
WorkChoice{mine_id, L"Шахта", WorkIcon::Pickaxe, 98, PlacementMode::Mine}, WorkChoice{mine_id, L"Шахта", WorkIcon::Pickaxe, 98, PlacementMode::Mine},
}; };
constexpr std::array carpenter_choices = {
WorkChoice{craft_door_id, L"Изготовить дверь", WorkIcon::Wood, 190},
};
constexpr std::array builder_choices = { constexpr std::array builder_choices = {
WorkChoice{cabin_button_id, L"Спальное место", WorkIcon::Bed, 153, PlacementMode::Building}, WorkChoice{cabin_button_id, L"Спальное место", WorkIcon::Bed, 153, PlacementMode::Building},
WorkChoice{loom_id, L"Ткацкий станок", WorkIcon::Loom, 149, PlacementMode::Loom}, WorkChoice{loom_id, L"Ткацкий станок", WorkIcon::Loom, 149, PlacementMode::Loom},
@@ -153,13 +171,29 @@ constexpr std::array builder_choices = {
WorkChoice{move_id, L"Перенести", WorkIcon::Move, 108, PlacementMode::Move}, WorkChoice{move_id, L"Перенести", WorkIcon::Move, 108, PlacementMode::Move},
WorkChoice{demolish_id, L"Снести", WorkIcon::Demolish, 90, PlacementMode::Demolish}, WorkChoice{demolish_id, L"Снести", WorkIcon::Demolish, 90, PlacementMode::Demolish},
WorkChoice{room_tool_id, L"Комната", WorkIcon::Hammer, 116, PlacementMode::Room}, WorkChoice{room_tool_id, L"Комната", WorkIcon::Hammer, 116, PlacementMode::Room},
WorkChoice{furnished_room_tool_id, L"Готовые дома", WorkIcon::House, 158},
}; };
std::array<HWND, builder_choices.size()> work_choice_buttons{}; std::array<HWND, builder_choices.size()> work_choice_buttons{};
constexpr std::array gathering_choices = {farmer_choices[0], miner_choices[0]}; 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], constexpr std::array zones_choices = {farmer_choices[1], farmer_choices[2], woodcutter_choices[0],
builder_choices[2], builder_choices[3]}; builder_choices[2], builder_choices[3]};
constexpr std::array construction_choices = {builder_choices[0], builder_choices[1], constexpr std::array construction_choices = {builder_choices[0], builder_choices[1],
builder_choices[6], builder_choices[4], builder_choices[5]}; builder_choices[6], builder_choices[7], builder_choices[4], builder_choices[5]};
constexpr std::array house_choices = {
WorkChoice{house_list_back_id, L"Назад", WorkIcon::Back, 93},
WorkChoice{first_house_tool_id, L"Дом врача", WorkIcon::House, 155,
PlacementMode::Room, settlement::RoomTemplate::Doctor},
WorkChoice{first_house_tool_id + 1, L"Дом шахтёра", WorkIcon::House, 175,
PlacementMode::Room, settlement::RoomTemplate::Miner},
WorkChoice{first_house_tool_id + 2, L"Дом ткача", WorkIcon::House, 155,
PlacementMode::Room, settlement::RoomTemplate::Weaver},
};
constexpr const wchar_t* house_contents[] = {
L"Деревянная кровать и аптечный шкаф",
L"Каменная кровать и стойка с инструментами",
L"Деревянная кровать и ткацкий станок",
};
std::array<HICON, 3> house_artwork{};
struct DockSection { struct DockSection {
WorkPanel panel; WorkPanel panel;
const wchar_t* title; const wchar_t* title;
@@ -182,6 +216,7 @@ constexpr std::array role_choices = {
RoleChoice{Profession::Woodcutter, L"Лесоруб", WorkIcon::Tree}, RoleChoice{Profession::Woodcutter, L"Лесоруб", WorkIcon::Tree},
RoleChoice{Profession::Miner, L"Шахтёр", WorkIcon::Pickaxe}, RoleChoice{Profession::Miner, L"Шахтёр", WorkIcon::Pickaxe},
RoleChoice{Profession::Builder, L"Строитель", WorkIcon::Hammer}, RoleChoice{Profession::Builder, L"Строитель", WorkIcon::Hammer},
RoleChoice{Profession::Carpenter, L"Плотник", WorkIcon::Wood},
}; };
struct ResidentRow { struct ResidentRow {
settlement::AgentId id; settlement::AgentId id;
@@ -203,6 +238,14 @@ std::optional<settlement::BedBase> selected_bed_base;
std::vector<settlement::viewer::BlueprintPart> blueprint; std::vector<settlement::viewer::BlueprintPart> blueprint;
std::vector<settlement::RoomPlan> room_blueprints; std::vector<settlement::RoomPlan> room_blueprints;
std::optional<settlement::GridPosition> room_anchor; std::optional<settlement::GridPosition> room_anchor;
settlement::RoomTemplate selected_room_template = settlement::RoomTemplate::Empty;
std::optional<settlement::RoomSide> preferred_room_entrance;
struct RoomDraftMove {
std::size_t index;
settlement::GridPosition grabbed_cell;
settlement::RoomSide entrance;
};
std::optional<RoomDraftMove> room_draft_move;
std::optional<settlement::GridPosition> move_source; std::optional<settlement::GridPosition> move_source;
settlement::viewer::MapCamera camera; settlement::viewer::MapCamera camera;
struct CameraDrag { struct CameraDrag {
@@ -344,6 +387,14 @@ void draw_work_icon(HDC dc, WorkIcon icon, int x, int y, int extent = 17) {
box(2, 8, 12, 11, metal); box(2, 8, 12, 11, metal);
box(2, 13, 8, 16, metal); box(2, 13, 8, 16, metal);
break; 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); RestoreDC(dc, state);
} }
@@ -393,12 +444,17 @@ void layout_scene(HWND window) {
if (!scene_window) return; if (!scene_window) return;
if (showing_title || !graphics.ready()) { if (showing_title || !graphics.ready()) {
ShowWindow(scene_window, SW_HIDE); ShowWindow(scene_window, SW_HIDE);
ShowWindow(building_view_button, SW_HIDE);
return; return;
} }
RECT client{}; RECT client{};
GetClientRect(window, &client); GetClientRect(window, &client);
SetWindowPos(scene_window, HWND_BOTTOM, 0, map_top, client.right, SetWindowPos(scene_window, HWND_BOTTOM, 0, map_top, client.right,
std::max(0, static_cast<int>(client.bottom) - map_top - dock_layout.height), SWP_NOACTIVATE | SWP_SHOWWINDOW); std::max(0, static_cast<int>(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) { void update_camera_drag(POINT point) {
@@ -475,6 +531,8 @@ std::span<const WorkChoice> work_choices() {
case WorkPanel::Gathering: return gathering_choices; case WorkPanel::Gathering: return gathering_choices;
case WorkPanel::Zones: return zones_choices; case WorkPanel::Zones: return zones_choices;
case WorkPanel::Construction: return construction_choices; case WorkPanel::Construction: return construction_choices;
case WorkPanel::Houses: return house_choices;
case WorkPanel::Carpenter: return carpenter_choices;
case WorkPanel::None: return {}; case WorkPanel::None: return {};
} }
return {}; return {};
@@ -539,7 +597,7 @@ DockLayout measure_command_dock(int width, int height, int scale, bool position_
const bool bed = choice.command == cabin_button_id; const bool bed = choice.command == cabin_button_id;
tools[index] = {work_choice_buttons[index], choice.width + (bed ? 32 : 14), bed && shows_bed_choices()}; tools[index] = {work_choice_buttons[index], choice.width + (bed ? 32 : 14), bed && shows_bed_choices()};
} }
const int tool_height = pixels(compact ? 30 : 36); const int tool_height = pixels(work_panel == WorkPanel::Houses ? 44 : (compact ? 30 : 36));
if (choices.empty()) bottom -= tool_height + gap; if (choices.empty()) bottom -= tool_height + gap;
else layout_rows(std::span(tools).first(choices.size()), tool_height); else layout_rows(std::span(tools).first(choices.size()), tool_height);
@@ -558,7 +616,7 @@ void update_dock_font() {
const auto face = reinterpret_cast<WPARAM>(font ? font : GetStockObject(DEFAULT_GUI_FONT)); const auto face = reinterpret_cast<WPARAM>(font ? font : GetStockObject(DEFAULT_GUI_FONT));
const auto set_font = [&](HWND button) { SendMessageW(button, WM_SETFONT, face, TRUE); }; 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, for (const auto button : {priority_button, work_list_button, residents_button, wood_bed_button,
stone_bed_button, build_blueprint_button, clear_blueprint_button}) set_font(button); stone_bed_button, build_blueprint_button, clear_blueprint_button, building_view_button}) set_font(button);
for (const auto button : dock_section_buttons) set_font(button); for (const auto button : dock_section_buttons) set_font(button);
for (const auto button : work_choice_buttons) set_font(button); for (const auto button : work_choice_buttons) set_font(button);
if (dock_font) DeleteObject(dock_font); if (dock_font) DeleteObject(dock_font);
@@ -639,6 +697,7 @@ void set_work_panel(HWND window, WorkPanel panel) {
const auto& choice = choices[index]; const auto& choice = choices[index];
SetWindowTextW(button, choice.command == cabin_button_id && world && !world->scenario_active() ? SetWindowTextW(button, choice.command == cabin_button_id && world && !world->scenario_active() ?
L"Чертёж домика" : choice.title); L"Чертёж домика" : choice.title);
EnableWindow(button, choice.command != craft_door_id || (world && world->scenario_active()));
ShowWindow(button, SW_SHOWNA); ShowWindow(button, SW_SHOWNA);
} }
for (const auto button : dock_section_buttons) InvalidateRect(button, nullptr, FALSE); for (const auto button : dock_section_buttons) InvalidateRect(button, nullptr, FALSE);
@@ -649,7 +708,8 @@ void set_work_panel(HWND window, WorkPanel panel) {
InvalidateRect(window, &row, FALSE); InvalidateRect(window, &row, FALSE);
} }
void draw_icon_button(const DRAWITEMSTRUCT& item, WorkIcon icon, bool active, bool dock = false, int icon_width = 17) { void draw_icon_button(const DRAWITEMSTRUCT& item, WorkIcon icon, bool active, bool dock = false,
int icon_width = 17, HICON artwork = nullptr) {
const bool disabled = (item.itemState & ODS_DISABLED) != 0; const bool disabled = (item.itemState & ODS_DISABLED) != 0;
const bool pressed = (item.itemState & ODS_SELECTED) != 0; const bool pressed = (item.itemState & ODS_SELECTED) != 0;
const auto dc = item.hDC; const auto dc = item.hDC;
@@ -681,7 +741,9 @@ void draw_icon_button(const DRAWITEMSTRUCT& item, WorkIcon icon, bool active, bo
constexpr int gap = 5; constexpr int gap = 5;
const int left = std::max(box.left + 2, (box.left + box.right - icon_width - gap - caption.cx) / 2); const int left = std::max(box.left + 2, (box.left + box.right - icon_width - gap - caption.cx) / 2);
const int offset = pressed ? 1 : 0; const int offset = pressed ? 1 : 0;
draw_work_icon(dc, icon, left + offset, (box.top + box.bottom - icon_width) / 2 + offset, icon_width); const int icon_x = left + offset, icon_y = (box.top + box.bottom - icon_width) / 2 + offset;
if (artwork) DrawIconEx(dc, icon_x, icon_y, artwork, icon_width, icon_width, 0, nullptr, DI_NORMAL);
else draw_work_icon(dc, icon, icon_x, icon_y, icon_width);
RECT caption_box{left + icon_width + gap + offset, box.top + offset, box.right - 1, box.bottom + offset}; RECT caption_box{left + icon_width + gap + offset, box.top + offset, box.right - 1, box.bottom + offset};
const auto previous_mode = SetBkMode(dc, TRANSPARENT); const auto previous_mode = SetBkMode(dc, TRANSPARENT);
@@ -708,15 +770,24 @@ bool draw_toolbar_button(const DRAWITEMSTRUCT& item) {
case priority_button_id: return draw(WorkIcon::Priority); case priority_button_id: return draw(WorkIcon::Priority);
case build_blueprint_id: return draw(WorkIcon::Hammer, has_blueprint()); case build_blueprint_id: return draw(WorkIcon::Hammer, has_blueprint());
case clear_blueprint_id: return draw(WorkIcon::Demolish); 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<std::size_t>(id - first_dock_section_id) < dock_sections.size()) { if (id >= first_dock_section_id && static_cast<std::size_t>(id - first_dock_section_id) < dock_sections.size()) {
const auto& section = dock_sections[static_cast<std::size_t>(id - first_dock_section_id)]; const auto& section = dock_sections[static_cast<std::size_t>(id - first_dock_section_id)];
return draw(section.icon, work_panel == section.panel); return draw(section.icon, work_panel == section.panel ||
(work_panel == WorkPanel::Houses && section.panel == WorkPanel::Construction));
} }
const auto choices = work_choices(); const auto choices = work_choices();
if (id < first_work_choice_id || static_cast<std::size_t>(id - first_work_choice_id) >= choices.size()) return false; if (id < first_work_choice_id || static_cast<std::size_t>(id - first_work_choice_id) >= choices.size()) return false;
const auto& choice = choices[static_cast<std::size_t>(id - first_work_choice_id)]; const auto& choice = choices[static_cast<std::size_t>(id - first_work_choice_id)];
return draw(choice.icon, placement_mode == choice.mode); const bool active = choice.mode != PlacementMode::None && placement_mode == choice.mode &&
(choice.mode != PlacementMode::Room || selected_room_template == choice.layout);
if (choice.layout != settlement::RoomTemplate::Empty) {
const auto artwork = house_artwork[static_cast<std::size_t>(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() { bool can_give_orders() {
@@ -795,6 +866,7 @@ void update_status() {
std::uint64_t berries = 0; std::uint64_t berries = 0;
std::uint64_t cloth = 0; std::uint64_t cloth = 0;
std::uint64_t flax = 0; std::uint64_t flax = 0;
std::uint64_t doors = 0;
for (const settlement::Storage& storage : world->storages()) { for (const settlement::Storage& storage : world->storages()) {
wood += storage.item_count(settlement::ItemType::Wood); wood += storage.item_count(settlement::ItemType::Wood);
stone += storage.item_count(settlement::ItemType::Stone); stone += storage.item_count(settlement::ItemType::Stone);
@@ -803,11 +875,13 @@ void update_status() {
berries += storage.item_count(settlement::ItemType::Berries); berries += storage.item_count(settlement::ItemType::Berries);
cloth += storage.item_count(settlement::ItemType::Cloth); cloth += storage.item_count(settlement::ItemType::Cloth);
flax += storage.item_count(settlement::ItemType::Flax); 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()) + const std::wstring text = L"Жители: " + std::to_wstring(world->agents().size()) +
L" Заняты: " + std::to_wstring(busy) + L" Заняты: " + std::to_wstring(busy) +
L" Выполнено работ: " + std::to_wstring(world->jobs_completed()) + L" Выполнено работ: " + std::to_wstring(world->jobs_completed()) +
L" Дерево: " + std::to_wstring(wood) + L" Камень: " + std::to_wstring(stone) + L" Дерево: " + std::to_wstring(wood) + L" Камень: " + std::to_wstring(stone) +
L" Двери: " + std::to_wstring(doors) +
L" Ход: " + std::to_wstring(world->tick()); L" Ход: " + std::to_wstring(world->tick());
SetWindowTextW(status_label, text.c_str()); SetWindowTextW(status_label, text.c_str());
const bool scenario = world->scenario_active(); const bool scenario = world->scenario_active();
@@ -818,7 +892,7 @@ void update_status() {
for (const HWND button : dock_section_buttons) EnableWindow(button, can_play); for (const HWND button : dock_section_buttons) EnableWindow(button, can_play);
EnableWindow(priority_button, scenario && can_play); EnableWindow(priority_button, scenario && can_play);
EnableWindow(work_list_button, can_play); EnableWindow(work_list_button, can_play);
EnableWindow(build_blueprint_button, has_blueprint() && can_play); EnableWindow(build_blueprint_button, has_blueprint() && can_play && !room_draft_move);
const wchar_t* priority = L"Равный приоритет"; const wchar_t* priority = L"Равный приоритет";
if (world->work_priority() == settlement::WorkPriority::FoodFirst) priority = L"Сначала еда"; if (world->work_priority() == settlement::WorkPriority::FoodFirst) priority = L"Сначала еда";
else if (world->work_priority() == settlement::WorkPriority::BuildingFirst) priority = L"Сначала стройка"; else if (world->work_priority() == settlement::WorkPriority::BuildingFirst) priority = L"Сначала стройка";
@@ -871,7 +945,7 @@ void update_blueprint_controls(HWND window) {
const int visibility = shows_blueprint_actions() ? SW_SHOWNA : SW_HIDE; const int visibility = shows_blueprint_actions() ? SW_SHOWNA : SW_HIDE;
ShowWindow(build_blueprint_button, visibility); ShowWindow(build_blueprint_button, visibility);
ShowWindow(clear_blueprint_button, visibility); ShowWindow(clear_blueprint_button, visibility);
EnableWindow(build_blueprint_button, has_blueprint() && can_give_orders()); EnableWindow(build_blueprint_button, has_blueprint() && can_give_orders() && !room_draft_move);
EnableWindow(clear_blueprint_button, has_blueprint()); EnableWindow(clear_blueprint_button, has_blueprint());
layout_command_dock(window); layout_command_dock(window);
} }
@@ -881,6 +955,9 @@ void set_placement_mode(HWND window, PlacementMode mode, const wchar_t* message
selected_bed_base.reset(); selected_bed_base.reset();
move_source.reset(); move_source.reset();
room_anchor.reset(); room_anchor.reset();
room_draft_move.reset();
preferred_room_entrance.reset();
selected_room_template = settlement::RoomTemplate::Empty;
hover_cell.reset(); hover_cell.reset();
placement_message = message; placement_message = message;
update_bed_choices(); update_bed_choices();
@@ -893,6 +970,7 @@ void clear_blueprints() {
blueprint.clear(); blueprint.clear();
room_blueprints.clear(); room_blueprints.clear();
room_anchor.reset(); room_anchor.reset();
room_draft_move.reset();
} }
void toggle_work_panel(HWND window, WorkPanel panel) { void toggle_work_panel(HWND window, WorkPanel panel) {
@@ -1305,22 +1383,43 @@ bool valid_edit_cell(settlement::GridPosition cell) {
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) { auto room_at(settlement::GridPosition cell) {
return std::find_if(room_blueprints.begin(), room_blueprints.end(), return std::find_if(room_blueprints.begin(), room_blueprints.end(),
[cell](const auto& room) { return room.contains(cell); }); [cell](const auto& room) { return room.contains(cell); });
} }
bool room_fits_blueprint(const settlement::RoomPlan& room) { bool room_fits_blueprint(const settlement::RoomPlan& room, const settlement::RoomPlan* ignored = nullptr) {
return std::none_of(blueprint.begin(), blueprint.end(), return std::none_of(blueprint.begin(), blueprint.end(),
[&](const auto& part) { return room.contains(part.cell); }) && [&](const auto& part) { return room.contains(part.cell); }) &&
std::none_of(room_blueprints.begin(), room_blueprints.end(), [&](const auto& other) { std::none_of(room_blueprints.begin(), room_blueprints.end(), [&](const auto& other) {
return room.first.x <= other.last.x && room.last.x >= other.first.x && return &other != ignored && room.first.x <= other.last.x && room.last.x >= other.first.x &&
room.first.y <= other.last.y && room.last.y >= other.first.y; room.first.y <= other.last.y && room.last.y >= other.first.y;
}); });
} }
settlement::RoomPlan preview_room(settlement::GridPosition cell) { settlement::RoomPlan preview_room(settlement::GridPosition cell) {
auto room = settlement::make_room_plan(*room_anchor, cell); if (room_draft_move) {
auto room = room_blueprints[room_draft_move->index];
const int x = cell.x - room_draft_move->grabbed_cell.x;
const int y = cell.y - room_draft_move->grabbed_cell.y;
room.first = {room.first.x + x, room.first.y + y};
room.last = {room.last.x + x, room.last.y + y};
room.entrance = room_draft_move->entrance;
return room;
}
constexpr int edge = settlement::furnished_room_size - 1;
auto room = room_anchor ? settlement::make_room_plan(*room_anchor, cell) :
settlement::RoomPlan{cell, {cell.x + edge, cell.y + edge}};
room.layout = selected_room_template;
if (preferred_room_entrance) {
room.entrance = *preferred_room_entrance;
return room;
}
if (room.valid_size() && !world->can_place_room(room)) { if (room.valid_size() && !world->can_place_room(room)) {
for (const auto side : {settlement::RoomSide::North, settlement::RoomSide::East, settlement::RoomSide::West}) { for (const auto side : {settlement::RoomSide::North, settlement::RoomSide::East, settlement::RoomSide::West}) {
room.entrance = side; room.entrance = side;
@@ -1331,10 +1430,36 @@ settlement::RoomPlan preview_room(settlement::GridPosition cell) {
return room; return room;
} }
void edit_room_blueprint(HWND window, settlement::GridPosition cell) { void rotate_room_preview(HWND window, int direction) {
using settlement::RoomSide;
const auto next = [direction](RoomSide side) {
return static_cast<RoomSide>((static_cast<int>(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; if (!can_give_orders()) return;
using settlement::RoomSide; using settlement::RoomSide;
if (room_anchor) { if (room_draft_move) {
auto& original = room_blueprints[room_draft_move->index];
const auto room = preview_room(cell);
if (world->can_place_room(room) && room_fits_blueprint(room, &original)) {
original = room;
room_draft_move.reset();
placement_message.clear();
} else {
placement_message = L"Здесь дом не помещается. Выберите другую площадку или отмените перенос.";
}
} else if (room_anchor) {
const auto room = preview_room(cell); const auto room = preview_room(cell);
if (!room.valid_size()) { if (!room.valid_size()) {
placement_message = L"Ширина и длина комнаты должны быть от 3 до 12 клеток."; placement_message = L"Ширина и длина комнаты должны быть от 3 до 12 клеток.";
@@ -1345,23 +1470,40 @@ void edit_room_blueprint(HWND window, settlement::GridPosition cell) {
room_anchor.reset(); room_anchor.reset();
placement_message.clear(); placement_message.clear();
} }
} else if (const auto room = room_at(cell); room != room_blueprints.end()) { } else if (const auto draft = room_at(cell); draft != room_blueprints.end()) {
auto candidate = *room; if (shift) {
if (cell.y == room->first.y) candidate.entrance = RoomSide::North; room_draft_move = RoomDraftMove{static_cast<std::size_t>(draft - room_blueprints.begin()),
else if (cell.y == room->last.y) candidate.entrance = RoomSide::South; cell, draft->entrance};
else if (cell.x == room->first.x) candidate.entrance = RoomSide::West; hover_cell = cell;
else if (cell.x == room->last.x) candidate.entrance = RoomSide::East; 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 { else {
placement_message = L"Щёлкните по краю комнаты, чтобы перенести вход."; placement_message = L"Щёлкните по краю комнаты, чтобы перенести вход.";
invalidate_scene(window); invalidate_scene(window);
return; return;
} }
if (world->can_place_room(candidate)) { if (world->can_place_room(candidate)) {
*room = candidate; *draft = candidate;
placement_message.clear(); placement_message.clear();
} else { } else {
placement_message = L"С этой стороны нет свободного прохода."; 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 { } else {
room_anchor = cell; room_anchor = cell;
placement_message.clear(); placement_message.clear();
@@ -1401,12 +1543,12 @@ void edit_blueprint(HWND window, settlement::GridPosition cell) {
} }
void submit_blueprint(HWND window) { void submit_blueprint(HWND window) {
if (!world || !has_blueprint() || !can_give_orders()) return; if (!world || !has_blueprint() || room_draft_move || !can_give_orders()) return;
using settlement::CommandKind; using settlement::CommandKind;
using settlement::RecipeId; using settlement::RecipeId;
const auto rooms_sent = std::erase_if(room_blueprints, [](const auto& room) { const auto rooms_sent = std::erase_if(room_blueprints, [](const auto& room) {
return world->can_place_room(room) && submit_command(CommandKind::PlaceRoom, room.first, return world->can_place_room(room) && submit_command(CommandKind::PlaceRoom, room.first,
static_cast<std::uint8_t>(room.entrance), room.last) == settlement::CommandStatus::Accepted; room.placement_value(), room.last) == settlement::CommandStatus::Accepted;
}); });
const auto objects_sent = std::erase_if(blueprint, [](const auto& part) { const auto objects_sent = std::erase_if(blueprint, [](const auto& part) {
switch (part.recipe) { switch (part.recipe) {
@@ -1435,6 +1577,9 @@ void submit_blueprint(HWND window) {
} else { } else {
placement_message = (lan.is_guest() ? L"Передано хозяину мест: " : L"Утверждено мест: ") + count + L"."; 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_blueprint_controls(window);
update_status(); update_status();
invalidate_scene(window); invalidate_scene(window);
@@ -1506,9 +1651,11 @@ void edit_at_cell(HWND window, settlement::GridPosition cell) {
HMENU create_work_menu() { HMENU create_work_menu() {
HMENU menu = CreatePopupMenu(); HMENU menu = CreatePopupMenu();
if (menu == nullptr) return nullptr; if (menu == nullptr) return nullptr;
for (std::size_t index = 0; index + 1 < role_choices.size(); ++index) { for (int id = farmer_menu_id; id <= builder_menu_id; ++id) {
AppendMenuW(menu, MF_STRING, farmer_menu_id + index, role_choices[index + 1].title); AppendMenuW(menu, MF_STRING, static_cast<UINT_PTR>(id),
role_choices[static_cast<std::size_t>(id - farmer_menu_id + 1)].title);
} }
AppendMenuW(menu, MF_STRING, carpenter_menu_id, L"Плотник");
AppendMenuW(menu, MF_SEPARATOR, 0, nullptr); AppendMenuW(menu, MF_SEPARATOR, 0, nullptr);
AppendMenuW(menu, MF_STRING, residents_button_id, L"Жители…\tC"); AppendMenuW(menu, MF_STRING, residents_button_id, L"Жители…\tC");
return menu; return menu;
@@ -1546,7 +1693,7 @@ LRESULT CALLBACK resident_roster_proc(HWND window, UINT message, WPARAM wparam,
}; };
roster.list = control(WC_LISTVIEWW, L"", resident_list_id, roster.list = control(WC_LISTVIEWW, L"", resident_list_id,
WS_TABSTOP | LVS_REPORT | LVS_OWNERDATA | LVS_SINGLESEL | LVS_SHOWSELALWAYS | LVS_NOSORTHEADER, 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); ListView_SetExtendedListViewStyle(roster.list, LVS_EX_FULLROWSELECT | LVS_EX_DOUBLEBUFFER);
wchar_t resident_header[] = L"Житель"; wchar_t resident_header[] = L"Житель";
wchar_t profession_header[] = L"Профессия"; wchar_t profession_header[] = L"Профессия";
@@ -1566,10 +1713,10 @@ LRESULT CALLBACK resident_roster_proc(HWND window, UINT message, WPARAM wparam,
WS_TABSTOP | BS_OWNERDRAW, 316, 43 + static_cast<int>(index) * 34, 234, 30); WS_TABSTOP | BS_OWNERDRAW, 316, 43 + static_cast<int>(index) * 34, 234, 30);
} }
roster.apply = control(L"BUTTON", L"Назначить профессию", IDOK, WS_TABSTOP | BS_DEFPUSHBUTTON, roster.apply = control(L"BUTTON", L"Назначить профессию", IDOK, WS_TABSTOP | BS_DEFPUSHBUTTON,
316, 218, 234, 30); 316, 252, 234, 30);
roster.notice = control(L"STATIC", L"", 0, SS_LEFT, 316, 256, 234, 44); 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, 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 || 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; std::find(roster.roles.begin(), roster.roles.end(), nullptr) != roster.roles.end()) return -1;
return 0; return 0;
@@ -1660,7 +1807,7 @@ void show_resident_roster(HWND owner) {
if (!RegisterClassW(&window_info) && GetLastError() != ERROR_CLASS_ALREADY_EXISTS) return; if (!RegisterClassW(&window_info) && GetLastError() != ERROR_CLASS_ALREADY_EXISTS) return;
constexpr auto style = WS_POPUP | WS_CAPTION | WS_SYSMENU | WS_CLIPCHILDREN; constexpr auto style = WS_POPUP | WS_CAPTION | WS_SYSMENU | WS_CLIPCHILDREN;
constexpr auto ex_style = WS_EX_TOOLWINDOW | WS_EX_CONTROLPARENT; 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); AdjustWindowRectEx(&area, style, FALSE, ex_style);
RECT owner_rect{}; RECT owner_rect{};
GetWindowRect(owner, &owner_rect); GetWindowRect(owner, &owner_rect);
@@ -1709,7 +1856,7 @@ std::wstring resident_details() {
constexpr std::pair<ItemType, const wchar_t*> items[] = { constexpr std::pair<ItemType, const wchar_t*> items[] = {
{ItemType::Wood, L"древесина"}, {ItemType::Stone, L"камень"}, {ItemType::Plank, L"доски"}, {ItemType::Wood, L"древесина"}, {ItemType::Stone, L"камень"}, {ItemType::Plank, L"доски"},
{ItemType::StoneBlock, L"блоки"}, {ItemType::Berries, L"ягоды"}, {ItemType::Cloth, L"ткань"}, {ItemType::StoneBlock, L"блоки"}, {ItemType::Berries, L"ягоды"}, {ItemType::Cloth, L"ткань"},
{ItemType::Flax, L"лён"} {ItemType::Flax, L"лён"}, {ItemType::WoodenDoor, L"деревянная дверь"}
}; };
std::wstring cargo; std::wstring cargo;
for (const auto& [type, name] : items) { for (const auto& [type, name] : items) {
@@ -1723,6 +1870,11 @@ std::wstring resident_details() {
profession_name(resident->profession) + L" Голод " + std::to_wstring(hunger) + L"%"; profession_name(resident->profession) + L" Голод " + std::to_wstring(hunger) + L"%";
if (resident->state == settlement::AgentState::GoingToEat) text += L" Идёт к кладовой"; if (resident->state == settlement::AgentState::GoingToEat) text += L" Идёт к кладовой";
else if (resident->state == settlement::AgentState::Eating) text += L" Ест"; else if (resident->state == settlement::AgentState::Eating) text += L" Ест";
else if (resident->production_index != settlement::no_entity_index &&
world->production_orders()[resident->production_index].recipe == settlement::RecipeId::CraftWoodenDoor) {
text += resident->state == settlement::AgentState::Working ? L" Изготавливает дверь" :
L" Везёт дерево в мастерскую";
}
else if (resident->resource_node_index != settlement::no_entity_index && else if (resident->resource_node_index != settlement::no_entity_index &&
resident->storage_index == settlement::no_entity_index) { resident->storage_index == settlement::no_entity_index) {
const auto& site = world->resource_nodes()[resident->resource_node_index]; const auto& site = world->resource_nodes()[resident->resource_node_index];
@@ -1759,7 +1911,8 @@ std::wstring blueprint_details() {
const wchar_t* name; const wchar_t* name;
}; };
constexpr Material materials[] = {{ItemType::Wood, L"дерево"}, {ItemType::Stone, L"камень"}, constexpr Material materials[] = {{ItemType::Wood, L"дерево"}, {ItemType::Stone, L"камень"},
{ItemType::Cloth, L"ткань"}, {ItemType::Plank, L"доски"}, {ItemType::StoneBlock, L"каменные блоки"}}; {ItemType::Cloth, L"ткань"}, {ItemType::Plank, L"доски"}, {ItemType::StoneBlock, L"каменные блоки"},
{ItemType::WoodenDoor, L"готовые двери"}};
std::array<unsigned, settlement::item_type_count + 1> totals{}; std::array<unsigned, settlement::item_type_count + 1> totals{};
for (const auto& part : blueprint) { for (const auto& part : blueprint) {
for (const auto& material : world->construction_materials(part.recipe, part.base)) { for (const auto& material : world->construction_materials(part.recipe, part.base)) {
@@ -1769,10 +1922,18 @@ std::wstring blueprint_details() {
for (const auto& room : room_blueprints) { for (const auto& room : room_blueprints) {
for (int y = room.first.y; y <= room.last.y; ++y) { for (int y = room.first.y; y <= room.last.y; ++y) {
for (int x = room.first.x; x <= room.last.x; ++x) { for (int x = room.first.x; x <= room.last.x; ++x) {
const auto ingredients = world->construction_materials(room.recipe_at({x, y}), settlement::BedBase::Wood); const auto recipe = world->room_construction_recipe(room.recipe_at({x, y}));
const auto ingredients = world->construction_materials(recipe, settlement::BedBase::Wood);
for (const auto& item : ingredients) totals[static_cast<std::size_t>(item.type)] += item.count; for (const auto& item : ingredients) totals[static_cast<std::size_t>(item.type)] += item.count;
} }
} }
if (const auto furnishings = room.furnishings()) {
for (const auto& part : *furnishings) {
for (const auto& item : world->construction_materials(part.recipe, part.bed_base)) {
totals[static_cast<std::size_t>(item.type)] += item.count;
}
}
}
} }
std::wstring text = L"Чертёж · объектов " + std::to_wstring(blueprint.size() + room_blueprints.size()); std::wstring text = L"Чертёж · объектов " + std::to_wstring(blueprint.size() + room_blueprints.size());
for (const auto& material : materials) { for (const auto& material : materials) {
@@ -1829,18 +1990,41 @@ void draw_world(HDC dc, int width, int height) {
} else if (placement_mode == PlacementMode::Demolish) { } else if (placement_mode == PlacementMode::Demolish) {
hint = L"Щёлкните по объекту, чтобы снести его. Правая кнопка — отмена."; hint = L"Щёлкните по объекту, чтобы снести его. Правая кнопка — отмена.";
} else if (placement_mode == PlacementMode::Room) { } else if (placement_mode == PlacementMode::Room) {
hint = room_anchor ? L"Укажите противоположный угол комнаты." : if (room_draft_move) {
L"Укажите первый угол. Щелчок по краю чертежа меняет вход, правый щелчок удаляет комнату."; hint = L"Щёлкните по новой площадке. R поворачивает дом, правый щелчок отменяет перенос.";
} else if (selected_room_template != settlement::RoomTemplate::Empty) {
hint = L"Выберите площадку 4×4. R поворачивает дом, Shift + щелчок переносит чертёж.";
} else {
hint = room_anchor ? L"Укажите противоположный угол комнаты. R меняет сторону входа." :
L"Укажите первый угол. Щелчок по краю меняет вход, Shift + щелчок переносит чертёж.";
}
} else if (is_blueprint_tool()) { } else if (is_blueprint_tool()) {
hint = shows_bed_choices() && !selected_bed_base hint = shows_bed_choices() && !selected_bed_base
? L"Выберите «Дерево» или «Камень» под кнопкой «Спальное место»." ? L"Выберите «Дерево» или «Камень» под кнопкой «Спальное место»."
: L"Щёлкните по клетке, чтобы добавить объект или убрать его из чертежа."; : L"Щёлкните по клетке, чтобы добавить объект или убрать его из чертежа.";
} else if (work_panel == WorkPanel::Houses) {
hint = L"Выберите проект дома для площадки 4×4.";
} else if (work_panel == WorkPanel::Carpenter) {
hint = L"Плотник делает дверь из двух единиц дерева. При подтверждении дома заказ создаётся автоматически.";
} }
const auto previous_font = dock_font ? SelectObject(dc, dock_font) : nullptr; const auto previous_font = dock_font ? SelectObject(dc, dock_font) : nullptr;
const int margin = dock_pixels(12); const int margin = dock_pixels(12);
RECT legend{margin, dock_layout.hint_top, width - margin, dock_layout.hint_top + dock_layout.line_height}; 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); DrawTextW(dc, hint, -1, &legend, DT_LEFT | DT_VCENTER | DT_SINGLELINE | DT_END_ELLIPSIS);
const auto details = has_blueprint() ? blueprint_details() : resident_details(); auto details = has_blueprint() ? blueprint_details() :
selected_room_template != settlement::RoomTemplate::Empty
? std::wstring(house_contents[static_cast<std::size_t>(selected_room_template) - 1])
: resident_details();
if (work_panel == WorkPanel::Carpenter) {
const auto orders = std::count_if(world->production_orders().begin(), world->production_orders().end(),
[](const auto& order) {
return order.recipe == settlement::RecipeId::CraftWoodenDoor && order.state != settlement::JobState::Completed;
});
details = L"Заказов на двери " + std::to_wstring(orders);
if (!has_carpenter()) {
details += L" Назначьте плотника в списке «Жители».";
}
}
SetTextColor(dc, color(190, 201, 178)); SetTextColor(dc, color(190, 201, 178));
RECT inspector{margin, legend.bottom, width - margin, legend.bottom + dock_layout.line_height}; 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); DrawTextW(dc, details.c_str(), -1, &inspector, DT_LEFT | DT_VCENTER | DT_SINGLELINE | DT_END_ELLIPSIS);
@@ -1852,11 +2036,14 @@ settlement::viewer::SceneView scene_view(int width, int height) {
const auto scale = camera.scale(); const auto scale = camera.scale();
const auto cursor = !shows_bed_choices() || selected_bed_base ? hover_cell : std::nullopt; const auto cursor = !shows_bed_choices() || selected_bed_base ? hover_cell : std::nullopt;
std::optional<settlement::RoomPlan> room_preview; std::optional<settlement::RoomPlan> room_preview;
if (cursor && room_anchor && placement_mode == PlacementMode::Room) { if (cursor && placement_mode == PlacementMode::Room &&
(room_draft_move || room_anchor || (selected_room_template != settlement::RoomTemplate::Empty &&
room_at(*cursor) == room_blueprints.end()))) {
const auto room = preview_room(*cursor); const auto room = preview_room(*cursor);
if (room.valid_size()) room_preview = room; if (room.valid_size()) room_preview = room;
} }
const bool valid_cursor = room_preview ? world->can_place_room(*room_preview) && room_fits_blueprint(*room_preview) const auto ignore = room_draft_move ? &room_blueprints[room_draft_move->index] : nullptr;
const bool valid_cursor = room_preview ? world->can_place_room(*room_preview) && room_fits_blueprint(*room_preview, ignore)
: cursor && (placement_mode == PlacementMode::Room ? !room_anchor : valid_edit_cell(*cursor)); : cursor && (placement_mode == PlacementMode::Room ? !room_anchor : valid_edit_cell(*cursor));
const auto preview = valid_cursor && is_blueprint_tool() && const auto preview = valid_cursor && is_blueprint_tool() &&
cursor && room_at(*cursor) == room_blueprints.end() && cursor && room_at(*cursor) == room_blueprints.end() &&
@@ -1865,7 +2052,8 @@ settlement::viewer::SceneView scene_view(int width, int height) {
return {width, height, static_cast<float>(width / 2 * scale + pan.x), return {width, height, static_cast<float>(width / 2 * scale + pan.x),
static_cast<float>(map_origin_y * scale + pan.y - map_top), static_cast<float>(map_origin_y * scale + pan.y - map_top),
static_cast<float>(scale), tile_width / 2.f, tile_height / 2.f, static_cast<float>(scale), tile_width / 2.f, tile_height / 2.f,
cursor, valid_cursor, move_source, selected_resident, blueprint, preview, room_blueprints, room_preview}; cursor, valid_cursor, move_source, selected_resident, blueprint, preview, room_blueprints, room_preview,
building_view, room_draft_move ? std::optional(room_draft_move->index) : std::nullopt};
} }
LRESULT CALLBACK scene_window_proc(HWND window, UINT message, WPARAM wparam, LPARAM lparam) { LRESULT CALLBACK scene_window_proc(HWND window, UINT message, WPARAM wparam, LPARAM lparam) {
@@ -2159,6 +2347,12 @@ LRESULT CALLBACK window_proc(HWND window, UINT message, WPARAM wparam, LPARAM lp
stone_bed_button = button(stone_bed_button_id, 0, 90, L"Камень", BS_OWNERDRAW, 0); 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); 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); 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<HICON>(LoadImageW(instance, MAKEINTRESOURCEW(icons[index]),
IMAGE_ICON, 0, 0, LR_SHARED));
}
for (std::size_t index = 0; index < work_choice_buttons.size(); ++index) { for (std::size_t index = 0; index < work_choice_buttons.size(); ++index) {
work_choice_buttons[index] = button(first_work_choice_id + static_cast<int>(index), work_choice_buttons[index] = button(first_work_choice_id + static_cast<int>(index),
0, 100, L"", BS_OWNERDRAW, 0); 0, 100, L"", BS_OWNERDRAW, 0);
@@ -2221,6 +2415,20 @@ LRESULT CALLBACK window_proc(HWND window, UINT message, WPARAM wparam, LPARAM lp
toggle_work_panel(window, panel); toggle_work_panel(window, panel);
return 0; return 0;
} }
if (LOWORD(wparam) == carpenter_menu_id && HIWORD(wparam) == BN_CLICKED) {
toggle_work_panel(window, WorkPanel::Carpenter);
update_status();
return 0;
}
if (LOWORD(wparam) == craft_door_id && HIWORD(wparam) == BN_CLICKED &&
world && world->carpenter_workshop() && can_give_orders()) {
if (send_command(settlement::CommandKind::CraftDoor)) {
placement_message = lan.is_guest() ? L"Заказ на дверь отправлен." : L"Дверь заказана в мастерской.";
}
SetFocus(window);
invalidate_scene(window);
return 0;
}
if (LOWORD(wparam) >= first_dock_section_id && if (LOWORD(wparam) >= first_dock_section_id &&
static_cast<std::size_t>(LOWORD(wparam) - first_dock_section_id) < dock_sections.size() && static_cast<std::size_t>(LOWORD(wparam) - first_dock_section_id) < dock_sections.size() &&
HIWORD(wparam) == BN_CLICKED) { HIWORD(wparam) == BN_CLICKED) {
@@ -2258,6 +2466,14 @@ LRESULT CALLBACK window_proc(HWND window, UINT message, WPARAM wparam, LPARAM lp
invalidate_scene(window); invalidate_scene(window);
return 0; return 0;
} }
if (LOWORD(wparam) == building_view_id && HIWORD(wparam) == BN_CLICKED) {
const auto index = (static_cast<std::size_t>(building_view) + 1) % std::size(building_view_labels);
building_view = static_cast<BuildingView>(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) { if (LOWORD(wparam) == cabin_button_id && HIWORD(wparam) == BN_CLICKED) {
set_placement_mode(window, placement_mode == PlacementMode::Building ? set_placement_mode(window, placement_mode == PlacementMode::Building ?
PlacementMode::None : PlacementMode::Building); PlacementMode::None : PlacementMode::Building);
@@ -2265,7 +2481,33 @@ LRESULT CALLBACK window_proc(HWND window, UINT message, WPARAM wparam, LPARAM lp
return 0; return 0;
} }
if (LOWORD(wparam) == room_tool_id && HIWORD(wparam) == BN_CLICKED && world && can_give_orders()) { if (LOWORD(wparam) == room_tool_id && HIWORD(wparam) == BN_CLICKED && world && can_give_orders()) {
set_placement_mode(window, placement_mode == PlacementMode::Room ? PlacementMode::None : PlacementMode::Room); const bool editing_empty_room = placement_mode == PlacementMode::Room &&
selected_room_template == settlement::RoomTemplate::Empty;
set_placement_mode(window, editing_empty_room ? PlacementMode::None : PlacementMode::Room);
SetFocus(window);
return 0;
}
if (LOWORD(wparam) == furnished_room_tool_id && HIWORD(wparam) == BN_CLICKED &&
world && world->scenario_active() && can_give_orders()) {
house_list_parent = work_panel;
set_placement_mode(window, PlacementMode::None);
set_work_panel(window, WorkPanel::Houses);
SetFocus(window);
return 0;
}
if (LOWORD(wparam) == house_list_back_id && HIWORD(wparam) == BN_CLICKED && work_panel == WorkPanel::Houses) {
set_placement_mode(window, PlacementMode::None);
set_work_panel(window, house_list_parent);
SetFocus(window);
return 0;
}
if (LOWORD(wparam) >= first_house_tool_id && LOWORD(wparam) < first_house_tool_id + house_artwork.size() &&
HIWORD(wparam) == BN_CLICKED && work_panel == WorkPanel::Houses && can_give_orders()) {
const auto layout = house_choices[LOWORD(wparam) - first_house_tool_id + 1].layout;
const bool already_selected = placement_mode == PlacementMode::Room && selected_room_template == layout;
set_placement_mode(window, already_selected ? PlacementMode::None : PlacementMode::Room);
if (!already_selected) selected_room_template = layout;
invalidate_work_choices();
SetFocus(window); SetFocus(window);
return 0; return 0;
} }
@@ -2378,7 +2620,7 @@ LRESULT CALLBACK window_proc(HWND window, UINT message, WPARAM wparam, LPARAM lp
} }
if (world && is_blueprint_tool()) { if (world && is_blueprint_tool()) {
if (const auto cell = map_cell(client, point)) { if (const auto cell = map_cell(client, point)) {
if (placement_mode == PlacementMode::Room) edit_room_blueprint(window, *cell); if (placement_mode == PlacementMode::Room) edit_room_blueprint(window, *cell, (wparam & MK_SHIFT) != 0);
else edit_blueprint(window, *cell); else edit_blueprint(window, *cell);
} }
return 0; return 0;
@@ -2398,6 +2640,13 @@ LRESULT CALLBACK window_proc(HWND window, UINT message, WPARAM wparam, LPARAM lp
} }
case WM_RBUTTONDOWN: case WM_RBUTTONDOWN:
if (placement_mode == PlacementMode::Room) { 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) { if (room_anchor) {
room_anchor.reset(); room_anchor.reset();
placement_message.clear(); placement_message.clear();
@@ -2425,6 +2674,11 @@ LRESULT CALLBACK window_proc(HWND window, UINT message, WPARAM wparam, LPARAM lp
break; break;
case WM_KEYDOWN: case WM_KEYDOWN:
if (showing_title) break; 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 ((GetKeyState(VK_CONTROL) & 0x8000) == 0 && (wparam == 'H' || wparam == 'Z' || wparam == 'B')) {
if ((lparam & (1L << 30)) == 0) { if ((lparam & (1L << 30)) == 0) {
toggle_work_panel(window, wparam == 'H' ? WorkPanel::Gathering : toggle_work_panel(window, wparam == 'H' ? WorkPanel::Gathering :
@@ -2465,8 +2719,8 @@ LRESULT CALLBACK window_proc(HWND window, UINT message, WPARAM wparam, LPARAM lp
using settlement::RecipeId; using settlement::RecipeId;
const bool bed = rejection->kind == CommandKind::PlaceBed; const bool bed = rejection->kind == CommandKind::PlaceBed;
if (rejection->kind == CommandKind::PlaceRoom) { if (rejection->kind == CommandKind::PlaceRoom) {
const settlement::RoomPlan room{rejection->cell, rejection->destination, const auto room = settlement::RoomPlan::from_placement(
static_cast<settlement::RoomSide>(rejection->value)}; rejection->cell, rejection->destination, rejection->value);
if (room.valid_size() && std::none_of(room_blueprints.begin(), room_blueprints.end(), 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; })) { [&](const auto& other) { return other.first == room.first && other.last == room.last; })) {
room_blueprints.push_back(room); room_blueprints.push_back(room);
+40 -50
View File
@@ -1,59 +1,49 @@
param( param(
[ValidateSet('Debug', 'Release', 'RelWithDebInfo')] [ValidateSet('Debug', 'Release', 'RelWithDebInfo')]
[string]$Configuration = 'Release' [string]$Configuration = 'Release',
[string]$Msys2Root = $env:SETTLEMENT_MSYS2_ROOT
) )
$ErrorActionPreference = 'Stop' $ErrorActionPreference = 'Stop'
$projectRoot = Split-Path -Parent $MyInvocation.MyCommand.Path $projectRoot = $PSScriptRoot
$toolRoot = Join-Path $projectRoot '.tools\toolchain' if (-not $Msys2Root) { $Msys2Root = Join-Path $projectRoot '.tools\toolchain\msys64' }
$bin = Join-Path $Msys2Root 'ucrt64\bin'
if (-not (Test-Path -LiteralPath $toolRoot -PathType Container)) { foreach ($tool in @('g++.exe', 'cmake.exe', 'ctest.exe', 'ninja.exe', 'windres.exe')) {
throw 'Portable tools are missing. Run .\setup-toolchain.ps1 first.' if (-not (Test-Path -LiteralPath (Join-Path $bin $tool) -PathType Leaf)) {
} throw "MSYS2 UCRT64 tool missing: $tool. Run .\setup-toolchain.ps1."
$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"
} }
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' foreach ($runtime in @('libstdc++-6.dll', 'libgcc_s_seh-1.dll', 'libwinpthread-1.dll')) {
if (-not (Test-Path -LiteralPath $ctestExe -PathType Leaf)) { Copy-Item -LiteralPath (Join-Path $bin $runtime) -Destination $buildRoot -Force
throw 'CTest was not found beside CMake.' }
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
+9 -1
View File
@@ -20,7 +20,15 @@ powershell.exe -NoProfile -ExecutionPolicy Bypass -File .\build.ps1
Нажмите «Начать стройку», чтобы отправить выбранные места в работу, или «Очистить чертёж», чтобы убрать всю раскладку. Чертёж остаётся доступным при смене инструмента и через Esc. Это локальная раскладка текущей партии. В сохранение и общую колонию попадают утверждённые постройки. Если хозяин отклоняет клетку в кооперативе, она возвращается в чертёж. Нажмите «Начать стройку», чтобы отправить выбранные места в работу, или «Очистить чертёж», чтобы убрать всю раскладку. Чертёж остаётся доступным при смене инструмента и через Esc. Это локальная раскладка текущей партии. В сохранение и общую колонию попадают утверждённые постройки. Если хозяин отклоняет клетку в кооперативе, она возвращается в чертёж.
В разделе «Строительство → Комната» укажите два противоположных угла прямоугольника от 3×3 до 12×12 клеток. По краям чертежа появятся стены, внутри — пол. Щёлкните по стороне, чтобы перенести вход в её середину. Правый щелчок по чертежу удаляет комнату. «Начать стройку» отправляет комнату в работу целиком. Поселенцы доставляют дерево и собирают пол, стены и проём по частям. На готовый пол можно поставить мебель. В этой версии маршруты жителей проходят через стены. В разделе «Строительство → Комната» укажите два противоположных угла прямоугольника от 3×3 до 12×12 клеток. По краям чертежа появятся стены, внутри — пол. Щёлкните по стороне, чтобы перенести вход в её середину. Правый щелчок по чертежу удаляет комнату. «Начать стройку» отправляет комнату в работу целиком. Поселенцы доставляют дерево для пола и стен. На готовый пол можно поставить мебель. В этой версии маршруты жителей проходят через стены.
В нижней панели «Строительство → Готовые дома» выберите проект 4×4 по картинке. В доме врача есть деревянная кровать и аптечный шкаф, в доме шахтёра — каменная кровать и стойка с инструментами, в доме ткача — деревянная кровать и рабочий ткацкий станок. Укажите площадку одним щелчком. Щелчок по краю переносит вход и переставляет мебель к противоположной стене. Смета включает мебель, а строители собирают её после укладки пола под ней. Аптечный шкаф и стойка служат обстановкой.
Когда пол, стены и вход готовы, у комнаты появляется крыша. Кнопка «Вид» в правом верхнем углу карты переключает полный вид, вид без крыш и вид без стен и крыш. Последний режим оставляет открытыми полы и мебель. Следующее нажатие возвращает полный вид.
Клавиша R поворачивает вход и раскладку готового дома ещё до размещения. Клавиши «,» и «.» поворачивают в обе стороны. Чтобы перенести уже поставленный чертёж, щёлкните по нему с Shift, затем укажите новое место. Правый щелчок во время переноса возвращает чертёж на старое место.
Новые комнаты и готовые дома требуют деревянную дверь как предмет. Если на складе нет свободной двери, «Начать стройку» автоматически ставит заказ в мастерскую. В списке «Жители» назначьте плотника. Он заберёт со склада две единицы дерева, сделает дверь за верстаком и отнесёт её на склад. Строитель или разнорабочий заберёт оттуда готовую дверь и установит её. Чтобы заготовить двери заранее, откройте «Работы → Плотник» и выберите «Изготовить дверь».
Жители отдельно доставляют основу, ткань для настила и ткань для подушки. Каждая деталь появляется после завершения своего этапа. Камень и ткань доступны в стартовых запасах. Жители получают по одному готовому месту. Жители отдельно доставляют основу, ткань для настила и ткань для подушки. Каждая деталь появляется после завершения своего этапа. Камень и ткань доступны в стартовых запасах. Жители получают по одному готовому месту.
+56 -6
View File
@@ -6,6 +6,7 @@
#include <cstdint> #include <cstdint>
#include <iosfwd> #include <iosfwd>
#include <memory> #include <memory>
#include <optional>
#include <string> #include <string>
#include <unordered_map> #include <unordered_map>
#include <vector> #include <vector>
@@ -51,9 +52,10 @@ enum class ItemType : std::uint8_t {
StoneBlock, StoneBlock,
Berries, Berries,
Cloth, Cloth,
Flax Flax,
WoodenDoor
}; };
inline constexpr std::size_t item_type_count = static_cast<std::size_t>(ItemType::Flax); inline constexpr std::size_t item_type_count = static_cast<std::size_t>(ItemType::WoodenDoor);
enum class StorageKind : std::uint8_t { Materials, Pantry }; enum class StorageKind : std::uint8_t { Materials, Pantry };
enum class ResourceSite : std::uint8_t { Natural, BerryField, TreePlot, Mine, FlaxField }; enum class ResourceSite : std::uint8_t { Natural, BerryField, TreePlot, Mine, FlaxField };
@@ -78,33 +80,68 @@ enum class RecipeId : std::uint8_t {
BuildFloor, BuildFloor,
BuildWall, BuildWall,
BuildDoorAlongX, BuildDoorAlongX,
BuildDoorAlongY BuildDoorAlongY,
BuildMedicineCabinet,
BuildMiningRack,
BuildLoom,
InstallDoorAlongX,
InstallDoorAlongY,
CraftWoodenDoor
}; };
enum class BedBase : std::uint8_t { Wood, Stone }; enum class BedBase : std::uint8_t { Wood, Stone };
enum class BedStage : std::uint8_t { Legacy, Foundation, Bedding, Pillow }; enum class BedStage : std::uint8_t { Legacy, Foundation, Bedding, Pillow };
constexpr RecipeId room_part_shape(RecipeId recipe) noexcept {
if (recipe == RecipeId::InstallDoorAlongX) return RecipeId::BuildDoorAlongX;
if (recipe == RecipeId::InstallDoorAlongY) return RecipeId::BuildDoorAlongY;
return recipe;
}
constexpr bool is_room_part(RecipeId recipe) noexcept {
recipe = room_part_shape(recipe);
return recipe >= RecipeId::BuildFloor && recipe <= RecipeId::BuildDoorAlongY;
}
constexpr bool is_construction(RecipeId recipe) noexcept { constexpr bool is_construction(RecipeId recipe) noexcept {
return recipe == RecipeId::BuildCabin || recipe == RecipeId::BuildBed || return recipe == RecipeId::BuildCabin || recipe == RecipeId::BuildBed ||
(recipe >= RecipeId::BuildFloor && recipe <= RecipeId::BuildDoorAlongY); (recipe >= RecipeId::BuildFloor && recipe <= RecipeId::InstallDoorAlongY);
}
constexpr bool delivers_materials(RecipeId recipe) noexcept {
return is_construction(recipe) || recipe == RecipeId::CraftWoodenDoor;
} }
enum class RoomSide : std::uint8_t { North, East, South, West }; enum class 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 { struct RoomPlan {
GridPosition first; GridPosition first;
GridPosition last; GridPosition last;
RoomSide entrance = RoomSide::South; RoomSide entrance = RoomSide::South;
RoomTemplate layout = RoomTemplate::Empty;
[[nodiscard]] bool valid_size() const noexcept; [[nodiscard]] bool valid_size() const noexcept;
[[nodiscard]] bool contains(GridPosition cell) const noexcept; [[nodiscard]] bool contains(GridPosition cell) const noexcept;
[[nodiscard]] RecipeId recipe_at(GridPosition cell) const noexcept; [[nodiscard]] RecipeId recipe_at(GridPosition cell) const noexcept;
[[nodiscard]] std::optional<std::array<RoomFurnishing, 2>> 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; [[nodiscard]] RoomPlan make_room_plan(GridPosition first, GridPosition last) noexcept;
enum class WorkPriority : std::uint8_t { Balanced, FoodFirst, BuildingFirst }; 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 { enum class CommandKind : std::uint8_t {
PlaceBed = 0, SetForaging = 1, SetPriority = 2, SetPaused = 3, PlaceBed = 0, SetForaging = 1, SetPriority = 2, SetPaused = 3,
PlaceBerryField = 4, PlaceTreePlot = 5, PlaceMine = 6, MoveObject = 7, DemolishObject = 8, PlaceBerryField = 4, PlaceTreePlot = 5, PlaceMine = 6, MoveObject = 7, DemolishObject = 8,
PlaceStorage = 9, AssignProfession = 10, PlaceFlaxField = 11, PlaceLoom = 12, PlaceRoom = 13 PlaceStorage = 9, AssignProfession = 10, PlaceFlaxField = 11, PlaceLoom = 12, PlaceRoom = 13,
CraftDoor = 14
}; };
enum class CommandStatus : std::uint8_t { Accepted, Unavailable, Unauthorized, WrongSequence, InvalidTarget, Busy }; enum class CommandStatus : std::uint8_t { Accepted, Unavailable, Unauthorized, WrongSequence, InvalidTarget, Busy };
@@ -234,6 +271,13 @@ struct Storage {
return 0; 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 { [[nodiscard]] std::uint64_t total_items() const noexcept {
std::uint64_t total = 0; std::uint64_t total = 0;
for (const ItemStack& stack : items) total += stack.count; for (const ItemStack& stack : items) total += stack.count;
@@ -291,6 +335,11 @@ public:
[[nodiscard]] bool can_place_cabin(GridPosition position) const noexcept; [[nodiscard]] bool can_place_cabin(GridPosition position) const noexcept;
[[nodiscard]] bool can_place_room(const RoomPlan& plan) const noexcept; [[nodiscard]] bool can_place_room(const RoomPlan& plan) const noexcept;
[[nodiscard]] std::array<ItemStack, 2> construction_materials(RecipeId recipe, BedBase base) const; [[nodiscard]] std::array<ItemStack, 2> construction_materials(RecipeId recipe, BedBase base) const;
[[nodiscard]] RecipeId room_construction_recipe(RecipeId part) const noexcept;
[[nodiscard]] std::optional<GridPosition> carpenter_workshop() const noexcept {
if (!scenario_active_) return std::nullopt;
return scenario_sawmill_;
}
void queue_cabin(GridPosition position, GridPosition sawmill, GridPosition stonecutter); void queue_cabin(GridPosition position, GridPosition sawmill, GridPosition stonecutter);
void start_scenario(GridPosition sawmill); void start_scenario(GridPosition sawmill);
[[nodiscard]] CommandReceipt apply_command(const PlayerCommand& command); [[nodiscard]] CommandReceipt apply_command(const PlayerCommand& command);
@@ -348,6 +397,7 @@ private:
void finish_rest_step(Agent& agent); void finish_rest_step(Agent& agent);
void advance_construction_delivery(Agent& agent); void advance_construction_delivery(Agent& agent);
void finish_production(Agent& agent); void finish_production(Agent& agent);
[[nodiscard]] std::size_t missing_door_orders(std::size_t new_installations = 0) const;
void update_scenario(); void update_scenario();
[[nodiscard]] bool resting_at(GridPosition position, AgentId except = 0) const noexcept; [[nodiscard]] bool resting_at(GridPosition position, AgentId except = 0) const noexcept;
[[nodiscard]] bool ground_rest_cell(GridPosition position, AgentId agent) const noexcept; [[nodiscard]] bool ground_rest_cell(GridPosition position, AgentId agent) const noexcept;
+149 -19
View File
@@ -69,6 +69,12 @@ const Recipe& recipe_for(RecipeId id) {
static constexpr Recipe floor{{ItemStack{ItemType::Wood, 1}, {}}, ItemType::None, 6}; 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 wall{{ItemStack{ItemType::Wood, 1}, {}}, ItemType::None, 9};
static constexpr Recipe door{{ItemStack{ItemType::Wood, 2}, {}}, ItemType::None, 12}; static constexpr Recipe door{{ItemStack{ItemType::Wood, 2}, {}}, ItemType::None, 12};
static constexpr Recipe cabinet{{ItemStack{ItemType::Wood, 1}, {}}, ItemType::None, 10};
static constexpr Recipe mining_rack{{ItemStack{ItemType::Wood, 1}, ItemStack{ItemType::Stone, 1}},
ItemType::None, 10};
static constexpr Recipe loom{{ItemStack{ItemType::Wood, 2}, {}}, ItemType::None, 12};
static constexpr Recipe install_door{{ItemStack{ItemType::WoodenDoor, 1}, {}}, ItemType::None, 8};
static constexpr Recipe craft_door{{ItemStack{ItemType::Wood, 2}, {}}, ItemType::WoodenDoor, 14};
switch (id) { switch (id) {
case RecipeId::SawPlank: return saw; case RecipeId::SawPlank: return saw;
case RecipeId::CutStoneBlock: return cut; case RecipeId::CutStoneBlock: return cut;
@@ -79,6 +85,12 @@ const Recipe& recipe_for(RecipeId id) {
case RecipeId::BuildWall: return wall; case RecipeId::BuildWall: return wall;
case RecipeId::BuildDoorAlongX: case RecipeId::BuildDoorAlongX:
case RecipeId::BuildDoorAlongY: return door; case RecipeId::BuildDoorAlongY: return door;
case RecipeId::BuildMedicineCabinet: return cabinet;
case RecipeId::BuildMiningRack: return mining_rack;
case RecipeId::BuildLoom: return loom;
case RecipeId::InstallDoorAlongX:
case RecipeId::InstallDoorAlongY: return install_door;
case RecipeId::CraftWoodenDoor: return craft_door;
} }
throw std::invalid_argument("unknown production recipe"); throw std::invalid_argument("unknown production recipe");
} }
@@ -143,7 +155,9 @@ RoomPlan make_room_plan(GridPosition first, GridPosition last) noexcept {
bool RoomPlan::valid_size() const noexcept { bool RoomPlan::valid_size() const noexcept {
const auto width = static_cast<std::int64_t>(last.x) - first.x + 1; const auto width = static_cast<std::int64_t>(last.x) - first.x + 1;
const auto height = static_cast<std::int64_t>(last.y) - first.y + 1; const auto height = static_cast<std::int64_t>(last.y) - first.y + 1;
return width >= 3 && width <= 12 && height >= 3 && height <= 12 && entrance <= RoomSide::West; if (entrance > RoomSide::West || layout > RoomTemplate::Weaver) return false;
if (layout == RoomTemplate::Empty) return width >= 3 && width <= 12 && height >= 3 && height <= 12;
return width == furnished_room_size && height == furnished_room_size;
} }
bool RoomPlan::contains(GridPosition cell) const noexcept { bool RoomPlan::contains(GridPosition cell) const noexcept {
@@ -167,6 +181,29 @@ RecipeId RoomPlan::recipe_at(GridPosition cell) const noexcept {
return RecipeId::BuildFloor; return RecipeId::BuildFloor;
} }
std::optional<std::array<RoomFurnishing, 2>> 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<std::size_t>(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<std::size_t>(layout) - 1]}};
}
std::uint8_t RoomPlan::placement_value() const noexcept {
return static_cast<std::uint8_t>((static_cast<unsigned>(layout) << 2) | static_cast<unsigned>(entrance));
}
RoomPlan RoomPlan::from_placement(GridPosition first, GridPosition last, std::uint8_t value) noexcept {
return {first, last, static_cast<RoomSide>(value & 3U), static_cast<RoomTemplate>(value >> 2)};
}
std::uint32_t Inventory::item_count(ItemType type) const noexcept { std::uint32_t Inventory::item_count(ItemType type) const noexcept {
const auto index = static_cast<std::size_t>(type); const auto index = static_cast<std::size_t>(type);
return index != 0 && index <= counts_.size() ? counts_[index - 1] : 0; return index != 0 && index <= counts_.size() ? counts_[index - 1] : 0;
@@ -263,8 +300,14 @@ void World::set_blocked(GridPosition position, bool blocked) {
} }
} }
for (const Agent& agent : agents_) { for (const Agent& agent : agents_) {
if (agent.production_index != no_entity_index &&
production_orders_[agent.production_index].recipe == RecipeId::CraftWoodenDoor &&
std::find(agent.haul_route.begin(), agent.haul_route.end(), position) != agent.haul_route.end()) {
throw std::logic_error("cannot block the carpenter's delivery route");
}
if (agent.production_index == no_entity_index && if (agent.production_index == no_entity_index &&
agent.state != AgentState::GoingToEat && agent.state != AgentState::GoingToSleep) continue; agent.state != AgentState::GoingToEat && agent.state != AgentState::GoingToSleep &&
agent.inventory.item_count(ItemType::WoodenDoor) == 0) continue;
const auto remaining = agent.route.begin() + static_cast<std::ptrdiff_t>(agent.route_cursor); const auto remaining = agent.route.begin() + static_cast<std::ptrdiff_t>(agent.route_cursor);
if (std::find(remaining, agent.route.end(), position) != agent.route.end()) { if (std::find(remaining, agent.route.end(), position) != agent.route.end()) {
throw std::logic_error("cannot block an active production, meal, or sleep route"); throw std::logic_error("cannot block an active production, meal, or sleep route");
@@ -357,6 +400,9 @@ void World::queue_production(GridPosition position, RecipeId recipe) {
if (!is_walkable(position)) { if (!is_walkable(position)) {
throw std::invalid_argument("production site must be on a walkable cell"); throw std::invalid_argument("production site must be on a walkable cell");
} }
if (recipe == RecipeId::CraftWoodenDoor && carpenter_workshop() != position) {
throw std::invalid_argument("wooden doors need the carpenter's workshop");
}
if (is_production_object(recipe) && !can_place_storage(position)) { if (is_production_object(recipe) && !can_place_storage(position)) {
throw std::invalid_argument("the production site is occupied"); throw std::invalid_argument("the production site is occupied");
} }
@@ -382,7 +428,8 @@ bool World::can_place_cabin(GridPosition position) const noexcept {
} }
bool World::can_place_room(const RoomPlan& plan) const noexcept { bool World::can_place_room(const RoomPlan& plan) const noexcept {
if (!plan.valid_size() || !is_walkable(plan.first) || !is_walkable(plan.last)) return false; if (!plan.valid_size() || (plan.layout != RoomTemplate::Empty && !scenario_active_) ||
!is_walkable(plan.first) || !is_walkable(plan.last)) return false;
const int middle_x = std::midpoint(plan.first.x, plan.last.x); const int middle_x = std::midpoint(plan.first.x, plan.last.x);
const int middle_y = std::midpoint(plan.first.y, plan.last.y); 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}, const GridPosition exits[] = {{middle_x, plan.first.y - 1}, {plan.last.x + 1, middle_y},
@@ -413,6 +460,35 @@ std::array<ItemStack, 2> World::construction_materials(RecipeId recipe, BedBase
return is_construction(recipe) ? recipe_for(recipe).ingredients : std::array<ItemStack, 2>{}; return is_construction(recipe) ? recipe_for(recipe).ingredients : std::array<ItemStack, 2>{};
} }
RecipeId World::room_construction_recipe(RecipeId part) const noexcept {
if (scenario_active_) {
if (part == RecipeId::BuildDoorAlongX) return RecipeId::InstallDoorAlongX;
if (part == RecipeId::BuildDoorAlongY) return RecipeId::InstallDoorAlongY;
}
return part;
}
std::size_t World::missing_door_orders(std::size_t new_installations) const {
std::uint64_t waiting_installations = new_installations, supply = 0;
for (const auto& order : production_orders_) {
if (order.recipe == RecipeId::CraftWoodenDoor && order.state != JobState::Completed) ++supply;
if (order.state == JobState::Available &&
(order.recipe == RecipeId::InstallDoorAlongX || order.recipe == RecipeId::InstallDoorAlongY)) {
++waiting_installations;
}
}
for (const auto& agent : agents_) {
if (agent.state == AgentState::Hauling && agent.production_index == no_entity_index) {
supply += agent.inventory.item_count(ItemType::WoodenDoor);
}
}
for (const auto& storage : storages_) {
const auto available = storage.available_item_count(ItemType::WoodenDoor);
if (available != 0 && find_path(scenario_sawmill_, storage.position).reachable) supply += available;
}
return waiting_installations > supply ? static_cast<std::size_t>(waiting_installations - supply) : 0;
}
void World::queue_cabin(GridPosition position, GridPosition sawmill, GridPosition stonecutter) { void World::queue_cabin(GridPosition position, GridPosition sawmill, GridPosition stonecutter) {
if (!can_place_cabin(position) || position == sawmill || position == stonecutter || if (!can_place_cabin(position) || position == sawmill || position == stonecutter ||
(scenario_active_ && position == scenario_sawmill_)) { (scenario_active_ && position == scenario_sawmill_)) {
@@ -485,7 +561,7 @@ CommandStatus World::object_status(GridPosition position, bool moving) const noe
for (const auto& order : production_orders_) { for (const auto& order : production_orders_) {
if (order.position != position || !is_production_object(order.recipe)) continue; if (order.position != position || !is_production_object(order.recipe)) continue;
if (is_finished_floor(order)) continue; if (is_finished_floor(order)) continue;
if (moving && order.recipe >= RecipeId::BuildFloor) return CommandStatus::InvalidTarget; if (moving && is_room_part(order.recipe)) return CommandStatus::InvalidTarget;
return order.state == JobState::InProgress || resting_at(position) ? busy : ready; return order.state == JobState::InProgress || resting_at(position) ? busy : ready;
} }
for (std::size_t i = 0; i < storages_.size(); ++i) { for (std::size_t i = 0; i < storages_.size(); ++i) {
@@ -537,6 +613,7 @@ CommandStatus World::edit_object(GridPosition position, const GridPosition* dest
if (storage != storages_.end()) { if (storage != storages_.end()) {
if (destination) storage->position = *destination; if (destination) storage->position = *destination;
else { else {
const bool loses_doors = storage->item_count(ItemType::WoodenDoor) != 0;
const auto removed = static_cast<std::size_t>(storage - storages_.begin()); const auto removed = static_cast<std::size_t>(storage - storages_.begin());
storages_.erase(storage); storages_.erase(storage);
for (auto& agent : agents_) shift_index(agent.storage_index, removed); for (auto& agent : agents_) shift_index(agent.storage_index, removed);
@@ -544,6 +621,10 @@ CommandStatus World::edit_object(GridPosition position, const GridPosition* dest
for (auto& material : entry.materials) shift_index(material.storage_index, removed); for (auto& material : entry.materials) shift_index(material.storage_index, removed);
for (auto& stop : entry.delivery_stops) shift_index(stop.storage_index, removed); for (auto& stop : entry.delivery_stops) shift_index(stop.storage_index, removed);
} }
if (scenario_active_ && loses_doors) {
const auto missing = missing_door_orders();
for (std::size_t i = 0; i < missing; ++i) queue_production(scenario_sawmill_, RecipeId::CraftWoodenDoor);
}
} }
return CommandStatus::Accepted; return CommandStatus::Accepted;
} }
@@ -661,23 +742,42 @@ CommandReceipt World::apply_command(const PlayerCommand& command) {
} }
queue_production(command.cell, RecipeId::WeaveCloth); queue_production(command.cell, RecipeId::WeaveCloth);
break; break;
case CommandKind::CraftDoor:
queue_production(scenario_sawmill_, RecipeId::CraftWoodenDoor);
break;
case CommandKind::PlaceRoom: { case CommandKind::PlaceRoom: {
const RoomPlan plan{command.cell, command.destination, static_cast<RoomSide>(command.value)}; const auto plan = RoomPlan::from_placement(command.cell, command.destination, command.value);
if (!can_place_room(plan) || !can_reach_object_cell(plan.first)) { if (!can_place_room(plan) || !can_reach_object_cell(plan.first)) {
return receipt(CommandStatus::InvalidTarget); return receipt(CommandStatus::InvalidTarget);
} }
const auto width = static_cast<std::size_t>(plan.last.x - plan.first.x + 1); const auto width = static_cast<std::size_t>(plan.last.x - plan.first.x + 1);
const auto height = static_cast<std::size_t>(plan.last.y - plan.first.y + 1); const auto height = static_cast<std::size_t>(plan.last.y - plan.first.y + 1);
production_orders_.reserve(production_orders_.size() + width * height); const auto furnishings = plan.furnishings();
const bool legacy_bed = furnishings.has_value() && !staged_beds_;
const auto door_orders = scenario_active_ ? missing_door_orders(1) : 0;
production_orders_.reserve(production_orders_.size() + width * height +
(furnishings ? furnishings->size() : 0) + (legacy_bed ? 1U : 0U) + door_orders);
if (legacy_bed) queue_production(scenario_sawmill_, RecipeId::SawPlank);
if (furnishings) {
for (const auto& part : *furnishings) {
ProductionOrder order{};
order.position = part.position;
order.recipe = part.recipe;
order.bed_base = part.bed_base;
if (order.recipe == RecipeId::BuildBed && staged_beds_) order.bed_stage = BedStage::Foundation;
production_orders_.push_back(std::move(order));
}
}
for (int y = plan.first.y; y <= plan.last.y; ++y) { for (int y = plan.first.y; y <= plan.last.y; ++y) {
for (int x = plan.first.x; x <= plan.last.x; ++x) { for (int x = plan.first.x; x <= plan.last.x; ++x) {
const GridPosition cell{x, y}; const GridPosition cell{x, y};
ProductionOrder order{}; ProductionOrder order{};
order.position = cell; order.position = cell;
order.recipe = plan.recipe_at(cell); order.recipe = room_construction_recipe(plan.recipe_at(cell));
production_orders_.push_back(std::move(order)); production_orders_.push_back(std::move(order));
} }
} }
for (std::size_t i = 0; i < door_orders; ++i) queue_production(scenario_sawmill_, RecipeId::CraftWoodenDoor);
break; break;
} }
case CommandKind::PlaceStorage: case CommandKind::PlaceStorage:
@@ -695,7 +795,7 @@ CommandReceipt World::apply_command(const PlayerCommand& command) {
break; break;
} }
case CommandKind::AssignProfession: { case CommandKind::AssignProfession: {
if (command.value > static_cast<std::uint8_t>(Profession::Builder) || command.resident == 0) { if (command.value > static_cast<std::uint8_t>(Profession::Carpenter) || command.resident == 0) {
return receipt(CommandStatus::InvalidTarget); return receipt(CommandStatus::InvalidTarget);
} }
const auto resident = std::lower_bound(agents_.begin(), agents_.end(), command.resident, const auto resident = std::lower_bound(agents_.begin(), agents_.end(), command.resident,
@@ -1004,10 +1104,11 @@ void World::assign_resource_tasks(ResourceFocus focus) {
} }
for (Agent& agent : agents_) { for (Agent& agent : agents_) {
if (open_pantry_count == 0 && open_material_store_count == 0 && untended_sites == 0) break; 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<std::size_t>(agent.profession);
if (profession >= available.size() || agent.state != AgentState::Idle || agent.current_job != 0 ||
!agent.inventory.empty()) continue; !agent.inventory.empty()) continue;
const auto& candidates = available[static_cast<std::size_t>(agent.profession)]; const auto& candidates = available[profession];
if (candidates.empty()) continue; if (candidates.empty()) continue;
std::vector<std::uint8_t> tried_nodes(candidates.size(), 0); std::vector<std::uint8_t> tried_nodes(candidates.size(), 0);
for (;;) { for (;;) {
@@ -1099,7 +1200,8 @@ void World::assign_production_tasks(bool weaving) {
if (production_orders_.empty() || storages_.empty() || if (production_orders_.empty() || storages_.empty() ||
std::none_of(agents_.begin(), agents_.end(), std::none_of(agents_.begin(), agents_.end(),
[](const Agent& agent) { [](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; })) return;
for (std::size_t index = 0; index < production_orders_.size(); ++index) { for (std::size_t index = 0; index < production_orders_.size(); ++index) {
ProductionOrder& order = production_orders_[index]; ProductionOrder& order = production_orders_[index];
@@ -1107,15 +1209,18 @@ void World::assign_production_tasks(bool weaving) {
const bool site_busy = std::any_of(production_orders_.begin(), production_orders_.end(), const bool site_busy = std::any_of(production_orders_.begin(), production_orders_.end(),
[&order](const ProductionOrder& other) { [&order](const ProductionOrder& other) {
return other.state == JobState::InProgress && return other.position == order.position &&
other.position.x == order.position.x && other.position.y == order.position.y; (other.state == JobState::InProgress ||
(order.recipe != RecipeId::BuildFloor && other.recipe == RecipeId::BuildFloor &&
other.state != JobState::Completed));
}); });
if (site_busy) continue; if (site_busy) continue;
const Recipe recipe = recipe_for(order); const Recipe recipe = recipe_for(order);
const bool construction = is_construction(order.recipe); const bool door_craft = order.recipe == RecipeId::CraftWoodenDoor;
const bool deliver_ingredients = delivers_materials(order.recipe);
enum class Access { Unknown, Reachable, Unreachable }; enum class Access { Unknown, Reachable, Unreachable };
std::vector<Access> storage_access(construction || weaving ? storages_.size() : 0, Access::Unknown); std::vector<Access> storage_access(deliver_ingredients || weaving ? storages_.size() : 0, Access::Unknown);
std::vector<MaterialReservation> materials; std::vector<MaterialReservation> materials;
bool supplied = true; bool supplied = true;
for (const ItemStack& ingredient : recipe.ingredients) { for (const ItemStack& ingredient : recipe.ingredients) {
@@ -1146,7 +1251,7 @@ void World::assign_production_tasks(bool weaving) {
if (!supplied) continue; if (!supplied) continue;
std::vector<ConstructionStop> stops; std::vector<ConstructionStop> stops;
if (construction) { if (deliver_ingredients) {
for (std::size_t s = 0; s < storage_access.size(); ++s) { for (std::size_t s = 0; s < storage_access.size(); ++s) {
if (storage_access[s] == Access::Reachable) stops.push_back({s, {}}); if (storage_access[s] == Access::Reachable) stops.push_back({s, {}});
} }
@@ -1160,12 +1265,18 @@ void World::assign_production_tasks(bool weaving) {
stops[i].route_to_next = std::move(path.positions); 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; ? storages_[stops.front().storage_index].position : order.position;
for (Agent& agent : agents_) { for (Agent& agent : agents_) {
if (agent.state != AgentState::Idle || !can_take_work(agent, Profession::Builder)) continue; const bool can_craft = agent.profession == Profession::Carpenter;
const bool eligible = door_craft ? can_craft :
can_take_work(agent, Profession::Builder) || (can_craft && order.recipe == RecipeId::SawPlank);
if (agent.state != AgentState::Idle || !eligible) continue;
auto path = assignment_path(agent.position, destination); auto path = assignment_path(agent.position, destination);
if (!path.reachable) continue; if (!path.reachable) continue;
if (door_craft) {
agent.haul_route = assignment_path(order.position, storages_[materials.front().storage_index].position).positions;
}
for (const auto& material : materials) { for (const auto& material : materials) {
stack_position(storages_[material.storage_index], material.type)->reserved += material.count; stack_position(storages_[material.storage_index], material.type)->reserved += material.count;
@@ -1177,7 +1288,7 @@ void World::assign_production_tasks(bool weaving) {
agent.route = std::move(path.positions); agent.route = std::move(path.positions);
agent.route_cursor = 0; agent.route_cursor = 0;
agent.work_remaining = recipe.ticks; agent.work_remaining = recipe.ticks;
agent.state = construction ? AgentState::FetchingMaterials : agent.state = deliver_ingredients ? AgentState::FetchingMaterials :
(agent.route.empty() ? AgentState::Working : AgentState::Travelling); (agent.route.empty() ? AgentState::Working : AgentState::Travelling);
break; break;
} }
@@ -1326,6 +1437,10 @@ void World::advance_construction_delivery(Agent& agent) {
agent.inventory.add(material.type, material.count); agent.inventory.add(material.type, material.count);
} }
} }
if (order.recipe == RecipeId::CraftWoodenDoor && stop.storage_index == order.materials.front().storage_index) {
// The wood just collected frees a slot for the completed door.
++storages_[stop.storage_index].reserved_slots;
}
++order.collected_stops; ++order.collected_stops;
agent.route = std::move(stop.route_to_next); agent.route = std::move(stop.route_to_next);
agent.route_cursor = 0; agent.route_cursor = 0;
@@ -1336,6 +1451,18 @@ void World::finish_production(Agent& agent) {
ProductionOrder& order = production_orders_[agent.production_index]; ProductionOrder& order = production_orders_[agent.production_index];
const Recipe recipe = recipe_for(order); const Recipe recipe = recipe_for(order);
assert(!order.materials.empty()); assert(!order.materials.empty());
if (order.recipe == RecipeId::CraftWoodenDoor) {
agent.inventory.add(recipe.output);
agent.storage_index = order.materials.front().storage_index;
agent.route = std::move(agent.haul_route);
agent.haul_route.clear();
agent.route_cursor = 0;
agent.production_index = no_entity_index;
agent.state = AgentState::Hauling;
order.materials.clear();
order.state = JobState::Completed;
return;
}
if (recipe.output != ItemType::None) { if (recipe.output != ItemType::None) {
for (const auto& material : order.materials) { for (const auto& material : order.materials) {
take_reserved_material(storages_[material.storage_index], material); take_reserved_material(storages_[material.storage_index], material);
@@ -1348,6 +1475,9 @@ void World::finish_production(Agent& agent) {
(order.bed_stage == BedStage::Foundation || order.bed_stage == BedStage::Bedding)) { (order.bed_stage == BedStage::Foundation || order.bed_stage == BedStage::Bedding)) {
order.bed_stage = order.bed_stage == BedStage::Foundation ? BedStage::Bedding : BedStage::Pillow; order.bed_stage = order.bed_stage == BedStage::Foundation ? BedStage::Bedding : BedStage::Pillow;
order.state = JobState::Available; order.state = JobState::Available;
} else if (order.recipe == RecipeId::BuildLoom) {
order.recipe = RecipeId::WeaveCloth;
order.state = JobState::Available;
} else if (order.recipe == RecipeId::WeaveCloth) { } else if (order.recipe == RecipeId::WeaveCloth) {
order.state = JobState::Available; order.state = JobState::Available;
} else { } else {
+28 -10
View File
@@ -13,7 +13,7 @@ namespace settlement {
namespace { namespace {
constexpr std::string_view signature = "SETTLERS"; constexpr std::string_view signature = "SETTLERS";
constexpr std::uint32_t save_version = 10; constexpr std::uint32_t save_version = 12;
constexpr std::uint32_t last_legacy_footer_version = 8; constexpr std::uint32_t last_legacy_footer_version = 8;
constexpr std::size_t max_records = 1'000'000; constexpr std::size_t max_records = 1'000'000;
constexpr std::size_t max_save_bytes = 128 * 1024 * 1024; constexpr std::size_t max_save_bytes = 128 * 1024 * 1024;
@@ -174,7 +174,7 @@ void flag(Archive& archive, Flag& value) {
struct WorldSaveCodec { struct WorldSaveCodec {
template<class Archive, class State> template<class Archive, class State>
static void body(Archive& archive, State& world, std::uint32_t version) { static void body(Archive& archive, State& world, std::uint32_t version) {
const auto max_item = version >= 7 ? ItemType::Flax : ItemType::Cloth; const auto max_item = version >= 12 ? ItemType::WoodenDoor : (version >= 7 ? ItemType::Flax : ItemType::Cloth);
const auto max_item_count = static_cast<std::size_t>(max_item); const auto max_item_count = static_cast<std::size_t>(max_item);
archive.field(world.tick_); archive.field(world.tick_);
archive.field(world.path_searches_); archive.field(world.path_searches_);
@@ -214,6 +214,7 @@ struct WorldSaveCodec {
if (version >= 4) archive.field(agent.fatigue); if (version >= 4) archive.field(agent.fatigue);
if (version >= 5) flag(archive, agent.resting_on_ground); if (version >= 5) flag(archive, agent.resting_on_ground);
if (version >= 6) archive.field(agent.profession); 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) { sequence(archive, world.jobs_, max_records, [&](auto& job) {
archive.field(job.id); archive.field(job.id);
@@ -256,6 +257,8 @@ struct WorldSaveCodec {
require_save(version >= 2 || order.recipe <= RecipeId::BuildCabin, "Unknown recipe for save version."); require_save(version >= 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 >= 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 >= 10 || order.recipe <= RecipeId::WeaveCloth, "Unknown recipe for save version.");
require_save(version >= 11 || order.recipe <= RecipeId::BuildDoorAlongY, "Unknown recipe for save version.");
require_save(version >= 12 || order.recipe <= RecipeId::BuildLoom, "Unknown recipe for save version.");
archive.field(order.state); archive.field(order.state);
sequence(archive, order.materials, item_types, [&](auto& material) { sequence(archive, order.materials, item_types, [&](auto& material) {
index(archive, material.storage_index); index(archive, material.storage_index);
@@ -362,9 +365,10 @@ void WorldSaveCodec::validate(const World& world) {
std::vector<AgentId> bed_owners; std::vector<AgentId> bed_owners;
for (std::size_t i = 0; i < world.production_orders_.size(); ++i) { for (std::size_t i = 0; i < world.production_orders_.size(); ++i) {
const auto& order = world.production_orders_[i]; const auto& order = world.production_orders_[i];
invalid(order.recipe <= RecipeId::BuildDoorAlongY && order.state <= JobState::Completed && invalid(order.recipe <= RecipeId::CraftWoodenDoor && order.state <= JobState::Completed &&
world.is_walkable(order.position) && world.is_walkable(order.position) &&
(order.recipe != RecipeId::WeaveCloth || order.state != JobState::Completed)); (order.recipe != RecipeId::WeaveCloth || order.state != JobState::Completed));
invalid(order.recipe != RecipeId::CraftWoodenDoor || world.carpenter_workshop() == order.position);
invalid(order.bed_base <= BedBase::Stone && order.bed_stage <= BedStage::Pillow && invalid(order.bed_base <= BedBase::Stone && order.bed_stage <= BedStage::Pillow &&
(order.bed_stage == BedStage::Legacy || (order.bed_stage == BedStage::Legacy ||
(world.staged_beds_ && order.recipe == RecipeId::BuildBed)) && (world.staged_beds_ && order.recipe == RecipeId::BuildBed)) &&
@@ -382,8 +386,8 @@ void WorldSaveCodec::validate(const World& world) {
continue; continue;
} }
const bool construction = is_construction(order.recipe); const bool delivery = delivers_materials(order.recipe);
invalid(order.collected_stops <= order.delivery_stops.size() && (construction || order.delivery_stops.empty())); invalid(order.collected_stops <= order.delivery_stops.size() && (delivery || order.delivery_stops.empty()));
std::size_t last_storage = 0; std::size_t last_storage = 0;
bool first_stop = true; bool first_stop = true;
for (const auto& stop : order.delivery_stops) { for (const auto& stop : order.delivery_stops) {
@@ -401,7 +405,7 @@ void WorldSaveCodec::validate(const World& world) {
invalid(material.storage_index < world.storages_.size() && material.count > 0 && invalid(material.storage_index < world.storages_.size() && material.count > 0 &&
world.storages_[material.storage_index].kind == StorageKind::Materials); world.storages_[material.storage_index].kind == StorageKind::Materials);
ingredients[type] += material.count; ingredients[type] += material.count;
if (!construction) { if (!delivery) {
reserved_items[material.storage_index][type] += material.count; reserved_items[material.storage_index][type] += material.count;
} else if (!order.delivery_stops.empty()) { } else if (!order.delivery_stops.empty()) {
const auto stop = std::find_if(order.delivery_stops.begin(), order.delivery_stops.end(), const auto stop = std::find_if(order.delivery_stops.begin(), order.delivery_stops.end(),
@@ -425,10 +429,16 @@ void WorldSaveCodec::validate(const World& world) {
break; break;
case RecipeId::BuildBed: required[item_index(order.bed_material())] = 1; break; case RecipeId::BuildBed: required[item_index(order.bed_material())] = 1; break;
case RecipeId::WeaveCloth: required[item_index(ItemType::Flax)] = 1; break; case RecipeId::WeaveCloth: required[item_index(ItemType::Flax)] = 1; break;
case RecipeId::CraftWoodenDoor: required[item_index(ItemType::Wood)] = 2; break;
case RecipeId::BuildFloor: case RecipeId::BuildFloor:
case RecipeId::BuildWall: case RecipeId::BuildWall:
case RecipeId::BuildDoorAlongX: case RecipeId::BuildDoorAlongX:
case RecipeId::BuildDoorAlongY: case RecipeId::BuildDoorAlongY:
case RecipeId::BuildMedicineCabinet:
case RecipeId::BuildMiningRack:
case RecipeId::BuildLoom:
case RecipeId::InstallDoorAlongX:
case RecipeId::InstallDoorAlongY:
for (const auto& item : world.construction_materials(order.recipe, order.bed_base)) { for (const auto& item : world.construction_materials(order.recipe, order.bed_base)) {
if (item.count) required[item_index(item.type)] = item.count; if (item.count) required[item_index(item.type)] = item.count;
} }
@@ -450,7 +460,7 @@ void WorldSaveCodec::validate(const World& world) {
(world.hunger_enabled_ || agent.hunger == 0) && agent.fatigue <= max_fatigue && (world.hunger_enabled_ || agent.hunger == 0) && agent.fatigue <= max_fatigue &&
(world.scenario_active_ || agent.fatigue == 0)); (world.scenario_active_ || agent.fatigue == 0));
invalid(!agent.resting_on_ground || agent.state == Sleeping || agent.state == GoingToSleep); 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.route);
valid_route(agent.haul_route); valid_route(agent.haul_route);
const bool has_job = agent.current_job != 0; const bool has_job = agent.current_job != 0;
@@ -458,7 +468,9 @@ void WorldSaveCodec::validate(const World& world) {
const bool has_source = agent.resource_node_index != no_entity_index; const bool has_source = agent.resource_node_index != no_entity_index;
const bool has_storage = agent.storage_index != no_entity_index; const bool has_storage = agent.storage_index != no_entity_index;
invalid(!has_storage || agent.storage_index < world.storages_.size()); invalid(!has_storage || agent.storage_index < world.storages_.size());
invalid(agent.haul_route.empty() || has_source); const bool door_craft = has_order && agent.production_index < world.production_orders_.size() &&
world.production_orders_[agent.production_index].recipe == RecipeId::CraftWoodenDoor;
invalid(agent.haul_route.empty() || has_source || door_craft);
if (has_job) { if (has_job) {
invalid(!has_order && !has_storage && !has_source && agent.inventory.empty() && invalid(!has_order && !has_storage && !has_source && agent.inventory.empty() &&
(agent.state == Travelling || agent.state == Working) && agent.work_remaining > 0); (agent.state == Travelling || agent.state == Working) && agent.work_remaining > 0);
@@ -477,7 +489,13 @@ void WorldSaveCodec::validate(const World& world) {
if (!order.delivery_stops.empty()) { if (!order.delivery_stops.empty()) {
invalid(agent.state == (order.collected_stops == 0 ? FetchingMaterials : Hauling)); invalid(agent.state == (order.collected_stops == 0 ? FetchingMaterials : Hauling));
} else { } else {
invalid(agent.state == Working || (agent.state == Travelling && !is_construction(order.recipe))); invalid(agent.state == Working || (agent.state == Travelling && !delivers_materials(order.recipe)));
}
if (door_craft) {
const auto storage = order.materials.front().storage_index;
const auto destination = world.storages_[storage].position;
invalid(agent.haul_route.empty() ? destination == order.position : agent.haul_route.back() == destination);
if (order.delivery_stops.empty() || order.collected_stops > 0) ++reserved_slots[storage];
} }
for (std::size_t i = 0; i < item_types; ++i) { for (std::size_t i = 0; i < item_types; ++i) {
invalid(agent.inventory.item_count(static_cast<ItemType>(i + 1)) == expected_cargo[agent.production_index][i]); invalid(agent.inventory.item_count(static_cast<ItemType>(i + 1)) == expected_cargo[agent.production_index][i]);
@@ -497,7 +515,7 @@ void WorldSaveCodec::validate(const World& world) {
} else if (agent.state == Hauling) { } else if (agent.state == Hauling) {
const auto cargo = agent.inventory.first_item(); const auto cargo = agent.inventory.first_item();
invalid(has_storage && (cargo == ItemType::Wood || cargo == ItemType::Stone || invalid(has_storage && (cargo == ItemType::Wood || cargo == ItemType::Stone ||
cargo == ItemType::Berries || cargo == ItemType::Flax) && cargo == ItemType::Berries || cargo == ItemType::Flax || cargo == ItemType::WoodenDoor) &&
agent.inventory.item_count(cargo) == 1 && agent.work_remaining == 0 && agent.inventory.item_count(cargo) == 1 && agent.work_remaining == 0 &&
world.storages_[agent.storage_index].accepts(cargo)); world.storages_[agent.storage_index].accepts(cargo));
for (std::size_t i = 1; i <= item_types; ++i) { for (std::size_t i = 1; i <= item_types; ++i) {
+45 -99
View File
@@ -1,111 +1,57 @@
param() param([string]$Msys2Root = $env:SETTLEMENT_MSYS2_ROOT)
$ErrorActionPreference = 'Stop' $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) { if (-not [Environment]::Is64BitOperatingSystem) {
throw 'This portable toolchain setup requires 64-bit Windows.' throw 'MSYS2 UCRT64 requires 64-bit Windows.'
} }
$toolRoot = Join-Path $PSScriptRoot '.tools\toolchain'
New-Item -ItemType Directory -Path $downloadRoot -Force | Out-Null $portableRoot = Join-Path $toolRoot 'msys64'
New-Item -ItemType Directory -Path $toolRoot -Force | Out-Null if (-not $Msys2Root) { $Msys2Root = $portableRoot }
$bash = Join-Path $Msys2Root 'usr\bin\bash.exe'
function Get-Download { $bin = Join-Path $Msys2Root 'ucrt64\bin'
param( $compiler = Join-Path $bin 'g++.exe'
[Parameter(Mandatory = $true)][string]$Uri, if ((Test-Path -LiteralPath $compiler -PathType Leaf) -and
[Parameter(Mandatory = $true)][string]$Destination (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 (-not (Test-Path -LiteralPath $Destination -PathType Leaf)) { if ($LASTEXITCODE -eq 0 -and $version -match '^16(\.|$)') {
Write-Host "Downloading $([System.IO.Path]::GetFileName($Destination))" Write-Output "MSYS2 UCRT64 GCC $version is ready."
Invoke-WebRequest -Uri $Uri -OutFile $Destination -UseBasicParsing return
} }
} }
if (-not (Test-Path -LiteralPath $bash -PathType Leaf)) {
function Expand-IfMissing { if ([IO.Path]::GetFullPath($Msys2Root) -ne [IO.Path]::GetFullPath($portableRoot)) {
param( throw "MSYS2 was not found at $Msys2Root."
[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
} }
} $downloadRoot = Join-Path $PSScriptRoot '.tools\downloads'
New-Item -ItemType Directory -Path $downloadRoot, $toolRoot -Force | Out-Null
$cmakeArchive = Join-Path $downloadRoot $cmakeArchiveName $name = 'msys2-base-x86_64-20261120.tar.zst'
$cmakeHashFile = Join-Path $downloadRoot $cmakeHashName $archive = Join-Path $downloadRoot $name
$cmakeBase = "https://github.com/Kitware/CMake/releases/download/v$cmakeVersion" $expected = 'adde59fcb53760bd0fd2aa3c3e8da516f03159b771dc62b77c340e4ac187fcdd'
Get-Download -Uri "$cmakeBase/$cmakeArchiveName" -Destination $cmakeArchive if (-not (Test-Path -LiteralPath $archive -PathType Leaf) -or
Get-Download -Uri "$cmakeBase/$cmakeHashName" -Destination $cmakeHashFile (Get-FileHash -LiteralPath $archive -Algorithm SHA256).Hash -ne $expected) {
Invoke-WebRequest -Uri "https://repo.msys2.org/distrib/x86_64/$name" -OutFile $archive -UseBasicParsing
$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
} }
} if ((Get-FileHash -LiteralPath $archive -Algorithm SHA256).Hash -ne $expected) {
if (-not $expectedCmakeHash) { throw 'MSYS2 archive hash does not match the release.'
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."
} }
} else { & tar.exe -xf $archive -C $toolRoot
Write-Warning 'GitHub did not publish a SHA-256 digest for this LLVM-MinGW asset; download is from the official release over HTTPS.' if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
} }
$cmakeInstall = Join-Path $toolRoot 'cmake' $previousMsysSystem = $env:MSYSTEM
$llvmInstall = Join-Path $toolRoot 'llvm-mingw' try {
Expand-IfMissing -Archive $cmakeArchive -Destination $cmakeInstall -ExpectedExecutable 'cmake.exe' $env:MSYSTEM = 'UCRT64'
Expand-IfMissing -Archive $llvmArchive -Destination $llvmInstall -ExpectedExecutable 'clang++.exe' # An MSYS2 runtime upgrade can close the first shell. Start a fresh shell for the remaining packages.
& $bash --login -c 'pacman -Syu --noconfirm'
$cmakeExe = Get-ChildItem -LiteralPath $cmakeInstall -Filter 'cmake.exe' -File -Recurse | Select-Object -First 1 if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
$clangxxExe = Get-ChildItem -LiteralPath $llvmInstall -Filter 'clang++.exe' -File -Recurse | Select-Object -First 1 & $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 ($null -eq $cmakeExe -or $null -eq $clangxxExe) { if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
throw 'Extraction completed, but CMake or Clang++ was not found in the toolchain folders.' } finally {
$env:MSYSTEM = $previousMsysSystem
} }
$version = & $compiler -dumpfullversion
Write-Host "CMake: $($cmakeExe.FullName)" if ($LASTEXITCODE -ne 0 -or $version -notmatch '^16(\.|$)') {
& $cmakeExe.FullName --version | Select-Object -First 1 throw "Expected GCC 16 in MSYS2 UCRT64. Found: $version"
Write-Host "C++ compiler: $($clangxxExe.FullName)" }
& $clangxxExe.FullName --version | Select-Object -First 1 Write-Output "MSYS2 UCRT64 GCC $version is ready."
Write-Host 'Portable toolchain is ready. Run .\build.ps1 to configure, build, and run CTest.'
+244 -55
View File
@@ -1,6 +1,9 @@
#include "testing.hpp"
#include "settlement/core/deterministic_rng.hpp" #include "settlement/core/deterministic_rng.hpp"
#include "settlement/core/world.hpp" #include "settlement/core/world.hpp"
#include <algorithm>
#include <cstdint> #include <cstdint>
#include <iostream> #include <iostream>
#include <sstream> #include <sstream>
@@ -30,7 +33,36 @@ std::unique_ptr<settlement::World> save_roundtrip(const settlement::World& world
return restored; return restored;
} }
void test_parallel_pathfinding_completes_the_jobs() { using Void::Testing::Test;
struct CoreTests : Void::Testing::Suite<CoreTests> {
Test test_parallel_pathfinding_completes_the_jobs();
Test test_single_worker_configuration_is_rejected();
Test test_rng_repeats_for_same_seed();
Test test_work_jobs_complete();
Test test_astar_route_uses_opening_in_wall();
Test test_residents_gather_and_deliver_resources();
[[= Void::Testing::tag("construction")]] Test test_production_reservations_and_construction();
[[= Void::Testing::tag("construction")]] Test test_cabin_placement_queues_a_complete_order();
Test test_hungry_resident_reserves_and_eats_a_berry();
Test test_invalid_save_is_rejected();
Test test_two_players_share_the_first_colony();
Test test_bed_parts_are_delivered_separately();
Test test_resident_uses_assigned_bed_and_sleep_survives_save();
Test test_fatigue_slows_work_without_interrupting_it();
Test test_ground_rest_never_uses_another_residents_bed();
Test test_fields_mines_and_reindexing_active_hauls();
Test test_specialists_take_their_own_jobs_and_finish_prior_assignments();
Test test_flax_and_loom_supply_a_bed_without_starting_cloth();
Test test_field_growth_requires_a_worker();
Test test_opening_a_mine_invalidates_unreachable_routes();
Test test_object_tools_work_in_an_older_demo_world();
[[= Void::Testing::tag("construction")]] Test test_room_builds_and_saves_as_separate_parts();
[[= Void::Testing::tag("construction")]] Test test_furnished_rooms_queue_and_build_their_contents();
[[= Void::Testing::tag("construction")]] Test test_carpenter_delivers_the_door_before_installation();
};
Test CoreTests::test_parallel_pathfinding_completes_the_jobs() {
settlement::World world(123, 48, 48, 6); settlement::World world(123, 48, 48, 6);
for (std::int32_t y = 0; y < 48; ++y) { for (std::int32_t y = 0; y < 48; ++y) {
if (y != 31) world.set_blocked({24, y}); if (y != 31) world.set_blocked({24, y});
@@ -42,26 +74,28 @@ void test_parallel_pathfinding_completes_the_jobs() {
} }
for (int tick = 0; tick < 120; ++tick) world.step(); for (int tick = 0; tick < 120; ++tick) world.step();
require(world.jobs_completed() == 24, "parallel pathfinding did not finish every job"); 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 { try {
settlement::World world(8, 8, 8, 1); settlement::World world(8, 8, 8, 1);
} catch (const std::invalid_argument&) { } catch (const std::invalid_argument&) {
return; return {};
} }
throw std::runtime_error("world accepted a single worker"); 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 left(12345);
settlement::DeterministicRng right(12345); settlement::DeterministicRng right(12345);
for (int index = 0; index < 1000; ++index) { 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); settlement::World world(1, 10, 10);
const settlement::AgentId agent_id = world.spawn_agent({1, 1}); const settlement::AgentId agent_id = world.spawn_agent({1, 1});
const settlement::JobId job_id = world.add_job({3, 1}, 2); const settlement::JobId job_id = world.add_job({3, 1}, 2);
@@ -81,9 +115,10 @@ void test_work_jobs_complete() {
"completed job retained an active state"); "completed job retained an active state");
require(world.agents().front().state == settlement::AgentState::Idle, require(world.agents().front().state == settlement::AgentState::Idle,
"worker did not return to idle after completing a job"); "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); settlement::World world(2, 10, 10);
for (std::int32_t y = 0; y < 10; ++y) { for (std::int32_t y = 0; y < 10; ++y) {
if (y != 8) { if (y != 8) {
@@ -103,9 +138,10 @@ void test_astar_route_uses_opening_in_wall() {
} }
require(world.path_searches() > 0, "path search counter was not updated"); require(world.path_searches() > 0, "path search counter was not updated");
require(world.path_nodes_visited() > 0, "A* did not report expanded nodes"); 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); settlement::World world(51, 16, 16, 4);
static_cast<void>(world.add_storage({1, 1}, 10)); static_cast<void>(world.add_storage({1, 1}, 10));
static_cast<void>(world.spawn_agent({1, 2})); static_cast<void>(world.spawn_agent({1, 2}));
@@ -126,9 +162,10 @@ void test_residents_gather_and_deliver_resources() {
"storage retained reservations after deliveries completed"); "storage retained reservations after deliveries completed");
require(world.resource_nodes()[0].quantity == 0 && world.resource_nodes()[1].quantity == 0, require(world.resource_nodes()[0].quantity == 0 && world.resource_nodes()[1].quantity == 0,
"resource nodes retained units after deliveries completed"); "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::ItemType;
using settlement::JobState; using settlement::JobState;
using settlement::RecipeId; using settlement::RecipeId;
@@ -207,9 +244,10 @@ void test_production_reservations_and_construction() {
require(world.storages()[0].items.empty() && world.storages()[1].items.empty(), require(world.storages()[0].items.empty() && world.storages()[1].items.empty(),
"building did not consume the crafted materials from both stores"); "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; using settlement::RecipeId;
settlement::World world(1, 10, 10); settlement::World world(1, 10, 10);
world.set_blocked({1, 1}); world.set_blocked({1, 1});
@@ -229,9 +267,10 @@ void test_cabin_placement_queues_a_complete_order() {
} catch (const std::invalid_argument&) { } catch (const std::invalid_argument&) {
require(orders.size() == 6, "invalid placement partially queued new orders"); 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::AgentState;
using settlement::ItemType; using settlement::ItemType;
const settlement::GridPosition pantry{1, 1}; const settlement::GridPosition pantry{1, 1};
@@ -278,9 +317,10 @@ void test_hungry_resident_reserves_and_eats_a_berry() {
static_cast<void>(world.add_job(pantry, 1)); static_cast<void>(world.add_job(pantry, 1));
world.step(); world.step();
require(world.jobs_completed() == 2, "the resident did not resume work after eating"); 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); const settlement::World world(5, 5, 5);
auto bytes = save_contents(world); auto bytes = save_contents(world);
const auto rejected = [](const std::string& save) { const auto rejected = [](const std::string& save) {
@@ -296,9 +336,10 @@ void test_invalid_save_is_rejected() {
require(rejected(bytes + 'x'), "save with trailing data was accepted"); require(rejected(bytes + 'x'), "save with trailing data was accepted");
bytes[8] = 127; bytes[8] = 127;
require(rejected(bytes), "unknown save version was accepted"); 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::CommandKind;
using settlement::CommandStatus; using settlement::CommandStatus;
auto world = settlement::make_first_colony(2); auto world = settlement::make_first_colony(2);
@@ -341,9 +382,10 @@ void test_two_players_share_the_first_colony() {
"the shared colony could not feed its residents and complete the objective"); "the shared colony could not feed its residents and complete the objective");
auto replay = save_roundtrip(*world); auto replay = save_roundtrip(*world);
require(replay->scenario_progress().completed, "completion was lost after loading"); 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; using namespace settlement;
auto world = make_first_colony(2); auto world = make_first_colony(2);
const GridPosition wood_bed{16, 18}; const GridPosition wood_bed{16, 18};
@@ -373,9 +415,10 @@ void test_bed_parts_are_delivered_separately() {
"the beds were not completed through three separate deliveries"); "the beds were not completed through three separate deliveries");
require(world->storages().back().item_count(ItemType::Cloth) == 8, require(world->storages().back().item_count(ItemType::Cloth) == 8,
"two beds must consume four pieces of cloth"); "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; using namespace settlement;
World world(4, 16, 16, 2); World world(4, 16, 16, 2);
const auto owner = world.spawn_agent({1, 2}); const auto owner = world.spawn_agent({1, 2});
@@ -423,9 +466,10 @@ void test_resident_uses_assigned_bed_and_sleep_survives_save() {
} }
require(from_route && woke_rested && rested_on_ground, "sleep and recovery phases were not observed"); require(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"); 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; using namespace settlement;
World world(6, 10, 10); World world(6, 10, 10);
static_cast<void>(world.spawn_agent({2, 2})); static_cast<void>(world.spawn_agent({2, 2}));
@@ -438,9 +482,10 @@ void test_fatigue_slows_work_without_interrupting_it() {
const auto before = resident.work_remaining; const auto before = resident.work_remaining;
for (int i = 0; i < 6; ++i) world.step(); for (int i = 0; i < 6; ++i) world.step();
require(before - resident.work_remaining == 2, "hunger and fatigue did not slow the ongoing work"); 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; using namespace settlement;
World world(15, 14, 14); World world(15, 14, 14);
const GridPosition cell{7, 6}; const GridPosition cell{7, 6};
@@ -479,9 +524,10 @@ void test_ground_rest_never_uses_another_residents_bed() {
require(world.assigned_bed(owner)->position == new_cell, "moving a bed lost its owner"); require(world.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 && 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"); 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; using namespace settlement;
World world(22, 18, 18, 2); World world(22, 18, 18, 2);
const GridPosition rock{9, 5}; const GridPosition rock{9, 5};
@@ -532,9 +578,10 @@ void test_fields_mines_and_reindexing_active_hauls() {
"growing, regrowing, or mining did not deliver resources"); "growing, regrowing, or mining did not deliver resources");
require(apply(CommandKind::PlaceStorage, {11, 7}) == CommandStatus::Accepted, require(apply(CommandKind::PlaceStorage, {11, 7}) == CommandStatus::Accepted,
"a new storage could not be placed"); "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; using namespace settlement;
World world(54, 14, 14, 2); World world(54, 14, 14, 2);
const auto farmer = world.spawn_agent({2, 2}); const auto farmer = world.spawn_agent({2, 2});
@@ -588,9 +635,10 @@ void test_specialists_take_their_own_jobs_and_finish_prior_assignments() {
} }
require(delivered_stone && later_cut_wood, "the reassigned miner did not finish mining and then cut wood"); require(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"); 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; using namespace settlement;
World world(92, 12, 12, 3); World world(92, 12, 12, 3);
const auto farmer = world.spawn_agent({2, 3}); const auto farmer = world.spawn_agent({2, 3});
@@ -648,9 +696,10 @@ void test_flax_and_loom_supply_a_bed_without_starting_cloth() {
require(world.scenario_progress().assigned_beds == 1 && require(world.scenario_progress().assigned_beds == 1 &&
world.storages().front().item_count(ItemType::Cloth) > 0, world.storages().front().item_count(ItemType::Cloth) > 0,
"the loom did not make enough cloth to finish and replenish a bed order"); "the loom did not make enough cloth to finish and replenish a bed order");
return {};
} }
void test_field_growth_requires_a_worker() { Test CoreTests::test_field_growth_requires_a_worker() {
using namespace settlement; using namespace settlement;
World world(58, 14, 14); World world(58, 14, 14);
const auto resident = world.spawn_agent({2, 2}); const auto resident = world.spawn_agent({2, 2});
@@ -677,9 +726,10 @@ void test_field_growth_requires_a_worker() {
require(save_contents(world) == save_contents(*restored), "sowing did not resume after loading"); require(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"); 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; using namespace settlement;
World world(44, 8, 8); World world(44, 8, 8);
const auto resident = world.spawn_agent({1, 4}); const auto resident = world.spawn_agent({1, 4});
@@ -698,9 +748,10 @@ void test_opening_a_mine_invalidates_unreachable_routes() {
world.step(); world.step();
require(world.agents().front().resource_node_index == 0 && require(world.agents().front().resource_node_index == 0 &&
world.agents().front().state == AgentState::Travelling, "terrain edit left a stale route in the cache"); 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; using namespace settlement;
World legacy(12, 12, 12); World legacy(12, 12, 12);
static_cast<void>(legacy.spawn_agent({4, 4})); static_cast<void>(legacy.spawn_agent({4, 4}));
@@ -719,9 +770,10 @@ void test_object_tools_work_in_an_older_demo_world() {
require(edit(CommandKind::DemolishObject, {4, 5}) == CommandStatus::Accepted, require(edit(CommandKind::DemolishObject, {4, 5}) == CommandStatus::Accepted,
"a field in a demonstration could not be demolished"); "a field in a demonstration could not be demolished");
static_cast<void>(save_roundtrip(*world)); static_cast<void>(save_roundtrip(*world));
return {};
} }
void test_room_builds_and_saves_as_separate_parts() { Test CoreTests::test_room_builds_and_saves_as_separate_parts() {
using namespace settlement; using namespace settlement;
World world(61, 16, 16); World world(61, 16, 16);
static_cast<void>(world.spawn_agent({3, 3})); static_cast<void>(world.spawn_agent({3, 3}));
@@ -761,39 +813,176 @@ void test_room_builds_and_saves_as_separate_parts() {
resumed->production_orders().size() == 16 && resumed->can_place_storage(floor), resumed->production_orders().size() == 16 && resumed->can_place_storage(floor),
"demolition removed the floor instead of the furniture"); "demolition removed the floor instead of the furniture");
static_cast<void>(save_roundtrip(*resumed)); static_cast<void>(save_roundtrip(*resumed));
return {};
}
Test CoreTests::test_furnished_rooms_queue_and_build_their_contents() {
using namespace settlement;
using enum RecipeId;
const std::pair<RoomTemplate, RecipeId> variants[] = {{RoomTemplate::Doctor, BuildMedicineCabinet},
{RoomTemplate::Miner, BuildMiningRack}, {RoomTemplate::Weaver, BuildLoom}};
for (const auto& [layout, fixture] : variants) {
World world(62, 16, 16);
static_cast<void>(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<std::uint8_t>(Profession::Carpenter), {}, carpenter}).status == CommandStatus::Accepted,
"could not assign a carpenter for the furnished room");
RoomPlan plan{{6, 5}, {9, 8}, RoomSide::East, layout};
for (const auto side : {RoomSide::North, RoomSide::East, RoomSide::South, RoomSide::West}) {
plan.entrance = side;
const auto decoded = RoomPlan::from_placement(plan.first, plan.last, plan.placement_value());
const auto parts = decoded.furnishings();
require(decoded.entrance == side && decoded.layout == layout && parts.has_value(),
"room command lost the direction or furnishings");
require((*parts)[0].recipe == BuildBed && (*parts)[1].recipe == fixture &&
(*parts)[0].position != (*parts)[1].position &&
plan.recipe_at((*parts)[0].position) == BuildFloor &&
plan.recipe_at((*parts)[1].position) == BuildFloor,
"the furnishings must occupy two distinct interior cells");
}
const auto parts = *plan.furnishings();
const auto place = [&](std::uint8_t player, std::uint8_t value) {
return world.apply_command({player, world.next_command_sequence(player), CommandKind::PlaceRoom,
plan.first, value, plan.last}).status;
};
require(place(2, 255) == CommandStatus::InvalidTarget && world.production_orders().empty(),
"an unknown layout partially queued a room");
require(place(2, plan.placement_value()) == CommandStatus::Accepted &&
world.production_orders().size() == 19, "the furnished room did not queue construction and the door");
require(place(1, plan.placement_value()) == CommandStatus::InvalidTarget &&
world.production_orders().size() == 19, "an overlapping furnished room left duplicate orders");
const auto floor_is_done = [&](const World& state, GridPosition cell) {
return std::any_of(state.production_orders().begin(), state.production_orders().end(),
[cell](const auto& order) {
return order.position == cell && order.recipe == BuildFloor && order.state == JobState::Completed;
});
};
world.step();
auto resumed = save_roundtrip(world);
for (int tick = 0; tick < 850; ++tick) {
resumed->step();
for (std::size_t i = 0; i < parts.size(); ++i) {
const auto& order = resumed->production_orders()[i];
if (order.state != JobState::Available || order.recipe == WeaveCloth) {
require(floor_is_done(*resumed, parts[i].position), "a furnishing started before its floor");
}
}
}
const auto& bed = resumed->production_orders()[0];
const auto& furniture = resumed->production_orders()[1];
require(bed.recipe == BuildBed && bed.position == parts[0].position && bed.state == JobState::Completed &&
bed.bed_owner != 0 && bed.bed_base == (layout == RoomTemplate::Miner ? BedBase::Stone : BedBase::Wood),
"the room's bed did not become usable");
require(furniture.position == parts[1].position, "the furnishing moved during construction");
if (fixture == BuildLoom) {
require(furniture.recipe == WeaveCloth && resumed->storages().front().item_count(ItemType::Cloth) == 1,
"the built loom did not process flax");
} else {
require(furniture.recipe == fixture && furniture.state == JobState::Completed,
"the themed furnishing did not finish");
}
static_cast<void>(save_roundtrip(*resumed));
}
return {};
}
Test CoreTests::test_carpenter_delivers_the_door_before_installation() {
using namespace settlement;
auto world = std::make_unique<World>(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<std::uint8_t>(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<void>(save_roundtrip(*world));
return {};
} }
} // namespace } // namespace
int main() { int main(int argc, char** argv) {
try { return CoreTests::run(argc, argv);
test_rng_repeats_for_same_seed();
test_work_jobs_complete();
test_astar_route_uses_opening_in_wall();
test_parallel_pathfinding_completes_the_jobs();
test_single_worker_configuration_is_rejected();
test_residents_gather_and_deliver_resources();
test_production_reservations_and_construction();
test_cabin_placement_queues_a_complete_order();
test_hungry_resident_reserves_and_eats_a_berry();
test_invalid_save_is_rejected();
test_two_players_share_the_first_colony();
test_bed_parts_are_delivered_separately();
test_resident_uses_assigned_bed_and_sleep_survives_save();
test_fatigue_slows_work_without_interrupting_it();
test_ground_rest_never_uses_another_residents_bed();
test_fields_mines_and_reindexing_active_hauls();
test_specialists_take_their_own_jobs_and_finish_prior_assignments();
test_flax_and_loom_supply_a_bed_without_starting_cloth();
test_field_growth_requires_a_worker();
test_opening_a_mine_invalidates_unreachable_routes();
test_object_tools_work_in_an_older_demo_world();
test_room_builds_and_saves_as_separate_parts();
} catch (const std::exception& error) {
std::cerr << "Test failed: " << error.what() << '\n';
return 1;
}
std::cout << "All core checks passed.\n";
return 0;
} }
+17 -11
View File
@@ -1,3 +1,5 @@
#include "testing.hpp"
#include "lan_session.hpp" #include "lan_session.hpp"
#include <chrono> #include <chrono>
@@ -15,7 +17,13 @@ void require(bool condition, const char* message) {
if (!condition) throw std::runtime_error(message); if (!condition) throw std::runtime_error(message);
} }
void test_shared_colony_over_loopback() { using Void::Testing::Test;
struct LanTests : Void::Testing::Suite<LanTests> {
[[= Void::Testing::tag("lan")]] Test test_shared_colony_over_loopback();
};
Test LanTests::test_shared_colony_over_loopback() {
auto authoritative = make_first_colony(4); auto authoritative = make_first_colony(4);
auto client_view = make_first_colony(4); auto client_view = make_first_colony(4);
for (int i = 0; i < 25; ++i) authoritative->step(); for (int i = 0; i < 25; ++i) authoritative->step();
@@ -149,8 +157,10 @@ void test_shared_colony_over_loopback() {
const auto previous_size = authoritative->production_orders().size(); const auto previous_size = authoritative->production_orders().size();
require(guest.submit(CommandKind::PlaceRoom, room.first, entrance, room.last), require(guest.submit(CommandKind::PlaceRoom, room.first, entrance, room.last),
"guest could not send the room"); "guest could not send the room");
pump_until([&] { return client_view->production_orders().size() == previous_size + 9; }, pump_until([&] {
"snapshot did not carry all room components"); 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), require(guest.submit(CommandKind::PlaceRoom, room.first, entrance, room.last),
"guest could not send the conflicting room"); "guest could not send the conflicting room");
pump_until([&] { pump_until([&] {
@@ -159,17 +169,13 @@ void test_shared_colony_over_loopback() {
rejected->destination == room.last && rejected->value == entrance && rejected->destination == room.last && rejected->value == entrance &&
rejected->status == CommandStatus::InvalidTarget; rejected->status == CommandStatus::InvalidTarget;
}, "room rejection lost the geometry needed to restore the draft"); }, "room rejection lost the geometry needed to restore the draft");
require(authoritative->production_orders().size() == previous_size + 9, "room conflict scheduled extra work"); require(authoritative->production_orders().size() == previous_size + 10, "room conflict scheduled extra work");
std::cout << "Loopback LAN checks passed.\n"; std::cout << "Loopback LAN checks passed.\n";
return {};
} }
} // namespace } // namespace
int main() { int main(int argc, char** argv) {
try { return LanTests::run(argc, argv);
test_shared_colony_over_loopback();
} catch (const std::exception& error) {
std::cerr << error.what() << '\n';
return 1;
}
} }
+115
View File
@@ -0,0 +1,115 @@
#pragma once
#include <algorithm>
#include <iostream>
#include <meta>
#include <source_location>
#include <stdexcept>
#include <string>
#include <string_view>
#include <vector>
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 <meta::info Member, class Annotation>
std::vector<std::string> annotation_values() {
std::vector<std::string> values;
template for (constexpr auto a : std::define_static_array(meta::annotations_of_with_type(Member, ^^Annotation))) {
constexpr auto annotation = meta::extract<Annotation>(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 <class Derived>
struct Suite {
template <class Actual, class Expected>
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<member, Tag>();
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<member, Skip>();
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