Windows game sources #2
No files matched your search
@@ -39,7 +39,7 @@
|
||||
- [x] Пул потоков для независимого выбора заданий, A* и продвижения жителей.
|
||||
- [x] Стабильное применение результатов в конце шага симуляции.
|
||||
- [x] Многопоточный режим с двумя и более рабочими потоками; проверка игровых результатов и загрузки.
|
||||
- [x] Выбор числа потоков в командной версии и Windows-клиенте.
|
||||
- [x] Автоматический выбор числа потоков в Windows-клиенте и параметр для командных бенчмарков.
|
||||
- [x] Повторный замер времени тика после расширения систем ресурсов.
|
||||
|
||||
### P4 — Игровой клиент
|
||||
@@ -48,6 +48,7 @@
|
||||
- [x] Отображение источников ресурсов, складов и текущих запасов.
|
||||
- [x] Камера с перемещением и масштабированием относительно курсора.
|
||||
- [x] Нижняя панель с жителями, добычей, участками и строительством.
|
||||
- [x] Главное меню перед игрой со списком сохранений, продолжением партии и подключением к другу.
|
||||
- [ ] Настоящий графический 3D-рендерер и объёмные модели.
|
||||
- [x] Постановка чертежа домика мышью в Windows-клиенте.
|
||||
- [ ] Интерфейс для остальных типов работ и зданий.
|
||||
|
||||
@@ -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_join_id = 1103;
|
||||
constexpr int title_exit_id = 1104;
|
||||
constexpr int title_saves_id = 1105;
|
||||
constexpr int title_open_id = 1106;
|
||||
|
||||
inline std::filesystem::path saves_directory() {
|
||||
const DWORD length = GetEnvironmentVariableW(L"LOCALAPPDATA", nullptr, 0);
|
||||
if (length == 0) return {};
|
||||
std::wstring base(length, L'\0');
|
||||
const DWORD copied = GetEnvironmentVariableW(L"LOCALAPPDATA", base.data(), length);
|
||||
if (copied == 0 || copied >= length) return {};
|
||||
base.resize(copied);
|
||||
return std::filesystem::path(base) / L"Settlement" / L"Saves";
|
||||
}
|
||||
|
||||
class TitleScreen {
|
||||
public:
|
||||
~TitleScreen() {
|
||||
if (list_background_) DeleteObject(list_background_);
|
||||
if (font_) DeleteObject(font_);
|
||||
}
|
||||
|
||||
void create(HWND owner) {
|
||||
constexpr const wchar_t* names[] = {
|
||||
L"Продолжить", L"Новая колония", L"Открыть файл…", L"Подключиться к другу…", L"Выход"
|
||||
};
|
||||
const auto instance = GetModuleHandleW(nullptr);
|
||||
for (std::size_t i = 0; i < buttons_.size(); ++i) {
|
||||
buttons_[i] = CreateWindowExW(0, L"BUTTON", names[i], WS_CHILD | WS_TABSTOP | BS_OWNERDRAW,
|
||||
0, 0, 0, 0, owner, id(title_continue_id + static_cast<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 has_session, bool connecting) const {
|
||||
EnableWindow(buttons_[0], !connecting && (has_session || !saves.empty()));
|
||||
for (std::size_t i = 1; i < buttons_.size() - 1; ++i) EnableWindow(buttons_[i], !connecting);
|
||||
EnableWindow(open_, !connecting && selected_index() < saves.size());
|
||||
EnableWindow(saves_, !connecting);
|
||||
}
|
||||
|
||||
HBRUSH paint_list_background(HWND control, HDC dc) const {
|
||||
if (control != saves_ || !list_background_) return nullptr;
|
||||
SetTextColor(dc, RGB(246, 237, 210));
|
||||
SetBkColor(dc, RGB(44, 63, 53));
|
||||
return list_background_;
|
||||
}
|
||||
|
||||
[[nodiscard]] std::optional<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));
|
||||
// A simple isometric landscape with the same palette as the colony map.
|
||||
const auto old_pen = SelectObject(dc, GetStockObject(NULL_PEN));
|
||||
const auto distant = CreateSolidBrush(RGB(32, 53, 44));
|
||||
const auto near_hills = CreateSolidBrush(RGB(41, 66, 50));
|
||||
const auto old_brush = SelectObject(dc, distant);
|
||||
const POINT hills[] = {{0, height}, {0, height * 5 / 8}, {width / 4, height / 4},
|
||||
{width * 5 / 9, height * 5 / 8}, {width * 5 / 6, height / 4}, {width, height / 2}, {width, height}};
|
||||
Polygon(dc, hills, static_cast<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
|
||||
+144
-54
@@ -8,6 +8,7 @@
|
||||
|
||||
#include "isometric_camera.hpp"
|
||||
#include "lan_session.hpp"
|
||||
#include "title_screen_win32.hpp"
|
||||
#include "settlement/core/world.hpp"
|
||||
|
||||
#include <algorithm>
|
||||
@@ -33,8 +34,7 @@ namespace {
|
||||
|
||||
constexpr wchar_t window_class[] = L"SettlementIsometricViewer";
|
||||
constexpr wchar_t resident_window_class[] = L"SettlementResidentRoster";
|
||||
constexpr int worker_combo_id = 1001;
|
||||
constexpr int apply_button_id = 1002;
|
||||
constexpr int title_menu_id = 1002;
|
||||
constexpr int status_label_id = 1003;
|
||||
constexpr int cabin_button_id = 1004;
|
||||
constexpr int save_menu_id = 1005;
|
||||
@@ -82,8 +82,6 @@ constexpr int work_button_gap = 8;
|
||||
constexpr settlement::GridPosition sawmill{15, 14};
|
||||
constexpr settlement::GridPosition stonecutter{17, 14};
|
||||
|
||||
HWND worker_combo = nullptr;
|
||||
HWND apply_button = nullptr;
|
||||
HWND status_label = nullptr;
|
||||
HWND production_label = nullptr;
|
||||
HWND wood_bed_button = nullptr;
|
||||
@@ -93,10 +91,16 @@ HWND pause_button = nullptr;
|
||||
HWND residents_button = nullptr;
|
||||
std::array<HWND, 3> dock_section_buttons{};
|
||||
std::unique_ptr<settlement::World> world;
|
||||
namespace title = settlement::viewer;
|
||||
title::TitleScreen title_screen;
|
||||
bool showing_title = true;
|
||||
bool has_session = false;
|
||||
HMENU play_menu = nullptr;
|
||||
using settlement::viewer::LanState;
|
||||
settlement::viewer::LanSession lan;
|
||||
LanState displayed_lan_state = LanState::Offline;
|
||||
std::size_t selected_workers = settlement::min_worker_count;
|
||||
const auto local_worker_count = std::clamp<std::size_t>(
|
||||
std::thread::hardware_concurrency(), settlement::min_worker_count, 8);
|
||||
enum class PlacementMode { None, Building, Foraging, BerryField, FlaxField, TreePlot, Mine, Loom, Storage, Pantry, Move, Demolish };
|
||||
PlacementMode placement_mode = PlacementMode::None;
|
||||
enum class WorkPanel { Farmer, Woodcutter, Miner, Builder, Gathering, Zones, Construction, None };
|
||||
@@ -316,7 +320,8 @@ bool shows_bed_choices() {
|
||||
}
|
||||
|
||||
bool is_map_point(const RECT& client, POINT point) {
|
||||
return point.x >= 0 && point.x < client.right && point.y >= map_top && point.y < client.bottom - map_footer;
|
||||
return !showing_title && point.x >= 0 && point.x < client.right &&
|
||||
point.y >= map_top && point.y < client.bottom - map_footer;
|
||||
}
|
||||
|
||||
POINT client_point(LPARAM coordinates) {
|
||||
@@ -832,8 +837,7 @@ void update_status() {
|
||||
L" Заняты: " + std::to_wstring(busy) +
|
||||
L" Выполнено работ: " + std::to_wstring(world->jobs_completed()) +
|
||||
L" Дерево: " + std::to_wstring(wood) + L" Камень: " + std::to_wstring(stone) +
|
||||
L" Ход: " + std::to_wstring(world->tick()) +
|
||||
(lan.is_guest() ? L" Симуляция у хозяина" : L" Потоков: " + std::to_wstring(world->worker_count()));
|
||||
L" Ход: " + std::to_wstring(world->tick());
|
||||
SetWindowTextW(status_label, text.c_str());
|
||||
const bool scenario = world->scenario_active();
|
||||
const bool can_play = can_give_orders();
|
||||
@@ -910,13 +914,41 @@ void toggle_work_panel(HWND window, WorkPanel panel) {
|
||||
SetFocus(window);
|
||||
}
|
||||
|
||||
void show_title_screen(HWND window, bool visible) {
|
||||
showing_title = visible;
|
||||
if (visible) {
|
||||
if (roster.window) DestroyWindow(roster.window);
|
||||
set_work_panel(window, WorkPanel::None);
|
||||
set_placement_mode(window, PlacementMode::None);
|
||||
title_screen.reload_saves();
|
||||
title_screen.update(has_session, lan.state() == LanState::Connecting);
|
||||
} else {
|
||||
has_session = true;
|
||||
}
|
||||
const int flags = visible ? SW_HIDE : SW_SHOWNA;
|
||||
for (const auto control : {status_label, production_label, priority_button, pause_button, residents_button}) {
|
||||
ShowWindow(control, flags);
|
||||
}
|
||||
for (const auto control : dock_section_buttons) ShowWindow(control, flags);
|
||||
title_screen.show(visible);
|
||||
SetMenu(window, visible ? nullptr : play_menu);
|
||||
DrawMenuBar(window);
|
||||
RECT client{};
|
||||
GetClientRect(window, &client);
|
||||
title_screen.layout(client.right, client.bottom);
|
||||
layout_command_dock(window);
|
||||
SetFocus(window);
|
||||
InvalidateRect(window, nullptr, FALSE);
|
||||
}
|
||||
|
||||
void reset_world(HWND window) {
|
||||
world = settlement::make_first_colony(selected_workers);
|
||||
world = settlement::make_first_colony(local_worker_count);
|
||||
camera = {};
|
||||
selected_resident.reset();
|
||||
sync_resident_roster(true);
|
||||
set_work_panel(window, WorkPanel::None);
|
||||
set_placement_mode(window, PlacementMode::None);
|
||||
show_title_screen(window, false);
|
||||
update_status();
|
||||
invalidate_scene(window);
|
||||
}
|
||||
@@ -932,6 +964,12 @@ std::optional<std::filesystem::path> choose_save_file(HWND window, bool saving)
|
||||
dialog.lpstrFile = filename;
|
||||
dialog.nMaxFile = static_cast<DWORD>(std::size(filename));
|
||||
dialog.lpstrDefExt = L"settlement";
|
||||
const auto folder = title::saves_directory();
|
||||
if (!folder.empty()) {
|
||||
std::error_code error;
|
||||
if (saving) std::filesystem::create_directories(folder, error);
|
||||
if (std::filesystem::is_directory(folder, error)) dialog.lpstrInitialDir = folder.c_str();
|
||||
}
|
||||
dialog.Flags = OFN_EXPLORER | OFN_NOCHANGEDIR | OFN_PATHMUSTEXIST |
|
||||
(saving ? OFN_OVERWRITEPROMPT : OFN_FILEMUSTEXIST);
|
||||
const BOOL accepted = saving ? GetSaveFileNameW(&dialog) : GetOpenFileNameW(&dialog);
|
||||
@@ -961,8 +999,8 @@ void save_world_file(const std::filesystem::path& path) {
|
||||
}
|
||||
}
|
||||
|
||||
void handle_save_menu(HWND window, bool saving) {
|
||||
if (file_dialog_active || !world) return;
|
||||
void handle_save_menu(HWND window, bool saving, std::optional<std::filesystem::path> selected = std::nullopt) {
|
||||
if (file_dialog_active || (saving && !world)) return;
|
||||
if (lan.is_guest() || (!saving && lan.state() != LanState::Offline)) return;
|
||||
file_dialog_active = true;
|
||||
struct RestoreTimer {
|
||||
@@ -970,7 +1008,7 @@ void handle_save_menu(HWND window, bool saving) {
|
||||
} restore_timer;
|
||||
|
||||
try {
|
||||
const auto path = choose_save_file(window, saving);
|
||||
const auto path = selected ? std::move(selected) : choose_save_file(window, saving);
|
||||
if (!path) return;
|
||||
if (saving) {
|
||||
save_world_file(*path);
|
||||
@@ -980,15 +1018,17 @@ void handle_save_menu(HWND window, bool saving) {
|
||||
}
|
||||
std::ifstream stream(*path, std::ios::binary);
|
||||
if (!stream) throw std::runtime_error("Could not open the requested save.");
|
||||
auto loaded = settlement::World::read_save(stream, selected_workers);
|
||||
auto loaded = settlement::World::read_save(stream, local_worker_count);
|
||||
if (loaded->width() != map_size || loaded->height() != map_size) {
|
||||
throw std::runtime_error("This viewer opens saves with a 32 by 32 map.");
|
||||
}
|
||||
world = std::move(loaded);
|
||||
camera = {};
|
||||
selected_resident.reset();
|
||||
sync_resident_roster(true);
|
||||
set_work_panel(window, WorkPanel::None);
|
||||
set_placement_mode(window, PlacementMode::None, L"Поселение загружено.");
|
||||
show_title_screen(window, false);
|
||||
update_status();
|
||||
} catch (const std::exception& error) {
|
||||
const std::string_view details(error.what());
|
||||
@@ -1104,17 +1144,15 @@ void refresh_lan_controls(HWND window) {
|
||||
const bool offline = state == LanState::Offline;
|
||||
const bool hosting = state == LanState::Hosting || state == LanState::HostConnected;
|
||||
const bool disconnected = state == LanState::GuestDisconnected;
|
||||
EnableWindow(worker_combo, offline);
|
||||
EnableWindow(apply_button, offline);
|
||||
const auto menu = GetMenu(window);
|
||||
const auto enable = [&](UINT command, bool enabled) {
|
||||
EnableMenuItem(menu, command, MF_BYCOMMAND | (enabled ? MF_ENABLED : MF_GRAYED));
|
||||
if (play_menu) EnableMenuItem(play_menu, command, MF_BYCOMMAND | (enabled ? MF_ENABLED : MF_GRAYED));
|
||||
};
|
||||
enable(lan_host_id, offline);
|
||||
enable(lan_join_id, offline || disconnected);
|
||||
enable(lan_info_id, hosting);
|
||||
enable(lan_reconnect_id, disconnected);
|
||||
enable(lan_leave_id, !offline);
|
||||
enable(title_menu_id, offline);
|
||||
enable(save_menu_id, !lan.is_guest());
|
||||
enable(load_menu_id, offline);
|
||||
const wchar_t* suffix = L"";
|
||||
@@ -1126,24 +1164,29 @@ void refresh_lan_controls(HWND window) {
|
||||
case LanState::GuestConnected: suffix = L" · гость"; break;
|
||||
case LanState::GuestDisconnected: suffix = L" · связь потеряна"; break;
|
||||
}
|
||||
const std::wstring title = std::wstring(L"Settlement — Первое поселение") + suffix;
|
||||
SetWindowTextW(window, title.c_str());
|
||||
const auto caption = std::wstring(showing_title ? L"Settlement" : L"Settlement — Первое поселение") + suffix;
|
||||
SetWindowTextW(window, caption.c_str());
|
||||
if (disconnected) {
|
||||
set_placement_mode(window, PlacementMode::None);
|
||||
placement_message = L"Связь прервана. «Кооператив → Подключиться снова». " + widen_ascii(lan.detail());
|
||||
placement_message = showing_title ? L"Не удалось подключиться. Проверьте адрес и код." :
|
||||
L"Связь прервана. «Кооператив → Подключиться снова». " + widen_ascii(lan.detail());
|
||||
} else if (state == LanState::GuestConnected) {
|
||||
placement_message = L"Подключено к колонии хозяина.";
|
||||
}
|
||||
DrawMenuBar(window);
|
||||
if (roster.window) update_roster_details();
|
||||
update_status();
|
||||
if (showing_title) {
|
||||
title_screen.update(has_session, state == LanState::Connecting);
|
||||
InvalidateRect(window, nullptr, FALSE);
|
||||
}
|
||||
invalidate_scene(window);
|
||||
}
|
||||
|
||||
void handle_lan_menu(HWND window, int command) {
|
||||
try {
|
||||
if (command == lan_host_id && lan.state() == LanState::Offline) {
|
||||
if (!world->scenario_active()) {
|
||||
if (!world || !world->scenario_active()) {
|
||||
throw std::runtime_error("Start the playable colony before hosting.");
|
||||
}
|
||||
lan.host();
|
||||
@@ -1153,6 +1196,7 @@ void handle_lan_menu(HWND window, int command) {
|
||||
(lan.state() == LanState::Offline || lan.state() == LanState::GuestDisconnected)) {
|
||||
const auto request = ask_join_address(window);
|
||||
if (!request) return;
|
||||
if (!world) world = settlement::make_first_colony(local_worker_count);
|
||||
lan.join(narrow_lan_input(request->address.data()), narrow_lan_input(request->code.data()));
|
||||
selected_resident.reset();
|
||||
sync_resident_roster(true);
|
||||
@@ -1175,6 +1219,41 @@ void handle_lan_menu(HWND window, int command) {
|
||||
}
|
||||
}
|
||||
|
||||
void handle_title_command(HWND window, int command, int notification) {
|
||||
if (command == title::title_exit_id && notification == BN_CLICKED) {
|
||||
DestroyWindow(window);
|
||||
return;
|
||||
}
|
||||
if (lan.state() == LanState::Connecting) return;
|
||||
if (command == title::title_saves_id && notification == LBN_SELCHANGE) {
|
||||
title_screen.update(has_session, false);
|
||||
return;
|
||||
}
|
||||
if (command == title::title_join_id && notification == BN_CLICKED) {
|
||||
handle_lan_menu(window, lan_join_id);
|
||||
return;
|
||||
}
|
||||
const bool open_selected = (command == title::title_open_id && notification == BN_CLICKED) ||
|
||||
(command == title::title_saves_id && notification == LBN_DBLCLK);
|
||||
if (!open_selected && (notification != BN_CLICKED ||
|
||||
(command != title::title_new_id && command != title::title_continue_id && command != title::title_browse_id))) {
|
||||
return;
|
||||
}
|
||||
if (lan.state() == LanState::GuestDisconnected) lan.leave();
|
||||
if (open_selected) {
|
||||
if (const auto path = title_screen.selected_save()) handle_save_menu(window, false, path);
|
||||
} else if (command == title::title_new_id) {
|
||||
reset_world(window);
|
||||
} else if (command == title::title_browse_id) {
|
||||
handle_save_menu(window, false);
|
||||
} else if (has_session) {
|
||||
show_title_screen(window, false);
|
||||
} else if (const auto path = title_screen.latest_save()) {
|
||||
handle_save_menu(window, false, path);
|
||||
}
|
||||
refresh_lan_controls(window);
|
||||
}
|
||||
|
||||
const settlement::ResourceNode* berry_source(settlement::GridPosition cell) {
|
||||
for (const auto& node : world->resource_nodes()) {
|
||||
if (node.position == cell && node.type == settlement::ItemType::Berries) return &node;
|
||||
@@ -1714,27 +1793,9 @@ LRESULT CALLBACK window_proc(HWND window, UINT message, WPARAM wparam, LPARAM lp
|
||||
return 0;
|
||||
}
|
||||
case WM_CREATE: {
|
||||
constexpr auto minimum = static_cast<int>(settlement::min_worker_count);
|
||||
const UINT hardware = std::max(static_cast<UINT>(minimum), std::thread::hardware_concurrency());
|
||||
const int max_workers = static_cast<int>(std::min(hardware, 32U));
|
||||
selected_workers = static_cast<std::size_t>(std::min(max_workers, 8));
|
||||
CreateWindowExW(0, L"STATIC", L"Число потоков:", WS_CHILD | WS_VISIBLE,
|
||||
18, 14, 112, 25, window, nullptr, nullptr, nullptr);
|
||||
worker_combo = CreateWindowExW(0, WC_COMBOBOXW, L"", WS_CHILD | WS_VISIBLE | CBS_DROPDOWNLIST,
|
||||
132, 10, 76, 280, window,
|
||||
reinterpret_cast<HMENU>(static_cast<INT_PTR>(worker_combo_id)),
|
||||
GetModuleHandleW(nullptr), nullptr);
|
||||
for (int count = minimum; count <= max_workers; ++count) {
|
||||
const std::wstring option = std::to_wstring(count);
|
||||
SendMessageW(worker_combo, CB_ADDSTRING, 0, reinterpret_cast<LPARAM>(option.c_str()));
|
||||
}
|
||||
SendMessageW(worker_combo, CB_SETCURSEL, static_cast<WPARAM>(selected_workers - settlement::min_worker_count), 0);
|
||||
apply_button = CreateWindowExW(0, L"BUTTON", L"Применить и начать заново", WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON,
|
||||
220, 10, 190, 28, window,
|
||||
reinterpret_cast<HMENU>(static_cast<INT_PTR>(apply_button_id)),
|
||||
GetModuleHandleW(nullptr), nullptr);
|
||||
play_menu = GetMenu(window);
|
||||
status_label = CreateWindowExW(0, L"STATIC", L"", WS_CHILD | WS_VISIBLE,
|
||||
430, 14, 620, 24, window,
|
||||
18, 14, 735, 24, window,
|
||||
reinterpret_cast<HMENU>(static_cast<INT_PTR>(status_label_id)),
|
||||
GetModuleHandleW(nullptr), nullptr);
|
||||
production_label = CreateWindowExW(0, L"STATIC", L"", WS_CHILD | WS_VISIBLE,
|
||||
@@ -1760,17 +1821,29 @@ LRESULT CALLBACK window_proc(HWND window, UINT message, WPARAM wparam, LPARAM lp
|
||||
0, 100, L"", BS_OWNERDRAW, 0);
|
||||
ShowWindow(work_choice_buttons[index], SW_HIDE);
|
||||
}
|
||||
layout_command_dock(window);
|
||||
reset_world(window);
|
||||
title_screen.create(window);
|
||||
show_title_screen(window, true);
|
||||
refresh_lan_controls(window);
|
||||
SetTimer(window, timer_id, 60, nullptr);
|
||||
return 0;
|
||||
}
|
||||
case WM_DRAWITEM:
|
||||
if (const auto* item = reinterpret_cast<const DRAWITEMSTRUCT*>(lparam);
|
||||
item && item->CtlType == ODT_BUTTON && draw_toolbar_button(*item)) return TRUE;
|
||||
item && item->CtlType == ODT_BUTTON) {
|
||||
if (showing_title ? title::TitleScreen::draw_button(*item) : draw_toolbar_button(*item)) return TRUE;
|
||||
}
|
||||
break;
|
||||
case WM_CTLCOLORLISTBOX:
|
||||
if (showing_title) {
|
||||
if (const auto brush = title_screen.paint_list_background(reinterpret_cast<HWND>(lparam),
|
||||
reinterpret_cast<HDC>(wparam))) return reinterpret_cast<LRESULT>(brush);
|
||||
}
|
||||
break;
|
||||
case WM_COMMAND:
|
||||
if (showing_title) {
|
||||
handle_title_command(window, LOWORD(wparam), HIWORD(wparam));
|
||||
return 0;
|
||||
}
|
||||
if (LOWORD(wparam) == residents_button_id && HIWORD(wparam) == BN_CLICKED) {
|
||||
if (world) show_resident_roster(window);
|
||||
return 0;
|
||||
@@ -1825,11 +1898,11 @@ LRESULT CALLBACK window_proc(HWND window, UINT message, WPARAM wparam, LPARAM lp
|
||||
handle_save_menu(window, LOWORD(wparam) == save_menu_id);
|
||||
return 0;
|
||||
}
|
||||
if (LOWORD(wparam) == apply_button_id) {
|
||||
if (lan.state() != LanState::Offline) return 0;
|
||||
const LRESULT selection = SendMessageW(worker_combo, CB_GETCURSEL, 0, 0);
|
||||
if (selection != CB_ERR) selected_workers = static_cast<std::size_t>(selection) + settlement::min_worker_count;
|
||||
reset_world(window);
|
||||
if (LOWORD(wparam) == title_menu_id) {
|
||||
if (lan.state() == LanState::Offline) {
|
||||
show_title_screen(window, true);
|
||||
refresh_lan_controls(window);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
if (LOWORD(wparam) == cabin_button_id && HIWORD(wparam) == BN_CLICKED) {
|
||||
@@ -2016,6 +2089,7 @@ LRESULT CALLBACK window_proc(HWND window, UINT message, WPARAM wparam, LPARAM lp
|
||||
}
|
||||
break;
|
||||
case WM_KEYDOWN:
|
||||
if (showing_title) break;
|
||||
if ((GetKeyState(VK_CONTROL) & 0x8000) == 0 && (wparam == 'H' || wparam == 'Z' || wparam == 'B')) {
|
||||
if ((lparam & (1L << 30)) == 0) {
|
||||
toggle_work_panel(window, wparam == 'H' ? WorkPanel::Gathering :
|
||||
@@ -2039,8 +2113,12 @@ LRESULT CALLBACK window_proc(HWND window, UINT message, WPARAM wparam, LPARAM lp
|
||||
break;
|
||||
case WM_TIMER:
|
||||
if (wparam == timer_id && world) {
|
||||
if (!file_dialog_active && !lan.is_guest()) world->step();
|
||||
if (auto snapshot = lan.poll(*world)) world = std::move(snapshot);
|
||||
if (showing_title && lan.state() != LanState::Connecting) return 0;
|
||||
if (!showing_title && !file_dialog_active && !lan.is_guest()) world->step();
|
||||
if (auto snapshot = lan.poll(*world)) {
|
||||
world = std::move(snapshot);
|
||||
if (showing_title) show_title_screen(window, false);
|
||||
}
|
||||
sync_resident_roster();
|
||||
if (lan.state() != displayed_lan_state) refresh_lan_controls(window);
|
||||
if (const auto rejection = lan.take_rejection()) {
|
||||
@@ -2056,7 +2134,13 @@ LRESULT CALLBACK window_proc(HWND window, UINT message, WPARAM wparam, LPARAM lp
|
||||
case WM_ERASEBKGND:
|
||||
return 1;
|
||||
case WM_SIZE:
|
||||
layout_command_dock(window);
|
||||
if (showing_title) {
|
||||
RECT client{};
|
||||
GetClientRect(window, &client);
|
||||
title_screen.layout(client.right, client.bottom);
|
||||
} else {
|
||||
layout_command_dock(window);
|
||||
}
|
||||
InvalidateRect(window, nullptr, FALSE);
|
||||
break;
|
||||
case WM_PAINT: {
|
||||
@@ -2069,7 +2153,8 @@ LRESULT CALLBACK window_proc(HWND window, UINT message, WPARAM wparam, LPARAM lp
|
||||
HDC buffer = CreateCompatibleDC(target);
|
||||
HBITMAP bitmap = CreateCompatibleBitmap(target, width, height);
|
||||
HGDIOBJ old_bitmap = SelectObject(buffer, bitmap);
|
||||
draw_world(buffer, width, height);
|
||||
if (showing_title) title_screen.draw(buffer, width, height, placement_message);
|
||||
else draw_world(buffer, width, height);
|
||||
const RECT& dirty = paint.rcPaint;
|
||||
BitBlt(target, dirty.left, dirty.top, dirty.right - dirty.left, dirty.bottom - dirty.top,
|
||||
buffer, dirty.left, dirty.top, SRCCOPY);
|
||||
@@ -2082,6 +2167,8 @@ LRESULT CALLBACK window_proc(HWND window, UINT message, WPARAM wparam, LPARAM lp
|
||||
case WM_DESTROY:
|
||||
KillTimer(window, timer_id);
|
||||
lan.leave();
|
||||
if (play_menu && GetMenu(window) != play_menu) DestroyMenu(play_menu);
|
||||
play_menu = nullptr;
|
||||
PostQuitMessage(0);
|
||||
return 0;
|
||||
}
|
||||
@@ -2109,6 +2196,8 @@ int WINAPI wWinMain(HINSTANCE instance, HINSTANCE, PWSTR, int show_command) {
|
||||
HMENU work_menu = create_work_menu();
|
||||
AppendMenuW(file_menu, MF_STRING, save_menu_id, L"Сохранить поселение…");
|
||||
AppendMenuW(file_menu, MF_STRING, load_menu_id, L"Загрузить поселение…");
|
||||
AppendMenuW(file_menu, MF_SEPARATOR, 0, nullptr);
|
||||
AppendMenuW(file_menu, MF_STRING, title_menu_id, L"Главное меню");
|
||||
AppendMenuW(menu_bar, MF_POPUP, reinterpret_cast<UINT_PTR>(file_menu), L"Поселение");
|
||||
AppendMenuW(view_menu, MF_STRING, reset_camera_id, L"Общий план\tHome");
|
||||
AppendMenuW(menu_bar, MF_POPUP, reinterpret_cast<UINT_PTR>(view_menu), L"Вид");
|
||||
@@ -2122,7 +2211,7 @@ int WINAPI wWinMain(HINSTANCE instance, HINSTANCE, PWSTR, int show_command) {
|
||||
AppendMenuW(coop_menu, MF_SEPARATOR, 0, nullptr);
|
||||
AppendMenuW(coop_menu, MF_STRING, lan_leave_id, L"Выйти из сетевой игры");
|
||||
AppendMenuW(menu_bar, MF_POPUP, reinterpret_cast<UINT_PTR>(coop_menu), L"Кооператив");
|
||||
HWND window = CreateWindowExW(0, window_class, L"Settlement — Первое поселение",
|
||||
HWND window = CreateWindowExW(0, window_class, L"Settlement",
|
||||
WS_OVERLAPPEDWINDOW | WS_CLIPCHILDREN, CW_USEDEFAULT, CW_USEDEFAULT, 1120, 752,
|
||||
nullptr, menu_bar, instance, nullptr);
|
||||
if (!window) {
|
||||
@@ -2135,6 +2224,7 @@ int WINAPI wWinMain(HINSTANCE instance, HINSTANCE, PWSTR, int show_command) {
|
||||
MSG message{};
|
||||
while (GetMessageW(&message, nullptr, 0, 0) > 0) {
|
||||
if (roster.window && IsDialogMessageW(roster.window, &message)) continue;
|
||||
if (showing_title && IsDialogMessageW(window, &message)) continue;
|
||||
TranslateMessage(&message);
|
||||
DispatchMessageW(&message);
|
||||
}
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
|
||||
- Ядро симуляции с фиксированными тиками.
|
||||
- Пул потоков для выбора заданий, поиска маршрутов и продвижения жителей.
|
||||
- Настройка числа потоков в командной версии и в Windows-просмотрщике.
|
||||
- Автоматический выбор числа потоков в Windows-клиенте и параметр для командных бенчмарков.
|
||||
- Изометрический прототип карты с жителями, заданиями и маршрутами.
|
||||
- Базовый цикл ресурсов: источник дерева/камня → резервирование → добыча → перенос → склад.
|
||||
- Складской инвентарь со стеками `Wood` и `Stone` и учётом свободной вместимости.
|
||||
@@ -26,6 +26,7 @@
|
||||
- Рост полей и посадок начинается после выполнения поручения фермером или лесорубом. После сбора участка выдаётся новое поручение.
|
||||
- Производительность ядра измерена на колониях с 50–500 жителями, полями, складами и ремеслом. Результаты и команда запуска описаны в [отчёте](../benchmarks/colony-performance.md).
|
||||
- Основные команды собраны в нижней панели «Жители», «Добыча», «Участки» и «Строительство». Меню «Работы» открывает те же команды по профессиям.
|
||||
- Главное меню открывается при запуске. В нём можно начать новую колонию, выбрать сохранение или подключиться к другу.
|
||||
- Поиск ресурсных работ отбирает подходящие поручения по профессиям. Повторные запросы путей используют кэш.
|
||||
- Движение, прогресс работ жителей и поиск маршрутов для общих заданий выполняются в пуле из двух и более потоков. Тесты проверяют игровые результаты, сохранения и команды кооператива.
|
||||
|
||||
|
||||
+6
-4
@@ -6,7 +6,9 @@
|
||||
powershell.exe -NoProfile -ExecutionPolicy Bypass -File .\build.ps1
|
||||
```
|
||||
|
||||
После сборки запустите `build\settlement_viewer.exe`. В списке доступны от двух рабочих потоков до числа логических процессоров компьютера, максимум 32. Нажмите «Применить и начать заново», чтобы применить выбор и перезапустить демонстрационное поселение.
|
||||
После сборки запустите `build\settlement_viewer.exe`. Откроется главное меню. Здесь можно начать новую колонию, продолжить текущую партию, загрузить сохранение или подключиться к другу по локальной сети. Игра автоматически выбирает от двух до восьми рабочих потоков с учётом числа логических процессоров.
|
||||
|
||||
Список показывает файлы `.settlement` из папки `%LOCALAPPDATA%\Settlement\Saves`, начиная с самого свежего. Дважды щёлкните по сохранению или нажмите «Загрузить выбранное». «Открыть файл…» позволяет загрузить сохранение из любой папки. При первом запуске «Продолжить» открывает самое свежее сохранение из списка.
|
||||
|
||||
При запуске без явного параметра командная версия выбирает от двух до восьми потоков с учётом числа логических процессоров. Для ручного выбора используйте `settlement_sim.exe --workers N`, где N от 2 до 32.
|
||||
|
||||
@@ -32,14 +34,14 @@ powershell.exe -NoProfile -ExecutionPolicy Bypass -File .\build.ps1
|
||||
|
||||
Кусты дают ягоды, которые жители несут в кладовую с розовой крышкой. Розовый маршрут ведёт к еде. Чтобы увидеть голод жителя и его груз, щёлкните по фигурке вне режима размещения чертежа.
|
||||
|
||||
В меню «Поселение» выберите «Сохранить поселение…» или «Загрузить поселение…». Время останавливается на время выбора файла. Файл `.settlement` хранит карту, текущий такт, голод, запасы, заказы и маршруты. При загрузке используются рабочие потоки текущего окна. Если файл повреждён или его версия не подходит, окно показывает ошибку и продолжает текущую партию.
|
||||
В меню «Поселение» выберите «Сохранить поселение…» или «Загрузить поселение…». Время останавливается на время выбора файла. Файл `.settlement` хранит карту, текущий такт, голод, запасы, заказы и маршруты. Если файл повреждён или его версия не подходит, окно показывает ошибку и продолжает текущую партию.
|
||||
|
||||
Старые сохранения продолжаются со своими правилами стройки. Кнопка «Применить и начать заново» запускает партию с поэтапной сборкой и стартовым запасом ткани.
|
||||
В одиночной игре «Поселение → Главное меню» останавливает симуляцию. «Продолжить» возвращает к текущей колонии. «Новая колония» запускает отдельную партию с поэтапной сборкой и стартовым запасом ткани. Старые сохранения продолжаются со своими правилами стройки.
|
||||
|
||||
## Кооператив по локальной сети
|
||||
|
||||
1. Запустите одинаковую версию игры на двух компьютерах в одной локальной сети.
|
||||
2. Хозяин открывает свою колонию через «Кооператив → Открыть колонию для друга…» и передаёт гостю IPv4 и код партии. Порт игры — TCP 41727.
|
||||
3. Гость выбирает «Кооператив → Подключиться…» и вводит эти данные. При обрыве связи можно выбрать «Подключиться снова», пока хозяин оставляет партию открытой.
|
||||
3. Гость выбирает «Подключиться к другу…» в главном меню или «Кооператив → Подключиться…» в игре и вводит эти данные. При обрыве связи можно выбрать «Подключиться снова», пока хозяин оставляет партию открытой.
|
||||
|
||||
Оба игрока строят и меняют задания в общей колонии. Хозяин ставит симуляцию на паузу и сохраняет игру. После выхода гостя хозяин может продолжить партию.
|
||||
Reference in new issue
Block a user