From c72c388fe9bc13560be39b8d953911950ed90018 Mon Sep 17 00:00:00 2001 From: Lagg1ng <12+lagg1ng@noreply@faumaray.com> Date: Sat, 28 Nov 2026 16:38:57 +0000 Subject: [PATCH] Import Windows client and LAN simulation --- app/isometric_camera.hpp | 40 + app/lan_session.hpp | 43 + app/lan_session_win32.cpp | 508 +++++++++ app/main.cpp | 234 ++++ app/viewer_win32.cpp | 2142 +++++++++++++++++++++++++++++++++++++ 5 files changed, 2967 insertions(+) create mode 100644 app/isometric_camera.hpp create mode 100644 app/lan_session.hpp create mode 100644 app/lan_session_win32.cpp create mode 100644 app/main.cpp create mode 100644 app/viewer_win32.cpp diff --git a/app/isometric_camera.hpp b/app/isometric_camera.hpp new file mode 100644 index 0000000..0bdf4ba --- /dev/null +++ b/app/isometric_camera.hpp @@ -0,0 +1,40 @@ +#pragma once + +#include +#include + +namespace settlement::viewer { + +struct ScreenPoint { + double x; + double y; +}; + +class IsometricCamera { +public: + [[nodiscard]] double scale() const noexcept { return scale_; } + [[nodiscard]] ScreenPoint offset() const noexcept { return offset_; } + + [[nodiscard]] ScreenPoint to_scene(ScreenPoint screen) const noexcept { + return {(screen.x - offset_.x) / scale_, (screen.y - offset_.y) / scale_}; + } + + void zoom_at(ScreenPoint cursor, double steps) noexcept { + const double next_scale = std::clamp(scale_ * std::pow(1.25, steps), 0.65, 4.0); + if (next_scale == scale_) return; + const ScreenPoint anchor = to_scene(cursor); + scale_ = next_scale; + offset_ = {cursor.x - anchor.x * scale_, cursor.y - anchor.y * scale_}; + } + + void pan(double dx, double dy) noexcept { + offset_.x += dx; + offset_.y += dy; + } + +private: + double scale_ = 1.0; + ScreenPoint offset_{0.0, 0.0}; +}; + +} // namespace settlement::viewer diff --git a/app/lan_session.hpp b/app/lan_session.hpp new file mode 100644 index 0000000..0ee6cef --- /dev/null +++ b/app/lan_session.hpp @@ -0,0 +1,43 @@ +#pragma once + +#include "settlement/core/world.hpp" + +#include +#include +#include +#include + +namespace settlement::viewer { + +enum class LanState { Offline, Hosting, HostConnected, Connecting, GuestConnected, GuestDisconnected }; +inline constexpr std::uint16_t colony_lan_port = 41727; + +class LanSession { +public: + LanSession(); + ~LanSession(); + LanSession(const LanSession&) = delete; + LanSession& operator=(const LanSession&) = delete; + + void host(std::uint16_t port = colony_lan_port, bool loopback_only = false); + void join(std::string address, std::string code, std::uint16_t port = colony_lan_port); + void reconnect(); + void leave() noexcept; + [[nodiscard]] LanState state() const noexcept; + [[nodiscard]] bool is_guest() const noexcept; + [[nodiscard]] std::string join_code() const; + [[nodiscard]] std::uint16_t port() const noexcept; + [[nodiscard]] const std::string& detail() const noexcept; + [[nodiscard]] bool submit(CommandKind kind, GridPosition cell, std::uint8_t value, + GridPosition destination = {}, AgentId resident = 0); + [[nodiscard]] std::optional take_rejection() noexcept; + [[nodiscard]] std::unique_ptr poll(World& world); + +private: + struct Impl; + std::unique_ptr impl_; +}; + +[[nodiscard]] std::string local_lan_addresses(); + +} // namespace settlement::viewer diff --git a/app/lan_session_win32.cpp b/app/lan_session_win32.cpp new file mode 100644 index 0000000..9688c9f --- /dev/null +++ b/app/lan_session_win32.cpp @@ -0,0 +1,508 @@ +#define NOMINMAX +#include +#include +#include +#include + +#include "lan_session.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace settlement::viewer { +namespace { + +using Clock = std::chrono::steady_clock; +using namespace std::chrono_literals; +constexpr std::uint32_t protocol_version = 7; +constexpr std::size_t frame_limit = 4 * 1024 * 1024; +constexpr auto poll_budget = 16; +constexpr std::size_t command_queue_limit = 32; +enum class Message : std::uint8_t { Hello = 1, Snapshot, Command, Receipt, Reject, Ping }; + +struct Socket { + SOCKET handle = INVALID_SOCKET; + + Socket() = default; + explicit Socket(SOCKET raw) : handle(raw) {} + ~Socket() { reset(); } + Socket(const Socket&) = delete; + Socket& operator=(const Socket&) = delete; + Socket(Socket&& other) noexcept : handle(std::exchange(other.handle, INVALID_SOCKET)) {} + Socket& operator=(Socket&& other) noexcept { + if (this != &other) { + reset(); + handle = std::exchange(other.handle, INVALID_SOCKET); + } + return *this; + } + explicit operator bool() const noexcept { return handle != INVALID_SOCKET; } + void reset() noexcept { + if (*this) closesocket(std::exchange(handle, INVALID_SOCKET)); + } +}; + +void set_nonblocking(SOCKET socket) { + u_long enabled = 1; + if (ioctlsocket(socket, static_cast(FIONBIO), &enabled) != 0) { + throw std::runtime_error("Could not configure the socket."); + } +} + +void tune_stream(SOCKET socket) { + const int enabled = 1; + setsockopt(socket, IPPROTO_TCP, TCP_NODELAY, reinterpret_cast(&enabled), sizeof(enabled)); +} + +void append_number(std::string& bytes, std::uint64_t value, unsigned length) { + for (unsigned i = 0; i < length; ++i) { + bytes.push_back(std::bit_cast(static_cast(value))); + value >>= 8U; + } +} + +std::uint64_t number(std::string_view bytes) noexcept { + std::uint64_t value = 0; + for (std::size_t i = 0; i < bytes.size(); ++i) { + value |= static_cast(static_cast(bytes[i])) << (8U * i); + } + return value; +} + +std::string frame(Message message, std::string_view payload = {}) { + if (payload.size() >= frame_limit) throw std::runtime_error("The colony snapshot is too large for LAN play."); + std::string bytes; + bytes.reserve(5 + payload.size()); + append_number(bytes, 1 + payload.size(), 4); + bytes.push_back(static_cast(message)); + bytes.append(payload); + return bytes; +} + +struct Channel { + Socket socket; + std::string input; + std::string output; + std::size_t sent = 0; + Clock::time_point opened = Clock::now(); + Clock::time_point last_received = Clock::now(); + + Channel() = default; + explicit Channel(Socket incoming) : socket(std::move(incoming)) {} + + bool pending() const noexcept { return sent < output.size(); } + + void queue(Message message, std::string_view payload = {}) { + if (sent != 0) { + output.erase(0, sent); + sent = 0; + } + if (output.size() + payload.size() + 5 > frame_limit + 1024) { + throw std::runtime_error("The peer is not receiving data fast enough."); + } + output += frame(message, payload); + } + + void flush() { + if (!pending()) return; + const int size = static_cast(std::min(output.size() - sent, std::size_t{64 * 1024})); + const int written = send(socket.handle, output.data() + sent, size, 0); + if (written == SOCKET_ERROR) { + if (WSAGetLastError() != WSAEWOULDBLOCK) throw std::runtime_error("Connection interrupted."); + return; + } + if (written == 0) throw std::runtime_error("Connection closed."); + sent += static_cast(written); + if (sent == output.size()) { + output.clear(); + sent = 0; + } + } + + template + void receive(Deliver on_message) { + std::array bytes{}; + for (int read = 0; read < poll_budget; ++read) { + const int count = recv(socket.handle, bytes.data(), static_cast(bytes.size()), 0); + if (count == SOCKET_ERROR) { + if (WSAGetLastError() != WSAEWOULDBLOCK) throw std::runtime_error("Connection interrupted."); + break; + } + if (count == 0) throw std::runtime_error("Connection closed."); + last_received = Clock::now(); + input.append(bytes.data(), static_cast(count)); + std::size_t cursor = 0; + while (input.size() - cursor >= 4) { + const std::string_view remaining(input.data() + cursor, input.size() - cursor); + const auto length = number(remaining.substr(0, 4)); + if (length == 0 || length > frame_limit) throw std::runtime_error("Invalid LAN message size."); + const auto end = 4 + static_cast(length); + if (remaining.size() < end) break; + on_message(static_cast(static_cast(remaining[4])), + remaining.substr(5, static_cast(length - 1))); + cursor += end; + } + if (cursor != 0) input.erase(0, cursor); + } + } +}; + +std::uint64_t parse_code(std::string_view code) { + std::uint64_t key = 0; + const auto end = code.data() + code.size(); + const auto result = std::from_chars(code.data(), end, key, 16); + if (code.size() != 16 || result.ec != std::errc{} || result.ptr != end || key == 0) { + throw std::invalid_argument("Enter the 16-character game code from the host."); + } + return key; +} + +std::string format_code(std::uint64_t key) { + std::array digits{}; + const auto result = std::to_chars(digits.data(), digits.data() + digits.size(), key, 16); + const auto size = static_cast(result.ptr - digits.data()); + return std::string(16 - size, '0') + std::string(digits.data(), size); +} + +struct Action { + CommandKind kind; + GridPosition cell; + std::uint8_t value; + GridPosition destination; + AgentId resident; +}; + +} // namespace + +struct LanSession::Impl { + bool winsock = false; + Socket listener; + Channel peer; + bool guest = false; + bool connecting = false; + bool authenticated = false; + bool reject_pending = false; + bool waiting_reply = false; + std::uint16_t network_port = 0; + std::uint64_t key = 0; + std::string host_address; + std::string notice; + std::deque actions; + std::optional rejected_command; + std::uint64_t guest_sequence = 0; + Clock::time_point last_ping{}; + Clock::time_point last_snapshot{}; + std::uint64_t sent_tick = 0; + std::uint64_t sent_host_sequence = 0; + std::uint64_t sent_guest_sequence = 0; + + Impl() { + WSADATA data{}; + winsock = WSAStartup(MAKEWORD(2, 2), &data) == 0; + } + ~Impl() { + peer.socket.reset(); + listener.reset(); + if (winsock) WSACleanup(); + } + + void drop_peer() noexcept { + peer = Channel{}; + connecting = authenticated = reject_pending = waiting_reply = false; + guest_sequence = 0; + actions.clear(); + rejected_command.reset(); + last_snapshot = {}; + last_ping = {}; + } + + void accept_guest() { + if (peer.socket) return; + Socket socket(accept(listener.handle, nullptr, nullptr)); + if (!socket) return; + set_nonblocking(socket.handle); + tune_stream(socket.handle); + drop_peer(); + peer = Channel(std::move(socket)); + } + + void finish_connection() { + fd_set write{}, error{}; + FD_SET(peer.socket.handle, &write); + FD_SET(peer.socket.handle, &error); + timeval instant{}; + const int ready = select(0, nullptr, &write, &error, &instant); + if (ready == SOCKET_ERROR) throw std::runtime_error("Could not connect to the host."); + if (ready == 0) return; + int code = 0; + int length = sizeof(code); + if (FD_ISSET(peer.socket.handle, &error) || + getsockopt(peer.socket.handle, SOL_SOCKET, SO_ERROR, reinterpret_cast(&code), &length) != 0 || + code != 0) { + throw std::runtime_error("Could not connect to the host."); + } + connecting = false; + } + + void handle_host(World& world, Message message, std::string_view payload) { + if (!authenticated) { + if (reject_pending) return; + if (message != Message::Hello || payload.size() != 12 || + number(payload.substr(0, 4)) != protocol_version || number(payload.substr(4)) != key) { + peer.queue(Message::Reject); + reject_pending = true; + return; + } + authenticated = true; + notice.clear(); + return; + } + if (message == Message::Ping && payload.empty()) return; + if (message != Message::Command || payload.size() != 34) throw std::runtime_error("Invalid guest command."); + const PlayerCommand command{2, number(payload.substr(0, 8)), + static_cast(static_cast(payload[8])), + {std::bit_cast(static_cast(number(payload.substr(9, 4)))), + std::bit_cast(static_cast(number(payload.substr(13, 4))))}, + static_cast(payload[17]), + {std::bit_cast(static_cast(number(payload.substr(18, 4)))), + std::bit_cast(static_cast(number(payload.substr(22, 4))))}, + number(payload.substr(26, 8))}; + const auto result = world.apply_command(command); + std::string reply; + append_number(reply, static_cast(result.status), 1); + append_number(reply, world.next_command_sequence(2), 8); + peer.queue(Message::Receipt, reply); + } + + void handle_guest(std::unique_ptr& latest, Message message, std::string_view payload) { + if (message == Message::Reject) throw std::runtime_error("Wrong game code or incompatible version."); + if (message == Message::Snapshot) { + std::istringstream data(std::string(payload), std::ios::binary); + latest = World::read_save(data); + if (!latest->scenario_active() || latest->width() != first_colony_map_size || + latest->height() != first_colony_map_size) { + throw std::runtime_error("The host sent an unsupported colony."); + } + if (!authenticated) guest_sequence = latest->next_command_sequence(2); + authenticated = true; + notice.clear(); + return; + } + if (message != Message::Receipt || payload.size() != 9 || !waiting_reply) { + throw std::runtime_error("Invalid message from the host."); + } + const auto status = static_cast(static_cast(payload[0])); + if (status > CommandStatus::Busy) throw std::runtime_error("Invalid command result."); + if (status != CommandStatus::Accepted) rejected_command = status; + guest_sequence = number(payload.substr(1)); + waiting_reply = false; + } + + void send_snapshot(const World& world, Clock::time_point now) { + if (peer.pending()) return; + const auto host_seq = world.next_command_sequence(1); + const auto guest_seq = world.next_command_sequence(2); + const bool changed = world.tick() != sent_tick || host_seq != sent_host_sequence || guest_seq != sent_guest_sequence; + const auto elapsed = now - last_snapshot; + if (last_snapshot != Clock::time_point{} && elapsed < 2s && + (!changed || (elapsed < 120ms && host_seq == sent_host_sequence && guest_seq == sent_guest_sequence))) return; + std::ostringstream data(std::ios::binary); + world.write_save(data); + peer.queue(Message::Snapshot, data.str()); + last_snapshot = now; + sent_tick = world.tick(); + sent_host_sequence = host_seq; + sent_guest_sequence = guest_seq; + } + + void send_action() { + if (waiting_reply || actions.empty() || guest_sequence == 0 || peer.pending()) return; + const Action action = actions.front(); + std::string payload; + append_number(payload, guest_sequence, 8); + append_number(payload, static_cast(action.kind), 1); + append_number(payload, std::bit_cast(action.cell.x), 4); + append_number(payload, std::bit_cast(action.cell.y), 4); + append_number(payload, action.value, 1); + append_number(payload, std::bit_cast(action.destination.x), 4); + append_number(payload, std::bit_cast(action.destination.y), 4); + append_number(payload, action.resident, 8); + peer.queue(Message::Command, payload); + actions.pop_front(); + waiting_reply = true; + } +}; + +LanSession::LanSession() : impl_(std::make_unique()) {} +LanSession::~LanSession() = default; + +void LanSession::host(std::uint16_t port, bool loopback_only) { + if (!impl_->winsock) throw std::runtime_error("Windows networking is unavailable."); + Socket socket(::socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)); + if (!socket) throw std::runtime_error("Could not open the LAN listener."); + const int exclusive = 1; + setsockopt(socket.handle, SOL_SOCKET, SO_EXCLUSIVEADDRUSE, + reinterpret_cast(&exclusive), sizeof(exclusive)); + sockaddr_in local{}; + local.sin_family = AF_INET; + local.sin_addr.s_addr = htonl(loopback_only ? INADDR_LOOPBACK : INADDR_ANY); + local.sin_port = htons(port); + if (bind(socket.handle, reinterpret_cast(&local), sizeof(local)) != 0 || + listen(socket.handle, 1) != 0) { + throw std::runtime_error("Could not listen on the selected LAN port."); + } + int length = sizeof(local); + if (getsockname(socket.handle, reinterpret_cast(&local), &length) != 0) { + throw std::runtime_error("Could not determine the local LAN port."); + } + std::uint64_t key = 0; + if (BCryptGenRandom(nullptr, reinterpret_cast(&key), sizeof(key), BCRYPT_USE_SYSTEM_PREFERRED_RNG) != 0 || + key == 0) throw std::runtime_error("Could not generate a join code."); + set_nonblocking(socket.handle); + leave(); + impl_->listener = std::move(socket); + impl_->key = key; + impl_->network_port = ntohs(local.sin_port); +} + +void LanSession::join(std::string address, std::string code, std::uint16_t port) { + if (!impl_->winsock) throw std::runtime_error("Windows networking is unavailable."); + const auto key = parse_code(code); + sockaddr_in remote{}; + remote.sin_family = AF_INET; + remote.sin_port = htons(port); + if (InetPtonA(AF_INET, address.c_str(), &remote.sin_addr) != 1 || port == 0) { + throw std::invalid_argument("Enter a valid IPv4 address for the host."); + } + Socket socket(::socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)); + if (!socket) throw std::runtime_error("Could not open the guest connection."); + set_nonblocking(socket.handle); + tune_stream(socket.handle); + const bool pending = connect(socket.handle, reinterpret_cast(&remote), sizeof(remote)) != 0; + if (pending && WSAGetLastError() != WSAEWOULDBLOCK) throw std::runtime_error("Could not connect to the host."); + std::string identity; + append_number(identity, protocol_version, 4); + append_number(identity, key, 8); + Channel channel(std::move(socket)); + channel.queue(Message::Hello, identity); + leave(); + impl_->guest = true; + impl_->connecting = pending; + impl_->network_port = port; + impl_->key = key; + impl_->host_address = std::move(address); + impl_->peer = std::move(channel); +} + +void LanSession::reconnect() { + if (state() == LanState::GuestDisconnected) join(impl_->host_address, join_code(), impl_->network_port); +} + +void LanSession::leave() noexcept { + impl_->drop_peer(); + impl_->listener.reset(); + impl_->guest = false; + impl_->notice.clear(); + impl_->network_port = 0; + impl_->key = 0; + impl_->host_address.clear(); +} + +LanState LanSession::state() const noexcept { + if (impl_->listener) return impl_->authenticated ? LanState::HostConnected : LanState::Hosting; + if (!impl_->guest) return LanState::Offline; + if (!impl_->peer.socket) return LanState::GuestDisconnected; + return impl_->authenticated ? LanState::GuestConnected : LanState::Connecting; +} + +bool LanSession::is_guest() const noexcept { return impl_->guest; } +std::string LanSession::join_code() const { return format_code(impl_->key); } +std::uint16_t LanSession::port() const noexcept { return impl_->network_port; } +const std::string& LanSession::detail() const noexcept { return impl_->notice; } + +bool LanSession::submit(CommandKind kind, GridPosition cell, std::uint8_t value, GridPosition destination, + AgentId resident) { + if (state() != LanState::GuestConnected || impl_->guest_sequence == 0 || kind == CommandKind::SetPaused || + impl_->actions.size() >= command_queue_limit) return false; + impl_->actions.push_back({kind, cell, value, destination, resident}); + return true; +} + +std::optional LanSession::take_rejection() noexcept { + return std::exchange(impl_->rejected_command, std::nullopt); +} + +std::unique_ptr LanSession::poll(World& world) { + auto& connection = *impl_; + std::unique_ptr latest; + try { + if (connection.listener) connection.accept_guest(); + if (!connection.peer.socket) return nullptr; + const auto now = Clock::now(); + if ((!connection.authenticated && now - connection.peer.opened > 8s) || + (connection.authenticated && now - connection.peer.last_received > 15s)) { + throw std::runtime_error("The peer did not respond."); + } + if (connection.connecting) connection.finish_connection(); + if (connection.connecting) return nullptr; + connection.peer.receive([&](Message message, std::string_view payload) { + if (connection.guest) connection.handle_guest(latest, message, payload); + else connection.handle_host(world, message, payload); + }); + if (connection.authenticated && connection.guest) { + connection.send_action(); + if (!connection.peer.pending() && now - connection.last_ping >= 2s) { + connection.peer.queue(Message::Ping); + connection.last_ping = now; + } + } else if (connection.authenticated) { + connection.send_snapshot(world, now); + } + connection.peer.flush(); + if (connection.reject_pending && !connection.peer.pending()) connection.drop_peer(); + } catch (const std::exception& error) { + connection.notice = error.what(); + connection.drop_peer(); + latest.reset(); + } + return latest; +} + +std::string local_lan_addresses() { + constexpr ULONG flags = GAA_FLAG_SKIP_ANYCAST | GAA_FLAG_SKIP_MULTICAST | GAA_FLAG_SKIP_DNS_SERVER; + ULONG size = 15 * 1024; + std::vector buffer(size); + auto* addresses = reinterpret_cast(buffer.data()); + auto result = GetAdaptersAddresses(AF_INET, flags, nullptr, addresses, &size); + if (result == ERROR_BUFFER_OVERFLOW) { + buffer.resize(size); + addresses = reinterpret_cast(buffer.data()); + result = GetAdaptersAddresses(AF_INET, flags, nullptr, addresses, &size); + } + std::string usable; + if (result != NO_ERROR) return usable; + for (auto* adapter = addresses; adapter != nullptr; adapter = adapter->Next) { + if (adapter->OperStatus != IfOperStatusUp || adapter->IfType == IF_TYPE_SOFTWARE_LOOPBACK) continue; + for (auto* addr = adapter->FirstUnicastAddress; addr != nullptr; addr = addr->Next) { + if (addr->Address.lpSockaddr == nullptr || addr->Address.lpSockaddr->sa_family != AF_INET) continue; + const auto* ipv4 = reinterpret_cast(addr->Address.lpSockaddr); + std::array digits{}; + if (!InetNtopA(AF_INET, &ipv4->sin_addr, digits.data(), digits.size())) continue; + if (!usable.empty()) usable += ", "; + usable += digits.data(); + } + } + return usable; +} + +} // namespace settlement::viewer diff --git a/app/main.cpp b/app/main.cpp new file mode 100644 index 0000000..2c04d22 --- /dev/null +++ b/app/main.cpp @@ -0,0 +1,234 @@ +#include "settlement/core/deterministic_rng.hpp" +#include "settlement/core/world.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +struct Options { + std::uint64_t seed = 42; + std::uint64_t agent_count = 50; + std::uint64_t job_count = 3000; + std::uint64_t ticks = 2000; + std::uint64_t warmup_ticks = 100; + std::uint64_t map_size = 160; + std::uint64_t blocked_percent = 8; + std::uint64_t workers = [] { + return static_cast(std::min(8U, + std::max(static_cast(settlement::min_worker_count), std::thread::hardware_concurrency()))); + }(); + std::string svg_path; +}; + +bool parse_u64(std::string_view text, std::uint64_t& value) { + const char* const begin = text.data(); + const char* const end = begin + text.size(); + const auto result = std::from_chars(begin, end, value); + return result.ec == std::errc{} && result.ptr == end; +} + +bool parse_options(int argc, char** argv, Options& options) { + for (int index = 1; index < argc; ++index) { + const std::string_view flag(argv[index]); + if (index + 1 >= argc) { + return false; + } + + const std::string_view value_text(argv[++index]); + if (flag == "--svg") { + options.svg_path = std::string(value_text); + continue; + } + + std::uint64_t value = 0; + if (!parse_u64(value_text, value)) { + return false; + } + + if (flag == "--seed") { + options.seed = value; + } else if (flag == "--agents") { + options.agent_count = value; + } else if (flag == "--jobs") { + options.job_count = value; + } else if (flag == "--ticks") { + options.ticks = value; + } else if (flag == "--warmup") { + options.warmup_ticks = value; + } else if (flag == "--map-size") { + options.map_size = value; + } else if (flag == "--blocked-percent") { + options.blocked_percent = value; + } else if (flag == "--workers") { + options.workers = value; + } else { + return false; + } + } + + constexpr std::uint64_t max_ticks = 1000000; + constexpr std::uint64_t max_agent_ticks = 100000000; + if (options.agent_count > 100000 || options.job_count > 100000 || + options.map_size < 32 || options.map_size > 512 || options.blocked_percent > 30 || + options.ticks > max_ticks || options.warmup_ticks > max_ticks || + options.ticks > max_ticks - options.warmup_ticks || + options.workers < settlement::min_worker_count || options.workers > 32) { + return false; + } + + const std::uint64_t total_ticks = options.ticks + options.warmup_ticks; + const std::uint64_t map_cells = options.map_size * options.map_size; + const std::uint64_t open_cells = map_cells - map_cells * options.blocked_percent / 100; + return (options.agent_count == 0 || total_ticks <= max_agent_ticks / options.agent_count) && + options.job_count <= open_cells; +} + +} // namespace + +int main(int argc, char** argv) { + Options options; + if (!parse_options(argc, argv, options)) { + std::cerr << "Usage: settlement_sim [--seed N] [--agents N] [--jobs N] [--ticks N] " + "[--warmup N] [--map-size N] [--blocked-percent N] [--workers 2..32] [--svg PATH]\n"; + return 2; + } + + try { + const auto map_size = static_cast(options.map_size); + settlement::World world(options.seed, map_size, map_size, + static_cast(options.workers)); + settlement::DeterministicRng terrain_rng(options.seed ^ 0x5445525241494E31ULL); + settlement::DeterministicRng agent_rng(options.seed ^ 0x4147454E545F3031ULL); + settlement::DeterministicRng job_rng(options.seed ^ 0x4A4F42535F303031ULL); + + const std::uint64_t map_cells = options.map_size * options.map_size; + const std::uint64_t blocked_cell_count = map_cells * options.blocked_percent / 100; + std::uint64_t blocked_cells = 0; + while (blocked_cells < blocked_cell_count) { + const std::uint64_t cell = terrain_rng.bounded(map_cells); + const auto x = static_cast(cell % options.map_size); + const auto y = static_cast(cell / options.map_size); + const settlement::GridPosition position{x, y}; + if (world.is_walkable(position)) { + world.set_blocked(position); + ++blocked_cells; + } + } + + const settlement::GridPosition town_center{map_size / 2, map_size / 2}; + const std::int32_t camp_radius = 5; + const std::int32_t job_min_distance = std::max(8, map_size / 10); + std::vector camp_spawn_cells; + std::vector job_spawn_cells; + for (std::int32_t y = 0; y < map_size; ++y) { + for (std::int32_t x = 0; x < map_size; ++x) { + const settlement::GridPosition position{x, y}; + if (!world.is_walkable(position)) { + continue; + } + const std::int32_t dx = x > town_center.x ? x - town_center.x : town_center.x - x; + const std::int32_t dy = y > town_center.y ? y - town_center.y : town_center.y - y; + const std::int32_t distance_from_center = dx + dy; + if (distance_from_center <= camp_radius) { + camp_spawn_cells.push_back(position); + } + if (distance_from_center >= job_min_distance) { + job_spawn_cells.push_back(position); + } + } + } + if (camp_spawn_cells.empty() || options.job_count > job_spawn_cells.size()) { + throw std::runtime_error("map has too few open cells for the selected camp and jobs"); + } + + for (std::size_t index = job_spawn_cells.size(); index > 1; --index) { + const auto other = static_cast(job_rng.bounded(static_cast(index))); + std::swap(job_spawn_cells[index - 1], job_spawn_cells[other]); + } + + for (std::uint64_t index = 0; index < options.agent_count; ++index) { + const auto camp_index = static_cast( + agent_rng.bounded(static_cast(camp_spawn_cells.size()))); + static_cast(world.spawn_agent(camp_spawn_cells[camp_index])); + } + for (std::uint64_t index = 0; index < options.job_count; ++index) { + const std::uint32_t work_required = static_cast(20 + job_rng.bounded(61)); + const auto job_index = static_cast(index); + static_cast(world.add_job(job_spawn_cells[job_index], work_required)); + } + + for (std::uint64_t tick = 0; tick < options.warmup_ticks; ++tick) { + world.step(); + } + if (!options.svg_path.empty()) { + world.write_svg(options.svg_path); + } + + std::vector tick_times_microseconds; + tick_times_microseconds.reserve(static_cast(options.ticks)); + const auto benchmark_start = std::chrono::steady_clock::now(); + for (std::uint64_t tick = 0; tick < options.ticks; ++tick) { + const auto tick_start = std::chrono::steady_clock::now(); + world.step(); + const auto tick_end = std::chrono::steady_clock::now(); + const std::chrono::duration elapsed = tick_end - tick_start; + tick_times_microseconds.push_back(elapsed.count()); + } + const auto benchmark_end = std::chrono::steady_clock::now(); + + std::sort(tick_times_microseconds.begin(), tick_times_microseconds.end()); + const auto percentile = [&tick_times_microseconds](double fraction) { + if (tick_times_microseconds.empty()) { + return 0.0; + } + const auto index = static_cast( + fraction * static_cast(tick_times_microseconds.size() - 1)); + return tick_times_microseconds[index]; + }; + const std::chrono::duration total_elapsed = benchmark_end - benchmark_start; + const double average_microseconds = options.ticks == 0 + ? 0.0 + : total_elapsed.count() * 1000.0 / static_cast(options.ticks); + + const auto active_agents = std::count_if( + world.agents().begin(), world.agents().end(), + [](const settlement::Agent& agent) { return agent.state != settlement::AgentState::Idle; }); + + std::cout << "scenario=work_and_astar\n" + << "seed=" << world.seed() << '\n' + << "map=" << world.width() << 'x' << world.height() << '\n' + << "agents=" << world.agents().size() << '\n' + << "workers=" << world.worker_count() << '\n' + << "jobs=" << world.jobs().size() << '\n' + << "blocked_percent=" << options.blocked_percent << '\n' + << "warmup_ticks=" << options.warmup_ticks << '\n' + << "measured_ticks=" << options.ticks << '\n' + << "world_ticks=" << world.tick() << '\n' + << "active_agents=" << active_agents << '\n' + << "completed_jobs=" << world.jobs_completed() << '\n' + << "path_searches=" << world.path_searches() << '\n' + << "path_nodes_visited=" << world.path_nodes_visited() << '\n' + << "total_ms=" << total_elapsed.count() << '\n' + << "avg_tick_us=" << average_microseconds << '\n' + << "p50_tick_us=" << percentile(0.50) << '\n' + << "p95_tick_us=" << percentile(0.95) << '\n'; + if (!options.svg_path.empty()) { + std::cout << "svg=" << options.svg_path << '\n'; + } + } catch (const std::exception& error) { + std::cerr << "Simulation failed: " << error.what() << '\n'; + return 1; + } + + return 0; +} diff --git a/app/viewer_win32.cpp b/app/viewer_win32.cpp new file mode 100644 index 0000000..0d4c221 --- /dev/null +++ b/app/viewer_win32.cpp @@ -0,0 +1,2142 @@ +#define NOMINMAX +#define UNICODE +#define _UNICODE +#include +#include +#include +#include + +#include "isometric_camera.hpp" +#include "lan_session.hpp" +#include "settlement/core/world.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +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 status_label_id = 1003; +constexpr int cabin_button_id = 1004; +constexpr int save_menu_id = 1005; +constexpr int load_menu_id = 1006; +constexpr int forage_action_id = 1007; +constexpr int priority_button_id = 1008; +constexpr int pause_button_id = 1009; +constexpr int reset_camera_id = 1010; +constexpr int wood_bed_button_id = 1011; +constexpr int stone_bed_button_id = 1012; +constexpr int lan_host_id = 1020; +constexpr int lan_join_id = 1021; +constexpr int lan_info_id = 1022; +constexpr int lan_reconnect_id = 1023; +constexpr int lan_leave_id = 1024; +constexpr int berry_field_id = 1030; +constexpr int tree_plot_id = 1031; +constexpr int mine_id = 1032; +constexpr int storage_id = 1033; +constexpr int pantry_id = 1034; +constexpr int move_id = 1035; +constexpr int demolish_id = 1036; +constexpr int residents_button_id = 1037; +constexpr int flax_field_id = 1038; +constexpr int loom_id = 1039; +constexpr int farmer_menu_id = 1040; +constexpr int builder_menu_id = 1043; +constexpr int first_work_choice_id = 1050; +constexpr int resident_list_id = 1060; +constexpr int first_role_id = 1070; +constexpr int first_dock_section_id = 1080; +constexpr int timer_id = 1; +constexpr int map_size = settlement::first_colony_map_size; +constexpr int tile_width = 24; +constexpr int tile_height = 14; +constexpr int map_origin_y = 86; +constexpr int map_top = 76; +constexpr int map_footer = 166; +constexpr int dock_sections_offset = 40; +constexpr int dock_actions_offset = 110; +constexpr int dock_materials_offset = 77; +constexpr int bed_choice_width = 78; +constexpr int bed_choice_height = 28; +constexpr int work_button_gap = 8; +constexpr settlement::GridPosition sawmill{15, 14}; +constexpr settlement::GridPosition stonecutter{17, 14}; + +HWND worker_combo = nullptr; +HWND apply_button = nullptr; +HWND status_label = nullptr; +HWND production_label = nullptr; +HWND wood_bed_button = nullptr; +HWND stone_bed_button = nullptr; +HWND priority_button = nullptr; +HWND pause_button = nullptr; +HWND residents_button = nullptr; +std::array dock_section_buttons{}; +std::unique_ptr world; +using settlement::viewer::LanState; +settlement::viewer::LanSession lan; +LanState displayed_lan_state = LanState::Offline; +std::size_t selected_workers = settlement::min_worker_count; +enum class PlacementMode { None, Building, Foraging, BerryField, FlaxField, TreePlot, Mine, Loom, Storage, Pantry, Move, Demolish }; +PlacementMode placement_mode = PlacementMode::None; +enum class WorkPanel { Farmer, Woodcutter, Miner, Builder, Gathering, Zones, Construction, None }; +WorkPanel work_panel = WorkPanel::None; +enum class WorkIcon { Berries, Field, Flax, Tree, Pickaxe, Hammer, Loom, Resident, Bed, Wood, Stone, Crate, Pantry, Move, Demolish }; +struct WorkChoice { + int command; + const wchar_t* title; + WorkIcon icon; + int width; + PlacementMode mode = PlacementMode::None; +}; +constexpr std::array farmer_choices = { + WorkChoice{forage_action_id, L"Сбор ягод", WorkIcon::Berries, 113, PlacementMode::Foraging}, + WorkChoice{berry_field_id, L"Поле ягод", WorkIcon::Field, 113, PlacementMode::BerryField}, + WorkChoice{flax_field_id, L"Поле льна", WorkIcon::Flax, 112, PlacementMode::FlaxField}, +}; +constexpr std::array woodcutter_choices = { + WorkChoice{tree_plot_id, L"Посадить деревья", WorkIcon::Tree, 168, PlacementMode::TreePlot}, +}; +constexpr std::array miner_choices = { + WorkChoice{mine_id, L"Шахта", WorkIcon::Pickaxe, 98, PlacementMode::Mine}, +}; +constexpr std::array builder_choices = { + WorkChoice{cabin_button_id, L"Спальное место", WorkIcon::Bed, 153, PlacementMode::Building}, + WorkChoice{loom_id, L"Ткацкий станок", WorkIcon::Loom, 149, PlacementMode::Loom}, + WorkChoice{storage_id, L"Склад", WorkIcon::Crate, 84, PlacementMode::Storage}, + WorkChoice{pantry_id, L"Кладовая", WorkIcon::Pantry, 103, PlacementMode::Pantry}, + WorkChoice{move_id, L"Перенести", WorkIcon::Move, 108, PlacementMode::Move}, + WorkChoice{demolish_id, L"Снести", WorkIcon::Demolish, 90, PlacementMode::Demolish}, +}; +std::array work_choice_buttons{}; +constexpr std::array gathering_choices = {farmer_choices[0], miner_choices[0]}; +constexpr std::array zones_choices = {farmer_choices[1], farmer_choices[2], woodcutter_choices[0], + builder_choices[2], builder_choices[3]}; +constexpr std::array construction_choices = {builder_choices[0], builder_choices[1], + builder_choices[4], builder_choices[5]}; +struct DockSection { + WorkPanel panel; + const wchar_t* title; + WorkIcon icon; +}; +constexpr std::array dock_sections = { + DockSection{WorkPanel::Gathering, L"Добыча", WorkIcon::Pickaxe}, + DockSection{WorkPanel::Zones, L"Участки", WorkIcon::Field}, + DockSection{WorkPanel::Construction, L"Строительство", WorkIcon::Hammer}, +}; +using settlement::Profession; +struct RoleChoice { + Profession role; + const wchar_t* title; + WorkIcon icon; +}; +constexpr std::array role_choices = { + RoleChoice{Profession::Generalist, L"Разнорабочий", WorkIcon::Resident}, + RoleChoice{Profession::Farmer, L"Фермер", WorkIcon::Berries}, + RoleChoice{Profession::Woodcutter, L"Лесоруб", WorkIcon::Tree}, + RoleChoice{Profession::Miner, L"Шахтёр", WorkIcon::Pickaxe}, + RoleChoice{Profession::Builder, L"Строитель", WorkIcon::Hammer}, +}; +struct ResidentRow { + settlement::AgentId id; + Profession role; +}; +struct ResidentRoster { + HWND window = nullptr; + HWND list = nullptr; + HWND current_role = nullptr; + HWND notice = nullptr; + HWND apply = nullptr; + std::array roles{}; + std::vector rows; + std::optional pending_role; + bool updating_selection = false; +}; +ResidentRoster roster; +std::optional selected_bed_base; +std::optional move_source; +settlement::viewer::IsometricCamera camera; +struct CameraDrag { + POINT previous; + bool left_button; + bool moved; +}; +std::optional camera_drag; +bool file_dialog_active = false; +std::optional hover_cell; +std::optional selected_resident; +std::wstring placement_message; + +COLORREF color(int red, int green, int blue) { + return RGB(red, green, blue); +} + +void fill_polygon(HDC dc, const POINT* points, int count, COLORREF fill, COLORREF outline) { + HBRUSH brush = CreateSolidBrush(fill); + HPEN pen = CreatePen(PS_SOLID, 1, outline); + HGDIOBJ old_brush = SelectObject(dc, brush); + HGDIOBJ old_pen = SelectObject(dc, pen); + Polygon(dc, points, count); + SelectObject(dc, old_brush); + SelectObject(dc, old_pen); + DeleteObject(brush); + DeleteObject(pen); +} + +void fill_ellipse(HDC dc, int left, int top, int right, int bottom, + COLORREF fill, COLORREF outline) { + HBRUSH brush = CreateSolidBrush(fill); + HPEN pen = CreatePen(PS_SOLID, 1, outline); + HGDIOBJ old_brush = SelectObject(dc, brush); + HGDIOBJ old_pen = SelectObject(dc, pen); + Ellipse(dc, left, top, right, bottom); + SelectObject(dc, old_brush); + SelectObject(dc, old_pen); + DeleteObject(brush); + DeleteObject(pen); +} + +void draw_work_icon(HDC dc, WorkIcon icon, int x, int y) { + const auto ink = color(54, 61, 58); + const auto wood = color(158, 101, 52); + const auto leaf = color(76, 137, 74); + const auto metal = color(143, 168, 180); + const auto berry = color(180, 62, 103); + const auto blue = color(91, 136, 184); + const int state = SaveDC(dc); + if (state == 0) return; + OffsetViewportOrgEx(dc, x, y, nullptr); + const auto shape = [&](std::initializer_list points, COLORREF fill) { + fill_polygon(dc, points.begin(), static_cast(points.size()), fill, ink); + }; + const auto box = [&](int left, int top, int right, int bottom, COLORREF fill) { + shape({{left, top}, {right, top}, {right, bottom}, {left, bottom}}, fill); + }; + const auto circle = [&](int left, int top, int right, int bottom, COLORREF fill) { + fill_ellipse(dc, left, top, right, bottom, fill, ink); + }; + switch (icon) { + case WorkIcon::Berries: + shape({{8, 7}, {8, 3}, {14, 1}, {13, 5}}, leaf); + circle(2, 5, 9, 12, berry); + circle(9, 5, 16, 12, berry); + circle(5, 9, 13, 17, berry); + break; + case WorkIcon::Field: + shape({{1, 10}, {8, 6}, {16, 10}, {16, 12}, {8, 16}, {1, 12}}, wood); + shape({{8, 11}, {3, 7}, {3, 4}, {7, 5}, {9, 8}, {12, 3}, {15, 3}, {14, 8}}, leaf); + break; + case WorkIcon::Flax: + shape({{5, 15}, {6, 6}, {9, 8}, {10, 4}, {12, 14}, {9, 16}}, leaf); + circle(3, 3, 9, 9, blue); + circle(8, 1, 14, 7, blue); + break; + case WorkIcon::Tree: + box(7, 11, 10, 16, wood); + shape({{8, 1}, {13, 8}, {11, 8}, {15, 13}, {2, 13}, {6, 8}, {4, 8}}, leaf); + break; + case WorkIcon::Pickaxe: + shape({{2, 14}, {10, 4}, {13, 6}, {5, 16}}, wood); + shape({{3, 3}, {8, 1}, {14, 4}, {17, 9}, {12, 6}, {8, 4}}, metal); + break; + case WorkIcon::Hammer: + shape({{2, 14}, {10, 5}, {13, 7}, {5, 16}}, wood); + shape({{9, 1}, {16, 7}, {13, 11}, {6, 5}}, metal); + break; + case WorkIcon::Loom: + box(2, 2, 5, 16, wood); + box(12, 2, 15, 16, wood); + box(2, 2, 15, 5, wood); + box(5, 5, 12, 12, color(240, 230, 201)); + box(2, 12, 15, 14, wood); + break; + case WorkIcon::Resident: + circle(2, 8, 15, 17, blue); + circle(5, 1, 12, 9, color(232, 194, 143)); + break; + case WorkIcon::Bed: + box(1, 4, 3, 15, wood); + box(13, 10, 16, 15, wood); + box(3, 6, 7, 11, color(249, 240, 213)); + box(7, 7, 16, 12, blue); + break; + case WorkIcon::Wood: + box(2, 4, 16, 13, wood); + circle(1, 4, 8, 14, color(214, 166, 98)); + break; + case WorkIcon::Stone: + shape({{1, 12}, {4, 5}, {10, 2}, {15, 7}, {16, 13}, {6, 16}}, metal); + break; + case WorkIcon::Crate: + case WorkIcon::Pantry: + box(2, 4, 15, 15, icon == WorkIcon::Crate ? wood : leaf); + box(1, 3, 16, 7, icon == WorkIcon::Crate ? color(214, 166, 98) : color(152, 183, 108)); + box(7, 8, 10, 11, color(241, 205, 119)); + break; + case WorkIcon::Move: + shape({{1, 8}, {6, 3}, {6, 6}, {11, 6}, {11, 3}, {16, 8}, + {11, 13}, {11, 10}, {6, 10}, {6, 13}}, blue); + break; + case WorkIcon::Demolish: + shape({{3, 5}, {14, 5}, {13, 16}, {4, 16}}, color(181, 102, 87)); + box(6, 2, 11, 5, metal); + box(2, 5, 15, 7, metal); + break; + } + RestoreDC(dc, state); +} + +POINT iso_point(int x, int y, int origin_x, int origin_y) { + return POINT{origin_x + (x - y) * tile_width / 2, + origin_y + (x + y) * tile_height / 2}; +} + +bool shows_bed_choices() { + return world && world->staged_beds() && placement_mode == PlacementMode::Building; +} + +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; +} + +POINT client_point(LPARAM coordinates) { + return {GET_X_LPARAM(coordinates), GET_Y_LPARAM(coordinates)}; +} + +void invalidate_scene(HWND window) { + RECT scene{}; + GetClientRect(window, &scene); + scene.top = map_top; + if (scene.bottom > scene.top) InvalidateRect(window, &scene, FALSE); +} + +void update_camera_drag(POINT point) { + if (!camera_drag) return; + const auto dx = point.x - camera_drag->previous.x; + const auto dy = point.y - camera_drag->previous.y; + if (camera_drag->left_button && !camera_drag->moved && std::abs(dx) < 4 && std::abs(dy) < 4) return; + camera.pan(dx, dy); + camera_drag->previous = point; + camera_drag->moved = true; +} + +std::optional map_cell(const RECT& client, POINT point) { + if (!is_map_point(client, point)) return std::nullopt; + const auto scene = camera.to_scene({static_cast(point.x), static_cast(point.y)}); + const double horizontal = (scene.x - client.right / 2) / (tile_width / 2.0); + const double vertical = (scene.y - map_origin_y) / (tile_height / 2.0); + const double x = std::floor((vertical + horizontal) / 2.0 + 0.5); + const double y = std::floor((vertical - horizontal) / 2.0 + 0.5); + if (x < 0 || y < 0 || x >= map_size || y >= map_size) return std::nullopt; + return settlement::GridPosition{static_cast(x), static_cast(y)}; +} + +void update_map_hover(HWND window, POINT point) { + if (placement_mode == PlacementMode::None) return; + TRACKMOUSEEVENT tracking{sizeof(tracking), TME_LEAVE, window, 0}; + TrackMouseEvent(&tracking); + RECT client{}; + GetClientRect(window, &client); + const auto cell = map_cell(client, point); + if (cell == hover_cell) return; + hover_cell = cell; + placement_message.clear(); + invalidate_scene(window); +} + +void draw_ground_tile(HDC dc, POINT center, COLORREF fill, COLORREF outline) { + const POINT diamond[] = { + {center.x, center.y - tile_height / 2}, + {center.x + tile_width / 2, center.y}, + {center.x, center.y + tile_height / 2}, + {center.x - tile_width / 2, center.y} + }; + fill_polygon(dc, diamond, 4, fill, outline); +} + +void draw_rock(HDC dc, POINT ground_center) { + constexpr int block_height = 17; + const int x = ground_center.x; + const int y = ground_center.y; + const POINT left_face[] = { + {x - tile_width / 2, y}, {x, y + tile_height / 2}, + {x, y + tile_height / 2 - block_height}, {x - tile_width / 2, y - block_height} + }; + const POINT right_face[] = { + {x, y + tile_height / 2}, {x + tile_width / 2, y}, + {x + tile_width / 2, y - block_height}, {x, y + tile_height / 2 - block_height} + }; + const POINT top_face[] = { + {x, y - tile_height / 2 - block_height}, + {x + tile_width / 2, y - block_height}, + {x, y + tile_height / 2 - block_height}, + {x - tile_width / 2, y - block_height} + }; + fill_polygon(dc, left_face, 4, color(91, 109, 103), color(70, 87, 81)); + fill_polygon(dc, right_face, 4, color(67, 84, 79), color(60, 76, 71)); + fill_polygon(dc, top_face, 4, color(132, 148, 132), color(76, 94, 83)); +} + +void draw_resource(HDC dc, POINT center, settlement::ItemType type) { + if (type == settlement::ItemType::Berries) { + fill_ellipse(dc, center.x - 7, center.y - 7, center.x + 7, center.y + 3, + color(77, 135, 67), color(51, 98, 57)); + for (const POINT berry : {POINT{-3, -4}, POINT{1, -1}, POINT{3, -5}}) { + fill_ellipse(dc, center.x + berry.x - 1, center.y + berry.y - 1, + center.x + berry.x + 2, center.y + berry.y + 2, + color(190, 76, 112), color(115, 48, 76)); + } + } else if (type == settlement::ItemType::Flax) { + for (const POINT stalk : {POINT{-5, -4}, POINT{0, -10}, POINT{5, -6}}) { + const LONG x = center.x + stalk.x; + const LONG y = center.y + stalk.y; + const POINT stem[] = {{x - 1, y}, {x + 1, y}, {x + 2, y + 8}, {x, y + 8}}; + fill_polygon(dc, stem, 4, color(114, 160, 79), color(64, 106, 65)); + fill_ellipse(dc, x - 2, y - 3, x + 3, y + 2, color(117, 160, 234), color(61, 86, 156)); + } + } else if (type == settlement::ItemType::Wood) { + HPEN trunk = CreatePen(PS_SOLID, 2, color(104, 83, 54)); + HGDIOBJ old_pen = SelectObject(dc, trunk); + MoveToEx(dc, center.x, center.y + 3, nullptr); + LineTo(dc, center.x, center.y - 8); + SelectObject(dc, old_pen); + DeleteObject(trunk); + fill_ellipse(dc, center.x - 7, center.y - 13, center.x + 1, center.y - 5, + color(71, 128, 69), color(62, 104, 61)); + fill_ellipse(dc, center.x - 1, center.y - 17, center.x + 7, center.y - 9, + color(92, 148, 77), color(62, 104, 61)); + } else { + const POINT rock[] = { + {center.x - 7, center.y + 2}, {center.x - 5, center.y - 5}, + {center.x + 2, center.y - 8}, {center.x + 7, center.y - 2}, + {center.x + 6, center.y + 3} + }; + fill_polygon(dc, rock, 5, color(133, 143, 143), color(86, 100, 101)); + } +} + +void draw_site(HDC dc, POINT center, const settlement::ResourceNode& node) { + using settlement::ResourceSite; + if (node.site == ResourceSite::Mine) { + const int x = center.x; + const int y = center.y; + const POINT pit[] = {{x - 10, y - 1}, {x, y + 5}, {x + 10, y - 1}, {x, y - 7}}; + const POINT beam[] = {{x - 7, y - 2}, {x - 6, y - 10}, {x + 5, y - 10}, {x + 6, y - 2}}; + fill_polygon(dc, beam, 4, color(124, 104, 78), color(66, 62, 53)); + fill_polygon(dc, pit, 4, node.quantity != 0 ? color(68, 75, 79) : color(122, 122, 113), + color(55, 63, 65)); + return; + } + if (node.site != ResourceSite::Natural) { + draw_ground_tile(dc, center, color(161, 125, 80), color(107, 95, 64)); + if (node.quantity == 0) { + if (!node.needs_tending()) { + fill_ellipse(dc, center.x - 4, center.y - 3, center.x + 3, center.y + 1, + color(91, 139, 80), color(64, 91, 62)); + } else if (node.reserved_workers > 0) { + fill_ellipse(dc, center.x - 3, center.y - 2, center.x + 3, center.y + 2, + color(225, 192, 117), color(122, 99, 56)); + } + return; + } + } + draw_resource(dc, center, node.type); +} + +void draw_storage(HDC dc, POINT center, settlement::StorageKind kind) { + const POINT front[] = {{center.x - 7, center.y - 1}, {center.x, center.y + 3}, + {center.x, center.y - 6}, {center.x - 7, center.y - 10}}; + const POINT side[] = {{center.x, center.y + 3}, {center.x + 7, center.y - 1}, + {center.x + 7, center.y - 10}, {center.x, center.y - 6}}; + const POINT lid[] = {{center.x - 7, center.y - 10}, {center.x, center.y - 14}, + {center.x + 7, center.y - 10}, {center.x, center.y - 6}}; + fill_polygon(dc, front, 4, color(165, 111, 59), color(93, 66, 42)); + fill_polygon(dc, side, 4, color(128, 82, 45), color(93, 66, 42)); + const COLORREF lid_color = kind == settlement::StorageKind::Pantry ? color(176, 89, 125) : color(193, 143, 84); + fill_polygon(dc, lid, 4, lid_color, color(93, 66, 42)); +} + +void draw_production(HDC dc, POINT center, const settlement::ProductionOrder& order) { + using settlement::JobState; + using settlement::RecipeId; + if (order.recipe == RecipeId::WeaveCloth) { + const auto [x, y] = center; + const POINT frame[] = {{x - 8, y + 3}, {x - 8, y - 14}, {x + 8, y - 10}, {x + 8, y + 6}}; + const POINT fabric[] = {{x - 5, y - 11}, {x + 5, y - 8}, {x + 5, y + 1}, {x - 5, y - 2}}; + fill_polygon(dc, frame, 4, color(176, 124, 74), color(91, 63, 45)); + fill_polygon(dc, fabric, 4, order.state == JobState::InProgress ? color(250, 230, 170) : + color(227, 216, 194), color(127, 112, 85)); + return; + } + if (!settlement::is_construction(order.recipe)) { + const POINT bench[] = {{center.x - 8, center.y - 4}, {center.x, center.y}, + {center.x + 8, center.y - 4}, {center.x, center.y - 8}}; + const COLORREF fill = order.recipe == RecipeId::SawPlank ? color(180, 118, 69) : color(131, 145, 151); + fill_polygon(dc, bench, 4, fill, color(65, 62, 50)); + return; + } + + if (order.state != JobState::Completed) { + const COLORREF fill = order.state == JobState::Available ? color(145, 191, 205) : + order.delivery_stops.empty() ? color(223, 165, 72) : color(83, 162, 150); + draw_ground_tile(dc, center, fill, color(74, 111, 126)); + if (order.recipe != RecipeId::BuildBed || order.bed_stage == settlement::BedStage::Legacy || + order.bed_stage == settlement::BedStage::Foundation) return; + } + + const int x = center.x; + const int y = center.y; + if (order.recipe == RecipeId::BuildBed) { + const POINT frame[] = {{x - 10, y - 4}, {x, y + 2}, {x + 10, y - 4}, {x, y - 10}}; + const POINT mattress[] = {{x - 8, y - 6}, {x, y - 1}, {x + 8, y - 6}, {x, y - 11}}; + const POINT pillow[] = {{x - 6, y - 6}, {x - 3, y - 4}, {x + 1, y - 6}, {x - 2, y - 8}}; + const auto frame_color = order.bed_base == settlement::BedBase::Stone + ? color(148, 153, 156) : color(156, 103, 63); + fill_polygon(dc, frame, 4, frame_color, color(87, 61, 44)); + if (order.state == JobState::Completed || order.bed_stage == settlement::BedStage::Pillow) { + fill_polygon(dc, mattress, 4, color(116, 146, 186), color(67, 85, 111)); + } + if (order.state == JobState::Completed) { + fill_polygon(dc, pillow, 4, color(244, 234, 206), color(143, 132, 113)); + } + return; + } + const COLORREF outline = color(89, 60, 47); + const POINT front[] = {{x - 11, y - 10}, {x, y - 4}, {x, y + 6}, {x - 11, y}}; + const POINT side[] = {{x, y - 4}, {x + 11, y - 10}, {x + 11, y}, {x, y + 6}}; + const POINT roof_left[] = {{x - 12, y - 10}, {x - 5, y - 20}, {x + 6, y - 14}, {x, y - 4}}; + const POINT roof_right[] = {{x + 6, y - 14}, {x + 12, y - 10}, {x, y - 4}}; + fill_polygon(dc, front, 4, color(210, 158, 98), outline); + fill_polygon(dc, side, 4, color(172, 125, 74), outline); + fill_polygon(dc, roof_left, 4, color(173, 83, 62), outline); + fill_polygon(dc, roof_right, 3, color(135, 63, 53), outline); +} + +POINT resident_position(POINT center, settlement::AgentId id) { + const int offset = static_cast(id % 5) - 2; + return {center.x + offset * 2, center.y - 4}; +} + +POINT resident_anchor(POINT center, const settlement::Agent& agent) { + if (agent.state != settlement::AgentState::Sleeping && world->is_bed_cell(agent.position) && + std::any_of(world->agents().begin(), world->agents().end(), [&](const auto& other) { + return other.state == settlement::AgentState::Sleeping && !other.resting_on_ground && + other.position == agent.position; + })) { + center.x += tile_width / 2; + center.y += tile_height / 2; + } + return resident_position(center, agent.id); +} + +void draw_resident(HDC dc, POINT center, const settlement::Agent& agent) { + using settlement::AgentState; + using settlement::ItemType; + COLORREF body = color(51, 145, 137); + switch (agent.state) { + case AgentState::Idle: body = color(56, 111, 174); break; + case AgentState::Travelling: + case AgentState::FetchingMaterials: body = color(125, 81, 181); break; + case AgentState::Working: body = color(199, 88, 65); break; + case AgentState::Gathering: body = color(193, 143, 64); break; + case AgentState::GoingToEat: + case AgentState::Eating: body = color(189, 89, 134); break; + case AgentState::GoingToSleep: + case AgentState::Sleeping: body = color(78, 99, 147); break; + case AgentState::Hauling: break; + } + const auto [x, y] = resident_anchor(center, agent); + const COLORREF ground = selected_resident == agent.id ? color(248, 218, 107) : color(116, 108, 90); + fill_ellipse(dc, x - 6, y + 7, x + 6, y + 11, ground, color(116, 108, 90)); + if (agent.state == AgentState::Sleeping) { + fill_ellipse(dc, x - 7, y + 1, x + 6, y + 8, body, color(55, 66, 98)); + fill_ellipse(dc, x + 3, y, x + 8, y + 6, color(232, 194, 143), color(113, 88, 64)); + return; + } + fill_ellipse(dc, x - 4, y, x + 4, y + 8, body, color(255, 255, 255)); + fill_ellipse(dc, x - 3, y - 5, x + 3, y + 1, color(232, 194, 143), color(113, 88, 64)); + if (!agent.inventory.empty()) { + const POINT pack[] = {{x + 2, y + 2}, {x + 8, y + 2}, {x + 8, y + 8}, {x + 2, y + 8}}; + COLORREF cargo = color(229, 186, 112); + if (agent.inventory.item_count(ItemType::Berries) > 0) cargo = color(211, 108, 149); + if (agent.inventory.item_count(ItemType::Flax) > 0) cargo = color(135, 172, 235); + if (agent.inventory.item_count(ItemType::Cloth) > 0) cargo = color(244, 232, 204); + fill_polygon(dc, pack, 4, cargo, color(97, 73, 48)); + } +} + +const wchar_t* profession_name(settlement::Profession profession) { + const auto choice = std::find_if(role_choices.begin(), role_choices.end(), + [profession](const auto& entry) { return entry.role == profession; }); + return choice == role_choices.end() ? L"" : choice->title; +} + +const settlement::Agent* selected_agent() { + if (!world || !selected_resident) return nullptr; + const auto& agents = world->agents(); + const auto agent = std::find_if(agents.begin(), agents.end(), + [](const auto& entry) { return entry.id == *selected_resident; }); + return agent == agents.end() ? nullptr : &*agent; +} + +std::span work_choices() { + switch (work_panel) { + case WorkPanel::Farmer: return farmer_choices; + case WorkPanel::Woodcutter: return woodcutter_choices; + case WorkPanel::Miner: return miner_choices; + case WorkPanel::Builder: return builder_choices; + case WorkPanel::Gathering: return gathering_choices; + case WorkPanel::Zones: return zones_choices; + case WorkPanel::Construction: return construction_choices; + case WorkPanel::None: return {}; + } + return {}; +} + +void layout_command_dock(HWND window) { + const auto choices = work_choices(); + RECT client{}; + GetClientRect(window, &client); + const auto width = static_cast(client.right); + const auto height = static_cast(client.bottom); + constexpr int section_widths[] = {112, 112, 112, 160}; + constexpr int sections_width = 112 * 3 + 160 + 3 * work_button_gap; + int section_x = std::max(16, (width - sections_width) / 2); + const auto place = [](HWND button, int x, int y, int w, int h) { + SetWindowPos(button, nullptr, x, y, w, h, SWP_NOZORDER | SWP_NOACTIVATE); + }; + place(residents_button, section_x, height - dock_sections_offset, section_widths[0], 31); + section_x += section_widths[0] + work_button_gap; + for (std::size_t index = 0; index < dock_section_buttons.size(); ++index) { + const int button_width = section_widths[index + 1]; + place(dock_section_buttons[index], section_x, height - dock_sections_offset, button_width, 31); + section_x += button_width + work_button_gap; + } + int row_width = choices.empty() ? 0 : -work_button_gap; + for (const auto& choice : choices) row_width += choice.width + work_button_gap; + int x = std::max(16, (width - row_width) / 2); + for (std::size_t index = 0; index < choices.size(); ++index) { + const auto& choice = choices[index]; + place(work_choice_buttons[index], x, height - dock_actions_offset, choice.width, 28); + if (choice.command == cabin_button_id) { + place(wood_bed_button, x, height - dock_materials_offset, bed_choice_width, bed_choice_height); + place(stone_bed_button, x + bed_choice_width + 4, height - dock_materials_offset, + bed_choice_width, bed_choice_height); + } + x += choice.width + work_button_gap; + } +} + +void invalidate_work_choices() { + const auto choices = work_choices(); + for (std::size_t index = 0; index < choices.size(); ++index) { + InvalidateRect(work_choice_buttons[index], nullptr, FALSE); + } +} + +void set_work_panel(HWND window, WorkPanel panel) { + if (work_panel == panel) return; + work_panel = panel; + const auto choices = work_choices(); + layout_command_dock(window); + for (std::size_t index = 0; index < work_choice_buttons.size(); ++index) { + const auto button = work_choice_buttons[index]; + if (index >= choices.size()) { + ShowWindow(button, SW_HIDE); + continue; + } + const auto& choice = choices[index]; + SetWindowTextW(button, choice.command == cabin_button_id && world && !world->scenario_active() ? + L"Чертёж домика" : choice.title); + ShowWindow(button, SW_SHOWNA); + } + for (const auto button : dock_section_buttons) InvalidateRect(button, nullptr, FALSE); + invalidate_work_choices(); + RECT row{}; + GetClientRect(window, &row); + row.top = row.bottom - map_footer; + InvalidateRect(window, &row, FALSE); +} + +void draw_icon_button(const DRAWITEMSTRUCT& item, WorkIcon icon, bool active, bool dock = false) { + const bool disabled = (item.itemState & ODS_DISABLED) != 0; + const bool pressed = (item.itemState & ODS_SELECTED) != 0; + const auto dc = item.hDC; + RECT box = item.rcItem; + if (dock) { + const bool highlighted = !disabled && (active || pressed); + const auto brush = CreateSolidBrush(highlighted ? color(85, 105, 72) : color(48, 62, 55)); + const auto border = CreateSolidBrush(highlighted ? color(206, 177, 114) : color(92, 106, 86)); + FillRect(dc, &box, brush); + FrameRect(dc, &box, border); + DeleteObject(border); + DeleteObject(brush); + } else { + DrawFrameControl(dc, &box, DFC_BUTTON, DFCS_BUTTONPUSH | (pressed || active ? DFCS_PUSHED : 0U)); + } + InflateRect(&box, -3, -3); + if (!dock && active && !disabled) { + const auto brush = CreateSolidBrush(color(211, 229, 194)); + FillRect(dc, &box, brush); + DeleteObject(brush); + } + + wchar_t title[64]{}; + const int length = GetWindowTextW(item.hwndItem, title, static_cast(std::size(title))); + const auto font = reinterpret_cast(SendMessageW(item.hwndItem, WM_GETFONT, 0, 0)); + const auto previous_font = SelectObject(dc, font ? font : GetStockObject(DEFAULT_GUI_FONT)); + SIZE caption{}; + GetTextExtentPoint32W(dc, title, length, &caption); + constexpr int icon_width = 17; + constexpr int gap = 5; + const int left = std::max(box.left + 2, (box.left + box.right - icon_width - gap - caption.cx) / 2); + const int offset = pressed ? 1 : 0; + draw_work_icon(dc, icon, left + offset, (box.top + box.bottom - icon_width) / 2 + offset); + + RECT caption_box{left + icon_width + gap + offset, box.top + offset, box.right - 1, box.bottom + offset}; + const auto previous_mode = SetBkMode(dc, TRANSPARENT); + const auto previous_color = SetTextColor(dc, dock ? (disabled ? color(165, 174, 162) : color(246, 240, 220)) : + GetSysColor(disabled ? COLOR_GRAYTEXT : COLOR_BTNTEXT)); + DrawTextW(dc, title, length, &caption_box, DT_SINGLELINE | DT_VCENTER | DT_END_ELLIPSIS | DT_NOPREFIX); + SetTextColor(dc, previous_color); + SetBkMode(dc, previous_mode); + if (previous_font) SelectObject(dc, previous_font); + if ((item.itemState & (ODS_FOCUS | ODS_NOFOCUSRECT)) == ODS_FOCUS) DrawFocusRect(dc, &box); +} + +bool draw_toolbar_button(const DRAWITEMSTRUCT& item) { + const auto id = static_cast(item.CtlID); + switch (id) { + case wood_bed_button_id: draw_icon_button(item, WorkIcon::Wood, selected_bed_base == settlement::BedBase::Wood, true); return true; + case stone_bed_button_id: draw_icon_button(item, WorkIcon::Stone, selected_bed_base == settlement::BedBase::Stone, true); return true; + case residents_button_id: draw_icon_button(item, WorkIcon::Resident, roster.window != nullptr, true); return true; + } + if (id >= first_dock_section_id && static_cast(id - first_dock_section_id) < dock_sections.size()) { + const auto& section = dock_sections[static_cast(id - first_dock_section_id)]; + draw_icon_button(item, section.icon, work_panel == section.panel, true); + return true; + } + const auto choices = work_choices(); + if (id < first_work_choice_id || static_cast(id - first_work_choice_id) >= choices.size()) return false; + const auto& choice = choices[static_cast(id - first_work_choice_id)]; + draw_icon_button(item, choice.icon, placement_mode == choice.mode, true); + return true; +} + +bool can_give_orders() { + return !lan.is_guest() || lan.state() == LanState::GuestConnected; +} + +void update_roster_details() { + const auto* resident = selected_agent(); + const auto role = resident ? profession_name(resident->profession) : L""; + const std::wstring title = resident ? L"Текущая роль: " + std::wstring(role) : L"Выберите жителя в списке."; + SetWindowTextW(roster.current_role, title.c_str()); + const bool can_assign = resident && can_give_orders(); + EnableWindow(roster.apply, can_assign && roster.pending_role && *roster.pending_role != resident->profession); + for (const auto button : roster.roles) { + EnableWindow(button, can_assign); + InvalidateRect(button, nullptr, FALSE); + } +} + +void sync_resident_roster(bool update_selection = false) { + if (!roster.window) return; + const auto& agents = world->agents(); + const bool rows_changed = !std::equal(agents.begin(), agents.end(), roster.rows.begin(), roster.rows.end(), + [](const auto& agent, const auto& row) { return agent.id == row.id && agent.profession == row.role; }); + if (!rows_changed && !update_selection) return; + if (rows_changed) { + const auto old_count = roster.rows.size(); + roster.rows.clear(); + roster.rows.reserve(agents.size()); + for (const auto& agent : agents) roster.rows.push_back({agent.id, agent.profession}); + roster.updating_selection = true; + if (old_count != roster.rows.size()) { + ListView_SetItemCountEx(roster.list, static_cast(roster.rows.size()), LVSICF_NOSCROLL); + } + roster.updating_selection = false; + InvalidateRect(roster.list, nullptr, FALSE); + std::array counts{}; + for (const auto& row : roster.rows) { + for (std::size_t index = 0; index < role_choices.size(); ++index) { + if (row.role == role_choices[index].role) ++counts[index]; + } + } + for (std::size_t index = 0; index < role_choices.size(); ++index) { + const auto title = std::wstring(role_choices[index].title) + L" (" + std::to_wstring(counts[index]) + L")"; + SetWindowTextW(roster.roles[index], title.c_str()); + } + } + + if (update_selection) { + roster.pending_role.reset(); + SetWindowTextW(roster.notice, L""); + } + const auto row = std::find_if(roster.rows.begin(), roster.rows.end(), + [](const auto& entry) { return selected_resident == entry.id; }); + const int index = row == roster.rows.end() ? -1 : static_cast(row - roster.rows.begin()); + if (ListView_GetNextItem(roster.list, -1, LVNI_SELECTED) != index) { + roster.updating_selection = true; + ListView_SetItemState(roster.list, -1, 0, LVIS_SELECTED | LVIS_FOCUSED); + if (index >= 0) { + ListView_SetItemState(roster.list, index, LVIS_SELECTED | LVIS_FOCUSED, LVIS_SELECTED | LVIS_FOCUSED); + if (update_selection) ListView_EnsureVisible(roster.list, index, FALSE); + } + roster.updating_selection = false; + } + update_roster_details(); +} + +void update_status() { + if (status_label == nullptr || !world) return; + const auto busy = std::count_if(world->agents().begin(), world->agents().end(), + [](const settlement::Agent& agent) { return agent.state != settlement::AgentState::Idle; }); + std::uint64_t wood = 0; + std::uint64_t stone = 0; + std::uint64_t planks = 0; + std::uint64_t blocks = 0; + std::uint64_t berries = 0; + std::uint64_t cloth = 0; + std::uint64_t flax = 0; + for (const settlement::Storage& storage : world->storages()) { + wood += storage.item_count(settlement::ItemType::Wood); + stone += storage.item_count(settlement::ItemType::Stone); + planks += storage.item_count(settlement::ItemType::Plank); + blocks += storage.item_count(settlement::ItemType::StoneBlock); + berries += storage.item_count(settlement::ItemType::Berries); + cloth += storage.item_count(settlement::ItemType::Cloth); + flax += storage.item_count(settlement::ItemType::Flax); + } + const std::wstring text = L"Жители: " + std::to_wstring(world->agents().size()) + + L" Заняты: " + std::to_wstring(busy) + + L" Выполнено работ: " + std::to_wstring(world->jobs_completed()) + + L" Дерево: " + std::to_wstring(wood) + L" Камень: " + std::to_wstring(stone) + + L" Ход: " + std::to_wstring(world->tick()) + + (lan.is_guest() ? L" Симуляция у хозяина" : L" Потоков: " + std::to_wstring(world->worker_count())); + SetWindowTextW(status_label, text.c_str()); + const bool scenario = world->scenario_active(); + const bool can_play = can_give_orders(); + if (work_panel != WorkPanel::None && !can_play) { + set_work_panel(GetParent(residents_button), WorkPanel::None); + } + for (const HWND button : dock_section_buttons) EnableWindow(button, can_play); + EnableWindow(priority_button, scenario && can_play); + EnableWindow(pause_button, scenario && !lan.is_guest()); + const wchar_t* priority = L"Равный приоритет"; + if (world->work_priority() == settlement::WorkPriority::FoodFirst) priority = L"Сначала еда"; + else if (world->work_priority() == settlement::WorkPriority::BuildingFirst) priority = L"Сначала стройка"; + SetWindowTextW(priority_button, priority); + SetWindowTextW(pause_button, world->paused() ? L"Продолжить" : L"Пауза"); + if (scenario && production_label != nullptr) { + const auto progress = world->scenario_progress(); + const auto sleeping = std::count_if(world->agents().begin(), world->agents().end(), + [](const auto& agent) { return agent.state == settlement::AgentState::Sleeping; }); + const std::wstring goal = (progress.completed ? std::wstring(L"Цель выполнена ") : std::wstring{}) + + L"Спальные места " + std::to_wstring(progress.assigned_beds) + L"/" + + std::to_wstring(progress.residents) + L" Еда " + std::to_wstring(progress.available_food) + + L"/" + std::to_wstring(progress.food_goal) + L" Ткань " + std::to_wstring(cloth) + + L" Лён " + std::to_wstring(flax) + L" Спят " + std::to_wstring(sleeping); + SetWindowTextW(production_label, goal.c_str()); + return; + } + if (production_label != nullptr) { + unsigned waiting = 0; + unsigned carrying = 0; + unsigned building = 0; + unsigned built = 0; + for (const auto& order : world->production_orders()) { + if (order.recipe != settlement::RecipeId::BuildCabin) continue; + if (order.state == settlement::JobState::Available) ++waiting; + else if (order.state == settlement::JobState::Completed) ++built; + else if (order.delivery_stops.empty()) ++building; + else ++carrying; + } + const auto hungry = std::count_if(world->agents().begin(), world->agents().end(), + [](const settlement::Agent& agent) { return agent.hungry(); }); + const std::wstring production = L"Ягоды: " + std::to_wstring(berries) + + L" Голодны: " + std::to_wstring(hungry) + L" Доски: " + std::to_wstring(planks) + + L" Блоки: " + std::to_wstring(blocks) + L" Лён: " + std::to_wstring(flax) + + L" Ткань: " + std::to_wstring(cloth) + L" Домики В очереди: " + std::to_wstring(waiting) + + L" Доставка: " + std::to_wstring(carrying) + L" Строятся: " + std::to_wstring(building) + + L" Готовы: " + std::to_wstring(built); + SetWindowTextW(production_label, production.c_str()); + } +} + +void update_bed_choices() { + const int visibility = shows_bed_choices() ? SW_SHOW : SW_HIDE; + ShowWindow(wood_bed_button, visibility); + ShowWindow(stone_bed_button, visibility); + InvalidateRect(wood_bed_button, nullptr, FALSE); + InvalidateRect(stone_bed_button, nullptr, FALSE); +} + +void set_placement_mode(HWND window, PlacementMode mode, const wchar_t* message = L"") { + placement_mode = mode; + selected_bed_base.reset(); + move_source.reset(); + hover_cell.reset(); + placement_message = message; + update_bed_choices(); + invalidate_work_choices(); + invalidate_scene(window); +} + +void toggle_work_panel(HWND window, WorkPanel panel) { + if (!can_give_orders()) return; + set_placement_mode(window, PlacementMode::None); + set_work_panel(window, work_panel == panel ? WorkPanel::None : panel); + SetFocus(window); +} + +void reset_world(HWND window) { + world = settlement::make_first_colony(selected_workers); + camera = {}; + selected_resident.reset(); + sync_resident_roster(true); + set_work_panel(window, WorkPanel::None); + set_placement_mode(window, PlacementMode::None); + update_status(); + invalidate_scene(window); +} + +std::optional choose_save_file(HWND window, bool saving) { + wchar_t filename[32768]{}; + constexpr std::wstring_view default_name = L"Поселение.settlement"; + if (saving) std::copy(default_name.begin(), default_name.end(), filename); + OPENFILENAMEW dialog{}; + dialog.lStructSize = sizeof(dialog); + dialog.hwndOwner = window; + dialog.lpstrFilter = L"Сохранение поселения (*.settlement)\0*.settlement\0Все файлы\0*.*\0"; + dialog.lpstrFile = filename; + dialog.nMaxFile = static_cast(std::size(filename)); + dialog.lpstrDefExt = L"settlement"; + dialog.Flags = OFN_EXPLORER | OFN_NOCHANGEDIR | OFN_PATHMUSTEXIST | + (saving ? OFN_OVERWRITEPROMPT : OFN_FILEMUSTEXIST); + const BOOL accepted = saving ? GetSaveFileNameW(&dialog) : GetOpenFileNameW(&dialog); + if (accepted) return std::filesystem::path(filename); + if (CommDlgExtendedError() != 0) throw std::runtime_error("Could not open the file picker."); + return std::nullopt; +} + +void save_world_file(const std::filesystem::path& path) { + // Stage the complete file beside its destination before replacing an existing save. + wchar_t temporary[MAX_PATH]{}; + if (GetTempFileNameW(path.parent_path().c_str(), L"stl", 0, temporary) == 0) { + throw std::runtime_error("Could not create a temporary save in this folder."); + } + try { + std::ofstream stream(std::filesystem::path(temporary), std::ios::binary | std::ios::trunc); + if (!stream) throw std::runtime_error("Could not open the temporary save for writing."); + world->write_save(stream); + stream.close(); + if (!stream) throw std::runtime_error("Could not finish writing the temporary save."); + if (!MoveFileExW(temporary, path.c_str(), MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH)) { + throw std::runtime_error("Could not move the completed save into place."); + } + } catch (...) { + DeleteFileW(temporary); + throw; + } +} + +void handle_save_menu(HWND window, bool saving) { + if (file_dialog_active || !world) return; + if (lan.is_guest() || (!saving && lan.state() != LanState::Offline)) return; + file_dialog_active = true; + struct RestoreTimer { + ~RestoreTimer() { file_dialog_active = false; } + } restore_timer; + + try { + const auto path = choose_save_file(window, saving); + if (!path) return; + if (saving) { + save_world_file(*path); + placement_message = L"Поселение сохранено."; + invalidate_scene(window); + return; + } + 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); + 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); + selected_resident.reset(); + sync_resident_roster(true); + set_work_panel(window, WorkPanel::None); + set_placement_mode(window, PlacementMode::None, L"Поселение загружено."); + update_status(); + } catch (const std::exception& error) { + const std::string_view details(error.what()); + const std::wstring message = std::wstring(saving ? L"Не удалось сохранить поселение.\n" : + L"Не удалось загрузить поселение.\n") + + std::wstring(details.begin(), details.end()); + MessageBoxW(window, message.c_str(), L"Поселение", MB_OK | MB_ICONERROR); + } +} + +std::wstring widen_ascii(std::string_view text) { + return {text.begin(), text.end()}; +} + +struct JoinForm { + std::array address{}; + std::array code{}; +}; + +INT_PTR CALLBACK join_dialog_proc(HWND dialog, UINT message, WPARAM wparam, LPARAM lparam) { + constexpr int address_id = 10; + constexpr int code_id = 11; + switch (message) { + case WM_INITDIALOG: { + SetWindowLongPtrW(dialog, DWLP_USER, static_cast(lparam)); + SetWindowTextW(dialog, L"Подключиться к поселению"); + const auto control = [&](const wchar_t* type, const wchar_t* title, DWORD style, DWORD ex_style, + int id, RECT units) { + MapDialogRect(dialog, &units); + const HWND child = CreateWindowExW(ex_style, type, title, WS_CHILD | WS_VISIBLE | style, + units.left, units.top, units.right - units.left, units.bottom - units.top, dialog, + reinterpret_cast(static_cast(id)), GetModuleHandleW(nullptr), nullptr); + SendMessageW(child, WM_SETFONT, reinterpret_cast(GetStockObject(DEFAULT_GUI_FONT)), TRUE); + return child; + }; + control(L"STATIC", L"IPv4 хозяина", 0, 0, 0, {10, 13, 77, 26}); + const HWND address = control(L"EDIT", L"", WS_TABSTOP | ES_AUTOHSCROLL, WS_EX_CLIENTEDGE, + address_id, {82, 10, 216, 25}); + control(L"STATIC", L"Код партии", 0, 0, 0, {10, 38, 77, 51}); + const HWND code = control(L"EDIT", L"", WS_TABSTOP | ES_AUTOHSCROLL, WS_EX_CLIENTEDGE, + code_id, {82, 35, 216, 50}); + SendMessageW(address, EM_SETLIMITTEXT, 63, 0); + SendMessageW(code, EM_SETLIMITTEXT, 31, 0); + control(L"BUTTON", L"Подключиться", WS_TABSTOP | BS_DEFPUSHBUTTON, 0, IDOK, {68, 62, 151, 79}); + control(L"BUTTON", L"Отмена", WS_TABSTOP | BS_PUSHBUTTON, 0, IDCANCEL, {158, 62, 216, 79}); + SendMessageW(dialog, DM_SETDEFID, IDOK, 0); + SetFocus(address); + return FALSE; + } + case WM_COMMAND: + if (LOWORD(wparam) == IDOK) { + auto* form = reinterpret_cast(GetWindowLongPtrW(dialog, DWLP_USER)); + GetDlgItemTextW(dialog, address_id, form->address.data(), static_cast(form->address.size())); + GetDlgItemTextW(dialog, code_id, form->code.data(), static_cast(form->code.size())); + EndDialog(dialog, IDOK); + return TRUE; + } + if (LOWORD(wparam) == IDCANCEL) { + EndDialog(dialog, IDCANCEL); + return TRUE; + } + break; + case WM_CLOSE: + EndDialog(dialog, IDCANCEL); + return TRUE; + } + return FALSE; +} + +std::optional ask_join_address(HWND window) { + struct alignas(DWORD) EmptyDialog { + DLGTEMPLATE header{}; + WORD menu = 0; + WORD window_class = 0; + WORD title = 0; + } layout; + layout.header.style = WS_POPUP | WS_CAPTION | WS_SYSMENU | DS_MODALFRAME | DS_CENTER; + layout.header.cx = 226; + layout.header.cy = 91; + JoinForm values; + const auto result = DialogBoxIndirectParamW(GetModuleHandleW(nullptr), &layout.header, window, join_dialog_proc, + reinterpret_cast(&values)); + if (result == -1) throw std::runtime_error("Could not display the connection window."); + if (result != IDOK) return std::nullopt; + return values; +} + +std::string narrow_lan_input(std::wstring_view value) { + const auto begin = value.find_first_not_of(L" \t"); + if (begin == std::wstring_view::npos) return {}; + value = value.substr(begin, value.find_last_not_of(L" \t") - begin + 1); + std::string ascii; + for (const auto letter : value) { + if (letter > 127) throw std::invalid_argument("Use ASCII digits and letters for the address and code."); + ascii.push_back(static_cast(letter)); + } + return ascii; +} + +void show_lan_info(HWND window) { + const auto addresses = settlement::viewer::local_lan_addresses(); + const auto text = L"Передайте другу IPv4 вашего компьютера и код партии.\n\nIPv4: " + + (addresses.empty() ? std::wstring(L"см. ipconfig") : widen_ascii(addresses)) + + L"\nКод партии: " + widen_ascii(lan.join_code()) + + L"\nПорт TCP: " + std::to_wstring(lan.port()) + + L"\n\nДруг в той же сети выбирает «Кооператив → Подключиться…»."; + MessageBoxW(window, text.c_str(), L"Кооператив по локальной сети", MB_OK | MB_ICONINFORMATION); +} + +void refresh_lan_controls(HWND window) { + const auto state = lan.state(); + displayed_lan_state = state; + const bool offline = state == LanState::Offline; + const bool hosting = state == LanState::Hosting || state == LanState::HostConnected; + const bool disconnected = state == LanState::GuestDisconnected; + EnableWindow(worker_combo, offline); + EnableWindow(apply_button, offline); + const auto menu = GetMenu(window); + const auto enable = [&](UINT command, bool enabled) { + EnableMenuItem(menu, command, MF_BYCOMMAND | (enabled ? MF_ENABLED : MF_GRAYED)); + }; + enable(lan_host_id, offline); + enable(lan_join_id, offline || disconnected); + enable(lan_info_id, hosting); + enable(lan_reconnect_id, disconnected); + enable(lan_leave_id, !offline); + enable(save_menu_id, !lan.is_guest()); + enable(load_menu_id, offline); + const wchar_t* suffix = L""; + switch (state) { + case LanState::Offline: break; + case LanState::Hosting: suffix = L" · ждём гостя"; break; + case LanState::HostConnected: suffix = L" · хозяин, гость подключён"; break; + case LanState::Connecting: suffix = L" · подключение"; break; + 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()); + if (disconnected) { + set_placement_mode(window, PlacementMode::None); + placement_message = L"Связь прервана. «Кооператив → Подключиться снова». " + widen_ascii(lan.detail()); + } else if (state == LanState::GuestConnected) { + placement_message = L"Подключено к колонии хозяина."; + } + DrawMenuBar(window); + if (roster.window) update_roster_details(); + update_status(); + 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()) { + throw std::runtime_error("Start the playable colony before hosting."); + } + lan.host(); + refresh_lan_controls(window); + show_lan_info(window); + } else if (command == lan_join_id && + (lan.state() == LanState::Offline || lan.state() == LanState::GuestDisconnected)) { + const auto request = ask_join_address(window); + if (!request) return; + lan.join(narrow_lan_input(request->address.data()), narrow_lan_input(request->code.data())); + selected_resident.reset(); + sync_resident_roster(true); + set_work_panel(window, WorkPanel::None); + set_placement_mode(window, PlacementMode::None, L"Подключаемся к хозяину…"); + } else if (command == lan_info_id && !lan.is_guest() && lan.state() != LanState::Offline) { + show_lan_info(window); + return; + } else if (command == lan_reconnect_id) { + lan.reconnect(); + } else if (command == lan_leave_id) { + lan.leave(); + set_work_panel(window, WorkPanel::None); + set_placement_mode(window, PlacementMode::None, L"Сетевая игра завершена."); + } + refresh_lan_controls(window); + } catch (const std::exception& error) { + const auto text = L"Не удалось выполнить действие.\n" + widen_ascii(error.what()); + MessageBoxW(window, text.c_str(), L"Кооператив", MB_OK | MB_ICONERROR); + } +} + +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; + } + return nullptr; +} + +settlement::CommandStatus submit_command(settlement::CommandKind kind, settlement::GridPosition cell, + std::uint8_t value, settlement::GridPosition destination = {}, + settlement::AgentId resident = 0) { + if (lan.is_guest()) { + return lan.submit(kind, cell, value, destination, resident) ? settlement::CommandStatus::Accepted : + settlement::CommandStatus::Unavailable; + } + constexpr auto host = settlement::colony_host; + return world->apply_command({host, world->next_command_sequence(host), kind, cell, value, destination, resident}).status; +} + +bool send_command(settlement::CommandKind kind, settlement::GridPosition cell = {}, std::uint8_t value = 0) { + return submit_command(kind, cell, value) == settlement::CommandStatus::Accepted; +} + +bool valid_edit_cell(settlement::GridPosition cell) { + using settlement::CommandStatus; + using settlement::ResourceSite; + switch (placement_mode) { + case PlacementMode::Foraging: return berry_source(cell) != nullptr; + case PlacementMode::BerryField: return world->can_place_site(cell, ResourceSite::BerryField); + case PlacementMode::FlaxField: return world->can_place_site(cell, ResourceSite::FlaxField); + case PlacementMode::TreePlot: return world->can_place_site(cell, ResourceSite::TreePlot); + case PlacementMode::Mine: return world->can_place_site(cell, ResourceSite::Mine); + case PlacementMode::Storage: + case PlacementMode::Loom: + case PlacementMode::Pantry: return world->can_place_storage(cell); + case PlacementMode::Move: + return move_source ? world->can_place_storage(cell) : world->object_status(cell, true) == CommandStatus::Accepted; + case PlacementMode::Demolish: return world->object_status(cell, false) == CommandStatus::Accepted; + case PlacementMode::Building: + return world->scenario_active() ? world->can_place_bed(cell) : world->can_place_cabin(cell); + case PlacementMode::None: return false; + } + return false; +} + +void edit_at_cell(HWND window, settlement::GridPosition cell) { + using settlement::CommandKind; + using settlement::CommandStatus; + using settlement::StorageKind; + CommandKind command = CommandKind::DemolishObject; + auto source = cell; + settlement::GridPosition destination{}; + std::uint8_t value = 0; + + if (placement_mode == PlacementMode::Move) { + if (!move_source) { + const auto status = world->object_status(cell, true); + if (status == CommandStatus::Accepted) { + move_source = cell; + placement_message = L"Объект выбран. Щёлкните по свободной клетке для переноса."; + } else if (status == CommandStatus::Busy) { + placement_message = L"Объект сейчас используется. Дождитесь завершения работы или сна."; + } else { + placement_message = L"Выберите кровать, склад, станок или посаженный участок."; + } + invalidate_scene(window); + return; + } + command = CommandKind::MoveObject; + source = *move_source; + destination = cell; + } else if (placement_mode == PlacementMode::Demolish) { + const auto store = std::find_if(world->storages().begin(), world->storages().end(), + [&](const auto& storage) { return storage.position == cell; }); + if (store != world->storages().end() && store->total_items() > 0 && + world->object_status(cell, false) == CommandStatus::Accepted && + MessageBoxW(window, L"Снести склад вместе с его запасами?", L"Снос склада", + MB_YESNO | MB_ICONQUESTION | MB_DEFBUTTON2) != IDYES) return; + } else if (placement_mode == PlacementMode::BerryField) { + command = CommandKind::PlaceBerryField; + } else if (placement_mode == PlacementMode::FlaxField) { + command = CommandKind::PlaceFlaxField; + } else if (placement_mode == PlacementMode::TreePlot) { + command = CommandKind::PlaceTreePlot; + } else if (placement_mode == PlacementMode::Mine) { + command = CommandKind::PlaceMine; + } else if (placement_mode == PlacementMode::Loom) { + command = CommandKind::PlaceLoom; + } else { + command = CommandKind::PlaceStorage; + value = static_cast(placement_mode == PlacementMode::Pantry ? StorageKind::Pantry : + StorageKind::Materials); + } + + const auto result = submit_command(command, source, value, destination); + if (result == CommandStatus::Accepted) { + move_source.reset(); + placement_message = lan.is_guest() ? L"Команда отправлена хозяину." : L"Готово."; + } else if (result == CommandStatus::Busy) { + placement_message = L"Объект сейчас используется. Дождитесь завершения работы или сна."; + } else { + if (command == CommandKind::MoveObject && world->object_status(source, true) != CommandStatus::Accepted) { + move_source.reset(); + } + placement_message = L"Действие недоступно для выбранной клетки."; + } + update_status(); + invalidate_scene(window); +} + +HMENU create_work_menu() { + HMENU menu = CreatePopupMenu(); + if (menu == nullptr) return nullptr; + for (std::size_t index = 0; index + 1 < role_choices.size(); ++index) { + AppendMenuW(menu, MF_STRING, farmer_menu_id + index, role_choices[index + 1].title); + } + AppendMenuW(menu, MF_SEPARATOR, 0, nullptr); + AppendMenuW(menu, MF_STRING, residents_button_id, L"Жители…\tC"); + return menu; +} + +void apply_resident_role(HWND owner) { + const auto* resident = selected_agent(); + if (!resident || !roster.pending_role || *roster.pending_role == resident->profession || !can_give_orders()) return; + using settlement::CommandStatus; + const auto result = submit_command(settlement::CommandKind::AssignProfession, {}, + static_cast(*roster.pending_role), {}, resident->id); + if (result == CommandStatus::Accepted) { + roster.pending_role.reset(); + SetWindowTextW(roster.notice, lan.is_guest() ? L"Назначение отправлено хозяину." : + L"Профессия назначена. Житель закончит текущее поручение."); + } else { + SetWindowTextW(roster.notice, L"Не удалось назначить профессию."); + } + sync_resident_roster(); + update_roster_details(); + invalidate_scene(owner); +} + +LRESULT CALLBACK resident_roster_proc(HWND window, UINT message, WPARAM wparam, LPARAM lparam) { + const auto owner = GetWindow(window, GW_OWNER); + switch (message) { + case WM_CREATE: { + const auto control = [&](const wchar_t* type, const wchar_t* text, int id, DWORD style, + int x, int y, int width, int height, DWORD ex_style = 0) { + const auto child = CreateWindowExW(ex_style, type, text, WS_CHILD | WS_VISIBLE | style, + x, y, width, height, window, reinterpret_cast(static_cast(id)), + GetModuleHandleW(nullptr), nullptr); + SendMessageW(child, WM_SETFONT, reinterpret_cast(GetStockObject(DEFAULT_GUI_FONT)), FALSE); + return child; + }; + roster.list = control(WC_LISTVIEWW, L"", resident_list_id, + WS_TABSTOP | LVS_REPORT | LVS_OWNERDATA | LVS_SINGLESEL | LVS_SHOWSELALWAYS | LVS_NOSORTHEADER, + 16, 16, 282, 311, WS_EX_CLIENTEDGE); + ListView_SetExtendedListViewStyle(roster.list, LVS_EX_FULLROWSELECT | LVS_EX_DOUBLEBUFFER); + wchar_t resident_header[] = L"Житель"; + wchar_t profession_header[] = L"Профессия"; + LVCOLUMNW column{}; + column.mask = LVCF_TEXT | LVCF_WIDTH; + column.cx = 102; + column.pszText = resident_header; + ListView_InsertColumn(roster.list, 0, &column); + column.cx = 156; + column.pszText = profession_header; + ListView_InsertColumn(roster.list, 1, &column); + + roster.current_role = control(L"STATIC", L"", 0, SS_LEFT, 316, 16, 234, 22); + for (std::size_t index = 0; index < role_choices.size(); ++index) { + const auto title = std::wstring(role_choices[index].title) + L" (0)"; + roster.roles[index] = control(L"BUTTON", title.c_str(), first_role_id + static_cast(index), + WS_TABSTOP | BS_OWNERDRAW, 316, 43 + static_cast(index) * 34, 234, 30); + } + roster.apply = control(L"BUTTON", L"Назначить профессию", IDOK, WS_TABSTOP | BS_DEFPUSHBUTTON, + 316, 218, 234, 30); + roster.notice = control(L"STATIC", L"", 0, SS_LEFT, 316, 256, 234, 44); + const auto close = control(L"BUTTON", L"Закрыть", IDCANCEL, WS_TABSTOP | BS_PUSHBUTTON, + 447, 301, 103, 26); + if (!roster.list || !roster.current_role || !roster.apply || !roster.notice || !close || + std::find(roster.roles.begin(), roster.roles.end(), nullptr) != roster.roles.end()) return -1; + return 0; + } + case WM_NOTIFY: { + const auto* notification = reinterpret_cast(lparam); + if (!notification || notification->hwndFrom != roster.list) break; + if (notification->code == LVN_GETDISPINFOW) { + auto& item = reinterpret_cast(lparam)->item; + if ((item.mask & LVIF_TEXT) != 0 && item.pszText && item.cchTextMax > 0 && + item.iItem >= 0 && static_cast(item.iItem) < roster.rows.size()) { + const auto& row = roster.rows[static_cast(item.iItem)]; + const auto name = item.iSubItem == 0 ? L"Житель №" + std::to_wstring(row.id) : + std::wstring(profession_name(row.role)); + lstrcpynW(item.pszText, name.c_str(), item.cchTextMax); + } + return 0; + } + if (notification->code == LVN_ITEMCHANGED && !roster.updating_selection) { + const auto& change = *reinterpret_cast(lparam); + if ((change.uChanged & LVIF_STATE) != 0 && ((change.uOldState ^ change.uNewState) & LVIS_SELECTED) != 0) { + const int index = ListView_GetNextItem(roster.list, -1, LVNI_SELECTED); + std::optional resident; + if (index >= 0 && static_cast(index) < roster.rows.size()) { + resident = roster.rows[static_cast(index)].id; + } + if (selected_resident != resident) { + selected_resident = resident; + sync_resident_roster(true); + invalidate_scene(owner); + } + } + } + break; + } + case WM_DRAWITEM: { + const auto* item = reinterpret_cast(lparam); + if (item && item->CtlType == ODT_BUTTON && item->CtlID >= first_role_id && + item->CtlID < first_role_id + role_choices.size()) { + const auto& choice = role_choices[item->CtlID - first_role_id]; + const auto* resident = selected_agent(); + const bool active = resident && roster.pending_role.value_or(resident->profession) == choice.role; + draw_icon_button(*item, choice.icon, active); + return TRUE; + } + break; + } + case WM_COMMAND: + if (HIWORD(wparam) != BN_CLICKED) break; + if (LOWORD(wparam) == IDCANCEL) { + DestroyWindow(window); + return 0; + } + if (LOWORD(wparam) == IDOK) { + apply_resident_role(owner); + return 0; + } + if (LOWORD(wparam) >= first_role_id && LOWORD(wparam) < first_role_id + role_choices.size() && + selected_agent() && can_give_orders()) { + roster.pending_role = role_choices[LOWORD(wparam) - first_role_id].role; + SetWindowTextW(roster.notice, L""); + update_roster_details(); + return 0; + } + break; + case DM_GETDEFID: + return MAKELONG(IDOK, DC_HASDEFID); + case WM_DESTROY: + roster = {}; + InvalidateRect(residents_button, nullptr, FALSE); + return 0; + } + return DefWindowProcW(window, message, wparam, lparam); +} + +void show_resident_roster(HWND owner) { + if (roster.window) { + SetActiveWindow(roster.window); + return; + } + const auto instance = GetModuleHandleW(nullptr); + WNDCLASSW window_info{}; + window_info.lpfnWndProc = resident_roster_proc; + window_info.hInstance = instance; + window_info.lpszClassName = resident_window_class; + window_info.hCursor = LoadCursorW(nullptr, IDC_ARROW); + window_info.hbrBackground = GetSysColorBrush(COLOR_BTNFACE); + if (!RegisterClassW(&window_info) && GetLastError() != ERROR_CLASS_ALREADY_EXISTS) return; + constexpr auto style = WS_POPUP | WS_CAPTION | WS_SYSMENU | WS_CLIPCHILDREN; + constexpr auto ex_style = WS_EX_TOOLWINDOW | WS_EX_CONTROLPARENT; + RECT area{0, 0, 566, 343}; + AdjustWindowRectEx(&area, style, FALSE, ex_style); + RECT owner_rect{}; + GetWindowRect(owner, &owner_rect); + const int width = area.right - area.left; + const int height = area.bottom - area.top; + const int x = (owner_rect.left + owner_rect.right - width) / 2; + const int y = (owner_rect.top + owner_rect.bottom - height) / 2; + roster.window = CreateWindowExW(ex_style, resident_window_class, L"Жители поселения", style, + x, y, width, height, owner, nullptr, instance, nullptr); + if (!roster.window) return; + if (!selected_agent() && !world->agents().empty()) selected_resident = world->agents().front().id; + sync_resident_roster(true); + InvalidateRect(residents_button, nullptr, FALSE); + invalidate_scene(owner); + ShowWindow(roster.window, SW_SHOW); + SetFocus(roster.list); +} + +std::optional resident_at(HWND window, POINT point) { + RECT client{}; + GetClientRect(window, &client); + if (!is_map_point(client, point)) return std::nullopt; + const auto scene = camera.to_scene({static_cast(point.x), static_cast(point.y)}); + std::optional picked; + double closest = 65.0; + for (const auto& agent : world->agents()) { + const auto position = resident_anchor( + iso_point(agent.position.x, agent.position.y, client.right / 2, map_origin_y), agent); + const double dx = scene.x - position.x; + const double dy = scene.y - (position.y + 2); + if (std::abs(dx) > 8 || std::abs(dy) > 8) continue; + const double distance = dx * dx + dy * dy; + if (distance <= closest) { + closest = distance; + picked = agent.id; + } + } + return picked; +} + +std::wstring resident_details() { + const auto* resident = selected_agent(); + if (resident == nullptr) return L"Щёлкните по жителю, чтобы увидеть его состояние и назначить профессию."; + + using settlement::ItemType; + constexpr std::pair items[] = { + {ItemType::Wood, L"древесина"}, {ItemType::Stone, L"камень"}, {ItemType::Plank, L"доски"}, + {ItemType::StoneBlock, L"блоки"}, {ItemType::Berries, L"ягоды"}, {ItemType::Cloth, L"ткань"}, + {ItemType::Flax, L"лён"} + }; + std::wstring cargo; + for (const auto& [type, name] : items) { + const auto count = resident->inventory.item_count(type); + if (count == 0) continue; + if (!cargo.empty()) cargo += L", "; + cargo += std::wstring(name) + L" ×" + std::to_wstring(count); + } + const auto hunger = 100U * resident->hunger / settlement::max_hunger; + std::wstring text = L"Житель №" + std::to_wstring(resident->id) + L" " + + profession_name(resident->profession) + L" Голод " + std::to_wstring(hunger) + L"%"; + if (resident->state == settlement::AgentState::GoingToEat) text += L" Идёт к кладовой"; + else if (resident->state == settlement::AgentState::Eating) text += L" Ест"; + else if (resident->resource_node_index != settlement::no_entity_index && + resident->storage_index == settlement::no_entity_index) { + const auto& site = world->resource_nodes()[resident->resource_node_index]; + const bool trees = site.site == settlement::ResourceSite::TreePlot; + if (resident->state == settlement::AgentState::Travelling) { + text += trees ? L" Идёт на посадку деревьев" : L" Идёт засевать поле"; + } else { + text += trees ? L" Сажает деревья" : L" Засевает поле"; + } + } + text += L" В сумке "; + text += cargo.empty() ? L"пусто" : cargo; + if (world->scenario_active()) { + const auto* bed = world->assigned_bed(resident->id); + const auto fatigue = 100U * resident->fatigue / settlement::max_fatigue; + text += L" Усталость " + std::to_wstring(fatigue) + L"%"; + if (resident->state == settlement::AgentState::GoingToSleep) { + text += resident->resting_on_ground ? L" Идёт отдыхать" : L" Идёт к кровати"; + } + if (resident->state == settlement::AgentState::Sleeping) { + text += resident->resting_on_ground ? L" Отдыхает на земле" : L" Спит в кровати"; + } + text += bed == nullptr ? L" Место ещё не назначено" : + L" Место [" + std::to_wstring(bed->position.x + 1) + L", " + + std::to_wstring(bed->position.y + 1) + L"]"; + } + return text; +} + +void draw_map(HDC dc, int width) { + const int origin_x = width / 2; + const int origin_y = map_origin_y; + for (int y = 0; y < map_size; ++y) { + for (int x = 0; x < map_size; ++x) { + const POINT center = iso_point(x, y, origin_x, origin_y); + const bool walkable = world->is_walkable({x, y}); + const COLORREF grass = ((x * 7 + y * 11) % 9 == 0) ? color(158, 183, 124) : color(171, 195, 135); + draw_ground_tile(dc, center, walkable ? grass : color(118, 133, 118), color(149, 170, 130)); + if (hover_cell && *hover_cell == settlement::GridPosition{x, y} && + (!shows_bed_choices() || selected_bed_base.has_value())) { + const bool valid = valid_edit_cell(*hover_cell); + draw_ground_tile(dc, center, valid ? color(154, 207, 225) : color(216, 140, 126), + valid ? color(53, 116, 141) : color(147, 70, 58)); + } + if (move_source == settlement::GridPosition{x, y}) { + draw_ground_tile(dc, center, color(224, 197, 125), color(124, 98, 47)); + } + } + } + + const HPEN trail_pen = CreatePen(PS_SOLID, 1, color(100, 82, 134)); + const HPEN delivery_pen = CreatePen(PS_SOLID, 2, color(38, 122, 112)); + const HPEN meal_pen = CreatePen(PS_SOLID, 2, color(168, 67, 109)); + const HPEN sleep_pen = CreatePen(PS_SOLID, 2, color(76, 98, 142)); + const HGDIOBJ original_pen = SelectObject(dc, trail_pen); + for (const auto& agent : world->agents()) { + using settlement::AgentState; + if (agent.state != AgentState::Travelling && agent.state != AgentState::Hauling && + agent.state != AgentState::FetchingMaterials && agent.state != AgentState::GoingToEat && + agent.state != AgentState::GoingToSleep) continue; + HPEN pen = trail_pen; + if (agent.state == AgentState::GoingToEat) pen = meal_pen; + else if (agent.state == AgentState::GoingToSleep) pen = sleep_pen; + else if (agent.production_index != settlement::no_entity_index && agent.state == AgentState::Hauling) { + pen = delivery_pen; + } + SelectObject(dc, pen); + const POINT start = iso_point(agent.position.x, agent.position.y, origin_x, origin_y); + MoveToEx(dc, start.x, start.y, nullptr); + for (std::size_t i = agent.route_cursor; i < agent.route.size(); ++i) { + const POINT point = iso_point(agent.route[i].x, agent.route[i].y, origin_x, origin_y); + LineTo(dc, point.x, point.y); + } + } + SelectObject(dc, original_pen); + DeleteObject(trail_pen); + DeleteObject(delivery_pen); + DeleteObject(meal_pen); + DeleteObject(sleep_pen); + + for (int depth = 0; depth <= (map_size - 1) * 2; ++depth) { + const int min_x = std::max(0, depth - (map_size - 1)); + const int max_x = std::min(map_size - 1, depth); + for (int x = min_x; x <= max_x; ++x) { + const int y = depth - x; + const POINT center = iso_point(x, y, origin_x, origin_y); + if (!world->is_walkable({x, y})) draw_rock(dc, center); + + for (const settlement::ResourceNode& node : world->resource_nodes()) { + if (node.position.x == x && node.position.y == y && + (node.quantity > 0 || node.type == settlement::ItemType::Berries || + node.site != settlement::ResourceSite::Natural)) { + if (node.type == settlement::ItemType::Berries && node.foraging_enabled) { + draw_ground_tile(dc, center, color(169, 202, 120), color(57, 112, 65)); + } + draw_site(dc, center, node); + } + } + for (const settlement::Storage& storage : world->storages()) { + if (storage.position.x == x && storage.position.y == y) draw_storage(dc, center, storage.kind); + } + for (const settlement::ProductionOrder& order : world->production_orders()) { + if (order.position.x != x || order.position.y != y) continue; + draw_production(dc, center, order); + break; + } + + for (const settlement::WorkJob& job : world->jobs()) { + if (job.position.x != x || job.position.y != y) continue; + const COLORREF job_color = job.state == settlement::JobState::Available ? color(66, 143, 85) : + job.state == settlement::JobState::InProgress ? color(220, 151, 53) : color(148, 151, 145); + const POINT marker[] = { + {center.x, center.y - 4}, {center.x + 4, center.y - 2}, + {center.x, center.y}, {center.x - 4, center.y - 2} + }; + fill_polygon(dc, marker, 4, job_color, color(75, 83, 69)); + } + + for (const settlement::Agent& agent : world->agents()) { + if (agent.position.x != x || agent.position.y != y) continue; + draw_resident(dc, center, agent); + } + } + } + +} + +void draw_world(HDC dc, int width, int height) { + RECT bounds{0, 0, width, height}; + HBRUSH background = CreateSolidBrush(color(239, 235, 222)); + FillRect(dc, &bounds, background); + DeleteObject(background); + if (!world) return; + + if (height > map_top + map_footer) { + const int saved = SaveDC(dc); + if (saved != 0) { + IntersectClipRect(dc, 0, map_top, width, height - map_footer); + const auto offset = camera.offset(); + const auto scale = static_cast(camera.scale()); + const XFORM transform{scale, 0.0F, 0.0F, scale, + static_cast(offset.x), static_cast(offset.y)}; + if (SetGraphicsMode(dc, GM_ADVANCED) != 0 && SetWorldTransform(dc, &transform)) { + draw_map(dc, width); + } + RestoreDC(dc, saved); + } + } + + const RECT dock{0, height - map_footer, width, height}; + const auto dock_brush = CreateSolidBrush(color(34, 46, 40)); + FillRect(dc, &dock, dock_brush); + DeleteObject(dock_brush); + const RECT dock_edge{0, dock.top, width, dock.top + 2}; + const auto edge_brush = CreateSolidBrush(color(142, 132, 92)); + FillRect(dc, &dock_edge, edge_brush); + DeleteObject(edge_brush); + SetBkMode(dc, TRANSPARENT); + SetTextColor(dc, color(231, 227, 205)); + const wchar_t* hint = world->scenario_active() ? + L"Колесо — масштаб Перетаскивание — сдвиг карты Home — общий план" : + L"Голубой — очередь Бирюзовый — доставка Янтарный — строительство"; + if (!placement_message.empty()) hint = placement_message.c_str(); + else if (placement_mode == PlacementMode::Foraging) { + hint = L"Щёлкните по ягодному кусту, чтобы включить или выключить сбор. Esc — отмена."; + } else if (placement_mode == PlacementMode::BerryField) { + hint = L"Поле ягод. Выберите свободную клетку. Фермер засеет поле и соберёт урожай."; + } else if (placement_mode == PlacementMode::FlaxField) { + hint = L"Поле льна. Выберите свободную клетку. Фермер сначала засеет поле, затем соберёт лён."; + } else if (placement_mode == PlacementMode::TreePlot) { + hint = L"Посадка деревьев. Выберите свободную клетку. Лесоруб высадит деревья."; + } else if (placement_mode == PlacementMode::Mine) { + hint = L"Шахта. Щёлкните по скале, к которой ведёт свободный проход."; + } else if (placement_mode == PlacementMode::Loom) { + hint = L"Ткацкий станок. Выберите свободную клетку. Строитель будет делать ткань из льна."; + } else if (placement_mode == PlacementMode::Storage || placement_mode == PlacementMode::Pantry) { + hint = L"Выберите свободную клетку для склада или кладовой."; + } else if (placement_mode == PlacementMode::Move) { + hint = move_source ? L"Выберите свободную клетку для переноса." : + L"Выберите кровать, склад, станок или посаженный участок."; + } else if (placement_mode == PlacementMode::Demolish) { + hint = L"Щёлкните по объекту, чтобы снести его. Esc отменяет режим."; + } else if (placement_mode == PlacementMode::Building) { + if (world->staged_beds()) { + hint = selected_bed_base + ? L"Щёлкайте по свободным клеткам. Основу можно сменить под кнопкой «Спальное место»." + : L"Выберите «Дерево» или «Камень» под кнопкой «Спальное место»."; + } else if (world->scenario_active()) { + hint = L"Щёлкайте по свободным клеткам. Одно место требует доску. Esc — выход."; + } else { + hint = L"Выберите свободную клетку. Домик стоит три доски и два блока. Esc — отмена."; + } + } + RECT legend{24, height - 159, width - 24, height - 136}; + DrawTextW(dc, hint, -1, &legend, DT_LEFT | DT_VCENTER | DT_SINGLELINE | DT_END_ELLIPSIS); + const auto details = resident_details(); + SetTextColor(dc, color(190, 201, 178)); + RECT inspector{24, height - 135, width - 24, height - 113}; + DrawTextW(dc, details.c_str(), -1, &inspector, DT_LEFT | DT_VCENTER | DT_SINGLELINE | DT_END_ELLIPSIS); +} + +LRESULT CALLBACK window_proc(HWND window, UINT message, WPARAM wparam, LPARAM lparam) { + switch (message) { + case WM_GETMINMAXINFO: { + auto& size = *reinterpret_cast(lparam); + size.ptMinTrackSize.x = 775; + size.ptMinTrackSize.y = 490; + return 0; + } + case WM_CREATE: { + constexpr auto minimum = static_cast(settlement::min_worker_count); + const UINT hardware = std::max(static_cast(minimum), std::thread::hardware_concurrency()); + const int max_workers = static_cast(std::min(hardware, 32U)); + selected_workers = static_cast(std::min(max_workers, 8)); + CreateWindowExW(0, L"STATIC", L"Число потоков:", WS_CHILD | WS_VISIBLE, + 18, 14, 112, 25, window, nullptr, nullptr, nullptr); + worker_combo = CreateWindowExW(0, WC_COMBOBOXW, L"", WS_CHILD | WS_VISIBLE | CBS_DROPDOWNLIST, + 132, 10, 76, 280, window, + reinterpret_cast(static_cast(worker_combo_id)), + GetModuleHandleW(nullptr), nullptr); + for (int count = minimum; count <= max_workers; ++count) { + const std::wstring option = std::to_wstring(count); + SendMessageW(worker_combo, CB_ADDSTRING, 0, reinterpret_cast(option.c_str())); + } + SendMessageW(worker_combo, CB_SETCURSEL, static_cast(selected_workers - settlement::min_worker_count), 0); + apply_button = CreateWindowExW(0, L"BUTTON", L"Применить и начать заново", WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON, + 220, 10, 190, 28, window, + reinterpret_cast(static_cast(apply_button_id)), + GetModuleHandleW(nullptr), nullptr); + status_label = CreateWindowExW(0, L"STATIC", L"", WS_CHILD | WS_VISIBLE, + 430, 14, 620, 24, window, + reinterpret_cast(static_cast(status_label_id)), + GetModuleHandleW(nullptr), nullptr); + production_label = CreateWindowExW(0, L"STATIC", L"", WS_CHILD | WS_VISIBLE, + 288, 47, 817, 24, window, nullptr, nullptr, nullptr); + const auto button = [&](int id, int x, int width, const wchar_t* title, + DWORD style = BS_PUSHBUTTON, int y = 41, int height = 28) { + return CreateWindowExW(0, L"BUTTON", title, WS_CHILD | WS_VISIBLE | style, + x, y, width, height, window, + reinterpret_cast(static_cast(id)), + GetModuleHandleW(nullptr), nullptr); + }; + priority_button = button(priority_button_id, 18, 142, L"Равный приоритет"); + pause_button = button(pause_button_id, 168, 96, L"Пауза"); + residents_button = button(residents_button_id, 0, 112, L"Жители", BS_OWNERDRAW, 0); + for (std::size_t index = 0; index < dock_sections.size(); ++index) { + dock_section_buttons[index] = button(first_dock_section_id + static_cast(index), 0, 112, + dock_sections[index].title, BS_OWNERDRAW, 0); + } + wood_bed_button = button(wood_bed_button_id, 0, bed_choice_width, L"Дерево", BS_OWNERDRAW, 0); + stone_bed_button = button(stone_bed_button_id, 0, bed_choice_width, L"Камень", BS_OWNERDRAW, 0); + for (std::size_t index = 0; index < work_choice_buttons.size(); ++index) { + work_choice_buttons[index] = button(first_work_choice_id + static_cast(index), + 0, 100, L"", BS_OWNERDRAW, 0); + ShowWindow(work_choice_buttons[index], SW_HIDE); + } + layout_command_dock(window); + reset_world(window); + refresh_lan_controls(window); + SetTimer(window, timer_id, 60, nullptr); + return 0; + } + case WM_DRAWITEM: + if (const auto* item = reinterpret_cast(lparam); + item && item->CtlType == ODT_BUTTON && draw_toolbar_button(*item)) return TRUE; + break; + case WM_COMMAND: + if (LOWORD(wparam) == residents_button_id && HIWORD(wparam) == BN_CLICKED) { + if (world) show_resident_roster(window); + return 0; + } + if (LOWORD(wparam) >= farmer_menu_id && LOWORD(wparam) <= builder_menu_id && HIWORD(wparam) == BN_CLICKED) { + const auto panel = static_cast(LOWORD(wparam) - farmer_menu_id); + toggle_work_panel(window, panel); + return 0; + } + if (LOWORD(wparam) >= first_dock_section_id && + static_cast(LOWORD(wparam) - first_dock_section_id) < dock_sections.size() && + HIWORD(wparam) == BN_CLICKED) { + const auto panel = dock_sections[static_cast(LOWORD(wparam) - first_dock_section_id)].panel; + toggle_work_panel(window, panel); + return 0; + } + if (LOWORD(wparam) >= first_work_choice_id && + static_cast(LOWORD(wparam) - first_work_choice_id) < work_choice_buttons.size() && + HIWORD(wparam) == BN_CLICKED) { + const auto choices = work_choices(); + const auto index = static_cast(LOWORD(wparam) - first_work_choice_id); + if (index >= choices.size() || (lan.is_guest() && lan.state() != LanState::GuestConnected)) return 0; + SendMessageW(window, WM_COMMAND, static_cast(choices[index].command), 0); + return 0; + } + if (LOWORD(wparam) >= lan_host_id && LOWORD(wparam) <= lan_leave_id) { + handle_lan_menu(window, LOWORD(wparam)); + return 0; + } + if (LOWORD(wparam) >= berry_field_id && LOWORD(wparam) <= demolish_id) { + if (!world || (lan.is_guest() && lan.state() != LanState::GuestConnected)) return 0; + constexpr PlacementMode modes[] = {PlacementMode::BerryField, PlacementMode::TreePlot, + PlacementMode::Mine, PlacementMode::Storage, PlacementMode::Pantry, PlacementMode::Move, + PlacementMode::Demolish}; + set_placement_mode(window, modes[LOWORD(wparam) - berry_field_id]); + SetFocus(window); + return 0; + } + if ((LOWORD(wparam) == flax_field_id || LOWORD(wparam) == loom_id) && HIWORD(wparam) == BN_CLICKED) { + if (!world || !can_give_orders()) return 0; + set_placement_mode(window, LOWORD(wparam) == flax_field_id ? PlacementMode::FlaxField : PlacementMode::Loom); + SetFocus(window); + return 0; + } + if (LOWORD(wparam) == reset_camera_id) { + camera = {}; + hover_cell.reset(); + invalidate_scene(window); + return 0; + } + if (LOWORD(wparam) == save_menu_id || LOWORD(wparam) == load_menu_id) { + handle_save_menu(window, LOWORD(wparam) == save_menu_id); + return 0; + } + if (LOWORD(wparam) == apply_button_id) { + if (lan.state() != LanState::Offline) return 0; + const LRESULT selection = SendMessageW(worker_combo, CB_GETCURSEL, 0, 0); + if (selection != CB_ERR) selected_workers = static_cast(selection) + settlement::min_worker_count; + reset_world(window); + return 0; + } + if (LOWORD(wparam) == cabin_button_id && HIWORD(wparam) == BN_CLICKED) { + set_placement_mode(window, placement_mode == PlacementMode::Building ? + PlacementMode::None : PlacementMode::Building); + SetFocus(window); + return 0; + } + if (HIWORD(wparam) == BN_CLICKED && shows_bed_choices() && + (LOWORD(wparam) == wood_bed_button_id || LOWORD(wparam) == stone_bed_button_id)) { + selected_bed_base = LOWORD(wparam) == wood_bed_button_id ? settlement::BedBase::Wood : settlement::BedBase::Stone; + placement_message.clear(); + update_bed_choices(); + SetFocus(window); + invalidate_scene(window); + return 0; + } + if (LOWORD(wparam) == forage_action_id && HIWORD(wparam) == BN_CLICKED && world && + (!lan.is_guest() || lan.state() == LanState::GuestConnected)) { + set_placement_mode(window, placement_mode == PlacementMode::Foraging ? + PlacementMode::None : PlacementMode::Foraging); + SetFocus(window); + return 0; + } + if (HIWORD(wparam) == BN_CLICKED && world && world->scenario_active()) { + if (LOWORD(wparam) == priority_button_id) { + const auto next = (static_cast(world->work_priority()) + 1U) % 3U; + static_cast(send_command(settlement::CommandKind::SetPriority, {}, static_cast(next))); + update_status(); + return 0; + } + if (LOWORD(wparam) == pause_button_id) { + static_cast(send_command(settlement::CommandKind::SetPaused, {}, + static_cast(!world->paused()))); + update_status(); + return 0; + } + } + break; + case WM_MOUSEWHEEL: { + POINT point = client_point(lparam); + if (!ScreenToClient(window, &point)) break; + RECT client{}; + GetClientRect(window, &client); + if (!is_map_point(client, point)) break; + const double steps = static_cast(GET_WHEEL_DELTA_WPARAM(wparam)) / WHEEL_DELTA; + camera.zoom_at({static_cast(point.x), static_cast(point.y)}, steps); + update_map_hover(window, point); + invalidate_scene(window); + return 0; + } + case WM_MBUTTONDOWN: { + RECT client{}; + GetClientRect(window, &client); + const POINT point = client_point(lparam); + if (!is_map_point(client, point) || camera_drag) break; + SetFocus(window); + SetCapture(window); + camera_drag = CameraDrag{point, false, false}; + return 0; + } + case WM_MBUTTONUP: + if (camera_drag && !camera_drag->left_button) { + update_camera_drag(client_point(lparam)); + camera_drag.reset(); + if (GetCapture() == window) ReleaseCapture(); + invalidate_scene(window); + return 0; + } + break; + case WM_CAPTURECHANGED: + camera_drag.reset(); + break; + case WM_MOUSEMOVE: { + const POINT point = client_point(lparam); + if (camera_drag) { + update_camera_drag(point); + invalidate_scene(window); + } + update_map_hover(window, point); + return 0; + } + case WM_MOUSELEAVE: + hover_cell.reset(); + invalidate_scene(window); + return 0; + case WM_LBUTTONDOWN: { + RECT client{}; + GetClientRect(window, &client); + const POINT point = client_point(lparam); + if (camera_drag || !is_map_point(client, point)) break; + SetFocus(window); + SetCapture(window); + camera_drag = CameraDrag{point, true, false}; + return 0; + } + case WM_LBUTTONUP: { + if (!camera_drag || !camera_drag->left_button) break; + const POINT point = client_point(lparam); + update_camera_drag(point); + const bool moved = camera_drag->moved; + camera_drag.reset(); + if (GetCapture() == window) ReleaseCapture(); + if (moved) { + update_map_hover(window, point); + invalidate_scene(window); + return 0; + } + RECT client{}; + GetClientRect(window, &client); + if (!is_map_point(client, point)) break; + if (placement_mode == PlacementMode::Foraging && world) { + const auto cell = map_cell(client, point); + const auto* source = cell ? berry_source(*cell) : nullptr; + if (source != nullptr) { + static_cast(send_command(settlement::CommandKind::SetForaging, *cell, + static_cast(!source->foraging_enabled))); + } else { + placement_message = L"Для сбора выберите ягодный куст."; + } + invalidate_scene(window); + return 0; + } + if (placement_mode == PlacementMode::Building && world) { + const auto cell = map_cell(client, point); + if (world->scenario_active()) { + if (!cell || !world->can_place_bed(*cell)) { + placement_message = L"Для спального места нужна свободная клетка."; + invalidate_scene(window); + return 0; + } + if (shows_bed_choices() && !selected_bed_base) { + placement_message = L"Сначала выберите основу под кнопкой «Спальное место»."; + invalidate_scene(window); + return 0; + } + const auto base = selected_bed_base.value_or(settlement::BedBase::Wood); + if (send_command(settlement::CommandKind::PlaceBed, *cell, static_cast(base))) { + hover_cell = cell; + placement_message = lan.is_guest() + ? L"Запрос на спальное место отправлен. Можно выбрать следующую клетку." + : L"Спальное место заказано. Выберите следующую клетку или нажмите Esc."; + update_status(); + } else { + placement_message = L"Для спального места нужна свободная клетка с проходом к мастерской."; + } + invalidate_scene(window); + return 0; + } + if (!cell || !world->can_place_cabin(*cell)) { + placement_message = L"Здесь нельзя поставить домик. Выберите свободную клетку."; + invalidate_scene(window); + return 0; + } + try { + world->queue_cabin(*cell, sawmill, stonecutter); + } catch (const std::invalid_argument&) { + placement_message = L"К участку нет прохода от мастерских. Выберите другую клетку."; + invalidate_scene(window); + return 0; + } + set_placement_mode(window, PlacementMode::None, L"Чертёж поставлен. Материалы заказаны в мастерских."); + update_status(); + return 0; + } + if (world && placement_mode >= PlacementMode::BerryField) { + if (const auto cell = map_cell(client, point)) edit_at_cell(window, *cell); + return 0; + } + if (world) { + selected_resident = resident_at(window, point); + update_status(); + sync_resident_roster(true); + invalidate_scene(window); + return 0; + } + break; + } + case WM_RBUTTONDOWN: + if (placement_mode != PlacementMode::None || work_panel != WorkPanel::None) { + set_placement_mode(window, PlacementMode::None); + set_work_panel(window, WorkPanel::None); + return 0; + } + break; + case WM_KEYDOWN: + 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 : + wparam == 'Z' ? WorkPanel::Zones : WorkPanel::Construction); + } + return 0; + } + if (wparam == 'C' && (GetKeyState(VK_CONTROL) & 0x8000) == 0) { + if (world) show_resident_roster(window); + return 0; + } + if (wparam == VK_HOME) { + SendMessageW(window, WM_COMMAND, reset_camera_id, 0); + return 0; + } + if (wparam == VK_ESCAPE && (placement_mode != PlacementMode::None || work_panel != WorkPanel::None)) { + set_placement_mode(window, PlacementMode::None); + set_work_panel(window, WorkPanel::None); + return 0; + } + break; + case WM_TIMER: + if (wparam == timer_id && world) { + if (!file_dialog_active && !lan.is_guest()) world->step(); + if (auto snapshot = lan.poll(*world)) world = std::move(snapshot); + sync_resident_roster(); + if (lan.state() != displayed_lan_state) refresh_lan_controls(window); + if (const auto rejection = lan.take_rejection()) { + placement_message = *rejection == settlement::CommandStatus::Busy + ? L"Объект занят. Дождитесь окончания работы или сна." + : L"Хозяин отклонил команду. Проверьте выбранную клетку."; + } + update_status(); + invalidate_scene(window); + return 0; + } + break; + case WM_ERASEBKGND: + return 1; + case WM_SIZE: + layout_command_dock(window); + InvalidateRect(window, nullptr, FALSE); + break; + case WM_PAINT: { + PAINTSTRUCT paint{}; + HDC target = BeginPaint(window, &paint); + RECT client{}; + GetClientRect(window, &client); + const int width = client.right - client.left; + const int height = client.bottom - client.top; + HDC buffer = CreateCompatibleDC(target); + HBITMAP bitmap = CreateCompatibleBitmap(target, width, height); + HGDIOBJ old_bitmap = SelectObject(buffer, bitmap); + 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); + SelectObject(buffer, old_bitmap); + DeleteObject(bitmap); + DeleteDC(buffer); + EndPaint(window, &paint); + return 0; + } + case WM_DESTROY: + KillTimer(window, timer_id); + lan.leave(); + PostQuitMessage(0); + return 0; + } + return DefWindowProcW(window, message, wparam, lparam); +} + +} // namespace + +int WINAPI wWinMain(HINSTANCE instance, HINSTANCE, PWSTR, int show_command) { + INITCOMMONCONTROLSEX controls{sizeof(controls), ICC_STANDARD_CLASSES | ICC_LISTVIEW_CLASSES}; + InitCommonControlsEx(&controls); + WNDCLASSEXW window_class_info{}; + window_class_info.cbSize = sizeof(window_class_info); + window_class_info.hInstance = instance; + window_class_info.lpfnWndProc = window_proc; + window_class_info.lpszClassName = window_class; + window_class_info.hCursor = LoadCursorW(nullptr, IDC_ARROW); + window_class_info.hbrBackground = reinterpret_cast(COLOR_WINDOW + 1); + RegisterClassExW(&window_class_info); + + HMENU menu_bar = CreateMenu(); + HMENU file_menu = CreatePopupMenu(); + HMENU view_menu = CreatePopupMenu(); + HMENU coop_menu = CreatePopupMenu(); + HMENU work_menu = create_work_menu(); + AppendMenuW(file_menu, MF_STRING, save_menu_id, L"Сохранить поселение…"); + AppendMenuW(file_menu, MF_STRING, load_menu_id, L"Загрузить поселение…"); + AppendMenuW(menu_bar, MF_POPUP, reinterpret_cast(file_menu), L"Поселение"); + AppendMenuW(view_menu, MF_STRING, reset_camera_id, L"Общий план\tHome"); + AppendMenuW(menu_bar, MF_POPUP, reinterpret_cast(view_menu), L"Вид"); + if (work_menu != nullptr) { + AppendMenuW(menu_bar, MF_POPUP, reinterpret_cast(work_menu), L"Работы"); + } + AppendMenuW(coop_menu, MF_STRING, lan_host_id, L"Открыть колонию для друга…"); + AppendMenuW(coop_menu, MF_STRING, lan_join_id, L"Подключиться…"); + AppendMenuW(coop_menu, MF_STRING, lan_info_id, L"Адрес и код партии…"); + AppendMenuW(coop_menu, MF_STRING, lan_reconnect_id, L"Подключиться снова"); + AppendMenuW(coop_menu, MF_SEPARATOR, 0, nullptr); + AppendMenuW(coop_menu, MF_STRING, lan_leave_id, L"Выйти из сетевой игры"); + AppendMenuW(menu_bar, MF_POPUP, reinterpret_cast(coop_menu), L"Кооператив"); + HWND window = CreateWindowExW(0, window_class, L"Settlement — Первое поселение", + WS_OVERLAPPEDWINDOW | WS_CLIPCHILDREN, CW_USEDEFAULT, CW_USEDEFAULT, 1120, 752, + nullptr, menu_bar, instance, nullptr); + if (!window) { + DestroyMenu(menu_bar); + return 1; + } + ShowWindow(window, show_command); + UpdateWindow(window); + + MSG message{}; + while (GetMessageW(&message, nullptr, 0, 0) > 0) { + if (roster.window && IsDialogMessageW(roster.window, &message)) continue; + TranslateMessage(&message); + DispatchMessageW(&message); + } + return static_cast(message.wParam); +}