Merge pull request 'Windows game sources' (#2) from windows-game-sources into main

Reviewed-on: #2
This commit was merged in pull request #2.
This commit is contained in:
Lagg1ng committed 2026-12-01 09:58:25 +00:00
commit 74b89ae3ca
25 files changed
+3498 -852

No files matched your search

+13 -3
View File
@@ -35,16 +35,21 @@ add_executable(settlement_colony_benchmark benchmarks/colony.cpp)
target_link_libraries(settlement_colony_benchmark PRIVATE settlement_core)
if(WIN32)
enable_language(RC)
add_executable(settlement_viewer WIN32
app/d3d_scene_win32.cpp
app/viewer_win32.cpp
app/lan_session_win32.cpp
app/house_icons.rc
)
target_link_libraries(settlement_viewer PRIVATE settlement_core user32 gdi32 comctl32 comdlg32 ws2_32 bcrypt iphlpapi)
target_link_libraries(settlement_viewer PRIVATE settlement_core user32 gdi32 comctl32 comdlg32 ws2_32 bcrypt iphlpapi
d3d11 d3dcompiler)
if(NOT MSVC)
target_link_options(settlement_viewer PRIVATE -municode)
target_compile_options(settlement_viewer PRIVATE -Wall -Wextra -Wpedantic -Wconversion -Wshadow)
target_compile_options(settlement_viewer PRIVATE
$<$<COMPILE_LANGUAGE:CXX>:-Wall;-Wextra;-Wpedantic;-Wconversion;-Wshadow>)
else()
target_compile_options(settlement_viewer PRIVATE /W4 /permissive-)
target_compile_options(settlement_viewer PRIVATE $<$<COMPILE_LANGUAGE:CXX>:/W4;/permissive->)
endif()
endif()
@@ -56,13 +61,18 @@ endif()
include(CTest)
if(BUILD_TESTING)
if(NOT CMAKE_CXX_COMPILER_ID STREQUAL "GNU" OR CMAKE_CXX_COMPILER_VERSION VERSION_LESS 16)
message(FATAL_ERROR "The reflection test suites need GCC 16 or later. Set BUILD_TESTING=OFF to build the game alone.")
endif()
add_executable(settlement_core_tests
tests/core_tests.cpp
)
target_compile_options(settlement_core_tests PRIVATE -std=c++26 -freflection)
target_link_libraries(settlement_core_tests PRIVATE settlement_core)
add_test(NAME settlement_core_tests COMMAND settlement_core_tests)
if(WIN32)
add_executable(settlement_lan_tests tests/lan_tests.cpp app/lan_session_win32.cpp)
target_compile_options(settlement_lan_tests PRIVATE -std=c++26 -freflection)
target_include_directories(settlement_lan_tests PRIVATE app)
target_link_libraries(settlement_lan_tests PRIVATE settlement_core ws2_32 bcrypt iphlpapi)
add_test(NAME settlement_lan_tests COMMAND settlement_lan_tests)
+12 -5
View File
@@ -2,14 +2,14 @@
## Цель
Самостоятельная C++-игра о поселении с повторяемой симуляцией, многопоточным расчётом и изометрическим клиентом. Это отдельный проект, не совместимый движок для Stonehearth. Код и игровые ресурсы Stonehearth не включаются.
Самостоятельная C++-игра о поселении с повторяемой симуляцией, многопоточным расчётом и 3D-клиентом. Это отдельный проект, не совместимый движок для Stonehearth. Код и игровые ресурсы Stonehearth не включаются.
## Этапы
### P0 — Инструменты и границы проекта
- [x] Отдельный каталог, CMake, C++20, лицензия и базовая структура.
- [x] Portable-установщик CMake/LLVM-MinGW и скрипт сборки с CTest.
- [x] Portable-установщик MSYS2 UCRT64 с GCC 16 и сборка с CTest.
- [ ] CI для Windows и Linux.
- [x] Не включать код и ресурсы Stonehearth.
@@ -39,17 +39,24 @@
- [x] Пул потоков для независимого выбора заданий, A* и продвижения жителей.
- [x] Стабильное применение результатов в конце шага симуляции.
- [x] Многопоточный режим с двумя и более рабочими потоками; проверка игровых результатов и загрузки.
- [x] Выбор числа потоков в командной версии и Windows-клиенте.
- [x] Автоматический выбор числа потоков в Windows-клиенте и параметр для командных бенчмарков.
- [x] Повторный замер времени тика после расширения систем ресурсов.
### P4 — Игровой клиент
- [x] Изометрический Windows-просмотрщик карты, маршрутов и жителей.
- [x] Windows-клиент с отображением карты, маршрутов и жителей.
- [x] Отображение источников ресурсов, складов и текущих запасов.
- [x] Камера с перемещением и масштабированием относительно курсора.
- [x] Нижняя панель с жителями, добычей, участками и строительством.
- [ ] Настоящий графический 3D-рендерер и объёмные модели.
- [x] Нижние кнопки «Работы» и приоритета с настраиваемым масштабом панели.
- [x] Главное меню со списком сохранений, продолжением партии и управлением кооперативом.
- [x] Меню Esc с паузой, сохранениями, выходом в главное меню и завершением игры.
- [x] Игровая карта на Direct3D 11 с глубиной и базовыми объёмными моделями.
- [ ] Расширение набора 3D-моделей и освещения.
- [x] Постановка чертежа домика мышью в Windows-клиенте.
- [x] Редактируемая раскладка кроватей и станков с предпросмотром, списком материалов и подтверждением.
- [x] Прямоугольные чертежи комнат с полом, стенами, выбором стороны входа и поэтапной стройкой.
- [ ] Маршруты через дверные проёмы и настройка формы комнаты.
- [ ] Интерфейс для остальных типов работ и зданий.
### P5 — Игровые системы и совместная игра
+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`.
## Portable toolchain и сборка
## Сборка Windows на MSYS2 UCRT64
Требуется 64-битная Windows с доступом к GitHub. Toolchain устанавливается локально в `.tools/`, не меняет системный PATH и не требует администратора. Скрипт загружает CMake и LLVM-MinGW с официальных релизов и проверяет доступные SHA-256 digests.
Требуется 64-битная Windows. Скрипт установки разворачивает MSYS2 в `.tools/toolchain/msys64`, проверяет SHA-256 архива и устанавливает GCC 16, CMake и Ninja через UCRT64. Если MSYS2 уже установлен, передайте его каталог обоим скриптам через `-Msys2Root` или задайте `SETTLEMENT_MSYS2_ROOT`.
```powershell
powershell.exe -NoProfile -ExecutionPolicy Bypass -File .\setup-toolchain.ps1
powershell.exe -NoProfile -ExecutionPolicy Bypass -File .\build.ps1
```
Сборка запускает CTest и копирует runtime-библиотеки LLVM рядом с исполняемыми файлами, чтобы их можно было запускать без глобального PATH.
Сборка запускает CTest и помещает проверенные исполняемые файлы и библиотеки GCC в `build/`. Просмотрщик запускается из `build/settlement_viewer.exe`.
Тесты используют C++26 и `-freflection`. `Void::Testing::Suite<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

+674
View File
@@ -0,0 +1,674 @@
#define NOMINMAX
#include "d3d_scene_win32.hpp"
#include <d3d11.h>
#include <d3dcompiler.h>
#include <wrl/client.h>
#include <algorithm>
#include <array>
#include <cmath>
#include <cstring>
#include <iterator>
#include <limits>
#include <utility>
namespace settlement::viewer {
namespace {
using Microsoft::WRL::ComPtr;
struct Point { float x, y, z; };
struct Color { float r, g, b; };
struct Vertex { Point position; Color color; };
constexpr Color rgb(int r, int g, int b) {
return {static_cast<float>(r) / 255.f, static_cast<float>(g) / 255.f, static_cast<float>(b) / 255.f};
}
constexpr Color shade(Color color, float amount) {
return {color.r * amount, color.g * amount, color.b * amount};
}
class Mesh {
public:
std::vector<Vertex> vertices;
void quad(Point a, Point b, Point c, Point d, Color color) {
vertices.insert(vertices.end(), {{a, color}, {b, color}, {c, color}, {a, color}, {c, color}, {d, color}});
}
void flat(float a, float b, float c, float d, float z, Color color) {
quad({a, b, z}, {c, b, z}, {c, d, z}, {a, d, z}, color);
}
void box(float x, float y, float z, float w, float d, float h, Color color) {
const float a = x - w / 2, b = y - d / 2, c = x + w / 2, e = y + d / 2, top = z + h;
flat(a, b, c, e, top, color);
quad({c, b, z}, {c, e, z}, {c, e, top}, {c, b, top}, shade(color, .76f));
quad({a, e, z}, {c, e, z}, {c, e, top}, {a, e, top}, shade(color, .62f));
}
void track(GridPosition from, GridPosition to, Color color) {
const float x = static_cast<float>(from.x), y = static_cast<float>(from.y);
const float end_x = static_cast<float>(to.x), end_y = static_cast<float>(to.y);
constexpr float half = .035f;
flat(std::min(x, end_x) - half, std::min(y, end_y) - half,
std::max(x, end_x) + half, std::max(y, end_y) + half, .016f, color);
}
};
void terrain(Mesh& mesh, const World& world, const SceneView& view) {
mesh.box(static_cast<float>(world.width() - 1) / 2.f, static_cast<float>(world.height() - 1) / 2.f, -.65f,
static_cast<float>(world.width()), static_cast<float>(world.height()), .64f, rgb(133, 107, 71));
for (int y = 0; y < world.height(); ++y) {
for (int x = 0; x < world.width(); ++x) {
const GridPosition cell{x, y};
const float px = static_cast<float>(x), py = static_cast<float>(y);
const int variation = (x * 17 + y * 29 + x * y * 5) % 12;
const bool walkable = world.is_walkable(cell);
auto surface = walkable ? rgb(123 + variation, 157 + variation, 104 + variation) : rgb(103, 118, 106);
if (view.move_source == cell) surface = rgb(219, 189, 113);
if (view.cursor == cell) surface = view.valid_cursor ? rgb(150, 205, 219) : rgb(223, 139, 124);
mesh.flat(px - .50f, py - .50f, px + .50f, py + .50f, 0, shade(surface, .90f));
mesh.flat(px - .48f, py - .48f, px + .48f, py + .48f, .004f, surface);
if (walkable) continue;
const float height = .50f + static_cast<float>(variation % 4) * .10f;
mesh.box(px, py, .004f, .75f, .76f, height * .45f, rgb(114, 131, 119));
mesh.box(px - .06f, py - .04f, height * .45f, .55f, .59f, height * .55f, rgb(146, 157, 143));
}
}
}
void resources(Mesh& mesh, const World& world) {
for (const auto& node : world.resource_nodes()) {
const float x = static_cast<float>(node.position.x), y = static_cast<float>(node.position.y);
if (node.site != ResourceSite::Natural) {
mesh.flat(x - .43f, y - .43f, x + .43f, y + .43f, .025f, rgb(133, 103, 70));
}
if (node.site == ResourceSite::Mine) {
mesh.box(x, y, .025f, .74f, .76f, .09f, rgb(62, 67, 63));
mesh.box(x - .28f, y, .05f, .12f, .65f, .46f, rgb(140, 102, 67));
mesh.box(x + .28f, y, .05f, .12f, .65f, .46f, rgb(140, 102, 67));
mesh.box(x, y, .51f, .76f, .65f, .11f, rgb(181, 141, 90));
} else if (node.quantity == 0) {
if (node.growth_at != 0 || node.reserved_workers != 0) {
mesh.box(x, y, .025f, .16f, .14f, .15f, rgb(100, 150, 85));
}
} else if (node.type == ItemType::Wood) {
mesh.box(x, y, .02f, .19f, .19f, .75f, rgb(117, 83, 57));
mesh.box(x, y, .58f, .72f, .73f, .36f, rgb(67, 112, 72));
mesh.box(x - .07f, y - .07f, .94f, .49f, .49f, .29f, rgb(91, 143, 85));
} else if (node.type == ItemType::Berries || node.type == ItemType::Flax) {
const bool flax = node.type == ItemType::Flax;
if (node.type == ItemType::Berries && node.foraging_enabled) {
mesh.flat(x - .39f, y - .39f, x + .39f, y + .39f, .028f, rgb(159, 187, 102));
}
for (int i = 0; i < 3; ++i) {
const float shift = static_cast<float>(i - 1) * .19f;
mesh.box(x + shift, y - shift * .56f, .03f, flax ? .12f : .30f, flax ? .13f : .33f,
flax ? .34f : .24f, flax ? rgb(98, 143, 80) : rgb(78, 133, 75));
mesh.box(x + shift, y - shift * .56f, flax ? .37f : .27f, .13f, .15f, .08f,
flax ? rgb(147, 175, 229) : rgb(207, 105, 135));
}
} else {
mesh.box(x, y, .03f, .51f, .53f, .32f, rgb(151, 159, 150));
}
}
}
void room_part(Mesh& mesh, GridPosition cell, RecipeId recipe, Color color, bool draft) {
const float x = static_cast<float>(cell.x), y = static_cast<float>(cell.y);
if (recipe == RecipeId::BuildFloor) {
mesh.flat(x - .495f, y - .495f, x + .495f, y + .495f, .013f, shade(color, .76f));
for (int i = 0; i < 4; ++i) {
const auto strip = static_cast<float>(i) * .24f;
mesh.flat(x - .49f, y - .48f + strip, x + .49f, y - .25f + strip, .015f,
shade(color, i % 2 ? 1.f : .93f));
}
} else if (recipe == RecipeId::BuildWall) {
if (draft) {
mesh.box(x, y, .03f, .92f, .92f, .09f, shade(color, .69f));
mesh.box(x, y, .12f, .91f, .91f, .16f, color);
} else {
mesh.box(x, y, .02f, 1.f, 1.f, .73f, color);
mesh.box(x, y, .75f, 1.f, 1.f, .10f, shade(color, 1.13f));
}
} else {
const bool along_x = recipe == RecipeId::BuildDoorAlongX;
for (const float side : {-1.f, 1.f}) {
mesh.box(x + (along_x ? side * .40f : 0.f), y + (along_x ? 0.f : side * .40f),
.02f, along_x ? .20f : .62f, along_x ? .62f : .20f, .73f, color);
}
mesh.box(x, y, .75f, along_x ? 1.f : .62f, along_x ? .62f : 1.f, .10f, shade(color, 1.13f));
if (!draft) {
const auto leaf = [x, y, along_x](float side, float inward, float height) {
return along_x ? Point{x + side, y + inward, height} : Point{x + inward, y + side, height};
};
mesh.quad(leaf(-.28f, 0.f, .04f), leaf(-.06f, .40f, .04f), leaf(-.06f, .40f, .66f),
leaf(-.28f, 0.f, .66f), shade(color, .75f));
const auto handle = leaf(-.09f, .32f, .37f);
mesh.box(handle.x, handle.y, handle.z, .06f, .06f, .06f, rgb(215, 183, 107));
}
}
}
void draw_blueprint(Mesh& mesh, const BlueprintPart& part, bool preview);
void draw_furnishing(Mesh& mesh, GridPosition cell, RecipeId recipe, Color wood, Color detail) {
const float x = static_cast<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 (furnishing_shape(order.recipe)) {
case RecipeId::BuildMedicineCabinet: cell.furnishing = RoomTemplate::Doctor; break;
case RecipeId::BuildMiningRack: cell.furnishing = RoomTemplate::Miner; break;
case RecipeId::BuildLoom:
case RecipeId::WeaveCloth: cell.furnishing = RoomTemplate::Weaver; break;
default: break;
}
}
const auto in_bounds = [&](GridPosition cell) {
return cell.x >= 0 && cell.y >= 0 && cell.x < world.width() && cell.y < world.height();
};
const GridPosition neighbors[] = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
const auto intact = [&](const RoomPlan& plan) {
for (int y = plan.first.y; y <= plan.last.y; ++y) {
for (int x = plan.first.x; x <= plan.last.x; ++x) {
const GridPosition cell{x, y};
if (tile(cell).structure != plan.recipe_at(cell)) return false;
}
}
return true;
};
constexpr Color finishes[] = {rgb(146, 94, 66), rgb(107, 136, 76), rgb(86, 116, 136), rgb(169, 91, 65)};
std::vector<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()) {
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, .46f, .72f, .67f, .10f, storage.kind == StorageKind::Pantry ?
rgb(187, 120, 148) : rgb(202, 155, 91));
mesh.box(x + .34f, y, .30f, .052f, .13f, .13f, rgb(229, 195, 124));
}
for (const auto& order : world.production_orders()) {
if (is_carpentry_recipe(order.recipe) ||
(order.recipe == RecipeId::SawPlank && workshop == order.position)) continue;
const auto fixture = furnishing_shape(order.recipe);
const float x = static_cast<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)) {
mesh.box(x, y, .025f, .71f, .58f, .34f, rgb(150, 110, 73));
mesh.box(x, y, .37f, .77f, .62f, .10f, rgb(199, 156, 100));
continue;
}
if (order.state != JobState::Completed) {
const auto marked = order.state == JobState::Available ? rgb(121, 178, 195) : rgb(214, 171, 99);
mesh.flat(x - .44f, y - .44f, x + .44f, y + .44f, .03f, marked);
}
if (is_room_part(order.recipe)) {
const auto shape = room_part_shape(order.recipe);
if (building_view == BuildingView::FloorsOnly && shape != RecipeId::BuildFloor) continue;
if (order.state == JobState::Completed) {
room_part(mesh, order.position, shape, rgb(175, 123, 78), false);
} else if (shape != RecipeId::BuildFloor) {
room_part(mesh, order.position, shape,
order.state == JobState::Available ? rgb(121, 178, 195) : rgb(214, 171, 99), true);
}
} else if (fixture == RecipeId::BuildMedicineCabinet || fixture == RecipeId::BuildMiningRack ||
fixture == RecipeId::BuildLoom) {
const bool finished = order.state == JobState::Completed;
const auto wood = finished ? rgb(175, 123, 78) : rgb(117, 168, 181);
const auto detail = finished
? (fixture == RecipeId::BuildMedicineCabinet ? rgb(169, 214, 183) : rgb(153, 166, 172))
: rgb(158, 202, 209);
draw_furnishing(mesh, order.position, fixture, wood, detail);
} else if (order.recipe == RecipeId::BuildBed &&
(order.state == JobState::Completed || order.bed_stage == BedStage::Bedding || order.bed_stage == BedStage::Pillow)) {
mesh.box(x, y, .045f, .77f, .43f, .18f,
order.bed_base == BedBase::Stone ? rgb(145, 155, 151) : rgb(156, 107, 66));
if (order.bed_stage == BedStage::Pillow || order.state == JobState::Completed) {
mesh.box(x, y, .225f, .69f, .38f, .12f, rgb(115, 159, 185));
}
if (order.state == JobState::Completed) {
mesh.box(x - .23f, y, .345f, .2f, .32f, .07f, rgb(243, 230, 194));
}
} else if (order.recipe == RecipeId::BuildBed) {
draw_blueprint(mesh, {order.position, order.recipe, order.bed_base}, false);
} else if (order.recipe == RecipeId::BuildCabin && order.state == JobState::Completed) {
const float walls = building_view == BuildingView::FloorsOnly ? .07f : .65f;
mesh.box(x, y, .03f, .83f, .82f, walls, rgb(194, 151, 103));
if (building_view == BuildingView::Full) {
draw_gabled_roof(mesh, x - .415f, y - .41f, x + .415f, y + .41f,
.68f, 1.03f, true, rgb(159, 90, 66), rgb(174, 126, 80));
}
}
}
if (building_view == BuildingView::Full) draw_room_roofs(mesh, world);
for (const auto& job : world.jobs()) {
if (job.state == JobState::Completed) continue;
const float x = static_cast<float>(job.position.x), y = static_cast<float>(job.position.y);
mesh.box(x, y, .015f, .20f, .20f, .10f,
job.state == JobState::Available ? rgb(76, 134, 90) : rgb(208, 159, 77));
}
}
void draw_blueprint(Mesh& mesh, const BlueprintPart& part, bool preview) {
const float x = static_cast<float>(part.cell.x), y = static_cast<float>(part.cell.y);
const auto ink = preview ? rgb(168, 232, 243) : rgb(90, 189, 236);
const auto frame = part.recipe == RecipeId::BuildBed && part.base == BedBase::Stone
? shade(ink, .70f) : ink;
constexpr float beam = .055f;
const auto outline = [&](float width, float depth, float z, Color color) {
for (float side : {-1.f, 1.f}) {
mesh.box(x, y + side * depth / 2, z, width + beam, beam, beam, color);
mesh.box(x + side * width / 2, y, z, beam, depth, beam, color);
}
};
outline(.88f, .88f, .035f, ink);
const float width = part.recipe == RecipeId::BuildBed ? .72f : .70f;
const float depth = part.recipe == RecipeId::BuildBed ? .41f : .62f;
const float top = part.recipe == RecipeId::BuildBed ? .34f : .68f;
outline(width, depth, top, frame);
for (float side_x : {-1.f, 1.f}) {
for (float side_y : {-1.f, 1.f}) {
mesh.box(x + side_x * width / 2, y + side_y * depth / 2, .04f, beam, beam, top - .04f, frame);
}
}
if (part.recipe == RecipeId::WeaveCloth) mesh.box(x, y, .30f, width, beam, beam, ink);
}
void residents(Mesh& mesh, const World& world, const SceneView& view) {
for (const auto& agent : world.agents()) {
using enum AgentState;
if (agent.state != Sleeping) {
auto position = agent.position;
const auto trail = agent.state == Hauling ? rgb(104, 164, 159) : rgb(137, 126, 167);
for (std::size_t i = agent.route_cursor; i < agent.route.size(); ++i) {
mesh.track(position, agent.route[i], trail);
position = agent.route[i];
}
}
const float shift = static_cast<float>(static_cast<int>(agent.id % 5) - 2) / 12.f;
const float x = static_cast<float>(agent.position.x) + shift;
const float y = static_cast<float>(agent.position.y) - shift;
const auto clothes = agent.state == Working ? rgb(195, 98, 74) :
agent.state == Gathering ? rgb(196, 152, 74) :
agent.state == Hauling ? rgb(67, 146, 138) : rgb(89, 126, 172);
if (view.selected == agent.id) {
mesh.flat(x - .28f, y - .26f, x + .28f, y + .26f, .042f, rgb(247, 207, 114));
}
if (agent.state == Sleeping) {
const float bed_height = agent.resting_on_ground ? .035f : .36f;
mesh.box(x, y, bed_height, .54f, .25f, .14f, clothes);
mesh.box(x - .23f, y, bed_height + .01f, .16f, .20f, .15f, rgb(234, 195, 149));
continue;
}
mesh.box(x, y, .027f, .19f, .22f, .14f, rgb(75, 72, 71));
mesh.box(x, y, .167f, .27f, .22f, .22f, clothes);
mesh.box(x, y, .387f, .25f, .24f, .23f, rgb(232, 191, 144));
mesh.box(x - .025f, y - .02f, .59f, .27f, .25f, .065f, rgb(92, 73, 56));
if (is_carpentry_item(agent.inventory.first_item())) {
mesh.box(x - .14f, y - .12f, .09f, .13f, .30f, .39f, rgb(177, 116, 70));
} else if (!agent.inventory.empty()) {
mesh.box(x - .11f, y - .12f, .14f, .19f, .18f, .24f, rgb(200, 156, 92));
}
}
}
constexpr char hlsl[] = R"(
cbuffer Camera : register(b0) {
float2 origin;
float2 halfTile;
float2 screen;
float scale;
float padding;
};
struct Input { float3 position : POSITION; float3 color : COLOR; };
struct Pixel { float4 position : SV_Position; float3 color : COLOR; };
Pixel project(Input input) {
float3 p = input.position;
float2 screenPoint = origin + scale * float2((p.x - p.y) * halfTile.x,
(p.x + p.y) * halfTile.y - p.z * 16.0);
Pixel result;
result.position = float4(screenPoint.x * 2.0 / screen.x - 1.0,
1.0 - screenPoint.y * 2.0 / screen.y, 0.96 - (p.x + p.y + p.z * 1.5) * 0.009, 1.0);
result.color = input.color;
return result;
}
float4 paint(Pixel input) : SV_Target { return float4(input.color, 1.0); }
)";
} // namespace
struct D3DScene::Backend {
ComPtr<ID3D11Device> device;
ComPtr<ID3D11DeviceContext> context;
ComPtr<IDXGISwapChain> swap_chain;
ComPtr<ID3D11Texture2D> target_texture;
ComPtr<ID3D11RenderTargetView> target_view;
ComPtr<ID3D11DepthStencilView> depth_view;
ComPtr<ID3D11VertexShader> vertex_shader;
ComPtr<ID3D11PixelShader> pixel_shader;
ComPtr<ID3D11InputLayout> layout;
ComPtr<ID3D11RasterizerState> rasterizer;
ComPtr<ID3D11Buffer> camera;
ComPtr<ID3D11Buffer> geometry;
UINT buffer_bytes = 0;
int width = 0, height = 0;
Mesh mesh;
bool resize(int w, int h) {
if (w == width && h == height && target_view && depth_view) return true;
context->OMSetRenderTargets(0, nullptr, nullptr);
target_texture.Reset();
target_view.Reset();
depth_view.Reset();
D3D11_TEXTURE2D_DESC texture{};
texture.Width = static_cast<UINT>(w);
texture.Height = static_cast<UINT>(h);
texture.MipLevels = texture.ArraySize = texture.SampleDesc.Count = 1;
texture.Format = DXGI_FORMAT_B8G8R8A8_UNORM;
texture.BindFlags = D3D11_BIND_RENDER_TARGET;
if (swap_chain) {
if (FAILED(swap_chain->ResizeBuffers(0, texture.Width, texture.Height, DXGI_FORMAT_UNKNOWN, 0)) ||
FAILED(swap_chain->GetBuffer(0, IID_PPV_ARGS(target_texture.GetAddressOf())))) return false;
} else if (FAILED(device->CreateTexture2D(&texture, nullptr, &target_texture))) {
return false;
}
texture.Format = DXGI_FORMAT_D24_UNORM_S8_UINT;
texture.BindFlags = D3D11_BIND_DEPTH_STENCIL;
ComPtr<ID3D11Texture2D> depth;
if (FAILED(device->CreateRenderTargetView(target_texture.Get(), nullptr, &target_view)) ||
FAILED(device->CreateTexture2D(&texture, nullptr, &depth)) ||
FAILED(device->CreateDepthStencilView(depth.Get(), nullptr, &depth_view))) return false;
width = w;
height = h;
return true;
}
bool upload_geometry() {
const auto bytes = mesh.vertices.size() * sizeof(Vertex);
if (bytes > std::numeric_limits<UINT>::max()) return false;
if (bytes > buffer_bytes) {
D3D11_BUFFER_DESC desc{};
desc.ByteWidth = static_cast<UINT>(bytes);
desc.Usage = D3D11_USAGE_DYNAMIC;
desc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
desc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
if (FAILED(device->CreateBuffer(&desc, nullptr, geometry.ReleaseAndGetAddressOf()))) return false;
buffer_bytes = desc.ByteWidth;
}
D3D11_MAPPED_SUBRESOURCE mapped{};
if (FAILED(context->Map(geometry.Get(), 0, D3D11_MAP_WRITE_DISCARD, 0, &mapped))) return false;
std::memcpy(mapped.pData, mesh.vertices.data(), bytes);
context->Unmap(geometry.Get(), 0);
return true;
}
bool read_frame(std::vector<std::uint32_t>& pixels) {
D3D11_TEXTURE2D_DESC desc{};
target_texture->GetDesc(&desc);
desc.BindFlags = 0;
desc.Usage = D3D11_USAGE_STAGING;
desc.CPUAccessFlags = D3D11_CPU_ACCESS_READ;
ComPtr<ID3D11Texture2D> copy;
if (FAILED(device->CreateTexture2D(&desc, nullptr, &copy))) return false;
context->CopyResource(copy.Get(), target_texture.Get());
pixels.resize(static_cast<std::size_t>(width) * static_cast<std::size_t>(height));
D3D11_MAPPED_SUBRESOURCE mapped{};
if (FAILED(context->Map(copy.Get(), 0, D3D11_MAP_READ, 0, &mapped))) return false;
const auto* data = static_cast<const std::byte*>(mapped.pData);
for (int row = 0; row < height; ++row) {
std::memcpy(pixels.data() + static_cast<std::size_t>(row) * static_cast<std::size_t>(width),
data + static_cast<std::size_t>(row) * mapped.RowPitch,
static_cast<std::size_t>(width) * sizeof(std::uint32_t));
}
context->Unmap(copy.Get(), 0);
return true;
}
};
D3DScene::D3DScene() = default;
D3DScene::~D3DScene() = default;
bool D3DScene::initialize(HWND target, bool software) {
auto graphics = std::make_unique<Backend>();
const auto driver = software ? D3D_DRIVER_TYPE_WARP : D3D_DRIVER_TYPE_HARDWARE;
constexpr D3D_FEATURE_LEVEL levels[] = {D3D_FEATURE_LEVEL_11_0, D3D_FEATURE_LEVEL_10_1, D3D_FEATURE_LEVEL_10_0};
constexpr UINT flags = D3D11_CREATE_DEVICE_BGRA_SUPPORT;
if (target) {
DXGI_SWAP_CHAIN_DESC swap{};
swap.BufferDesc.Format = DXGI_FORMAT_B8G8R8A8_UNORM;
swap.SampleDesc.Count = 1;
swap.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
swap.BufferCount = 2;
swap.OutputWindow = target;
swap.Windowed = TRUE;
swap.SwapEffect = DXGI_SWAP_EFFECT_DISCARD;
if (FAILED(D3D11CreateDeviceAndSwapChain(nullptr, driver, nullptr, flags, levels, std::size(levels),
D3D11_SDK_VERSION, &swap, &graphics->swap_chain, &graphics->device, nullptr, &graphics->context))) return false;
} else if (FAILED(D3D11CreateDevice(nullptr, driver, nullptr, flags, levels, std::size(levels),
D3D11_SDK_VERSION, &graphics->device, nullptr, &graphics->context))) return false;
ComPtr<ID3DBlob> vertex, pixel;
constexpr UINT compile_flags = D3DCOMPILE_ENABLE_STRICTNESS | D3DCOMPILE_OPTIMIZATION_LEVEL3;
if (FAILED(D3DCompile(hlsl, sizeof(hlsl) - 1, nullptr, nullptr, nullptr, "project", "vs_4_0",
compile_flags, 0, &vertex, nullptr)) ||
FAILED(D3DCompile(hlsl, sizeof(hlsl) - 1, nullptr, nullptr, nullptr, "paint", "ps_4_0",
compile_flags, 0, &pixel, nullptr))) return false;
if (FAILED(graphics->device->CreateVertexShader(vertex->GetBufferPointer(), vertex->GetBufferSize(),
nullptr, &graphics->vertex_shader)) ||
FAILED(graphics->device->CreatePixelShader(pixel->GetBufferPointer(), pixel->GetBufferSize(),
nullptr, &graphics->pixel_shader))) return false;
constexpr D3D11_INPUT_ELEMENT_DESC elements[] = {
{"POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0},
{"COLOR", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, sizeof(Point), D3D11_INPUT_PER_VERTEX_DATA, 0}
};
D3D11_RASTERIZER_DESC raster{};
raster.FillMode = D3D11_FILL_SOLID;
raster.CullMode = D3D11_CULL_NONE;
raster.DepthClipEnable = TRUE;
D3D11_BUFFER_DESC constants{};
constants.ByteWidth = 32;
constants.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
if (FAILED(graphics->device->CreateInputLayout(elements, std::size(elements), vertex->GetBufferPointer(),
vertex->GetBufferSize(), &graphics->layout)) ||
FAILED(graphics->device->CreateRasterizerState(&raster, &graphics->rasterizer)) ||
FAILED(graphics->device->CreateBuffer(&constants, nullptr, &graphics->camera))) return false;
backend_ = std::move(graphics);
return true;
}
bool D3DScene::ready() const noexcept { return backend_ != nullptr; }
void D3DScene::reset() noexcept { backend_.reset(); }
bool D3DScene::render(const World& world, const SceneView& view, std::vector<std::uint32_t>* capture) {
if (!backend_ || view.width <= 0 || view.height <= 0) return false;
auto& graphics = *backend_;
if (!graphics.resize(view.width, view.height)) return false;
graphics.mesh.vertices.clear();
terrain(graphics.mesh, world, view);
resources(graphics.mesh, world);
construction(graphics.mesh, world, view.building_view);
for (std::size_t index = 0; index < view.room_blueprints.size(); ++index) {
if (view.moving_room == index) continue;
const auto& plan = view.room_blueprints[index];
draw_room_plan(graphics.mesh, plan, false, world.can_place_room(plan));
}
if (view.room_preview) draw_room_plan(graphics.mesh, *view.room_preview, true, view.valid_cursor);
for (const auto& part : view.blueprint) draw_blueprint(graphics.mesh, part, false);
if (view.preview) draw_blueprint(graphics.mesh, *view.preview, true);
residents(graphics.mesh, world, view);
if (!graphics.upload_geometry()) return false;
auto* ctx = graphics.context.Get();
constexpr float clear[] = {.83f, .87f, .79f, 1.f};
ctx->ClearRenderTargetView(graphics.target_view.Get(), clear);
ctx->ClearDepthStencilView(graphics.depth_view.Get(), D3D11_CLEAR_DEPTH, 1.f, 0);
ctx->OMSetRenderTargets(1, graphics.target_view.GetAddressOf(), graphics.depth_view.Get());
const D3D11_VIEWPORT viewport{0, 0, static_cast<float>(view.width), static_cast<float>(view.height), 0, 1};
ctx->RSSetViewports(1, &viewport);
ctx->RSSetState(graphics.rasterizer.Get());
const float constants[] = {view.origin_x, view.origin_y, view.tile_half_width, view.tile_half_height,
viewport.Width, viewport.Height, view.scale, 0};
ctx->UpdateSubresource(graphics.camera.Get(), 0, nullptr, constants, 0, 0);
constexpr UINT stride = sizeof(Vertex);
constexpr UINT offset = 0;
ctx->IASetInputLayout(graphics.layout.Get());
ctx->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
ctx->IASetVertexBuffers(0, 1, graphics.geometry.GetAddressOf(), &stride, &offset);
ctx->VSSetShader(graphics.vertex_shader.Get(), nullptr, 0);
ctx->VSSetConstantBuffers(0, 1, graphics.camera.GetAddressOf());
ctx->PSSetShader(graphics.pixel_shader.Get(), nullptr, 0);
ctx->Draw(static_cast<UINT>(graphics.mesh.vertices.size()), 0);
if (capture && !graphics.read_frame(*capture)) return false;
return !graphics.swap_chain || SUCCEEDED(graphics.swap_chain->Present(0, 0));
}
} // namespace settlement::viewer
+57
View File
@@ -0,0 +1,57 @@
#pragma once
#include <windows.h>
#include "settlement/core/world.hpp"
#include <cstdint>
#include <memory>
#include <optional>
#include <span>
#include <vector>
namespace settlement::viewer {
enum class BuildingView { Full, NoRoofs, FloorsOnly };
struct BlueprintPart {
GridPosition cell;
RecipeId recipe;
BedBase base = BedBase::Wood;
};
struct SceneView {
int width;
int height;
float origin_x;
float origin_y;
float scale;
float tile_half_width;
float tile_half_height;
std::optional<GridPosition> cursor;
bool valid_cursor;
std::optional<GridPosition> move_source;
std::optional<AgentId> selected;
std::span<const BlueprintPart> blueprint;
std::optional<BlueprintPart> preview;
std::span<const RoomPlan> room_blueprints;
std::optional<RoomPlan> room_preview;
BuildingView building_view = BuildingView::Full;
std::optional<std::size_t> moving_room;
};
class D3DScene {
public:
D3DScene();
~D3DScene();
bool initialize(HWND target, bool software = false);
[[nodiscard]] bool ready() const noexcept;
bool render(const World& world, const SceneView& view, std::vector<std::uint32_t>* capture = nullptr);
void reset() noexcept;
private:
struct Backend;
std::unique_ptr<Backend> backend_;
};
} // namespace settlement::viewer
+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"
+9 -1
View File
@@ -12,6 +12,14 @@ namespace settlement::viewer {
enum class LanState { Offline, Hosting, HostConnected, Connecting, GuestConnected, GuestDisconnected };
inline constexpr std::uint16_t colony_lan_port = 41727;
struct LanRejection {
CommandStatus status;
CommandKind kind;
GridPosition cell;
std::uint8_t value;
GridPosition destination;
};
class LanSession {
public:
LanSession();
@@ -30,7 +38,7 @@ public:
[[nodiscard]] const std::string& detail() const noexcept;
[[nodiscard]] bool submit(CommandKind kind, GridPosition cell, std::uint8_t value,
GridPosition destination = {}, AgentId resident = 0);
[[nodiscard]] std::optional<CommandStatus> take_rejection() noexcept;
[[nodiscard]] std::optional<LanRejection> take_rejection() noexcept;
[[nodiscard]] std::unique_ptr<World> poll(World& world);
private:
+14 -10
View File
@@ -24,7 +24,7 @@ namespace {
using Clock = std::chrono::steady_clock;
using namespace std::chrono_literals;
constexpr std::uint32_t protocol_version = 7;
constexpr std::uint32_t protocol_version = 11;
constexpr std::size_t frame_limit = 4 * 1024 * 1024;
constexpr auto poll_budget = 16;
constexpr std::size_t command_queue_limit = 32;
@@ -192,13 +192,13 @@ struct LanSession::Impl {
bool connecting = false;
bool authenticated = false;
bool reject_pending = false;
bool waiting_reply = false;
std::optional<Action> awaiting_receipt;
std::uint16_t network_port = 0;
std::uint64_t key = 0;
std::string host_address;
std::string notice;
std::deque<Action> actions;
std::optional<CommandStatus> rejected_command;
std::optional<LanRejection> rejected_command;
std::uint64_t guest_sequence = 0;
Clock::time_point last_ping{};
Clock::time_point last_snapshot{};
@@ -218,7 +218,8 @@ struct LanSession::Impl {
void drop_peer() noexcept {
peer = Channel{};
connecting = authenticated = reject_pending = waiting_reply = false;
connecting = authenticated = reject_pending = false;
awaiting_receipt.reset();
guest_sequence = 0;
actions.clear();
rejected_command.reset();
@@ -298,14 +299,17 @@ struct LanSession::Impl {
notice.clear();
return;
}
if (message != Message::Receipt || payload.size() != 9 || !waiting_reply) {
if (message != Message::Receipt || payload.size() != 9 || !awaiting_receipt) {
throw std::runtime_error("Invalid message from the host.");
}
const auto status = static_cast<CommandStatus>(static_cast<unsigned char>(payload[0]));
if (status > CommandStatus::Busy) throw std::runtime_error("Invalid command result.");
if (status != CommandStatus::Accepted) rejected_command = status;
if (status != CommandStatus::Accepted) {
rejected_command = LanRejection{status, awaiting_receipt->kind, awaiting_receipt->cell,
awaiting_receipt->value, awaiting_receipt->destination};
}
guest_sequence = number(payload.substr(1));
waiting_reply = false;
awaiting_receipt.reset();
}
void send_snapshot(const World& world, Clock::time_point now) {
@@ -326,7 +330,7 @@ struct LanSession::Impl {
}
void send_action() {
if (waiting_reply || actions.empty() || guest_sequence == 0 || peer.pending()) return;
if (awaiting_receipt || actions.empty() || guest_sequence == 0 || peer.pending()) return;
const Action action = actions.front();
std::string payload;
append_number(payload, guest_sequence, 8);
@@ -339,7 +343,7 @@ struct LanSession::Impl {
append_number(payload, action.resident, 8);
peer.queue(Message::Command, payload);
actions.pop_front();
waiting_reply = true;
awaiting_receipt = action;
}
};
@@ -438,7 +442,7 @@ bool LanSession::submit(CommandKind kind, GridPosition cell, std::uint8_t value,
return true;
}
std::optional<CommandStatus> LanSession::take_rejection() noexcept {
std::optional<LanRejection> LanSession::take_rejection() noexcept {
return std::exchange(impl_->rejected_command, std::nullopt);
}
@@ -10,7 +10,7 @@ struct ScreenPoint {
double y;
};
class IsometricCamera {
class MapCamera {
public:
[[nodiscard]] double scale() const noexcept { return scale_; }
[[nodiscard]] ScreenPoint offset() const noexcept { return offset_; }
+241
View File
@@ -0,0 +1,241 @@
#pragma once
#include <windows.h>
#include <algorithm>
#include <array>
#include <filesystem>
#include <iterator>
#include <optional>
#include <string>
#include <vector>
namespace settlement::viewer {
constexpr int title_continue_id = 1100;
constexpr int title_new_id = 1101;
constexpr int title_browse_id = 1102;
constexpr int title_coop_id = 1103;
constexpr int title_exit_id = 1104;
constexpr int title_saves_id = 1105;
constexpr int title_open_id = 1106;
inline std::filesystem::path saves_directory() {
const DWORD length = GetEnvironmentVariableW(L"LOCALAPPDATA", nullptr, 0);
if (length == 0) return {};
std::wstring base(length, L'\0');
const DWORD copied = GetEnvironmentVariableW(L"LOCALAPPDATA", base.data(), length);
if (copied == 0 || copied >= length) return {};
base.resize(copied);
return std::filesystem::path(base) / L"Settlement" / L"Saves";
}
class TitleScreen {
public:
~TitleScreen() {
if (list_background_) DeleteObject(list_background_);
if (font_) DeleteObject(font_);
}
void create(HWND owner) {
constexpr const wchar_t* names[] = {
L"Продолжить", L"Новая колония", L"Открыть файл…", L"Кооператив…", L"Выход"
};
const auto instance = GetModuleHandleW(nullptr);
for (std::size_t i = 0; i < buttons_.size(); ++i) {
buttons_[i] = CreateWindowExW(0, L"BUTTON", names[i], WS_CHILD | WS_TABSTOP | BS_OWNERDRAW,
0, 0, 0, 0, owner, id(title_continue_id + static_cast<int>(i)), instance, nullptr);
}
saves_ = CreateWindowExW(WS_EX_CLIENTEDGE, L"LISTBOX", L"",
WS_CHILD | WS_TABSTOP | WS_VSCROLL | LBS_NOTIFY | LBS_NOINTEGRALHEIGHT,
0, 0, 0, 0, owner, id(title_saves_id), instance, nullptr);
open_ = CreateWindowExW(0, L"BUTTON", L"Загрузить выбранное", WS_CHILD | WS_TABSTOP | BS_OWNERDRAW,
0, 0, 0, 0, owner, id(title_open_id), instance, nullptr);
list_background_ = CreateSolidBrush(RGB(44, 63, 53));
font_ = CreateFontW(-16, 0, 0, 0, FW_NORMAL, FALSE, FALSE, FALSE, DEFAULT_CHARSET,
OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS, CLEARTYPE_QUALITY, DEFAULT_PITCH | FF_SWISS, L"Segoe UI");
const auto font = reinterpret_cast<WPARAM>(font_ ? font_ : GetStockObject(DEFAULT_GUI_FONT));
for (const auto button : buttons_) SendMessageW(button, WM_SETFONT, font, FALSE);
SendMessageW(saves_, WM_SETFONT, font, FALSE);
SendMessageW(open_, WM_SETFONT, font, FALSE);
}
void reload_saves() {
const auto folder = saves_directory();
saves.clear();
SendMessageW(saves_, LB_RESETCONTENT, 0, 0);
if (folder.empty()) return;
std::error_code error;
for (auto entry = std::filesystem::directory_iterator(folder, error);
!error && entry != std::filesystem::directory_iterator{}; entry.increment(error)) {
std::error_code file_error;
if (!entry->is_regular_file(file_error)) continue;
if (_wcsicmp(entry->path().extension().c_str(), L".settlement") != 0) continue;
const auto written = entry->last_write_time(file_error);
if (!file_error) saves.push_back({entry->path(), written});
}
std::sort(saves.begin(), saves.end(), [](const auto& a, const auto& b) {
if (a.written != b.written) return a.written > b.written;
return a.path < b.path;
});
for (const auto& entry : saves) {
const auto name = entry.path.stem().wstring();
SendMessageW(saves_, LB_ADDSTRING, 0, reinterpret_cast<LPARAM>(name.c_str()));
}
if (!saves.empty()) SendMessageW(saves_, LB_SETCURSEL, 0, 0);
}
void show(bool visible) const {
const int flags = visible ? SW_SHOWNA : SW_HIDE;
for (const auto button : buttons_) ShowWindow(button, flags);
ShowWindow(saves_, flags);
ShowWindow(open_, flags);
}
void update(bool can_resume, bool offline) const {
EnableWindow(buttons_[0], can_resume || (offline && !saves.empty()));
EnableWindow(buttons_[title_new_id - title_continue_id], offline);
EnableWindow(buttons_[title_browse_id - title_continue_id], offline);
EnableWindow(open_, offline && selected_index() < saves.size());
EnableWindow(saves_, offline);
}
HBRUSH paint_list_background(HWND control, HDC dc) const {
if (control != saves_ || !list_background_) return nullptr;
SetTextColor(dc, RGB(246, 237, 210));
SetBkColor(dc, RGB(44, 63, 53));
return list_background_;
}
[[nodiscard]] std::optional<std::filesystem::path> selected_save() const {
const auto selected = selected_index();
return selected < saves.size() ? std::optional{saves[selected].path} : std::nullopt;
}
[[nodiscard]] std::optional<std::filesystem::path> latest_save() const {
return saves.empty() ? std::nullopt : std::optional{saves.front().path};
}
void layout(int width, int height) const {
const RECT panel = bounds(width, height);
for (std::size_t i = 0; i < buttons_.size(); ++i) {
position(buttons_[i], panel.left + 28, panel.top + 118 + static_cast<int>(i) * 40, 252, 33);
}
position(saves_, panel.left + 318, panel.top + 146, panel.right - panel.left - 346, 118);
position(open_, panel.left + 318, panel.top + 274, panel.right - panel.left - 346, 33);
}
void draw(HDC dc, int width, int height, const std::wstring& notice) const {
shade(dc, {0, 0, width, height}, RGB(24, 38, 34));
const auto old_pen = SelectObject(dc, GetStockObject(NULL_PEN));
const auto distant = CreateSolidBrush(RGB(32, 53, 44));
const auto near_hills = CreateSolidBrush(RGB(41, 66, 50));
const auto old_brush = SelectObject(dc, distant);
const POINT hills[] = {{0, height}, {0, height * 5 / 8}, {width / 4, height / 4},
{width * 5 / 9, height * 5 / 8}, {width * 5 / 6, height / 4}, {width, height / 2}, {width, height}};
Polygon(dc, hills, static_cast<int>(std::size(hills)));
SelectObject(dc, near_hills);
const POINT foreground[] = {{0, height}, {0, height * 7 / 8}, {width / 3, height / 2},
{width * 3 / 4, height * 7 / 8}, {width, height * 3 / 5}, {width, height}};
Polygon(dc, foreground, static_cast<int>(std::size(foreground)));
SelectObject(dc, old_brush);
SelectObject(dc, old_pen);
DeleteObject(near_hills);
DeleteObject(distant);
const RECT panel = bounds(width, height);
shade(dc, panel, RGB(35, 50, 43));
shade(dc, {panel.left, panel.top, panel.right, panel.top + 2}, RGB(179, 150, 92));
const auto face = CreateFontW(-46, 0, 0, 0, FW_BOLD, FALSE, FALSE, FALSE, DEFAULT_CHARSET,
OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS, CLEARTYPE_QUALITY, DEFAULT_PITCH | FF_ROMAN, L"Georgia");
const auto font = SelectObject(dc, face ? face : GetStockObject(DEFAULT_GUI_FONT));
const auto mode = SetBkMode(dc, TRANSPARENT);
const auto ink = SetTextColor(dc, RGB(248, 235, 204));
RECT heading{panel.left + 27, panel.top + 19, panel.right - 27, panel.top + 76};
DrawTextW(dc, L"Settlement", -1, &heading, DT_SINGLELINE | DT_VCENTER);
SelectObject(dc, font_ ? font_ : GetStockObject(DEFAULT_GUI_FONT));
RECT name{panel.left + 30, panel.top + 78, panel.right - 28, panel.top + 99};
DrawTextW(dc, L"Первое поселение", -1, &name, DT_SINGLELINE | DT_VCENTER);
RECT saves_label{panel.left + 318, panel.top + 117, panel.right - 27, panel.top + 140};
DrawTextW(dc, saves.empty() ? L"Сохранения · список пуст" : L"Сохранения", -1,
&saves_label, DT_SINGLELINE | DT_VCENTER);
if (!notice.empty()) {
RECT information{panel.left + 318, panel.top + 311, panel.right - 27, panel.bottom - 11};
DrawTextW(dc, notice.c_str(), -1, &information, DT_WORDBREAK | DT_NOPREFIX);
}
SetTextColor(dc, ink);
SetBkMode(dc, mode);
SelectObject(dc, font);
if (face) DeleteObject(face);
}
static bool draw_button(const DRAWITEMSTRUCT& item) {
if (item.CtlID < title_continue_id || item.CtlID > title_open_id || item.CtlID == title_saves_id) return false;
const bool disabled = (item.itemState & ODS_DISABLED) != 0;
const bool accented = (item.itemState & (ODS_SELECTED | ODS_FOCUS)) != 0;
const bool primary = item.CtlID == title_new_id && !disabled;
shade(item.hDC, item.rcItem, accented ? RGB(90, 105, 70) :
(primary ? RGB(69, 89, 60) : RGB(47, 65, 55)));
const auto edge = CreateSolidBrush(accented || primary ? RGB(186, 157, 100) : RGB(91, 110, 91));
FrameRect(item.hDC, &item.rcItem, edge);
DeleteObject(edge);
RECT label = item.rcItem;
InflateRect(&label, -12, 0);
wchar_t text[96]{};
GetWindowTextW(item.hwndItem, text, static_cast<int>(std::size(text)));
const auto face = reinterpret_cast<HFONT>(SendMessageW(item.hwndItem, WM_GETFONT, 0, 0));
const auto font = SelectObject(item.hDC, face ? face : GetStockObject(DEFAULT_GUI_FONT));
const auto mode = SetBkMode(item.hDC, TRANSPARENT);
const auto ink = SetTextColor(item.hDC, disabled ? RGB(162, 173, 157) : RGB(248, 240, 217));
DrawTextW(item.hDC, text, -1, &label, DT_LEFT | DT_VCENTER | DT_SINGLELINE | DT_END_ELLIPSIS);
SetTextColor(item.hDC, ink);
SetBkMode(item.hDC, mode);
SelectObject(item.hDC, font);
if ((item.itemState & ODS_FOCUS) != 0) {
RECT focus = item.rcItem;
InflateRect(&focus, -4, -4);
DrawFocusRect(item.hDC, &focus);
}
return true;
}
private:
struct SaveFile {
std::filesystem::path path;
std::filesystem::file_time_type written;
};
static HMENU id(int value) { return reinterpret_cast<HMENU>(static_cast<INT_PTR>(value)); }
static RECT bounds(int width, int height) {
constexpr int panel_width = 704;
constexpr int panel_height = 365;
const int left = (width - panel_width) / 2;
const int top = (height - panel_height) / 2;
return {left, top, left + panel_width, top + panel_height};
}
static void position(HWND control, int x, int y, int width, int height) {
SetWindowPos(control, nullptr, x, y, width, height, SWP_NOACTIVATE | SWP_NOZORDER);
}
static void shade(HDC dc, RECT area, COLORREF color) {
const auto brush = CreateSolidBrush(color);
FillRect(dc, &area, brush);
DeleteObject(brush);
}
[[nodiscard]] std::size_t selected_index() const {
const auto selection = SendMessageW(saves_, LB_GETCURSEL, 0, 0);
return selection == LB_ERR ? saves.size() : static_cast<std::size_t>(selection);
}
std::array<HWND, 5> buttons_{};
HWND saves_ = nullptr;
HWND open_ = nullptr;
HBRUSH list_background_ = nullptr;
HFONT font_ = nullptr;
std::vector<SaveFile> saves;
};
} // namespace settlement::viewer
+1276 -561
View File
File diff suppressed because it is too large. Load diff
+40 -50
View File
@@ -1,59 +1,49 @@
param(
[ValidateSet('Debug', 'Release', 'RelWithDebInfo')]
[string]$Configuration = 'Release'
[string]$Configuration = 'Release',
[string]$Msys2Root = $env:SETTLEMENT_MSYS2_ROOT
)
$ErrorActionPreference = 'Stop'
$projectRoot = Split-Path -Parent $MyInvocation.MyCommand.Path
$toolRoot = Join-Path $projectRoot '.tools\toolchain'
if (-not (Test-Path -LiteralPath $toolRoot -PathType Container)) {
throw 'Portable tools are missing. Run .\setup-toolchain.ps1 first.'
}
$cmakeExe = Get-ChildItem -LiteralPath (Join-Path $toolRoot 'cmake') -Filter 'cmake.exe' -File -Recurse -ErrorAction SilentlyContinue | Select-Object -First 1
$clangxxExe = Get-ChildItem -LiteralPath (Join-Path $toolRoot 'llvm-mingw') -Filter 'clang++.exe' -File -Recurse -ErrorAction SilentlyContinue | Select-Object -First 1
$ninjaExe = Get-ChildItem -LiteralPath (Join-Path $toolRoot 'llvm-mingw') -Filter 'ninja.exe' -File -Recurse -ErrorAction SilentlyContinue | Select-Object -First 1
$makeExe = Get-ChildItem -LiteralPath (Join-Path $toolRoot 'llvm-mingw') -Filter 'mingw32-make.exe' -File -Recurse -ErrorAction SilentlyContinue | Select-Object -First 1
if ($null -eq $cmakeExe -or $null -eq $clangxxExe) {
throw 'CMake or Clang is missing. Run .\setup-toolchain.ps1 again.'
}
$compilerBin = Split-Path -Parent $clangxxExe.FullName
$cmakeBin = Split-Path -Parent $cmakeExe.FullName
$env:Path = "$compilerBin;$cmakeBin;$env:Path"
$buildDirectory = Join-Path $projectRoot 'build'
$generatorArguments = @()
if ($null -ne $ninjaExe) {
$generatorArguments = @('-G', 'Ninja', "-DCMAKE_MAKE_PROGRAM=$($ninjaExe.FullName)")
} elseif ($null -ne $makeExe) {
$generatorArguments = @('-G', 'MinGW Makefiles', "-DCMAKE_MAKE_PROGRAM=$($makeExe.FullName)")
} else {
throw 'The LLVM-MinGW archive contains neither Ninja nor mingw32-make.'
}
& $cmakeExe.FullName -S $projectRoot -B $buildDirectory @generatorArguments -U CMAKE_C_COMPILER `
"-DCMAKE_CXX_COMPILER=$($clangxxExe.FullName)" `
"-DCMAKE_BUILD_TYPE=$Configuration"
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
& $cmakeExe.FullName --build $buildDirectory --parallel --config $Configuration
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
# LLVM-MinGW links libc++ dynamically. Copy its runtime beside the executables
# so they can be launched from Explorer without editing the system PATH.
foreach ($runtimeName in @('libc++.dll', 'libunwind.dll')) {
$runtimeSource = Join-Path $compilerBin $runtimeName
if (-not (Test-Path -LiteralPath $runtimeSource -PathType Leaf)) {
throw "Required LLVM-MinGW runtime was not found: $runtimeSource"
$projectRoot = $PSScriptRoot
if (-not $Msys2Root) { $Msys2Root = Join-Path $projectRoot '.tools\toolchain\msys64' }
$bin = Join-Path $Msys2Root 'ucrt64\bin'
foreach ($tool in @('g++.exe', 'cmake.exe', 'ctest.exe', 'ninja.exe', 'windres.exe')) {
if (-not (Test-Path -LiteralPath (Join-Path $bin $tool) -PathType Leaf)) {
throw "MSYS2 UCRT64 tool missing: $tool. Run .\setup-toolchain.ps1."
}
Copy-Item -LiteralPath $runtimeSource -Destination $buildDirectory -Force
}
$bin = (Get-Item -LiteralPath $bin).FullName.Replace('\', '/')
$buildRoot = Join-Path $projectRoot 'build'
$buildDirectory = Join-Path $buildRoot 'msys2-ucrt64'
$previousPath = $env:Path
try {
$env:Path = "$bin;$previousPath"
$version = & (Join-Path $bin 'g++.exe') -dumpfullversion
if ($LASTEXITCODE -ne 0 -or $version -notmatch '^16(\.|$)') {
throw "MSYS2 UCRT64 GCC 16 is required. Found: $version"
}
Write-Output "Building with MSYS2 UCRT64 GCC $version"
$cmake = Join-Path $bin 'cmake.exe'
$options = @('-S', $projectRoot, '-B', $buildDirectory, '-G', 'Ninja',
"-DCMAKE_CXX_COMPILER=$bin/g++.exe",
"-DCMAKE_RC_COMPILER=$bin/windres.exe",
"-DCMAKE_MAKE_PROGRAM=$bin/ninja.exe",
"-DCMAKE_BUILD_TYPE=$Configuration", '-DBUILD_TESTING=ON')
& $cmake @options
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
& $cmake --build $buildDirectory --parallel
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
& (Join-Path $bin 'ctest.exe') --test-dir $buildDirectory --output-on-failure
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
$ctestExe = Join-Path $cmakeBin 'ctest.exe'
if (-not (Test-Path -LiteralPath $ctestExe -PathType Leaf)) {
throw 'CTest was not found beside CMake.'
foreach ($runtime in @('libstdc++-6.dll', 'libgcc_s_seh-1.dll', 'libwinpthread-1.dll')) {
Copy-Item -LiteralPath (Join-Path $bin $runtime) -Destination $buildRoot -Force
}
foreach ($program in @('settlement_viewer', 'settlement_sim', 'settlement_colony_benchmark',
'settlement_core_tests', 'settlement_lan_tests')) {
Copy-Item -LiteralPath (Join-Path $buildDirectory "$program.exe") -Destination $buildRoot -Force
}
} finally {
$env:Path = $previousPath
}
& $ctestExe --test-dir $buildDirectory -C $Configuration --output-on-failure
exit $LASTEXITCODE
+6 -3
View File
@@ -4,8 +4,8 @@
- Ядро симуляции с фиксированными тиками.
- Пул потоков для выбора заданий, поиска маршрутов и продвижения жителей.
- Настройка числа потоков в командной версии и в Windows-просмотрщике.
- Изометрический прототип карты с жителями, заданиями и маршрутами.
- Автоматический выбор числа потоков в Windows-клиенте и параметр для командных бенчмарков.
- Объёмная карта с жителями, заданиями и маршрутами.
- Базовый цикл ресурсов: источник дерева/камня → резервирование → добыча → перенос → склад.
- Складской инвентарь со стеками `Wood` и `Stone` и учётом свободной вместимости.
- Два рецепта превращают древесину в доски и камень в блоки. Домик строится из трёх досок и двух блоков.
@@ -26,6 +26,9 @@
- Рост полей и посадок начинается после выполнения поручения фермером или лесорубом. После сбора участка выдаётся новое поручение.
- Производительность ядра измерена на колониях с 50–500 жителями, полями, складами и ремеслом. Результаты и команда запуска описаны в [отчёте](../benchmarks/colony-performance.md).
- Основные команды собраны в нижней панели «Жители», «Добыча», «Участки» и «Строительство». Меню «Работы» открывает те же команды по профессиям.
- Главное меню открывается при запуске. В нём можно начать новую колонию, выбрать сохранение или подключиться к другу.
- Esc открывает меню паузы и сохранений. Создание сетевой партии и подключение находятся в разделе «Кооператив» главного меню.
- Direct3D 11 рисует карту, жителей и постройки как объёмную геометрию с глубиной.
- Поиск ресурсных работ отбирает подходящие поручения по профессиям. Повторные запросы путей используют кэш.
- Движение, прогресс работ жителей и поиск маршрутов для общих заданий выполняются в пуле из двух и более потоков. Тесты проверяют игровые результаты, сохранения и команды кооператива.
@@ -35,7 +38,7 @@
## Ограничения прототипа
- Графика изометрическая и рисуется Win32/GDI; полноценного 3D-рендера пока нет.
- Камера поддерживает перемещение и масштабирование. Direct3D использует базовые модели и затенение граней.
- Каждый поход добытчика доставляет одну единицу сырья. Строитель везёт весь комплект для одного домика за рейс с остановками у нужных складов. Мастерские пока используют складское сырьё напрямую.
- Свободный житель сначала ищет еду, если проголодался. Если порции нет, он может снова взять работу. При голоде здоровье пока остаётся прежним.
- Завершённое спальное место назначается одному жителю. Сейчас жители идут спать по усталости.
+32 -12
View File
@@ -1,4 +1,4 @@
# Запуск изометрического прототипа
# Запуск игры на Windows
Соберите проект командой:
@@ -6,40 +6,60 @@
powershell.exe -NoProfile -ExecutionPolicy Bypass -File .\build.ps1
```
После сборки запустите `build\settlement_viewer.exe`. В списке доступны от двух рабочих потоков до числа логических процессоров компьютера, максимум 32. Нажмите «Применить и начать заново», чтобы применить выбор и перезапустить демонстрационное поселение.
После сборки запустите `build\settlement_viewer.exe`. Откроется главное меню. Здесь можно начать новую колонию, продолжить текущую партию, загрузить сохранение или подключиться к другу по локальной сети. Игра автоматически выбирает от двух до восьми рабочих потоков с учётом числа логических процессоров.
Список показывает файлы `.settlement` из папки `%LOCALAPPDATA%\Settlement\Saves`, начиная с самого свежего. Дважды щёлкните по сохранению или нажмите «Загрузить выбранное». «Открыть файл…» позволяет загрузить сохранение из любой папки. При первом запуске «Продолжить» открывает самое свежее сохранение из списка.
При запуске без явного параметра командная версия выбирает от двух до восьми потоков с учётом числа логических процессоров. Для ручного выбора используйте `settlement_sim.exe --workers N`, где N от 2 до 32.
Колесо мыши приближает и отдаляет карту относительно курсора. Чтобы сдвинуть карту, перетащите её с зажатой левой или средней кнопкой мыши. Короткий щелчок левой кнопкой выбирает жителя или ставит чертёж. Home или «Вид → Общий план» возвращает исходный вид.
Колесо мыши приближает и отдаляет карту относительно курсора. Чтобы сдвинуть карту, перетащите её с зажатой левой или средней кнопкой мыши. Короткий щелчок левой кнопкой выбирает жителя или ставит чертёж. Home возвращает исходный вид.
В новой партии три поселенца. На нижней панели откройте «Строительство → Спальное место». Под кнопкой появятся «Дерево» слева и «Камень» справа. Выберите основу, затем щёлкайте по свободным клеткам. Выбранная основа применяется к следующим кроватям до выхода из режима или смены основы. Повторное нажатие «Спальное место», Esc или правый щелчок завершает размещение.
Карту, постройки и жителей рисует Direct3D 11. Игра сначала пробует использовать видеокарту. Если устройство недоступно, Direct3D 11 пробует создать программное устройство WARP.
В новой партии три поселенца. На нижней панели откройте «Строительство → Спальное место». Под кнопкой появятся «Дерево» слева и «Камень» справа. Выберите основу и щёлкните по свободным клеткам. На карте появятся контуры чертежа, а под картой — количество объектов и список материалов. Выбранная основа применяется к следующим кроватям, пока вы её не смените. В режиме размещения повторный щелчок по контуру удаляет объект. В одном чертеже можно разместить кровати с разными основаниями и ткацкие станки.
Нажмите «Начать стройку», чтобы отправить выбранные места в работу, или «Очистить чертёж», чтобы убрать всю раскладку. Чертёж остаётся доступным при смене инструмента и через Esc. Это локальная раскладка текущей партии. В сохранение и общую колонию попадают утверждённые постройки. Если хозяин отклоняет клетку в кооперативе, она возвращается в чертёж.
В разделе «Строительство → Комната» укажите два противоположных угла прямоугольника от 3×3 до 12×12 клеток. По краям чертежа появятся стены, внутри — пол. Щёлкните по стороне, чтобы перенести вход в её середину. Правый щелчок по чертежу удаляет комнату. «Начать стройку» отправляет комнату в работу целиком. Поселенцы доставляют дерево для пола и стен. На готовый пол можно поставить мебель. В этой версии маршруты жителей проходят через стены.
В нижней панели «Строительство → Готовые дома» выберите проект 4×4 по картинке. В доме врача есть деревянная кровать и аптечный шкаф, в доме шахтёра — каменная кровать и стойка с инструментами, в доме ткача — деревянная кровать и рабочий ткацкий станок. Укажите площадку одним щелчком. Щелчок по краю переносит вход и переставляет мебель к противоположной стене. Смета включает мебель, а строители собирают её после укладки пола под ней. Аптечный шкаф и стойка служат обстановкой.
Когда пол, стены и вход готовы, у комнаты появляется крыша. Кнопка «Вид» в правом верхнем углу карты переключает полный вид, вид без крыш и вид без стен и крыш. Последний режим оставляет открытыми полы и мебель. Следующее нажатие возвращает полный вид.
Клавиша R поворачивает вход и раскладку готового дома ещё до размещения. Клавиши «,» и «.» поворачивают в обе стороны. Чтобы перенести уже поставленный чертёж, щёлкните по нему с Shift, затем укажите новое место. Правый щелчок во время переноса возвращает чертёж на старое место.
Новые комнаты и готовые дома требуют деревянную дверь как предмет. Если на складе нет свободной двери, «Начать стройку» автоматически ставит заказ в мастерскую. В списке «Жители» назначьте плотника. Он заберёт со склада две единицы дерева, сделает дверь за верстаком и отнесёт её на склад. Строитель или разнорабочий заберёт оттуда готовую дверь и установит её. Чтобы заготовить двери заранее, откройте «Работы → Плотник» и выберите «Изготовить дверь».
Аптечный шкаф, стойка шахтёра и ткацкий станок для готовых домов также заказываются у плотника. Для шкафа нужно одно дерево, для стойки — дерево и камень, для станка — два дерева. Плотник доставляет готовый предмет на склад, а строитель забирает и устанавливает его после укладки пола. Подходящие предметы из запаса идут в работу без нового заказа. Изготовить мебель заранее можно в панели «Работы → Плотник». Отдельный станок из меню «Строительство» тоже требует готовый станок со склада. Если запаса нет, утверждение чертежа создаст заказ для плотника.
Жители отдельно доставляют основу, ткань для настила и ткань для подушки. Каждая деталь появляется после завершения своего этапа. Камень и ткань доступны в стартовых запасах. Жители получают по одному готовому месту.
Уставшие жители работают медленнее и после поручения идут к закреплённой кровати. На земле они отдыхают только при сильной усталости и восстанавливают меньше сил. Щелчок по жителю показывает усталость и состояние сна.
На нижней панели «Добыча» (H) открывает сбор с кустов и шахту. «Участки» (Z) открывают поля, посадки, склад и кладовую. «Строительство» (B) открывает спальное место, станок, перенос и снос. Выбор раздела показывает его инструменты над панелью. Те же действия сгруппированы по профессиям в верхнем меню «Работы». Разнорабочий берёт работу любой профессии.
На нижней панели «Добыча» (H) открывает сбор с кустов и шахту. «Участки» (Z) открывают поля, посадки, склад и кладовую. «Строительство» (B) открывает спальное место, станок, перенос и снос. Выбор раздела показывает его инструменты над панелью. Кнопка «Работы» открывает те же действия по профессиям. Разнорабочий берёт работу любой профессии.
Откройте «Жители…» (клавиша C), выберите поселенца в списке, нажмите на нужную роль и подтвердите кнопкой «Назначить профессию». В списке видна текущая роль каждого жителя, а число рядом с названием профессии показывает, сколько жителей уже ею занимаются. Можно последовательно назначать роли всему поселению в одном окне. При смене профессии житель заканчивает текущее поручение.
Фермер засевает поля ягод и льна, лесоруб высаживает деревья. Разметка участка создаёт поручение. Когда житель выходит на участок и заканчивает работу, начинается рост. После сбора последней порции участок снова нужно засадить. Разнорабочий тоже может взять это поручение. Шахтёру можно открыть шахту на скале с доступной стороны.
Чтобы получать ткань, поставьте «Участки → Поле льна» и «Строительство → Ткацкий станок» на свободных клетках. Созревший лён фермер относит на обычный склад. Строитель перерабатывает одну единицу льна в одну единицу ткани. Запасы льна и ткани видны над картой. Если обычные склады заполнены, постройте дополнительный склад.
Чтобы получать ткань, поставьте «Участки → Поле льна», затем добавьте «Строительство → Ткацкий станок» в чертёж и утвердите его. Созревший лён фермер относит на обычный склад. Строитель перерабатывает одну единицу льна в одну единицу ткани. Запасы льна и ткани видны над картой. Если обычные склады заполнены, постройте дополнительный склад.
Для переноса выберите «Строительство → Перенести», щёлкните по кровати, складу, станку или посаженному участку и выберите новую клетку. Кровать сохраняет владельца, склад — содержимое. Там же находится «Снести». Снос склада с запасами требует подтверждения. Дождитесь освобождения занятого объекта перед переносом или сносом.
Нажмите «Добыча → Сбор ягод» и щёлкните по кусту, чтобы включить или отключить его сбор. Правый щелчок или Esc закрывает режим выбора. Кнопка приоритета переключает режимы «Равный приоритет», «Сначала еда» и «Сначала стройка». В паузе можно менять задания. Цель выполнена, когда каждому назначено место и в кладовой есть шесть свободных порций.
Нажмите «Добыча → Сбор ягод» и щёлкните по кусту, чтобы включить или отключить его сбор. Правый щелчок закрывает режим выбора. Кнопка приоритета переключает режимы «Равный приоритет», «Сначала еда» и «Сначала стройка». Цель выполнена, когда каждому назначено место и в кладовой есть шесть свободных порций.
Кусты дают ягоды, которые жители несут в кладовую с розовой крышкой. Розовый маршрут ведёт к еде. Чтобы увидеть голод жителя и его груз, щёлкните по фигурке вне режима размещения чертежа.
В меню «Поселение» выберите «Сохранить поселение…» или «Загрузить поселение…». Время останавливается на время выбора файла. Файл `.settlement` хранит карту, текущий такт, голод, запасы, заказы и маршруты. При загрузке используются рабочие потоки текущего окна. Если файл повреждён или его версия не подходит, окно показывает ошибку и продолжает текущую партию.
Esc открывает меню игры из любого режима строительства и выбора. В одиночной партии симуляция останавливается, пока меню открыто. «Продолжить» или Esc закрывает меню. Выбранный на карте инструмент можно использовать дальше. В этом меню доступны сохранение, загрузка, главное меню и выход. Файл `.settlement` хранит карту, текущий такт, голод, запасы, заказы и маршруты. При ошибке загрузки текущая колония остаётся открытой.
Старые сохранения продолжаются со своими правилами стройки. Кнопка «Применить и начать заново» запускает партию с поэтапной сборкой и стартовым запасом ткани.
«Esc → Масштаб панели» открывает ползунок от 50% до 250% с предпросмотром. «Применить» сохраняет выбор между запусками, «Отмена» возвращает предыдущий масштаб. В маленьком окне панель подстраивается под доступное место, чтобы оставить видимой карту. По умолчанию используется 125%.
В одиночной игре «Esc → Главное меню» возвращает на стартовый экран и останавливает симуляцию. «Продолжить» возвращает к текущей колонии. «Новая колония» запускает отдельную партию с поэтапной сборкой и стартовым запасом ткани. Старые сохранения продолжаются со своими правилами стройки.
## Кооператив по локальной сети
1. Запустите одинаковую версию игры на двух компьютерах в одной локальной сети.
2. Хозяин открывает свою колонию через «Кооператив → Открыть колонию для друга…» и передаёт гостю IPv4 и код партии. Порт игры — TCP 41727.
3. Гость выбирает «Кооператив → Подключиться…» и вводит эти данные. При обрыве связи можно выбрать «Подключиться снова», пока хозяин оставляет партию открытой.
2. Хозяин открывает «Кооператив…» в главном меню и создаёт сетевую колонию либо открывает для друга уже начатую. Он передаёт гостю IPv4 и код партии. Затем он нажимает «Продолжить». Порт игры — TCP 41727.
3. Гость выбирает «Кооператив → Подключиться к другу…» в главном меню и вводит эти данные. При обрыве связи в этом же разделе можно выбрать «Подключиться снова», пока хозяин держит партию открытой.
Оба игрока строят и меняют задания в общей колонии. Хозяин ставит симуляцию на паузу и сохраняет игру. После выхода гостя хозяин может продолжить партию.
Оба игрока строят и меняют задания в общей колонии. «Esc → Главное меню» позволяет открыть настройки кооператива и вернуться в колонию через «Продолжить». Хозяин сохраняет игру через Esc и может остановить симуляцию через «Кооператив → Пауза для всех» в главном меню.
+104 -7
View File
@@ -6,6 +6,7 @@
#include <cstdint>
#include <iosfwd>
#include <memory>
#include <optional>
#include <string>
#include <unordered_map>
#include <vector>
@@ -51,9 +52,17 @@ enum class ItemType : std::uint8_t {
StoneBlock,
Berries,
Cloth,
Flax
Flax,
WoodenDoor,
MedicineCabinet,
MiningRack,
Loom
};
inline constexpr std::size_t item_type_count = static_cast<std::size_t>(ItemType::Flax);
inline constexpr std::size_t item_type_count = static_cast<std::size_t>(ItemType::Loom);
constexpr bool is_carpentry_item(ItemType item) noexcept {
return item >= ItemType::WoodenDoor && item <= ItemType::Loom;
}
enum class StorageKind : std::uint8_t { Materials, Pantry };
enum class ResourceSite : std::uint8_t { Natural, BerryField, TreePlot, Mine, FlaxField };
@@ -74,21 +83,93 @@ enum class RecipeId : std::uint8_t {
CutStoneBlock,
BuildCabin,
BuildBed,
WeaveCloth
WeaveCloth,
BuildFloor,
BuildWall,
BuildDoorAlongX,
BuildDoorAlongY,
BuildMedicineCabinet,
BuildMiningRack,
BuildLoom,
InstallDoorAlongX,
InstallDoorAlongY,
CraftWoodenDoor,
InstallMedicineCabinet,
InstallMiningRack,
InstallLoom,
CraftMedicineCabinet,
CraftMiningRack,
CraftLoom
};
enum class BedBase : std::uint8_t { Wood, Stone };
enum class BedStage : std::uint8_t { Legacy, Foundation, Bedding, Pillow };
constexpr bool is_construction(RecipeId recipe) noexcept {
return recipe == RecipeId::BuildCabin || recipe == RecipeId::BuildBed;
constexpr RecipeId room_part_shape(RecipeId recipe) noexcept {
if (recipe == RecipeId::InstallDoorAlongX) return RecipeId::BuildDoorAlongX;
if (recipe == RecipeId::InstallDoorAlongY) return RecipeId::BuildDoorAlongY;
return recipe;
}
constexpr bool is_room_part(RecipeId recipe) noexcept {
recipe = room_part_shape(recipe);
return recipe >= RecipeId::BuildFloor && recipe <= RecipeId::BuildDoorAlongY;
}
constexpr bool is_construction(RecipeId recipe) noexcept {
return recipe == RecipeId::BuildCabin || recipe == RecipeId::BuildBed ||
(recipe >= RecipeId::BuildFloor && recipe <= RecipeId::InstallDoorAlongY) ||
(recipe >= RecipeId::InstallMedicineCabinet && recipe <= RecipeId::InstallLoom);
}
constexpr bool is_carpentry_recipe(RecipeId recipe) noexcept {
return recipe == RecipeId::CraftWoodenDoor ||
(recipe >= RecipeId::CraftMedicineCabinet && recipe <= RecipeId::CraftLoom);
}
constexpr RecipeId furnishing_shape(RecipeId recipe) noexcept {
switch (recipe) {
case RecipeId::InstallMedicineCabinet: return RecipeId::BuildMedicineCabinet;
case RecipeId::InstallMiningRack: return RecipeId::BuildMiningRack;
case RecipeId::InstallLoom: return RecipeId::BuildLoom;
default: return recipe;
}
}
constexpr bool delivers_materials(RecipeId recipe) noexcept {
return is_construction(recipe) || is_carpentry_recipe(recipe);
}
enum class RoomSide : std::uint8_t { North, East, South, West };
enum class RoomTemplate : std::uint8_t { Empty, Doctor, Miner, Weaver };
inline constexpr int furnished_room_size = 4;
struct RoomFurnishing {
GridPosition position;
RecipeId recipe;
BedBase bed_base = BedBase::Wood;
};
struct RoomPlan {
GridPosition first;
GridPosition last;
RoomSide entrance = RoomSide::South;
RoomTemplate layout = RoomTemplate::Empty;
[[nodiscard]] bool valid_size() const noexcept;
[[nodiscard]] bool contains(GridPosition cell) const noexcept;
[[nodiscard]] RecipeId recipe_at(GridPosition cell) const noexcept;
[[nodiscard]] std::optional<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;
enum class WorkPriority : std::uint8_t { Balanced, FoodFirst, BuildingFirst };
enum class Profession : std::uint8_t { Generalist = 0, Farmer, Woodcutter, Miner, Builder };
enum class Profession : std::uint8_t { Generalist = 0, Farmer, Woodcutter, Miner, Builder, Carpenter };
enum class CommandKind : std::uint8_t {
PlaceBed = 0, SetForaging = 1, SetPriority = 2, SetPaused = 3,
PlaceBerryField = 4, PlaceTreePlot = 5, PlaceMine = 6, MoveObject = 7, DemolishObject = 8,
PlaceStorage = 9, AssignProfession = 10, PlaceFlaxField = 11, PlaceLoom = 12
PlaceStorage = 9, AssignProfession = 10, PlaceFlaxField = 11, PlaceLoom = 12, PlaceRoom = 13,
CraftDoor = 14, CraftFurniture = 15
};
enum class CommandStatus : std::uint8_t { Accepted, Unavailable, Unauthorized, WrongSequence, InvalidTarget, Busy };
@@ -218,6 +299,13 @@ struct Storage {
return 0;
}
[[nodiscard]] std::uint32_t available_item_count(ItemType type) const noexcept {
for (const ItemStack& stack : items) {
if (stack.type == type) return stack.count - stack.reserved;
}
return 0;
}
[[nodiscard]] std::uint64_t total_items() const noexcept {
std::uint64_t total = 0;
for (const ItemStack& stack : items) total += stack.count;
@@ -273,6 +361,14 @@ public:
void enable_hunger() noexcept;
void queue_production(GridPosition position, RecipeId recipe);
[[nodiscard]] bool can_place_cabin(GridPosition position) const noexcept;
[[nodiscard]] bool can_place_room(const RoomPlan& plan) const noexcept;
[[nodiscard]] std::array<ItemStack, 2> construction_materials(RecipeId recipe, BedBase base) const;
[[nodiscard]] RecipeId room_construction_recipe(RecipeId part) const noexcept;
[[nodiscard]] std::array<ItemStack, 2> carpentry_materials(RecipeId recipe) const;
[[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 start_scenario(GridPosition sawmill);
[[nodiscard]] CommandReceipt apply_command(const PlayerCommand& command);
@@ -330,6 +426,7 @@ private:
void finish_rest_step(Agent& agent);
void advance_construction_delivery(Agent& agent);
void finish_production(Agent& agent);
[[nodiscard]] std::size_t missing_carpentry_orders(ItemType product, std::size_t new_installations = 0) const;
void update_scenario();
[[nodiscard]] bool resting_at(GridPosition position, AgentId except = 0) const noexcept;
[[nodiscard]] bool ground_rest_cell(GridPosition position, AgentId agent) const noexcept;
+319 -19
View File
@@ -35,6 +35,10 @@ bool is_production_object(RecipeId recipe) noexcept {
return is_construction(recipe) || recipe == RecipeId::WeaveCloth;
}
bool is_finished_floor(const ProductionOrder& order) noexcept {
return order.recipe == RecipeId::BuildFloor && order.state == JobState::Completed;
}
bool can_take_work(const Agent& agent, Profession profession) noexcept {
return agent.profession == Profession::Generalist || agent.profession == profession;
}
@@ -62,16 +66,61 @@ const Recipe& recipe_for(RecipeId id) {
ItemType::None, 28};
static constexpr Recipe bed{{ItemStack{ItemType::Plank, 1}, {}}, ItemType::None, 14};
static constexpr Recipe weave{{ItemStack{ItemType::Flax, 1}, {}}, ItemType::Cloth, 12};
static constexpr Recipe floor{{ItemStack{ItemType::Wood, 1}, {}}, ItemType::None, 6};
static constexpr Recipe wall{{ItemStack{ItemType::Wood, 1}, {}}, ItemType::None, 9};
static constexpr Recipe door{{ItemStack{ItemType::Wood, 2}, {}}, ItemType::None, 12};
static constexpr Recipe cabinet{{ItemStack{ItemType::Wood, 1}, {}}, ItemType::None, 10};
static constexpr Recipe mining_rack{{ItemStack{ItemType::Wood, 1}, ItemStack{ItemType::Stone, 1}},
ItemType::None, 10};
static constexpr Recipe loom{{ItemStack{ItemType::Wood, 2}, {}}, ItemType::None, 12};
static constexpr Recipe install_door{{ItemStack{ItemType::WoodenDoor, 1}, {}}, ItemType::None, 8};
static constexpr Recipe craft_door{{ItemStack{ItemType::Wood, 2}, {}}, ItemType::WoodenDoor, 14};
static constexpr Recipe craft_cabinet{cabinet.ingredients, ItemType::MedicineCabinet, 14};
static constexpr Recipe craft_rack{mining_rack.ingredients, ItemType::MiningRack, 14};
static constexpr Recipe craft_loom{loom.ingredients, ItemType::Loom, 16};
static constexpr Recipe install_cabinet{{ItemStack{ItemType::MedicineCabinet, 1}, {}}, ItemType::None, 8};
static constexpr Recipe install_rack{{ItemStack{ItemType::MiningRack, 1}, {}}, ItemType::None, 8};
static constexpr Recipe install_loom{{ItemStack{ItemType::Loom, 1}, {}}, ItemType::None, 8};
switch (id) {
case RecipeId::SawPlank: return saw;
case RecipeId::CutStoneBlock: return cut;
case RecipeId::BuildCabin: return cabin;
case RecipeId::BuildBed: return bed;
case RecipeId::WeaveCloth: return weave;
case RecipeId::BuildFloor: return floor;
case RecipeId::BuildWall: return wall;
case RecipeId::BuildDoorAlongX:
case RecipeId::BuildDoorAlongY: return door;
case RecipeId::BuildMedicineCabinet: return cabinet;
case RecipeId::BuildMiningRack: return mining_rack;
case RecipeId::BuildLoom: return loom;
case RecipeId::InstallDoorAlongX:
case RecipeId::InstallDoorAlongY: return install_door;
case RecipeId::CraftWoodenDoor: return craft_door;
case RecipeId::CraftMedicineCabinet: return craft_cabinet;
case RecipeId::CraftMiningRack: return craft_rack;
case RecipeId::CraftLoom: return craft_loom;
case RecipeId::InstallMedicineCabinet: return install_cabinet;
case RecipeId::InstallMiningRack: return install_rack;
case RecipeId::InstallLoom: return install_loom;
}
throw std::invalid_argument("unknown production recipe");
}
constexpr ItemType carpentry_products[] = {
ItemType::WoodenDoor, ItemType::MedicineCabinet, ItemType::MiningRack, ItemType::Loom,
};
RecipeId recipe_for_carpentry_item(ItemType item) {
switch (item) {
case ItemType::WoodenDoor: return RecipeId::CraftWoodenDoor;
case ItemType::MedicineCabinet: return RecipeId::CraftMedicineCabinet;
case ItemType::MiningRack: return RecipeId::CraftMiningRack;
case ItemType::Loom: return RecipeId::CraftLoom;
default: throw std::invalid_argument("unknown carpentry item");
}
}
Recipe recipe_for(const ProductionOrder& order) {
Recipe recipe = recipe_for(order.recipe);
if (order.recipe == RecipeId::BuildBed) recipe.ingredients[0].type = order.bed_material();
@@ -124,6 +173,63 @@ struct OpenNodeLater {
} // namespace
RoomPlan make_room_plan(GridPosition first, GridPosition last) noexcept {
return {{std::min(first.x, last.x), std::min(first.y, last.y)},
{std::max(first.x, last.x), std::max(first.y, last.y)}};
}
bool RoomPlan::valid_size() const noexcept {
const auto width = static_cast<std::int64_t>(last.x) - first.x + 1;
const auto height = static_cast<std::int64_t>(last.y) - first.y + 1;
if (entrance > RoomSide::West || layout > RoomTemplate::Weaver) return false;
if (layout == RoomTemplate::Empty) return width >= 3 && width <= 12 && height >= 3 && height <= 12;
return width == furnished_room_size && height == furnished_room_size;
}
bool RoomPlan::contains(GridPosition cell) const noexcept {
return cell.x >= first.x && cell.x <= last.x && cell.y >= first.y && cell.y <= last.y;
}
RecipeId RoomPlan::recipe_at(GridPosition cell) const noexcept {
const auto middle_x = std::midpoint(first.x, last.x), middle_y = std::midpoint(first.y, last.y);
if (cell.y == first.y || cell.y == last.y) {
if (cell.x == middle_x && (cell.y == first.y ? entrance == RoomSide::North : entrance == RoomSide::South)) {
return RecipeId::BuildDoorAlongX;
}
return RecipeId::BuildWall;
}
if (cell.x == first.x || cell.x == last.x) {
if (cell.y == middle_y && (cell.x == first.x ? entrance == RoomSide::West : entrance == RoomSide::East)) {
return RecipeId::BuildDoorAlongY;
}
return RecipeId::BuildWall;
}
return RecipeId::BuildFloor;
}
std::optional<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 {
const auto index = static_cast<std::size_t>(type);
return index != 0 && index <= counts_.size() ? counts_[index - 1] : 0;
@@ -220,8 +326,14 @@ void World::set_blocked(GridPosition position, bool blocked) {
}
}
for (const Agent& agent : agents_) {
if (agent.production_index != no_entity_index &&
is_carpentry_recipe(production_orders_[agent.production_index].recipe) &&
std::find(agent.haul_route.begin(), agent.haul_route.end(), position) != agent.haul_route.end()) {
throw std::logic_error("cannot block the carpenter's delivery route");
}
if (agent.production_index == no_entity_index &&
agent.state != AgentState::GoingToEat && agent.state != AgentState::GoingToSleep) continue;
agent.state != AgentState::GoingToEat && agent.state != AgentState::GoingToSleep &&
!is_carpentry_item(agent.inventory.first_item())) continue;
const auto remaining = agent.route.begin() + static_cast<std::ptrdiff_t>(agent.route_cursor);
if (std::find(remaining, agent.route.end(), position) != agent.route.end()) {
throw std::logic_error("cannot block an active production, meal, or sleep route");
@@ -314,11 +426,14 @@ void World::queue_production(GridPosition position, RecipeId recipe) {
if (!is_walkable(position)) {
throw std::invalid_argument("production site must be on a walkable cell");
}
if (is_carpentry_recipe(recipe) && carpenter_workshop() != position) {
throw std::invalid_argument("carpentry orders need the carpenter's workshop");
}
if (is_production_object(recipe) && !can_place_storage(position)) {
throw std::invalid_argument("the production site is occupied");
}
for (const ProductionOrder& order : production_orders_) {
if (is_production_object(order.recipe) && order.position == position) {
if (is_production_object(order.recipe) && order.position == position && !is_finished_floor(order)) {
throw std::invalid_argument("a building occupies the production site");
}
}
@@ -334,7 +449,78 @@ bool World::can_place_cabin(GridPosition position) const noexcept {
return std::none_of(storages_.begin(), storages_.end(), occupies_cell) &&
std::none_of(resource_nodes_.begin(), resource_nodes_.end(), occupies_cell) &&
std::none_of(jobs_.begin(), jobs_.end(), occupies_cell) &&
std::none_of(production_orders_.begin(), production_orders_.end(), occupies_cell);
std::none_of(production_orders_.begin(), production_orders_.end(),
[&](const auto& order) { return occupies_cell(order) && !is_finished_floor(order); });
}
bool World::can_place_room(const RoomPlan& plan) const noexcept {
if (!plan.valid_size() || (plan.layout != RoomTemplate::Empty && !scenario_active_) ||
!is_walkable(plan.first) || !is_walkable(plan.last)) return false;
const int middle_x = std::midpoint(plan.first.x, plan.last.x);
const int middle_y = std::midpoint(plan.first.y, plan.last.y);
const GridPosition exits[] = {{middle_x, plan.first.y - 1}, {plan.last.x + 1, middle_y},
{middle_x, plan.last.y + 1}, {plan.first.x - 1, middle_y}};
if (!is_walkable(exits[static_cast<std::size_t>(plan.entrance)]) ||
(scenario_active_ && plan.contains(scenario_sawmill_))) return false;
for (int y = plan.first.y; y <= plan.last.y; ++y) {
for (int x = plan.first.x; x <= plan.last.x; ++x) {
if (!is_walkable({x, y})) return false;
}
}
const auto inside = [&](const auto& entity) { return plan.contains(entity.position); };
return std::none_of(production_orders_.begin(), production_orders_.end(), inside) &&
std::none_of(resource_nodes_.begin(), resource_nodes_.end(), inside) &&
std::none_of(storages_.begin(), storages_.end(), inside) &&
std::none_of(jobs_.begin(), jobs_.end(), inside) &&
std::none_of(agents_.begin(), agents_.end(), [&](const Agent& agent) {
return (agent.state == AgentState::Sleeping && inside(agent)) ||
(agent.state == AgentState::GoingToSleep && !agent.route.empty() && plan.contains(agent.route.back()));
});
}
std::array<ItemStack, 2> World::construction_materials(RecipeId recipe, BedBase base) const {
if (recipe == RecipeId::BuildBed && staged_beds_) {
return {ItemStack{base == BedBase::Stone ? ItemType::Stone : ItemType::Wood, 1},
ItemStack{ItemType::Cloth, 2}};
}
return is_construction(recipe) ? recipe_for(recipe).ingredients : std::array<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;
if (part == RecipeId::BuildMedicineCabinet) return RecipeId::InstallMedicineCabinet;
if (part == RecipeId::BuildMiningRack) return RecipeId::InstallMiningRack;
if (part == RecipeId::BuildLoom) return RecipeId::InstallLoom;
}
return part;
}
std::array<ItemStack, 2> World::carpentry_materials(RecipeId recipe) const {
return is_carpentry_recipe(recipe) ? recipe_for(recipe).ingredients : std::array<ItemStack, 2>{};
}
std::size_t World::missing_carpentry_orders(ItemType product, std::size_t new_installations) const {
const auto craft = recipe_for_carpentry_item(product);
std::uint64_t waiting_installations = new_installations, supply = 0;
for (const auto& order : production_orders_) {
if (order.recipe == craft && order.state != JobState::Completed) ++supply;
if (order.state == JobState::Available && is_construction(order.recipe) &&
recipe_for(order).ingredients.front().type == product) {
++waiting_installations;
}
}
for (const auto& agent : agents_) {
if (agent.state == AgentState::Hauling && agent.production_index == no_entity_index) {
supply += agent.inventory.item_count(product);
}
}
for (const auto& storage : storages_) {
const auto available = storage.available_item_count(product);
if (available != 0 && find_path(scenario_sawmill_, storage.position).reachable) supply += available;
}
return waiting_installations > supply ? static_cast<std::size_t>(waiting_installations - supply) : 0;
}
void World::queue_cabin(GridPosition position, GridPosition sawmill, GridPosition stonecutter) {
@@ -408,6 +594,8 @@ CommandStatus World::object_status(GridPosition position, bool moving) const noe
constexpr auto ready = CommandStatus::Accepted;
for (const auto& order : production_orders_) {
if (order.position != position || !is_production_object(order.recipe)) continue;
if (is_finished_floor(order)) continue;
if (moving && is_room_part(order.recipe)) return CommandStatus::InvalidTarget;
return order.state == JobState::InProgress || resting_at(position) ? busy : ready;
}
for (std::size_t i = 0; i < storages_.size(); ++i) {
@@ -428,6 +616,8 @@ CommandStatus World::object_status(GridPosition position, bool moving) const noe
}
return node.reserved_workers != 0 ? busy : ready;
}
if (!moving && !resting_at(position) && std::any_of(production_orders_.begin(), production_orders_.end(),
[position](const auto& order) { return order.position == position && is_finished_floor(order); })) return ready;
return CommandStatus::InvalidTarget;
}
@@ -442,7 +632,7 @@ CommandStatus World::edit_object(GridPosition position, const GridPosition* dest
if (index != no_entity_index && index > removed) --index;
};
const auto order = std::find_if(production_orders_.begin(), production_orders_.end(), [&](const auto& entry) {
return is_production_object(entry.recipe) && at_position(entry);
return is_production_object(entry.recipe) && !is_finished_floor(entry) && at_position(entry);
});
if (order != production_orders_.end()) {
if (destination) order->position = *destination;
@@ -457,6 +647,10 @@ CommandStatus World::edit_object(GridPosition position, const GridPosition* dest
if (storage != storages_.end()) {
if (destination) storage->position = *destination;
else {
std::array<std::uint8_t, std::size(carpentry_products)> lost_products{};
for (std::size_t i = 0; i < std::size(carpentry_products); ++i) {
lost_products[i] = storage->item_count(carpentry_products[i]) != 0;
}
const auto removed = static_cast<std::size_t>(storage - storages_.begin());
storages_.erase(storage);
for (auto& agent : agents_) shift_index(agent.storage_index, removed);
@@ -464,11 +658,29 @@ CommandStatus World::edit_object(GridPosition position, const GridPosition* dest
for (auto& material : entry.materials) shift_index(material.storage_index, removed);
for (auto& stop : entry.delivery_stops) shift_index(stop.storage_index, removed);
}
if (scenario_active_) {
for (std::size_t i = 0; i < std::size(carpentry_products); ++i) {
if (!lost_products[i]) continue;
const auto product = carpentry_products[i];
const auto missing = missing_carpentry_orders(product);
for (std::size_t j = 0; j < missing; ++j) {
queue_production(scenario_sawmill_, recipe_for_carpentry_item(product));
}
}
}
}
return CommandStatus::Accepted;
}
const auto source = std::find_if(resource_nodes_.begin(), resource_nodes_.end(), at_position);
if (source == resource_nodes_.end()) return CommandStatus::InvalidTarget;
if (source == resource_nodes_.end()) {
const auto floor = std::find_if(production_orders_.begin(), production_orders_.end(),
[&](const auto& entry) { return is_finished_floor(entry) && at_position(entry); });
if (floor == production_orders_.end() || destination) return CommandStatus::InvalidTarget;
const auto removed = static_cast<std::size_t>(floor - production_orders_.begin());
production_orders_.erase(floor);
for (auto& agent : agents_) shift_index(agent.production_index, removed);
return CommandStatus::Accepted;
}
if (destination) source->position = *destination;
else {
const auto removed = static_cast<std::size_t>(source - resource_nodes_.begin());
@@ -487,7 +699,8 @@ std::uint64_t World::next_command_sequence(std::uint8_t player) const noexcept {
CommandReceipt World::apply_command(const PlayerCommand& command) {
const auto receipt = [&](CommandStatus status) { return CommandReceipt{status, tick_, command_revision_}; };
const bool object_command = (command.kind >= CommandKind::PlaceBerryField && command.kind <= CommandKind::PlaceStorage) ||
command.kind == CommandKind::PlaceFlaxField || command.kind == CommandKind::PlaceLoom;
command.kind == CommandKind::PlaceFlaxField || command.kind == CommandKind::PlaceLoom ||
command.kind == CommandKind::PlaceRoom;
if (!scenario_active_ && !object_command && command.kind != CommandKind::AssignProfession &&
command.kind != CommandKind::SetForaging) return receipt(CommandStatus::Unavailable);
if (command.player < colony_host || command.player > colony_player_slots) {
@@ -570,8 +783,65 @@ CommandReceipt World::apply_command(const PlayerCommand& command) {
if (!can_place_storage(command.cell) || !can_reach_object_cell(command.cell)) {
return receipt(CommandStatus::InvalidTarget);
}
queue_production(command.cell, RecipeId::WeaveCloth);
if (scenario_active_) {
const auto missing = missing_carpentry_orders(ItemType::Loom, 1);
production_orders_.reserve(production_orders_.size() + 1 + missing);
queue_production(command.cell, RecipeId::InstallLoom);
for (std::size_t i = 0; i < missing; ++i) queue_production(scenario_sawmill_, RecipeId::CraftLoom);
} else {
queue_production(command.cell, RecipeId::WeaveCloth);
}
break;
case CommandKind::CraftDoor:
queue_production(scenario_sawmill_, RecipeId::CraftWoodenDoor);
break;
case CommandKind::CraftFurniture: {
const auto product = static_cast<ItemType>(command.value);
if (!is_carpentry_item(product) || product == ItemType::WoodenDoor) return receipt(CommandStatus::InvalidTarget);
queue_production(scenario_sawmill_, recipe_for_carpentry_item(product));
break;
}
case CommandKind::PlaceRoom: {
const auto plan = RoomPlan::from_placement(command.cell, command.destination, command.value);
if (!can_place_room(plan) || !can_reach_object_cell(plan.first)) {
return receipt(CommandStatus::InvalidTarget);
}
const auto width = static_cast<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 furnishings = plan.furnishings();
const bool legacy_bed = furnishings.has_value() && !staged_beds_;
const auto door_orders = scenario_active_ ? missing_carpentry_orders(ItemType::WoodenDoor, 1) : 0;
const auto fixture = furnishings ? room_construction_recipe(furnishings->back().recipe) : RecipeId::BuildFloor;
const auto fixture_item = furnishings ? recipe_for(fixture).ingredients.front().type : ItemType::None;
const auto fixture_orders = furnishings ? missing_carpentry_orders(fixture_item, 1) : 0;
production_orders_.reserve(production_orders_.size() + width * height +
(furnishings ? furnishings->size() : 0) + (legacy_bed ? 1U : 0U) + door_orders + fixture_orders);
if (legacy_bed) queue_production(scenario_sawmill_, RecipeId::SawPlank);
if (furnishings) {
for (const auto& part : *furnishings) {
ProductionOrder order{};
order.position = part.position;
order.recipe = room_construction_recipe(part.recipe);
order.bed_base = part.bed_base;
if (order.recipe == RecipeId::BuildBed && staged_beds_) order.bed_stage = BedStage::Foundation;
production_orders_.push_back(std::move(order));
}
}
for (int y = plan.first.y; y <= plan.last.y; ++y) {
for (int x = plan.first.x; x <= plan.last.x; ++x) {
const GridPosition cell{x, y};
ProductionOrder order{};
order.position = cell;
order.recipe = room_construction_recipe(plan.recipe_at(cell));
production_orders_.push_back(std::move(order));
}
}
for (std::size_t i = 0; i < door_orders; ++i) queue_production(scenario_sawmill_, RecipeId::CraftWoodenDoor);
for (std::size_t i = 0; i < fixture_orders; ++i) {
queue_production(scenario_sawmill_, recipe_for_carpentry_item(fixture_item));
}
break;
}
case CommandKind::PlaceStorage:
if (command.value > static_cast<std::uint8_t>(StorageKind::Pantry) ||
!can_place_storage(command.cell) || !can_reach_object_cell(command.cell)) {
@@ -587,7 +857,7 @@ CommandReceipt World::apply_command(const PlayerCommand& command) {
break;
}
case CommandKind::AssignProfession: {
if (command.value > static_cast<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);
}
const auto resident = std::lower_bound(agents_.begin(), agents_.end(), command.resident,
@@ -896,10 +1166,11 @@ void World::assign_resource_tasks(ResourceFocus focus) {
}
for (Agent& agent : agents_) {
if (open_pantry_count == 0 && open_material_store_count == 0 && untended_sites == 0) break;
if (agent.profession == Profession::Builder || agent.state != AgentState::Idle || agent.current_job != 0 ||
const auto profession = static_cast<std::size_t>(agent.profession);
if (profession >= available.size() || agent.state != AgentState::Idle || agent.current_job != 0 ||
!agent.inventory.empty()) continue;
const auto& candidates = available[static_cast<std::size_t>(agent.profession)];
const auto& candidates = available[profession];
if (candidates.empty()) continue;
std::vector<std::uint8_t> tried_nodes(candidates.size(), 0);
for (;;) {
@@ -991,7 +1262,8 @@ void World::assign_production_tasks(bool weaving) {
if (production_orders_.empty() || storages_.empty() ||
std::none_of(agents_.begin(), agents_.end(),
[](const Agent& agent) {
return agent.state == AgentState::Idle && can_take_work(agent, Profession::Builder);
return agent.state == AgentState::Idle &&
(can_take_work(agent, Profession::Builder) || agent.profession == Profession::Carpenter);
})) return;
for (std::size_t index = 0; index < production_orders_.size(); ++index) {
ProductionOrder& order = production_orders_[index];
@@ -999,15 +1271,18 @@ void World::assign_production_tasks(bool weaving) {
const bool site_busy = std::any_of(production_orders_.begin(), production_orders_.end(),
[&order](const ProductionOrder& other) {
return other.state == JobState::InProgress &&
other.position.x == order.position.x && other.position.y == order.position.y;
return other.position == order.position &&
(other.state == JobState::InProgress ||
(order.recipe != RecipeId::BuildFloor && other.recipe == RecipeId::BuildFloor &&
other.state != JobState::Completed));
});
if (site_busy) continue;
const Recipe recipe = recipe_for(order);
const bool construction = is_construction(order.recipe);
const bool carpentry = is_carpentry_recipe(order.recipe);
const bool deliver_ingredients = delivers_materials(order.recipe);
enum class Access { Unknown, Reachable, Unreachable };
std::vector<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;
bool supplied = true;
for (const ItemStack& ingredient : recipe.ingredients) {
@@ -1038,7 +1313,7 @@ void World::assign_production_tasks(bool weaving) {
if (!supplied) continue;
std::vector<ConstructionStop> stops;
if (construction) {
if (deliver_ingredients) {
for (std::size_t s = 0; s < storage_access.size(); ++s) {
if (storage_access[s] == Access::Reachable) stops.push_back({s, {}});
}
@@ -1052,12 +1327,18 @@ void World::assign_production_tasks(bool weaving) {
stops[i].route_to_next = std::move(path.positions);
}
}
const GridPosition destination = construction
const GridPosition destination = deliver_ingredients
? storages_[stops.front().storage_index].position : order.position;
for (Agent& agent : agents_) {
if (agent.state != AgentState::Idle || !can_take_work(agent, Profession::Builder)) continue;
const bool can_craft = agent.profession == Profession::Carpenter;
const bool eligible = carpentry ? can_craft :
can_take_work(agent, Profession::Builder) || (can_craft && order.recipe == RecipeId::SawPlank);
if (agent.state != AgentState::Idle || !eligible) continue;
auto path = assignment_path(agent.position, destination);
if (!path.reachable) continue;
if (carpentry) {
agent.haul_route = assignment_path(order.position, storages_[materials.front().storage_index].position).positions;
}
for (const auto& material : materials) {
stack_position(storages_[material.storage_index], material.type)->reserved += material.count;
@@ -1069,7 +1350,7 @@ void World::assign_production_tasks(bool weaving) {
agent.route = std::move(path.positions);
agent.route_cursor = 0;
agent.work_remaining = recipe.ticks;
agent.state = construction ? AgentState::FetchingMaterials :
agent.state = deliver_ingredients ? AgentState::FetchingMaterials :
(agent.route.empty() ? AgentState::Working : AgentState::Travelling);
break;
}
@@ -1218,6 +1499,10 @@ void World::advance_construction_delivery(Agent& agent) {
agent.inventory.add(material.type, material.count);
}
}
if (is_carpentry_recipe(order.recipe) && stop.storage_index == order.materials.front().storage_index) {
// Collecting the first ingredient frees a slot for the finished item.
++storages_[stop.storage_index].reserved_slots;
}
++order.collected_stops;
agent.route = std::move(stop.route_to_next);
agent.route_cursor = 0;
@@ -1228,6 +1513,18 @@ void World::finish_production(Agent& agent) {
ProductionOrder& order = production_orders_[agent.production_index];
const Recipe recipe = recipe_for(order);
assert(!order.materials.empty());
if (is_carpentry_recipe(order.recipe)) {
agent.inventory.add(recipe.output);
agent.storage_index = order.materials.front().storage_index;
agent.route = std::move(agent.haul_route);
agent.haul_route.clear();
agent.route_cursor = 0;
agent.production_index = no_entity_index;
agent.state = AgentState::Hauling;
order.materials.clear();
order.state = JobState::Completed;
return;
}
if (recipe.output != ItemType::None) {
for (const auto& material : order.materials) {
take_reserved_material(storages_[material.storage_index], material);
@@ -1240,6 +1537,9 @@ void World::finish_production(Agent& agent) {
(order.bed_stage == BedStage::Foundation || order.bed_stage == BedStage::Bedding)) {
order.bed_stage = order.bed_stage == BedStage::Foundation ? BedStage::Bedding : BedStage::Pillow;
order.state = JobState::Available;
} else if (furnishing_shape(order.recipe) == RecipeId::BuildLoom) {
order.recipe = RecipeId::WeaveCloth;
order.state = JobState::Available;
} else if (order.recipe == RecipeId::WeaveCloth) {
order.state = JobState::Available;
} else {
+54 -10
View File
@@ -13,7 +13,7 @@ namespace settlement {
namespace {
constexpr std::string_view signature = "SETTLERS";
constexpr std::uint32_t save_version = 9;
constexpr std::uint32_t save_version = 13;
constexpr std::uint32_t last_legacy_footer_version = 8;
constexpr std::size_t max_records = 1'000'000;
constexpr std::size_t max_save_bytes = 128 * 1024 * 1024;
@@ -174,7 +174,8 @@ void flag(Archive& archive, Flag& value) {
struct WorldSaveCodec {
template<class Archive, class State>
static void body(Archive& archive, State& world, std::uint32_t version) {
const auto max_item = version >= 7 ? ItemType::Flax : ItemType::Cloth;
const auto max_item = version >= 13 ? ItemType::Loom :
version >= 12 ? ItemType::WoodenDoor : (version >= 7 ? ItemType::Flax : ItemType::Cloth);
const auto max_item_count = static_cast<std::size_t>(max_item);
archive.field(world.tick_);
archive.field(world.path_searches_);
@@ -214,6 +215,7 @@ struct WorldSaveCodec {
if (version >= 4) archive.field(agent.fatigue);
if (version >= 5) flag(archive, agent.resting_on_ground);
if (version >= 6) archive.field(agent.profession);
require_save(version >= 12 || agent.profession <= Profession::Builder, "Unknown profession for save version.");
});
sequence(archive, world.jobs_, max_records, [&](auto& job) {
archive.field(job.id);
@@ -255,6 +257,10 @@ struct WorldSaveCodec {
archive.field(order.recipe);
require_save(version >= 2 || order.recipe <= RecipeId::BuildCabin, "Unknown recipe for save version.");
require_save(version >= 7 || order.recipe <= RecipeId::BuildBed, "Unknown recipe for save version.");
require_save(version >= 10 || order.recipe <= RecipeId::WeaveCloth, "Unknown recipe for save version.");
require_save(version >= 11 || order.recipe <= RecipeId::BuildDoorAlongY, "Unknown recipe for save version.");
require_save(version >= 12 || order.recipe <= RecipeId::BuildLoom, "Unknown recipe for save version.");
require_save(version >= 13 || order.recipe <= RecipeId::CraftWoodenDoor, "Unknown recipe for save version.");
archive.field(order.state);
sequence(archive, order.materials, item_types, [&](auto& material) {
index(archive, material.storage_index);
@@ -361,9 +367,10 @@ void WorldSaveCodec::validate(const World& world) {
std::vector<AgentId> bed_owners;
for (std::size_t i = 0; i < world.production_orders_.size(); ++i) {
const auto& order = world.production_orders_[i];
invalid(order.recipe <= RecipeId::WeaveCloth && order.state <= JobState::Completed &&
invalid(order.recipe <= RecipeId::CraftLoom && order.state <= JobState::Completed &&
world.is_walkable(order.position) &&
(order.recipe != RecipeId::WeaveCloth || order.state != JobState::Completed));
invalid(!is_carpentry_recipe(order.recipe) || world.carpenter_workshop() == order.position);
invalid(order.bed_base <= BedBase::Stone && order.bed_stage <= BedStage::Pillow &&
(order.bed_stage == BedStage::Legacy ||
(world.staged_beds_ && order.recipe == RecipeId::BuildBed)) &&
@@ -381,8 +388,8 @@ void WorldSaveCodec::validate(const World& world) {
continue;
}
const bool construction = is_construction(order.recipe);
invalid(order.collected_stops <= order.delivery_stops.size() && (construction || order.delivery_stops.empty()));
const bool delivery = delivers_materials(order.recipe);
invalid(order.collected_stops <= order.delivery_stops.size() && (delivery || order.delivery_stops.empty()));
std::size_t last_storage = 0;
bool first_stop = true;
for (const auto& stop : order.delivery_stops) {
@@ -400,7 +407,7 @@ void WorldSaveCodec::validate(const World& world) {
invalid(material.storage_index < world.storages_.size() && material.count > 0 &&
world.storages_[material.storage_index].kind == StorageKind::Materials);
ingredients[type] += material.count;
if (!construction) {
if (!delivery) {
reserved_items[material.storage_index][type] += material.count;
} else if (!order.delivery_stops.empty()) {
const auto stop = std::find_if(order.delivery_stops.begin(), order.delivery_stops.end(),
@@ -424,6 +431,30 @@ void WorldSaveCodec::validate(const World& world) {
break;
case RecipeId::BuildBed: required[item_index(order.bed_material())] = 1; break;
case RecipeId::WeaveCloth: required[item_index(ItemType::Flax)] = 1; break;
case RecipeId::CraftWoodenDoor:
case RecipeId::CraftMedicineCabinet:
case RecipeId::CraftMiningRack:
case RecipeId::CraftLoom:
for (const auto& item : world.carpentry_materials(order.recipe)) {
if (item.count) required[item_index(item.type)] = item.count;
}
break;
case RecipeId::BuildFloor:
case RecipeId::BuildWall:
case RecipeId::BuildDoorAlongX:
case RecipeId::BuildDoorAlongY:
case RecipeId::BuildMedicineCabinet:
case RecipeId::BuildMiningRack:
case RecipeId::BuildLoom:
case RecipeId::InstallDoorAlongX:
case RecipeId::InstallDoorAlongY:
case RecipeId::InstallMedicineCabinet:
case RecipeId::InstallMiningRack:
case RecipeId::InstallLoom:
for (const auto& item : world.construction_materials(order.recipe, order.bed_base)) {
if (item.count) required[item_index(item.type)] = item.count;
}
break;
}
invalid(ingredients == required);
}
@@ -441,7 +472,7 @@ void WorldSaveCodec::validate(const World& world) {
(world.hunger_enabled_ || agent.hunger == 0) && agent.fatigue <= max_fatigue &&
(world.scenario_active_ || agent.fatigue == 0));
invalid(!agent.resting_on_ground || agent.state == Sleeping || agent.state == GoingToSleep);
invalid(agent.profession <= Profession::Builder);
invalid(agent.profession <= Profession::Carpenter);
valid_route(agent.route);
valid_route(agent.haul_route);
const bool has_job = agent.current_job != 0;
@@ -449,7 +480,9 @@ void WorldSaveCodec::validate(const World& world) {
const bool has_source = agent.resource_node_index != no_entity_index;
const bool has_storage = agent.storage_index != no_entity_index;
invalid(!has_storage || agent.storage_index < world.storages_.size());
invalid(agent.haul_route.empty() || has_source);
const bool carpentry = has_order && agent.production_index < world.production_orders_.size() &&
is_carpentry_recipe(world.production_orders_[agent.production_index].recipe);
invalid(agent.haul_route.empty() || has_source || carpentry);
if (has_job) {
invalid(!has_order && !has_storage && !has_source && agent.inventory.empty() &&
(agent.state == Travelling || agent.state == Working) && agent.work_remaining > 0);
@@ -468,7 +501,18 @@ void WorldSaveCodec::validate(const World& world) {
if (!order.delivery_stops.empty()) {
invalid(agent.state == (order.collected_stops == 0 ? FetchingMaterials : Hauling));
} else {
invalid(agent.state == Working || (agent.state == Travelling && !is_construction(order.recipe)));
invalid(agent.state == Working || (agent.state == Travelling && !delivers_materials(order.recipe)));
}
if (carpentry) {
const auto storage = order.materials.front().storage_index;
const auto destination = world.storages_[storage].position;
invalid(agent.haul_route.empty() ? destination == order.position : agent.haul_route.back() == destination);
const auto& stops = order.delivery_stops;
const auto output_stop = std::find_if(stops.begin(), stops.end(),
[storage](const auto& stop) { return stop.storage_index == storage; });
const bool collected = stops.empty() ||
static_cast<std::size_t>(output_stop - stops.begin()) < order.collected_stops;
if (collected) ++reserved_slots[storage];
}
for (std::size_t i = 0; i < item_types; ++i) {
invalid(agent.inventory.item_count(static_cast<ItemType>(i + 1)) == expected_cargo[agent.production_index][i]);
@@ -488,7 +532,7 @@ void WorldSaveCodec::validate(const World& world) {
} else if (agent.state == Hauling) {
const auto cargo = agent.inventory.first_item();
invalid(has_storage && (cargo == ItemType::Wood || cargo == ItemType::Stone ||
cargo == ItemType::Berries || cargo == ItemType::Flax) &&
cargo == ItemType::Berries || cargo == ItemType::Flax || is_carpentry_item(cargo)) &&
agent.inventory.item_count(cargo) == 1 && agent.work_remaining == 0 &&
world.storages_[agent.storage_index].accepts(cargo));
for (std::size_t i = 1; i <= item_types; ++i) {
+45 -99
View File
@@ -1,111 +1,57 @@
param()
param([string]$Msys2Root = $env:SETTLEMENT_MSYS2_ROOT)
$ErrorActionPreference = 'Stop'
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
$projectRoot = Split-Path -Parent $MyInvocation.MyCommand.Path
$toolRoot = Join-Path $projectRoot '.tools\toolchain'
$downloadRoot = Join-Path $projectRoot '.tools\downloads'
$cmakeVersion = '4.5.1'
$llvmVersion = '20261117'
$cmakeArchiveName = "cmake-$cmakeVersion-windows-x86_64.zip"
$cmakeHashName = "cmake-$cmakeVersion-SHA-256.txt"
$llvmArchiveName = "llvm-mingw-$llvmVersion-ucrt-x86_64.zip"
if (-not [Environment]::Is64BitOperatingSystem) {
throw 'This portable toolchain setup requires 64-bit Windows.'
throw 'MSYS2 UCRT64 requires 64-bit Windows.'
}
New-Item -ItemType Directory -Path $downloadRoot -Force | Out-Null
New-Item -ItemType Directory -Path $toolRoot -Force | Out-Null
function Get-Download {
param(
[Parameter(Mandatory = $true)][string]$Uri,
[Parameter(Mandatory = $true)][string]$Destination
)
if (-not (Test-Path -LiteralPath $Destination -PathType Leaf)) {
Write-Host "Downloading $([System.IO.Path]::GetFileName($Destination))"
Invoke-WebRequest -Uri $Uri -OutFile $Destination -UseBasicParsing
$toolRoot = Join-Path $PSScriptRoot '.tools\toolchain'
$portableRoot = Join-Path $toolRoot 'msys64'
if (-not $Msys2Root) { $Msys2Root = $portableRoot }
$bash = Join-Path $Msys2Root 'usr\bin\bash.exe'
$bin = Join-Path $Msys2Root 'ucrt64\bin'
$compiler = Join-Path $bin 'g++.exe'
if ((Test-Path -LiteralPath $compiler -PathType Leaf) -and
(Test-Path -LiteralPath (Join-Path $bin 'cmake.exe') -PathType Leaf) -and
(Test-Path -LiteralPath (Join-Path $bin 'ninja.exe') -PathType Leaf)) {
$version = & $compiler -dumpfullversion
if ($LASTEXITCODE -eq 0 -and $version -match '^16(\.|$)') {
Write-Output "MSYS2 UCRT64 GCC $version is ready."
return
}
}
function Expand-IfMissing {
param(
[Parameter(Mandatory = $true)][string]$Archive,
[Parameter(Mandatory = $true)][string]$Destination,
[Parameter(Mandatory = $true)][string]$ExpectedExecutable
)
$existingExecutable = Get-ChildItem -LiteralPath $Destination -Filter $ExpectedExecutable -File -Recurse -ErrorAction SilentlyContinue | Select-Object -First 1
if ($null -eq $existingExecutable) {
New-Item -ItemType Directory -Path $Destination -Force | Out-Null
Expand-Archive -LiteralPath $Archive -DestinationPath $Destination -Force
if (-not (Test-Path -LiteralPath $bash -PathType Leaf)) {
if ([IO.Path]::GetFullPath($Msys2Root) -ne [IO.Path]::GetFullPath($portableRoot)) {
throw "MSYS2 was not found at $Msys2Root."
}
}
$cmakeArchive = Join-Path $downloadRoot $cmakeArchiveName
$cmakeHashFile = Join-Path $downloadRoot $cmakeHashName
$cmakeBase = "https://github.com/Kitware/CMake/releases/download/v$cmakeVersion"
Get-Download -Uri "$cmakeBase/$cmakeArchiveName" -Destination $cmakeArchive
Get-Download -Uri "$cmakeBase/$cmakeHashName" -Destination $cmakeHashFile
$escapedCmakeName = [regex]::Escape($cmakeArchiveName)
$hashText = Get-Content -LiteralPath $cmakeHashFile -Raw
$hashPatterns = @(
"(?im)^\s*([0-9a-f]{64})\s+\*?$escapedCmakeName\s*$",
"(?im)^\s*SHA-?256\s*\(\s*$escapedCmakeName\s*\)\s*[:=]\s*([0-9a-f]{64})\s*$",
"(?im)^\s*$escapedCmakeName\s*[: ]+\s*([0-9a-f]{64})\s*$"
)
$expectedCmakeHash = $null
foreach ($pattern in $hashPatterns) {
$match = [regex]::Match($hashText, $pattern)
if ($match.Success) {
$expectedCmakeHash = $match.Groups[1].Value.ToLowerInvariant()
break
$downloadRoot = Join-Path $PSScriptRoot '.tools\downloads'
New-Item -ItemType Directory -Path $downloadRoot, $toolRoot -Force | Out-Null
$name = 'msys2-base-x86_64-20261120.tar.zst'
$archive = Join-Path $downloadRoot $name
$expected = 'adde59fcb53760bd0fd2aa3c3e8da516f03159b771dc62b77c340e4ac187fcdd'
if (-not (Test-Path -LiteralPath $archive -PathType Leaf) -or
(Get-FileHash -LiteralPath $archive -Algorithm SHA256).Hash -ne $expected) {
Invoke-WebRequest -Uri "https://repo.msys2.org/distrib/x86_64/$name" -OutFile $archive -UseBasicParsing
}
}
if (-not $expectedCmakeHash) {
throw "Could not read the official SHA-256 for $cmakeArchiveName. The archive was not extracted."
}
$actualCmakeHash = (Get-FileHash -LiteralPath $cmakeArchive -Algorithm SHA256).Hash.ToLowerInvariant()
if ($actualCmakeHash -ne $expectedCmakeHash) {
throw "CMake archive SHA-256 mismatch. Expected $expectedCmakeHash, got $actualCmakeHash."
}
$llvmArchive = Join-Path $downloadRoot $llvmArchiveName
$llvmReleaseUri = "https://api.github.com/repos/mstorsjo/llvm-mingw/releases/tags/$llvmVersion"
$llvmRelease = Invoke-RestMethod -Uri $llvmReleaseUri -Headers @{ 'User-Agent' = 'stonehearth-sim-toolchain-setup' }
$llvmAsset = $llvmRelease.assets | Where-Object { $_.name -eq $llvmArchiveName } | Select-Object -First 1
if ($null -eq $llvmAsset) {
throw "The official llvm-mingw release $llvmVersion does not contain $llvmArchiveName."
}
Get-Download -Uri $llvmAsset.browser_download_url -Destination $llvmArchive
if ($llvmAsset.digest -and $llvmAsset.digest -match '^sha256:([0-9a-fA-F]{64})$') {
$expectedLlvmHash = $Matches[1].ToLowerInvariant()
$actualLlvmHash = (Get-FileHash -LiteralPath $llvmArchive -Algorithm SHA256).Hash.ToLowerInvariant()
if ($actualLlvmHash -ne $expectedLlvmHash) {
throw "LLVM-MinGW archive SHA-256 mismatch. Expected $expectedLlvmHash, got $actualLlvmHash."
if ((Get-FileHash -LiteralPath $archive -Algorithm SHA256).Hash -ne $expected) {
throw 'MSYS2 archive hash does not match the release.'
}
} else {
Write-Warning 'GitHub did not publish a SHA-256 digest for this LLVM-MinGW asset; download is from the official release over HTTPS.'
& tar.exe -xf $archive -C $toolRoot
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
}
$cmakeInstall = Join-Path $toolRoot 'cmake'
$llvmInstall = Join-Path $toolRoot 'llvm-mingw'
Expand-IfMissing -Archive $cmakeArchive -Destination $cmakeInstall -ExpectedExecutable 'cmake.exe'
Expand-IfMissing -Archive $llvmArchive -Destination $llvmInstall -ExpectedExecutable 'clang++.exe'
$cmakeExe = Get-ChildItem -LiteralPath $cmakeInstall -Filter 'cmake.exe' -File -Recurse | Select-Object -First 1
$clangxxExe = Get-ChildItem -LiteralPath $llvmInstall -Filter 'clang++.exe' -File -Recurse | Select-Object -First 1
if ($null -eq $cmakeExe -or $null -eq $clangxxExe) {
throw 'Extraction completed, but CMake or Clang++ was not found in the toolchain folders.'
$previousMsysSystem = $env:MSYSTEM
try {
$env:MSYSTEM = 'UCRT64'
# An MSYS2 runtime upgrade can close the first shell. Start a fresh shell for the remaining packages.
& $bash --login -c 'pacman -Syu --noconfirm'
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
& $bash --login -c 'pacman -Syu --needed --noconfirm mingw-w64-ucrt-x86_64-gcc mingw-w64-ucrt-x86_64-cmake mingw-w64-ucrt-x86_64-ninja'
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
} finally {
$env:MSYSTEM = $previousMsysSystem
}
Write-Host "CMake: $($cmakeExe.FullName)"
& $cmakeExe.FullName --version | Select-Object -First 1
Write-Host "C++ compiler: $($clangxxExe.FullName)"
& $clangxxExe.FullName --version | Select-Object -First 1
Write-Host 'Portable toolchain is ready. Run .\build.ps1 to configure, build, and run CTest.'
$version = & $compiler -dumpfullversion
if ($LASTEXITCODE -ne 0 -or $version -notmatch '^16(\.|$)') {
throw "Expected GCC 16 in MSYS2 UCRT64. Found: $version"
}
Write-Output "MSYS2 UCRT64 GCC $version is ready."
+417 -56
View File
@@ -1,6 +1,9 @@
#include "testing.hpp"
#include "settlement/core/deterministic_rng.hpp"
#include "settlement/core/world.hpp"
#include <algorithm>
#include <cstdint>
#include <iostream>
#include <sstream>
@@ -30,7 +33,37 @@ std::unique_ptr<settlement::World> save_roundtrip(const settlement::World& world
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();
[[= Void::Testing::tag("construction")]] Test test_carpenter_makes_furnishings_for_rooms();
};
Test CoreTests::test_parallel_pathfinding_completes_the_jobs() {
settlement::World world(123, 48, 48, 6);
for (std::int32_t y = 0; y < 48; ++y) {
if (y != 31) world.set_blocked({24, y});
@@ -42,26 +75,28 @@ void test_parallel_pathfinding_completes_the_jobs() {
}
for (int tick = 0; tick < 120; ++tick) world.step();
require(world.jobs_completed() == 24, "parallel pathfinding did not finish every job");
return {};
}
void test_single_worker_configuration_is_rejected() {
Test CoreTests::test_single_worker_configuration_is_rejected() {
try {
settlement::World world(8, 8, 8, 1);
} catch (const std::invalid_argument&) {
return;
return {};
}
throw std::runtime_error("world accepted a single worker");
}
void test_rng_repeats_for_same_seed() {
Test CoreTests::test_rng_repeats_for_same_seed() {
settlement::DeterministicRng left(12345);
settlement::DeterministicRng right(12345);
for (int index = 0; index < 1000; ++index) {
require(left.next_u64() == right.next_u64(), "RNG diverged for matching seeds");
expect_eq(left.next_u64(), right.next_u64());
}
return {};
}
void test_work_jobs_complete() {
Test CoreTests::test_work_jobs_complete() {
settlement::World world(1, 10, 10);
const settlement::AgentId agent_id = world.spawn_agent({1, 1});
const settlement::JobId job_id = world.add_job({3, 1}, 2);
@@ -81,9 +116,10 @@ void test_work_jobs_complete() {
"completed job retained an active state");
require(world.agents().front().state == settlement::AgentState::Idle,
"worker did not return to idle after completing a job");
return {};
}
void test_astar_route_uses_opening_in_wall() {
Test CoreTests::test_astar_route_uses_opening_in_wall() {
settlement::World world(2, 10, 10);
for (std::int32_t y = 0; y < 10; ++y) {
if (y != 8) {
@@ -103,9 +139,10 @@ void test_astar_route_uses_opening_in_wall() {
}
require(world.path_searches() > 0, "path search counter was not updated");
require(world.path_nodes_visited() > 0, "A* did not report expanded nodes");
return {};
}
void test_residents_gather_and_deliver_resources() {
Test CoreTests::test_residents_gather_and_deliver_resources() {
settlement::World world(51, 16, 16, 4);
static_cast<void>(world.add_storage({1, 1}, 10));
static_cast<void>(world.spawn_agent({1, 2}));
@@ -126,9 +163,10 @@ void test_residents_gather_and_deliver_resources() {
"storage retained reservations after deliveries completed");
require(world.resource_nodes()[0].quantity == 0 && world.resource_nodes()[1].quantity == 0,
"resource nodes retained units after deliveries completed");
return {};
}
void test_production_reservations_and_construction() {
Test CoreTests::test_production_reservations_and_construction() {
using settlement::ItemType;
using settlement::JobState;
using settlement::RecipeId;
@@ -207,9 +245,10 @@ void test_production_reservations_and_construction() {
require(world.storages()[0].items.empty() && world.storages()[1].items.empty(),
"building did not consume the crafted materials from both stores");
return {};
}
void test_cabin_placement_queues_a_complete_order() {
Test CoreTests::test_cabin_placement_queues_a_complete_order() {
using settlement::RecipeId;
settlement::World world(1, 10, 10);
world.set_blocked({1, 1});
@@ -229,9 +268,10 @@ void test_cabin_placement_queues_a_complete_order() {
} catch (const std::invalid_argument&) {
require(orders.size() == 6, "invalid placement partially queued new orders");
}
return {};
}
void test_hungry_resident_reserves_and_eats_a_berry() {
Test CoreTests::test_hungry_resident_reserves_and_eats_a_berry() {
using settlement::AgentState;
using settlement::ItemType;
const settlement::GridPosition pantry{1, 1};
@@ -278,9 +318,10 @@ void test_hungry_resident_reserves_and_eats_a_berry() {
static_cast<void>(world.add_job(pantry, 1));
world.step();
require(world.jobs_completed() == 2, "the resident did not resume work after eating");
return {};
}
void test_invalid_save_is_rejected() {
Test CoreTests::test_invalid_save_is_rejected() {
const settlement::World world(5, 5, 5);
auto bytes = save_contents(world);
const auto rejected = [](const std::string& save) {
@@ -296,9 +337,10 @@ void test_invalid_save_is_rejected() {
require(rejected(bytes + 'x'), "save with trailing data was accepted");
bytes[8] = 127;
require(rejected(bytes), "unknown save version was accepted");
return {};
}
void test_two_players_share_the_first_colony() {
Test CoreTests::test_two_players_share_the_first_colony() {
using settlement::CommandKind;
using settlement::CommandStatus;
auto world = settlement::make_first_colony(2);
@@ -341,9 +383,10 @@ void test_two_players_share_the_first_colony() {
"the shared colony could not feed its residents and complete the objective");
auto replay = save_roundtrip(*world);
require(replay->scenario_progress().completed, "completion was lost after loading");
return {};
}
void test_bed_parts_are_delivered_separately() {
Test CoreTests::test_bed_parts_are_delivered_separately() {
using namespace settlement;
auto world = make_first_colony(2);
const GridPosition wood_bed{16, 18};
@@ -373,9 +416,10 @@ void test_bed_parts_are_delivered_separately() {
"the beds were not completed through three separate deliveries");
require(world->storages().back().item_count(ItemType::Cloth) == 8,
"two beds must consume four pieces of cloth");
return {};
}
void test_resident_uses_assigned_bed_and_sleep_survives_save() {
Test CoreTests::test_resident_uses_assigned_bed_and_sleep_survives_save() {
using namespace settlement;
World world(4, 16, 16, 2);
const auto owner = world.spawn_agent({1, 2});
@@ -423,9 +467,10 @@ void test_resident_uses_assigned_bed_and_sleep_survives_save() {
}
require(from_route && woke_rested && rested_on_ground, "sleep and recovery phases were not observed");
require(world.jobs_completed() == 2, "residents did not finish their existing work");
return {};
}
void test_fatigue_slows_work_without_interrupting_it() {
Test CoreTests::test_fatigue_slows_work_without_interrupting_it() {
using namespace settlement;
World world(6, 10, 10);
static_cast<void>(world.spawn_agent({2, 2}));
@@ -438,9 +483,10 @@ void test_fatigue_slows_work_without_interrupting_it() {
const auto before = resident.work_remaining;
for (int i = 0; i < 6; ++i) world.step();
require(before - resident.work_remaining == 2, "hunger and fatigue did not slow the ongoing work");
return {};
}
void test_ground_rest_never_uses_another_residents_bed() {
Test CoreTests::test_ground_rest_never_uses_another_residents_bed() {
using namespace settlement;
World world(15, 14, 14);
const GridPosition cell{7, 6};
@@ -479,9 +525,10 @@ void test_ground_rest_never_uses_another_residents_bed() {
require(world.assigned_bed(owner)->position == new_cell, "moving a bed lost its owner");
require(world.apply_command({1, 3, CommandKind::DemolishObject, new_cell}).status == CommandStatus::Accepted &&
world.assigned_bed(owner) == nullptr, "demolishing a bed left a stale assignment");
return {};
}
void test_fields_mines_and_reindexing_active_hauls() {
Test CoreTests::test_fields_mines_and_reindexing_active_hauls() {
using namespace settlement;
World world(22, 18, 18, 2);
const GridPosition rock{9, 5};
@@ -532,9 +579,10 @@ void test_fields_mines_and_reindexing_active_hauls() {
"growing, regrowing, or mining did not deliver resources");
require(apply(CommandKind::PlaceStorage, {11, 7}) == CommandStatus::Accepted,
"a new storage could not be placed");
return {};
}
void test_specialists_take_their_own_jobs_and_finish_prior_assignments() {
Test CoreTests::test_specialists_take_their_own_jobs_and_finish_prior_assignments() {
using namespace settlement;
World world(54, 14, 14, 2);
const auto farmer = world.spawn_agent({2, 2});
@@ -588,17 +636,20 @@ void test_specialists_take_their_own_jobs_and_finish_prior_assignments() {
}
require(delivered_stone && later_cut_wood, "the reassigned miner did not finish mining and then cut wood");
require(world.scenario_progress().assigned_beds == 1, "the builder did not complete the bed");
return {};
}
void test_flax_and_loom_supply_a_bed_without_starting_cloth() {
Test CoreTests::test_flax_and_loom_supply_a_bed_without_starting_cloth() {
using namespace settlement;
World world(92, 12, 12, 3);
const auto farmer = world.spawn_agent({2, 3});
const auto builder = world.spawn_agent({4, 4});
const auto carpenter = world.spawn_agent({5, 2});
const auto materials = world.add_storage({3, 3}, 30);
const auto pantry = world.add_storage({3, 4}, 12, StorageKind::Pantry);
world.stock_storage(pantry, ItemType::Berries, 12);
world.stock_storage(materials, ItemType::Stone, 1);
world.stock_storage(materials, ItemType::Wood, 2);
world.start_scenario({4, 2});
const auto send = [&](CommandKind kind, GridPosition cell = {}, std::uint8_t value = 0,
GridPosition destination = {}, AgentId resident = 0) {
@@ -617,13 +668,24 @@ void test_flax_and_loom_supply_a_bed_without_starting_cloth() {
send(CommandKind::MoveObject, loom, 0, moved_loom) == CommandStatus::Accepted &&
send(CommandKind::PlaceBed, {5, 4}, static_cast<std::uint8_t>(BedBase::Stone)) == CommandStatus::Accepted,
"a textile object collided with a field or could not be placed or moved");
require(world.production_orders().front().recipe == RecipeId::InstallLoom &&
world.production_orders().front().position == moved_loom &&
world.production_orders()[1].recipe == RecipeId::CraftLoom,
"placing or moving the loom bypassed or duplicated its craft order");
require(world.resource_nodes().front().needs_tending(), "flax started growing before being planted");
for (int i = 0; i < 24; ++i) world.step();
require(world.production_orders().front().state == JobState::Available &&
world.production_orders()[1].state == JobState::Available &&
world.storages().front().available_item_count(ItemType::Wood) == 2,
"the loom was installed or crafted without a carpenter");
require(send(CommandKind::AssignProfession, {}, static_cast<std::uint8_t>(Profession::Carpenter), {}, carpenter) ==
CommandStatus::Accepted, "could not assign a carpenter for the loom");
auto restored = save_roundtrip(world);
bool saved_flax_in_transit = false;
bool saved_active_weaving = false;
int sowings = 0;
std::uint64_t last_growth = 0;
for (int i = 0; i < 360; ++i) {
for (int i = 0; i < 500; ++i) {
world.step();
restored->step();
require(save_contents(world) == save_contents(*restored), "textile work diverged after loading");
@@ -632,8 +694,8 @@ void test_flax_and_loom_supply_a_bed_without_starting_cloth() {
restored = save_roundtrip(world);
saved_flax_in_transit = true;
}
if (!saved_active_weaving && loom_order.state == JobState::InProgress) {
require(world.agents().back().production_index == 0 &&
if (!saved_active_weaving && loom_order.recipe == RecipeId::WeaveCloth && loom_order.state == JobState::InProgress) {
require(world.agents()[1].production_index == 0 &&
world.object_status(moved_loom, true) == CommandStatus::Busy,
"the loom was assigned to the wrong worker or could move while active");
restored = save_roundtrip(world);
@@ -648,9 +710,13 @@ void test_flax_and_loom_supply_a_bed_without_starting_cloth() {
require(world.scenario_progress().assigned_beds == 1 &&
world.storages().front().item_count(ItemType::Cloth) > 0,
"the loom did not make enough cloth to finish and replenish a bed order");
require(world.storages().front().item_count(ItemType::Wood) == 0 &&
world.storages().front().item_count(ItemType::Loom) == 0,
"the installed loom did not consume the materials and finished item exactly once");
return {};
}
void test_field_growth_requires_a_worker() {
Test CoreTests::test_field_growth_requires_a_worker() {
using namespace settlement;
World world(58, 14, 14);
const auto resident = world.spawn_agent({2, 2});
@@ -677,9 +743,10 @@ void test_field_growth_requires_a_worker() {
require(save_contents(world) == save_contents(*restored), "sowing did not resume after loading");
}
require(world.resource_nodes().front().quantity > 0, "planting without a storage did not grow flax");
return {};
}
void test_opening_a_mine_invalidates_unreachable_routes() {
Test CoreTests::test_opening_a_mine_invalidates_unreachable_routes() {
using namespace settlement;
World world(44, 8, 8);
const auto resident = world.spawn_agent({1, 4});
@@ -698,9 +765,10 @@ void test_opening_a_mine_invalidates_unreachable_routes() {
world.step();
require(world.agents().front().resource_node_index == 0 &&
world.agents().front().state == AgentState::Travelling, "terrain edit left a stale route in the cache");
return {};
}
void test_object_tools_work_in_an_older_demo_world() {
Test CoreTests::test_object_tools_work_in_an_older_demo_world() {
using namespace settlement;
World legacy(12, 12, 12);
static_cast<void>(legacy.spawn_agent({4, 4}));
@@ -719,38 +787,331 @@ void test_object_tools_work_in_an_older_demo_world() {
require(edit(CommandKind::DemolishObject, {4, 5}) == CommandStatus::Accepted,
"a field in a demonstration could not be demolished");
static_cast<void>(save_roundtrip(*world));
return {};
}
Test CoreTests::test_room_builds_and_saves_as_separate_parts() {
using namespace settlement;
World world(61, 16, 16);
static_cast<void>(world.spawn_agent({3, 3}));
const auto storage = world.add_storage({2, 2}, 32);
world.stock_storage(storage, ItemType::Wood, 32);
auto room = make_room_plan({9, 8}, {6, 5});
room.entrance = RoomSide::East;
const auto place = [&](const RoomPlan& plan) {
return world.apply_command({1, world.next_command_sequence(1), CommandKind::PlaceRoom, plan.first,
static_cast<std::uint8_t>(plan.entrance), plan.last}).status;
};
require(room.recipe_at({9, 6}) == RecipeId::BuildDoorAlongY, "room lost its entrance");
world.set_blocked({10, 6}, true);
require(place(room) == CommandStatus::InvalidTarget && world.production_orders().empty(),
"a room with a blocked entrance was partially scheduled");
world.set_blocked({10, 6}, false);
require(place(room) == CommandStatus::Accepted && world.production_orders().size() == 16,
"room did not queue floor, walls and entrance together");
require(place(room) == CommandStatus::InvalidTarget && world.production_orders().size() == 16,
"duplicate room placement altered its construction orders");
world.step();
require(world.production_orders().front().state == JobState::InProgress, "builders did not start the room");
auto resumed = save_roundtrip(world);
for (int i = 0; i < 850; ++i) resumed->step();
for (const auto& order : resumed->production_orders()) {
require(order.state == JobState::Completed && order.recipe == room.recipe_at(order.position),
"room component did not survive delivery and construction after load");
}
require(resumed->storages().front().item_count(ItemType::Wood) == 15, "room used incorrect materials");
const auto apply = [&](CommandKind command, GridPosition cell) {
return resumed->apply_command({1, resumed->next_command_sequence(1), command, cell}).status;
};
const GridPosition floor{7, 6};
require(apply(CommandKind::PlaceLoom, floor) == CommandStatus::Accepted,
"finished floor could not hold furniture");
require(apply(CommandKind::DemolishObject, floor) == CommandStatus::Accepted &&
resumed->production_orders().size() == 16 && resumed->can_place_storage(floor),
"demolition removed the floor instead of the furniture");
static_cast<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() == 20, "the furnished room did not queue construction and carpentry");
require(place(1, plan.placement_value()) == CommandStatus::InvalidTarget &&
world.production_orders().size() == 20, "an overlapping furnished room left duplicate orders");
const auto floor_is_done = [&](const World& state, GridPosition cell) {
return std::any_of(state.production_orders().begin(), state.production_orders().end(),
[cell](const auto& order) {
return order.position == cell && order.recipe == BuildFloor && order.state == JobState::Completed;
});
};
world.step();
auto resumed = save_roundtrip(world);
for (int tick = 0; tick < 850; ++tick) {
resumed->step();
for (std::size_t i = 0; i < parts.size(); ++i) {
const auto& order = resumed->production_orders()[i];
if (order.state != JobState::Available || order.recipe == WeaveCloth) {
require(floor_is_done(*resumed, parts[i].position), "a furnishing started before its floor");
}
}
}
const auto& bed = resumed->production_orders()[0];
const auto& furniture = resumed->production_orders()[1];
require(bed.recipe == BuildBed && bed.position == parts[0].position && bed.state == JobState::Completed &&
bed.bed_owner != 0 && bed.bed_base == (layout == RoomTemplate::Miner ? BedBase::Stone : BedBase::Wood),
"the room's bed did not become usable");
require(furniture.position == parts[1].position, "the furnishing moved during construction");
if (fixture == BuildLoom) {
require(furniture.recipe == WeaveCloth && resumed->storages().front().item_count(ItemType::Cloth) == 1,
"the built loom did not process flax");
} else {
require(furnishing_shape(furniture.recipe) == fixture && furniture.state == JobState::Completed,
"the themed furnishing did not finish");
}
static_cast<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 {};
}
Test CoreTests::test_carpenter_makes_furnishings_for_rooms() {
using namespace settlement;
struct Variant {
RoomTemplate layout;
ItemType item;
RecipeId craft;
RecipeId installation;
};
const Variant variants[] = {
{RoomTemplate::Doctor, ItemType::MedicineCabinet, RecipeId::CraftMedicineCabinet, RecipeId::InstallMedicineCabinet},
{RoomTemplate::Miner, ItemType::MiningRack, RecipeId::CraftMiningRack, RecipeId::InstallMiningRack},
{RoomTemplate::Weaver, ItemType::Loom, RecipeId::CraftLoom, RecipeId::InstallLoom},
};
for (const auto& variant : variants) {
auto world = std::make_unique<World>(64, 20, 18);
const auto builder = world->spawn_agent({5, 3});
const auto carpenter = world->spawn_agent({3, 3});
// Stone is at the first delivery stop, but the product returns to the wood store.
const auto stone = world->add_storage({2, 3}, 6);
const auto wood = world->add_storage({3, 4}, 48);
world->stock_storage(stone, ItemType::Stone, 4);
world->stock_storage(wood, ItemType::Wood, 38);
world->stock_storage(wood, ItemType::Cloth, 2);
world->stock_storage(wood, ItemType::Flax, 1);
const GridPosition workshop{4, 3};
world->start_scenario(workshop);
auto send = [&](CommandKind kind, GridPosition cell = {}, std::uint8_t value = 0,
GridPosition target = {}, AgentId resident = 0) {
return world->apply_command({1, world->next_command_sequence(1), kind, cell, value, target, resident}).status;
};
const RoomPlan plan{{6, 5}, {9, 8}, RoomSide::East, variant.layout};
require(send(CommandKind::AssignProfession, {}, static_cast<std::uint8_t>(Profession::Builder), {}, builder) ==
CommandStatus::Accepted &&
send(CommandKind::PlaceRoom, plan.first, plan.placement_value(), plan.last) == CommandStatus::Accepted,
"could not place the furnished room");
const auto count_orders = [&](RecipeId recipe) {
return std::count_if(world->production_orders().begin(), world->production_orders().end(),
[recipe](const auto& order) { return order.recipe == recipe; });
};
require(count_orders(variant.craft) == 1 && count_orders(variant.installation) == 1,
"the blueprint did not request its furnishing");
for (int tick = 0; tick < 180; ++tick) world->step();
require(std::all_of(world->production_orders().begin(), world->production_orders().end(),
[&](const auto& order) {
return (order.recipe != variant.craft && order.recipe != variant.installation) ||
order.state == JobState::Available;
}), "a generalist or builder bypassed the carpenter");
require(send(CommandKind::AssignProfession, {}, static_cast<std::uint8_t>(Profession::Carpenter), {}, carpenter) ==
CommandStatus::Accepted, "could not assign the carpenter");
bool saved_stone_stop = false, saved_workshop = false, saved_delivery = false, saved_installation = false;
const auto fixture = plan.furnishings()->back().position;
for (int tick = 0; tick < 900; ++tick) {
world->step();
const auto& maker = world->agents()[1];
if (variant.item == ItemType::MiningRack && !saved_stone_stop &&
maker.production_index != no_entity_index &&
world->production_orders()[maker.production_index].recipe == variant.craft &&
maker.inventory.item_count(ItemType::Stone) != 0 && maker.inventory.item_count(ItemType::Wood) == 0) {
require(world->storages()[1].reserved_slots == 0, "output space was reserved before collecting wood");
saved_stone_stop = true;
world = save_roundtrip(*world);
continue;
}
if (!saved_workshop && maker.state == AgentState::Working && maker.position == workshop &&
maker.production_index != no_entity_index &&
world->production_orders()[maker.production_index].recipe == variant.craft) {
require(world->storages()[1].reserved_slots == 1, "output space was not reserved while crafting");
saved_workshop = true;
world = save_roundtrip(*world);
continue;
}
if (!saved_delivery && maker.inventory.item_count(variant.item) != 0) {
require(maker.state == AgentState::Hauling && world->storages()[1].item_count(variant.item) == 0,
"the furnishing appeared in stock before delivery");
saved_delivery = true;
world = save_roundtrip(*world);
continue;
}
if (!saved_installation && world->agents()[0].inventory.item_count(variant.item) != 0) {
saved_installation = true;
world = save_roundtrip(*world);
}
}
require(saved_workshop && saved_delivery && saved_installation &&
(variant.item != ItemType::MiningRack || saved_stone_stop),
"the furnishing did not survive every stage of crafting and delivery");
const auto active_recipe = variant.item == ItemType::Loom ? RecipeId::WeaveCloth : variant.installation;
require(std::any_of(world->production_orders().begin(), world->production_orders().end(),
[&](const auto& order) {
return order.position == fixture && order.recipe == active_recipe &&
(active_recipe == RecipeId::WeaveCloth || order.state == JobState::Completed);
}), "the stored furnishing was not installed");
if (variant.item == ItemType::Loom) {
require(world->storages()[1].item_count(ItemType::Cloth) == 1, "the installed loom did not weave");
}
const auto existing_work = world->production_orders().size();
require(send(CommandKind::CraftFurniture, {}, static_cast<std::uint8_t>(ItemType::Wood)) == CommandStatus::InvalidTarget &&
world->production_orders().size() == existing_work, "an invalid craft queued an order");
require(send(CommandKind::CraftFurniture, {}, static_cast<std::uint8_t>(variant.item)) == CommandStatus::Accepted,
"could not order a spare furnishing");
for (int tick = 0; tick < 450 && world->storages()[1].available_item_count(variant.item) == 0; ++tick) world->step();
require(world->storages()[1].available_item_count(variant.item) == 1, "the manual order yielded no spare");
const RoomPlan second{{11, 5}, {14, 8}, RoomSide::East, variant.layout};
require(send(CommandKind::PlaceRoom, second.first, second.placement_value(), second.last) == CommandStatus::Accepted &&
count_orders(variant.craft) == 2, "a room ignored the matching furnishing already in stock");
static_cast<void>(save_roundtrip(*world));
}
return {};
}
} // namespace
int main() {
try {
test_rng_repeats_for_same_seed();
test_work_jobs_complete();
test_astar_route_uses_opening_in_wall();
test_parallel_pathfinding_completes_the_jobs();
test_single_worker_configuration_is_rejected();
test_residents_gather_and_deliver_resources();
test_production_reservations_and_construction();
test_cabin_placement_queues_a_complete_order();
test_hungry_resident_reserves_and_eats_a_berry();
test_invalid_save_is_rejected();
test_two_players_share_the_first_colony();
test_bed_parts_are_delivered_separately();
test_resident_uses_assigned_bed_and_sleep_survives_save();
test_fatigue_slows_work_without_interrupting_it();
test_ground_rest_never_uses_another_residents_bed();
test_fields_mines_and_reindexing_active_hauls();
test_specialists_take_their_own_jobs_and_finish_prior_assignments();
test_flax_and_loom_supply_a_bed_without_starting_cloth();
test_field_growth_requires_a_worker();
test_opening_a_mine_invalidates_unreachable_routes();
test_object_tools_work_in_an_older_demo_world();
} catch (const std::exception& error) {
std::cerr << "Test failed: " << error.what() << '\n';
return 1;
}
std::cout << "All core checks passed.\n";
return 0;
int main(int argc, char** argv) {
return CoreTests::run(argc, argv);
}
+51 -12
View File
@@ -1,3 +1,5 @@
#include "testing.hpp"
#include "lan_session.hpp"
#include <chrono>
@@ -15,7 +17,13 @@ void require(bool condition, const char* message) {
if (!condition) throw std::runtime_error(message);
}
void test_shared_colony_over_loopback() {
using Void::Testing::Test;
struct LanTests : Void::Testing::Suite<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 client_view = make_first_colony(4);
for (int i = 0; i < 25; ++i) authoritative->step();
@@ -56,7 +64,12 @@ void test_shared_colony_over_loopback() {
require(authoritative->production_orders().front().bed_base == BedBase::Stone,
"the guest's choice of bed material was lost");
require(guest.submit(CommandKind::PlaceBed, {16, 18}, 0), "the guest could not send a conflicting command");
pump_until([&] { return guest.take_rejection() == CommandStatus::InvalidTarget; },
pump_until([&] {
const auto rejected = guest.take_rejection();
return rejected && rejected->status == CommandStatus::InvalidTarget &&
rejected->kind == CommandKind::PlaceBed && rejected->cell == GridPosition{16, 18} &&
rejected->value == 0;
},
"a conflicting guest command did not return a rejection");
require(authoritative->production_orders().size() == 1, "the same cell was claimed twice");
@@ -116,9 +129,11 @@ void test_shared_colony_over_loopback() {
}, "the flax field did not arrive in the guest snapshot");
require(guest.submit(CommandKind::PlaceLoom, new_field, 0), "the guest could not place a loom");
pump_until([&] {
return client_view->production_orders().back().recipe == RecipeId::WeaveCloth &&
client_view->production_orders().back().position == new_field;
}, "the loom did not arrive in the guest snapshot");
const auto& orders = client_view->production_orders();
return orders.size() >= 2 && orders.back().recipe == RecipeId::CraftLoom &&
orders[orders.size() - 2].recipe == RecipeId::InstallLoom &&
orders[orders.size() - 2].position == new_field;
}, "the loom installation and workshop order did not arrive in the guest snapshot");
for (int i = 0; i < 160 && authoritative->resource_nodes().back().reserved_workers == 0; ++i) {
authoritative->step();
}
@@ -129,16 +144,40 @@ void test_shared_colony_over_loopback() {
client_view->resource_nodes().back().needs_tending() &&
client_view->resource_nodes().back().reserved_workers == 1;
}, "a snapshot lost the resident's sowing assignment");
RoomPlan room{};
bool found_room = false;
for (int y = 2; y < 29 && !found_room; ++y) {
for (int x = 2; x < 29 && !found_room; ++x) {
const auto candidate = make_room_plan({x, y}, {x + 2, y + 2});
if (!authoritative->can_place_room(candidate)) continue;
room = candidate;
found_room = true;
}
}
require(found_room, "could not find a test plot for a room");
const auto entrance = static_cast<std::uint8_t>(room.entrance);
const auto previous_size = authoritative->production_orders().size();
require(guest.submit(CommandKind::PlaceRoom, room.first, entrance, room.last),
"guest could not send the room");
pump_until([&] {
return client_view->production_orders().size() == previous_size + 10 &&
client_view->production_orders().back().recipe == RecipeId::CraftWoodenDoor;
}, "snapshot did not carry the room and carpenter's order");
require(guest.submit(CommandKind::PlaceRoom, room.first, entrance, room.last),
"guest could not send the conflicting room");
pump_until([&] {
const auto rejected = guest.take_rejection();
return rejected && rejected->kind == CommandKind::PlaceRoom && rejected->cell == room.first &&
rejected->destination == room.last && rejected->value == entrance &&
rejected->status == CommandStatus::InvalidTarget;
}, "room rejection lost the geometry needed to restore the draft");
require(authoritative->production_orders().size() == previous_size + 10, "room conflict scheduled extra work");
std::cout << "Loopback LAN checks passed.\n";
return {};
}
} // namespace
int main() {
try {
test_shared_colony_over_loopback();
} catch (const std::exception& error) {
std::cerr << error.what() << '\n';
return 1;
}
int main(int argc, char** argv) {
return LanTests::run(argc, argv);
}
+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