game_engine.cpp 45 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491
  1. #include "game_engine.h"
  2. #include "../controllers/action_vfx.h"
  3. #include "../controllers/command_controller.h"
  4. #include "../models/audio_system_proxy.h"
  5. #include "../models/cursor_manager.h"
  6. #include "../models/hover_tracker.h"
  7. #include "AudioEventHandler.h"
  8. #include "ambient_state_manager.h"
  9. #include "app/models/cursor_mode.h"
  10. #include "app/utils/engine_view_helpers.h"
  11. #include "app/utils/movement_utils.h"
  12. #include "app/utils/selection_utils.h"
  13. #include "audio_resource_loader.h"
  14. #include "camera_controller.h"
  15. #include "core/system.h"
  16. #include "game/audio/AudioSystem.h"
  17. #include "game/units/spawn_type.h"
  18. #include "game/units/troop_type.h"
  19. #include "game_state_restorer.h"
  20. #include "input_command_handler.h"
  21. #include "level_orchestrator.h"
  22. #include "minimap_manager.h"
  23. #include "renderer_bootstrap.h"
  24. #include <QBuffer>
  25. #include <QCoreApplication>
  26. #include <QCursor>
  27. #include <QDebug>
  28. #include <QImage>
  29. #include <QOpenGLContext>
  30. #include <QPainter>
  31. #include <QQuickWindow>
  32. #include <QSize>
  33. #include <QVariant>
  34. #include <QVariantMap>
  35. #include <memory>
  36. #include <optional>
  37. #include <qbuffer.h>
  38. #include <qcoreapplication.h>
  39. #include <qdir.h>
  40. #include <qevent.h>
  41. #include <qglobal.h>
  42. #include <qimage.h>
  43. #include <qjsonobject.h>
  44. #include <qnamespace.h>
  45. #include <qobject.h>
  46. #include <qobjectdefs.h>
  47. #include <qpoint.h>
  48. #include <qsize.h>
  49. #include <qstringliteral.h>
  50. #include <qstringview.h>
  51. #include <qtmetamacros.h>
  52. #include <qvectornd.h>
  53. #include <unordered_set>
  54. #include "../models/selected_units_model.h"
  55. #include "game/core/component.h"
  56. #include "game/core/event_manager.h"
  57. #include "game/core/world.h"
  58. #include "game/game_config.h"
  59. #include "game/map/environment.h"
  60. #include "game/map/level_loader.h"
  61. #include "game/map/map_catalog.h"
  62. #include "game/map/map_loader.h"
  63. #include "game/map/map_transformer.h"
  64. #include "game/map/minimap/minimap_generator.h"
  65. #include "game/map/minimap/unit_layer.h"
  66. #include "game/map/skirmish_loader.h"
  67. #include "game/map/terrain_service.h"
  68. #include "game/map/visibility_service.h"
  69. #include "game/map/world_bootstrap.h"
  70. #include "game/systems/ai_system.h"
  71. #include "game/systems/arrow_system.h"
  72. #include "game/systems/ballista_attack_system.h"
  73. #include "game/systems/building_collision_registry.h"
  74. #include "game/systems/camera_service.h"
  75. #include "game/systems/capture_system.h"
  76. #include "game/systems/catapult_attack_system.h"
  77. #include "game/systems/cleanup_system.h"
  78. #include "game/systems/combat_system.h"
  79. #include "game/systems/command_service.h"
  80. #include "game/systems/formation_planner.h"
  81. #include "game/systems/game_state_serializer.h"
  82. #include "game/systems/global_stats_registry.h"
  83. #include "game/systems/healing_system.h"
  84. #include "game/systems/movement_system.h"
  85. #include "game/systems/nation_id.h"
  86. #include "game/systems/nation_registry.h"
  87. #include "game/systems/owner_registry.h"
  88. #include "game/systems/patrol_system.h"
  89. #include "game/systems/picking_service.h"
  90. #include "game/systems/production_service.h"
  91. #include "game/systems/production_system.h"
  92. #include "game/systems/projectile_system.h"
  93. #include "game/systems/save_load_service.h"
  94. #include "game/systems/selection_system.h"
  95. #include "game/systems/terrain_alignment_system.h"
  96. #include "game/systems/troop_count_registry.h"
  97. #include "game/systems/victory_service.h"
  98. #include "game/units/factory.h"
  99. #include "game/units/troop_config.h"
  100. #include "render/geom/arrow.h"
  101. #include "render/geom/patrol_flags.h"
  102. #include "render/geom/stone.h"
  103. #include "render/gl/bootstrap.h"
  104. #include "render/gl/camera.h"
  105. #include "render/ground/biome_renderer.h"
  106. #include "render/ground/bridge_renderer.h"
  107. #include "render/ground/firecamp_renderer.h"
  108. #include "render/ground/fog_renderer.h"
  109. #include "render/ground/ground_renderer.h"
  110. #include "render/ground/olive_renderer.h"
  111. #include "render/ground/pine_renderer.h"
  112. #include "render/ground/plant_renderer.h"
  113. #include "render/ground/river_renderer.h"
  114. #include "render/ground/riverbank_renderer.h"
  115. #include "render/ground/road_renderer.h"
  116. #include "render/ground/stone_renderer.h"
  117. #include "render/ground/terrain_renderer.h"
  118. #include "render/scene_renderer.h"
  119. #include <QDir>
  120. #include <QFile>
  121. #include <QJsonArray>
  122. #include <QJsonDocument>
  123. #include <QJsonObject>
  124. #include <QSet>
  125. #include <algorithm>
  126. #include <cmath>
  127. #include <utility>
  128. #include <vector>
  129. GameEngine::GameEngine(QObject *parent)
  130. : QObject(parent),
  131. m_selectedUnitsModel(new SelectedUnitsModel(this, this)) {
  132. Game::Systems::NationRegistry::instance().initialize_defaults();
  133. Game::Systems::TroopCountRegistry::instance().initialize();
  134. Game::Systems::GlobalStatsRegistry::instance().initialize();
  135. m_world = std::make_unique<Engine::Core::World>();
  136. auto rendering = RendererBootstrap::initialize_rendering();
  137. m_renderer = std::move(rendering.renderer);
  138. m_camera = std::move(rendering.camera);
  139. m_ground = std::move(rendering.ground);
  140. m_terrain = std::move(rendering.terrain);
  141. m_biome = std::move(rendering.biome);
  142. m_river = std::move(rendering.river);
  143. m_road = std::move(rendering.road);
  144. m_riverbank = std::move(rendering.riverbank);
  145. m_bridge = std::move(rendering.bridge);
  146. m_fog = std::move(rendering.fog);
  147. m_stone = std::move(rendering.stone);
  148. m_plant = std::move(rendering.plant);
  149. m_pine = std::move(rendering.pine);
  150. m_olive = std::move(rendering.olive);
  151. m_firecamp = std::move(rendering.firecamp);
  152. m_passes = std::move(rendering.passes);
  153. RendererBootstrap::initialize_world_systems(*m_world);
  154. m_pickingService = std::make_unique<Game::Systems::PickingService>();
  155. m_victoryService = std::make_unique<Game::Systems::VictoryService>();
  156. m_saveLoadService = std::make_unique<Game::Systems::SaveLoadService>();
  157. m_cameraService = std::make_unique<Game::Systems::CameraService>();
  158. auto *selection_system =
  159. m_world->get_system<Game::Systems::SelectionSystem>();
  160. m_selectionController = std::make_unique<Game::Systems::SelectionController>(
  161. m_world.get(), selection_system, m_pickingService.get());
  162. m_commandController = std::make_unique<App::Controllers::CommandController>(
  163. m_world.get(), selection_system, m_pickingService.get());
  164. m_cursorManager = std::make_unique<CursorManager>();
  165. m_hoverTracker = std::make_unique<HoverTracker>(m_pickingService.get());
  166. m_mapCatalog = std::make_unique<Game::Map::MapCatalog>(this);
  167. connect(m_mapCatalog.get(), &Game::Map::MapCatalog::map_loaded, this,
  168. [this](const QVariantMap &mapData) {
  169. m_available_maps.append(mapData);
  170. emit available_maps_changed();
  171. });
  172. connect(m_mapCatalog.get(), &Game::Map::MapCatalog::loading_changed, this,
  173. [this](bool loading) {
  174. m_maps_loading = loading;
  175. emit maps_loading_changed();
  176. });
  177. connect(m_mapCatalog.get(), &Game::Map::MapCatalog::all_maps_loaded, this,
  178. [this]() { emit available_maps_changed(); });
  179. if (AudioSystem::getInstance().initialize()) {
  180. qInfo() << "AudioSystem initialized successfully";
  181. AudioResourceLoader::load_audio_resources();
  182. } else {
  183. qWarning() << "Failed to initialize AudioSystem";
  184. }
  185. m_audio_systemProxy = std::make_unique<App::Models::AudioSystemProxy>(this);
  186. m_minimap_manager = std::make_unique<MinimapManager>();
  187. m_ambient_state_manager = std::make_unique<AmbientStateManager>();
  188. m_input_handler = std::make_unique<InputCommandHandler>(
  189. m_world.get(), m_selectionController.get(), m_commandController.get(),
  190. m_cursorManager.get(), m_hoverTracker.get(), m_pickingService.get(),
  191. m_camera.get());
  192. m_camera_controller = std::make_unique<CameraController>(
  193. m_camera.get(), m_cameraService.get(), m_world.get());
  194. m_audioEventHandler =
  195. std::make_unique<Game::Audio::AudioEventHandler>(m_world.get());
  196. if (m_audioEventHandler->initialize()) {
  197. qInfo() << "AudioEventHandler initialized successfully";
  198. m_audioEventHandler->loadUnitVoiceMapping("archer", "archer_voice");
  199. m_audioEventHandler->loadUnitVoiceMapping("swordsman", "swordsman_voice");
  200. m_audioEventHandler->loadUnitVoiceMapping("swordsman", "swordsman_voice");
  201. m_audioEventHandler->loadUnitVoiceMapping("spearman", "spearman_voice");
  202. m_audioEventHandler->loadAmbientMusic(Engine::Core::AmbientState::PEACEFUL,
  203. "music_peaceful");
  204. m_audioEventHandler->loadAmbientMusic(Engine::Core::AmbientState::TENSE,
  205. "music_tense");
  206. m_audioEventHandler->loadAmbientMusic(Engine::Core::AmbientState::COMBAT,
  207. "music_combat");
  208. m_audioEventHandler->loadAmbientMusic(Engine::Core::AmbientState::VICTORY,
  209. "music_victory");
  210. m_audioEventHandler->loadAmbientMusic(Engine::Core::AmbientState::DEFEAT,
  211. "music_defeat");
  212. qInfo() << "Audio mappings configured";
  213. } else {
  214. qWarning() << "Failed to initialize AudioEventHandler";
  215. }
  216. connect(m_cursorManager.get(), &CursorManager::modeChanged, this,
  217. &GameEngine::cursor_mode_changed);
  218. connect(m_cursorManager.get(), &CursorManager::globalCursorChanged, this,
  219. &GameEngine::global_cursor_changed);
  220. connect(m_selectionController.get(),
  221. &Game::Systems::SelectionController::selection_changed, this,
  222. &GameEngine::selected_units_changed);
  223. connect(m_selectionController.get(),
  224. &Game::Systems::SelectionController::selection_changed, this,
  225. &GameEngine::sync_selection_flags);
  226. connect(
  227. m_selectionController.get(),
  228. &Game::Systems::SelectionController::selection_model_refresh_requested,
  229. this, &GameEngine::selected_units_data_changed);
  230. connect(m_commandController.get(),
  231. &App::Controllers::CommandController::attack_targetSelected,
  232. [this]() {
  233. if (auto *sel_sys =
  234. m_world->get_system<Game::Systems::SelectionSystem>()) {
  235. const auto &sel = sel_sys->get_selected_units();
  236. if (!sel.empty()) {
  237. auto *cam = m_camera.get();
  238. auto *picking = m_pickingService.get();
  239. if ((cam != nullptr) && (picking != nullptr)) {
  240. Engine::Core::EntityID const target_id =
  241. Game::Systems::PickingService::pick_unit_first(
  242. 0.0F, 0.0F, *m_world, *cam, m_viewport.width,
  243. m_viewport.height, 0);
  244. if (target_id != 0) {
  245. App::Controllers::ActionVFX::spawnAttackArrow(m_world.get(),
  246. target_id);
  247. }
  248. }
  249. }
  250. }
  251. });
  252. connect(m_commandController.get(),
  253. &App::Controllers::CommandController::troopLimitReached, [this]() {
  254. set_error(
  255. "Maximum troop limit reached. Cannot produce more units.");
  256. });
  257. connect(m_commandController.get(),
  258. &App::Controllers::CommandController::hold_modeChanged, this,
  259. &GameEngine::hold_mode_changed);
  260. connect(this, SIGNAL(selected_units_changed()), m_selectedUnitsModel,
  261. SLOT(refresh()));
  262. connect(this, SIGNAL(selected_units_data_changed()), m_selectedUnitsModel,
  263. SLOT(refresh()));
  264. emit selected_units_changed();
  265. m_unit_died_subscription =
  266. Engine::Core::ScopedEventSubscription<Engine::Core::UnitDiedEvent>(
  267. [this](const Engine::Core::UnitDiedEvent &e) {
  268. on_unit_died(e);
  269. if (e.owner_id != m_runtime.local_owner_id) {
  270. int const individuals_per_unit =
  271. Game::Units::TroopConfig::instance().getIndividualsPerUnit(
  272. e.spawn_type);
  273. m_enemyTroopsDefeated += individuals_per_unit;
  274. emit enemy_troops_defeated_changed();
  275. }
  276. });
  277. m_unit_spawned_subscription =
  278. Engine::Core::ScopedEventSubscription<Engine::Core::UnitSpawnedEvent>(
  279. [this](const Engine::Core::UnitSpawnedEvent &e) {
  280. on_unit_spawned(e);
  281. });
  282. }
  283. GameEngine::~GameEngine() {
  284. if (m_audioEventHandler) {
  285. m_audioEventHandler->shutdown();
  286. }
  287. AudioSystem::getInstance().shutdown();
  288. qInfo() << "AudioSystem shut down";
  289. }
  290. void GameEngine::cleanup_opengl_resources() {
  291. qInfo() << "Cleaning up OpenGL resources...";
  292. QOpenGLContext *context = QOpenGLContext::currentContext();
  293. const bool has_valid_context = (context != nullptr);
  294. if (!has_valid_context) {
  295. qInfo() << "No valid OpenGL context, skipping OpenGL cleanup";
  296. }
  297. if (m_renderer && has_valid_context) {
  298. m_renderer->shutdown();
  299. qInfo() << "Renderer shut down";
  300. }
  301. m_passes.clear();
  302. m_ground.reset();
  303. m_terrain.reset();
  304. m_biome.reset();
  305. m_river.reset();
  306. m_road.reset();
  307. m_riverbank.reset();
  308. m_bridge.reset();
  309. m_fog.reset();
  310. m_stone.reset();
  311. m_plant.reset();
  312. m_pine.reset();
  313. m_olive.reset();
  314. m_firecamp.reset();
  315. m_renderer.reset();
  316. m_resources.reset();
  317. qInfo() << "OpenGL resources cleaned up";
  318. }
  319. void GameEngine::on_map_clicked(qreal sx, qreal sy) {
  320. if (m_window == nullptr) {
  321. return;
  322. }
  323. ensure_initialized();
  324. if (m_input_handler) {
  325. m_input_handler->on_map_clicked(sx, sy, m_runtime.local_owner_id,
  326. m_viewport);
  327. }
  328. }
  329. void GameEngine::on_right_click(qreal sx, qreal sy) {
  330. if (m_window == nullptr) {
  331. return;
  332. }
  333. ensure_initialized();
  334. if (m_input_handler) {
  335. m_input_handler->on_right_click(sx, sy, m_runtime.local_owner_id,
  336. m_viewport);
  337. }
  338. }
  339. void GameEngine::on_attack_click(qreal sx, qreal sy) {
  340. if (m_window == nullptr) {
  341. return;
  342. }
  343. ensure_initialized();
  344. if (m_input_handler) {
  345. m_input_handler->on_attack_click(sx, sy, m_viewport);
  346. }
  347. }
  348. void GameEngine::reset_movement(Engine::Core::Entity *entity) {
  349. InputCommandHandler::reset_movement(entity);
  350. }
  351. void GameEngine::on_stop_command() {
  352. if (!m_input_handler) {
  353. return;
  354. }
  355. ensure_initialized();
  356. m_input_handler->on_stop_command();
  357. }
  358. void GameEngine::on_hold_command() {
  359. if (!m_input_handler) {
  360. return;
  361. }
  362. ensure_initialized();
  363. m_input_handler->on_hold_command();
  364. }
  365. auto GameEngine::any_selected_in_hold_mode() const -> bool {
  366. if (!m_input_handler) {
  367. return false;
  368. }
  369. return m_input_handler->any_selected_in_hold_mode();
  370. }
  371. void GameEngine::on_patrol_click(qreal sx, qreal sy) {
  372. if (!m_input_handler || !m_camera) {
  373. return;
  374. }
  375. ensure_initialized();
  376. m_input_handler->on_patrol_click(sx, sy, m_viewport);
  377. }
  378. void GameEngine::update_cursor(Qt::CursorShape newCursor) {
  379. if (m_window == nullptr) {
  380. return;
  381. }
  382. if (m_runtime.current_cursor != newCursor) {
  383. m_runtime.current_cursor = newCursor;
  384. m_window->setCursor(newCursor);
  385. }
  386. }
  387. void GameEngine::set_error(const QString &errorMessage) {
  388. if (m_runtime.last_error != errorMessage) {
  389. m_runtime.last_error = errorMessage;
  390. qCritical() << "GameEngine error:" << errorMessage;
  391. emit last_error_changed();
  392. }
  393. }
  394. void GameEngine::set_cursor_mode(CursorMode mode) {
  395. if (!m_cursorManager) {
  396. return;
  397. }
  398. m_cursorManager->setMode(mode);
  399. m_cursorManager->updateCursorShape(m_window);
  400. }
  401. void GameEngine::set_cursor_mode(const QString &mode) {
  402. set_cursor_mode(CursorModeUtils::fromString(mode));
  403. }
  404. auto GameEngine::cursor_mode() const -> QString {
  405. if (!m_cursorManager) {
  406. return "normal";
  407. }
  408. return m_cursorManager->modeString();
  409. }
  410. auto GameEngine::global_cursor_x() const -> qreal {
  411. if (!m_cursorManager) {
  412. return 0;
  413. }
  414. return m_cursorManager->global_cursor_x(m_window);
  415. }
  416. auto GameEngine::global_cursor_y() const -> qreal {
  417. if (!m_cursorManager) {
  418. return 0;
  419. }
  420. return m_cursorManager->global_cursor_y(m_window);
  421. }
  422. void GameEngine::set_hover_at_screen(qreal sx, qreal sy) {
  423. if (m_window == nullptr) {
  424. return;
  425. }
  426. ensure_initialized();
  427. if (m_input_handler) {
  428. m_input_handler->set_hover_at_screen(sx, sy, m_viewport);
  429. }
  430. }
  431. void GameEngine::on_click_select(qreal sx, qreal sy, bool additive) {
  432. if (m_window == nullptr) {
  433. return;
  434. }
  435. ensure_initialized();
  436. if (m_input_handler) {
  437. m_input_handler->on_click_select(sx, sy, additive, m_runtime.local_owner_id,
  438. m_viewport);
  439. }
  440. }
  441. void GameEngine::on_area_selected(qreal x1, qreal y1, qreal x2, qreal y2,
  442. bool additive) {
  443. if (m_window == nullptr) {
  444. return;
  445. }
  446. ensure_initialized();
  447. if (m_input_handler) {
  448. m_input_handler->on_area_selected(x1, y1, x2, y2, additive,
  449. m_runtime.local_owner_id, m_viewport);
  450. }
  451. }
  452. void GameEngine::select_all_troops() {
  453. ensure_initialized();
  454. if (m_input_handler) {
  455. m_input_handler->select_all_troops(m_runtime.local_owner_id);
  456. }
  457. }
  458. void GameEngine::select_unit_by_id(int unitId) {
  459. ensure_initialized();
  460. if (m_input_handler) {
  461. m_input_handler->select_unit_by_id(unitId, m_runtime.local_owner_id);
  462. }
  463. }
  464. void GameEngine::ensure_initialized() {
  465. QString error;
  466. Game::Map::WorldBootstrap::ensure_initialized(
  467. m_runtime.initialized, *m_renderer, *m_camera, m_ground.get(), &error);
  468. if (!error.isEmpty()) {
  469. set_error(error);
  470. }
  471. }
  472. auto GameEngine::enemy_troops_defeated() const -> int {
  473. return m_enemyTroopsDefeated;
  474. }
  475. auto GameEngine::get_player_stats(int owner_id) -> QVariantMap {
  476. QVariantMap result;
  477. auto &stats_registry = Game::Systems::GlobalStatsRegistry::instance();
  478. const auto *stats = stats_registry.get_stats(owner_id);
  479. if (stats != nullptr) {
  480. result["troopsRecruited"] = stats->troops_recruited;
  481. result["enemiesKilled"] = stats->enemies_killed;
  482. result["barracksOwned"] = stats->barracks_owned;
  483. result["playTimeSec"] = stats->play_time_sec;
  484. result["gameEnded"] = stats->game_ended;
  485. } else {
  486. result["troopsRecruited"] = 0;
  487. result["enemiesKilled"] = 0;
  488. result["barracksOwned"] = 0;
  489. result["playTimeSec"] = 0.0F;
  490. result["gameEnded"] = false;
  491. }
  492. return result;
  493. }
  494. void GameEngine::update(float dt) {
  495. if (m_runtime.loading) {
  496. return;
  497. }
  498. if (m_runtime.paused) {
  499. dt = 0.0F;
  500. } else {
  501. dt *= m_runtime.time_scale;
  502. }
  503. if (!m_runtime.paused && !m_runtime.loading) {
  504. if (m_ambient_state_manager) {
  505. m_ambient_state_manager->update(dt, m_world.get(),
  506. m_runtime.local_owner_id, m_entity_cache,
  507. m_runtime.victory_state);
  508. }
  509. }
  510. if (m_renderer) {
  511. m_renderer->update_animation_time(dt);
  512. }
  513. if (m_camera) {
  514. m_camera->update(dt);
  515. }
  516. if (m_world) {
  517. m_world->update(dt);
  518. auto &visibility_service = Game::Map::VisibilityService::instance();
  519. if (visibility_service.is_initialized()) {
  520. m_runtime.visibility_update_accumulator += dt;
  521. const float visibility_update_interval =
  522. Game::GameConfig::instance().gameplay().visibility_update_interval;
  523. if (m_runtime.visibility_update_accumulator >=
  524. visibility_update_interval) {
  525. m_runtime.visibility_update_accumulator = 0.0F;
  526. visibility_service.update(*m_world, m_runtime.local_owner_id);
  527. }
  528. const auto new_version = visibility_service.version();
  529. if (new_version != m_runtime.visibility_version) {
  530. if (m_fog) {
  531. m_fog->update_mask(visibility_service.getWidth(),
  532. visibility_service.getHeight(),
  533. visibility_service.getTileSize(),
  534. visibility_service.snapshotCells());
  535. }
  536. m_runtime.visibility_version = new_version;
  537. }
  538. }
  539. if (m_minimap_manager) {
  540. m_minimap_manager->update_fog(dt, m_runtime.local_owner_id);
  541. auto *selection_system =
  542. m_world->get_system<Game::Systems::SelectionSystem>();
  543. m_minimap_manager->update_units(m_world.get(), selection_system);
  544. emit minimap_image_changed();
  545. }
  546. }
  547. if (m_victoryService && m_world) {
  548. m_victoryService->update(*m_world, dt);
  549. }
  550. if (m_camera_controller) {
  551. m_camera_controller->update_follow(m_followSelectionEnabled);
  552. }
  553. if (m_selectedUnitsModel != nullptr) {
  554. auto *selection_system =
  555. m_world->get_system<Game::Systems::SelectionSystem>();
  556. if ((selection_system != nullptr) &&
  557. !selection_system->get_selected_units().empty()) {
  558. m_runtime.selection_refresh_counter++;
  559. if (m_runtime.selection_refresh_counter >= 15) {
  560. m_runtime.selection_refresh_counter = 0;
  561. emit selected_units_data_changed();
  562. }
  563. }
  564. }
  565. }
  566. void GameEngine::render(int pixelWidth, int pixelHeight) {
  567. if (!m_renderer || !m_world || !m_runtime.initialized || m_runtime.loading) {
  568. return;
  569. }
  570. if (pixelWidth > 0 && pixelHeight > 0) {
  571. m_viewport.width = pixelWidth;
  572. m_viewport.height = pixelHeight;
  573. m_renderer->set_viewport(pixelWidth, pixelHeight);
  574. }
  575. if (auto *selection_system =
  576. m_world->get_system<Game::Systems::SelectionSystem>()) {
  577. const auto &sel = selection_system->get_selected_units();
  578. std::vector<unsigned int> const ids(sel.begin(), sel.end());
  579. m_renderer->set_selected_entities(ids);
  580. }
  581. m_renderer->begin_frame();
  582. if (auto *res = m_renderer->resources()) {
  583. for (auto *pass : m_passes) {
  584. if (pass != nullptr) {
  585. pass->submit(*m_renderer, res);
  586. }
  587. }
  588. }
  589. if (m_renderer && m_hoverTracker) {
  590. m_renderer->set_hovered_entity_id(m_hoverTracker->getLastHoveredEntity());
  591. }
  592. if (m_renderer) {
  593. m_renderer->set_local_owner_id(m_runtime.local_owner_id);
  594. }
  595. m_renderer->render_world(m_world.get());
  596. if (auto *arrow_system = m_world->get_system<Game::Systems::ArrowSystem>()) {
  597. if (auto *res = m_renderer->resources()) {
  598. Render::GL::render_arrows(m_renderer.get(), res, *arrow_system);
  599. }
  600. }
  601. if (auto *projectile_system =
  602. m_world->get_system<Game::Systems::ProjectileSystem>()) {
  603. if (auto *res = m_renderer->resources()) {
  604. Render::GL::render_projectiles(m_renderer.get(), res, *projectile_system);
  605. }
  606. }
  607. if (auto *res = m_renderer->resources()) {
  608. std::optional<QVector3D> preview_waypoint;
  609. if (m_commandController && m_commandController->hasPatrolFirstWaypoint()) {
  610. preview_waypoint = m_commandController->getPatrolFirstWaypoint();
  611. }
  612. Render::GL::renderPatrolFlags(m_renderer.get(), res, *m_world,
  613. preview_waypoint);
  614. }
  615. m_renderer->end_frame();
  616. qreal const current_x = global_cursor_x();
  617. qreal const current_y = global_cursor_y();
  618. if (current_x != m_runtime.last_cursor_x ||
  619. current_y != m_runtime.last_cursor_y) {
  620. m_runtime.last_cursor_x = current_x;
  621. m_runtime.last_cursor_y = current_y;
  622. emit global_cursor_changed();
  623. }
  624. }
  625. auto GameEngine::screen_to_ground(const QPointF &screenPt,
  626. QVector3D &outWorld) -> bool {
  627. return App::Utils::screen_to_ground(m_pickingService.get(), m_camera.get(),
  628. m_window, m_viewport.width,
  629. m_viewport.height, screenPt, outWorld);
  630. }
  631. auto GameEngine::world_to_screen(const QVector3D &world,
  632. QPointF &outScreen) const -> bool {
  633. return App::Utils::world_to_screen(m_pickingService.get(), m_camera.get(),
  634. m_window, m_viewport.width,
  635. m_viewport.height, world, outScreen);
  636. }
  637. void GameEngine::sync_selection_flags() {
  638. auto *selection_system =
  639. m_world->get_system<Game::Systems::SelectionSystem>();
  640. if (!m_world || (selection_system == nullptr)) {
  641. return;
  642. }
  643. App::Utils::sanitize_selection(m_world.get(), selection_system);
  644. if (selection_system->get_selected_units().empty()) {
  645. if (m_cursorManager && m_cursorManager->mode() != CursorMode::Normal) {
  646. set_cursor_mode(CursorMode::Normal);
  647. }
  648. }
  649. }
  650. void GameEngine::camera_move(float dx, float dz) {
  651. ensure_initialized();
  652. if (m_camera_controller) {
  653. m_camera_controller->move(dx, dz);
  654. }
  655. }
  656. void GameEngine::camera_elevate(float dy) {
  657. ensure_initialized();
  658. if (m_camera_controller) {
  659. m_camera_controller->elevate(dy);
  660. }
  661. }
  662. void GameEngine::reset_camera() {
  663. ensure_initialized();
  664. if (m_camera_controller) {
  665. m_camera_controller->reset(m_runtime.local_owner_id, m_level);
  666. }
  667. }
  668. void GameEngine::camera_zoom(float delta) {
  669. ensure_initialized();
  670. if (m_camera_controller) {
  671. m_camera_controller->zoom(delta);
  672. }
  673. }
  674. auto GameEngine::camera_distance() const -> float {
  675. if (m_camera_controller) {
  676. return m_camera_controller->distance();
  677. }
  678. return 0.0F;
  679. }
  680. void GameEngine::camera_yaw(float degrees) {
  681. ensure_initialized();
  682. if (m_camera_controller) {
  683. m_camera_controller->yaw(degrees);
  684. }
  685. }
  686. void GameEngine::camera_orbit(float yaw_deg, float pitch_deg) {
  687. ensure_initialized();
  688. if (m_camera_controller) {
  689. m_camera_controller->orbit(yaw_deg, pitch_deg);
  690. }
  691. }
  692. void GameEngine::camera_orbit_direction(int direction, bool shift) {
  693. if (m_camera_controller) {
  694. m_camera_controller->orbit_direction(direction, shift);
  695. }
  696. }
  697. void GameEngine::camera_follow_selection(bool enable) {
  698. ensure_initialized();
  699. m_followSelectionEnabled = enable;
  700. if (m_camera_controller) {
  701. m_camera_controller->follow_selection(enable);
  702. }
  703. }
  704. void GameEngine::camera_set_follow_lerp(float alpha) {
  705. ensure_initialized();
  706. if (m_camera_controller) {
  707. m_camera_controller->set_follow_lerp(alpha);
  708. }
  709. }
  710. auto GameEngine::selected_units_model() -> QAbstractItemModel * {
  711. return m_selectedUnitsModel;
  712. }
  713. auto GameEngine::audio_system() -> QObject * {
  714. return m_audio_systemProxy.get();
  715. }
  716. auto GameEngine::has_units_selected() const -> bool {
  717. if (!m_selectionController) {
  718. return false;
  719. }
  720. return m_selectionController->has_units_selected();
  721. }
  722. auto GameEngine::player_troop_count() const -> int {
  723. return m_entity_cache.player_troop_count;
  724. }
  725. auto GameEngine::has_selected_type(const QString &type) const -> bool {
  726. if (!m_selectionController) {
  727. return false;
  728. }
  729. return m_selectionController->has_selected_type(type);
  730. }
  731. void GameEngine::recruit_near_selected(const QString &unit_type) {
  732. ensure_initialized();
  733. if (!m_commandController) {
  734. return;
  735. }
  736. m_commandController->recruitNearSelected(unit_type, m_runtime.local_owner_id);
  737. }
  738. auto GameEngine::get_selected_production_state() const -> QVariantMap {
  739. QVariantMap m;
  740. m["has_barracks"] = false;
  741. m["in_progress"] = false;
  742. m["time_remaining"] = 0.0;
  743. m["build_time"] = 0.0;
  744. m["produced_count"] = 0;
  745. m["max_units"] = 0;
  746. m["villager_cost"] = 1;
  747. if (!m_world) {
  748. return m;
  749. }
  750. auto *selection_system =
  751. m_world->get_system<Game::Systems::SelectionSystem>();
  752. if (selection_system == nullptr) {
  753. return m;
  754. }
  755. Game::Systems::ProductionState st;
  756. Game::Systems::ProductionService::getSelectedBarracksState(
  757. *m_world, selection_system->get_selected_units(),
  758. m_runtime.local_owner_id, st);
  759. m["has_barracks"] = st.has_barracks;
  760. m["in_progress"] = st.in_progress;
  761. m["product_type"] =
  762. QString::fromStdString(Game::Units::troop_typeToString(st.product_type));
  763. m["time_remaining"] = st.time_remaining;
  764. m["build_time"] = st.build_time;
  765. m["produced_count"] = st.produced_count;
  766. m["max_units"] = st.max_units;
  767. m["villager_cost"] = st.villager_cost;
  768. m["queue_size"] = st.queue_size;
  769. m["nation_id"] =
  770. QString::fromStdString(Game::Systems::nationIDToString(st.nation_id));
  771. QVariantList queue_list;
  772. for (const auto &unit_type : st.production_queue) {
  773. queue_list.append(
  774. QString::fromStdString(Game::Units::troop_typeToString(unit_type)));
  775. }
  776. m["production_queue"] = queue_list;
  777. return m;
  778. }
  779. auto GameEngine::get_unit_production_info(const QString &unit_type) const
  780. -> QVariantMap {
  781. QVariantMap info;
  782. const auto &config = Game::Units::TroopConfig::instance();
  783. std::string type_str = unit_type.toStdString();
  784. info["cost"] = config.getProductionCost(type_str);
  785. info["build_time"] = static_cast<double>(config.getBuildTime(type_str));
  786. info["individuals_per_unit"] = config.getIndividualsPerUnit(type_str);
  787. return info;
  788. }
  789. auto GameEngine::get_selected_units_command_mode() const -> QString {
  790. if (!m_world) {
  791. return "normal";
  792. }
  793. auto *selection_system =
  794. m_world->get_system<Game::Systems::SelectionSystem>();
  795. if (selection_system == nullptr) {
  796. return "normal";
  797. }
  798. const auto &sel = selection_system->get_selected_units();
  799. if (sel.empty()) {
  800. return "normal";
  801. }
  802. int attacking_count = 0;
  803. int patrolling_count = 0;
  804. int total_units = 0;
  805. for (auto id : sel) {
  806. auto *e = m_world->get_entity(id);
  807. if (e == nullptr) {
  808. continue;
  809. }
  810. auto *u = e->get_component<Engine::Core::UnitComponent>();
  811. if (u == nullptr) {
  812. continue;
  813. }
  814. if (u->spawn_type == Game::Units::SpawnType::Barracks) {
  815. continue;
  816. }
  817. total_units++;
  818. if (e->get_component<Engine::Core::AttackTargetComponent>() != nullptr) {
  819. attacking_count++;
  820. }
  821. auto *patrol = e->get_component<Engine::Core::PatrolComponent>();
  822. if ((patrol != nullptr) && patrol->patrolling) {
  823. patrolling_count++;
  824. }
  825. }
  826. if (total_units == 0) {
  827. return "normal";
  828. }
  829. if (patrolling_count == total_units) {
  830. return "patrol";
  831. }
  832. if (attacking_count == total_units) {
  833. return "attack";
  834. }
  835. return "normal";
  836. }
  837. void GameEngine::set_rally_at_screen(qreal sx, qreal sy) {
  838. ensure_initialized();
  839. if (!m_commandController || !m_camera) {
  840. return;
  841. }
  842. m_commandController->setRallyAtScreen(sx, sy, m_viewport.width,
  843. m_viewport.height, m_camera.get(),
  844. m_runtime.local_owner_id);
  845. }
  846. void GameEngine::start_loading_maps() {
  847. m_available_maps.clear();
  848. if (m_mapCatalog) {
  849. m_mapCatalog->load_maps_async();
  850. }
  851. load_campaigns();
  852. }
  853. auto GameEngine::available_maps() const -> QVariantList {
  854. return m_available_maps;
  855. }
  856. auto GameEngine::available_nations() const -> QVariantList {
  857. QVariantList nations;
  858. const auto &registry = Game::Systems::NationRegistry::instance();
  859. const auto &all = registry.get_all_nations();
  860. QList<QVariantMap> ordered;
  861. ordered.reserve(static_cast<int>(all.size()));
  862. for (const auto &nation : all) {
  863. QVariantMap entry;
  864. entry.insert(
  865. QStringLiteral("id"),
  866. QString::fromStdString(Game::Systems::nationIDToString(nation.id)));
  867. entry.insert(QStringLiteral("name"),
  868. QString::fromStdString(nation.display_name));
  869. ordered.append(entry);
  870. }
  871. std::sort(ordered.begin(), ordered.end(),
  872. [](const QVariantMap &a, const QVariantMap &b) {
  873. return a.value(QStringLiteral("name"))
  874. .toString()
  875. .localeAwareCompare(
  876. b.value(QStringLiteral("name")).toString()) < 0;
  877. });
  878. for (const auto &entry : ordered) {
  879. nations.append(entry);
  880. }
  881. return nations;
  882. }
  883. auto GameEngine::available_campaigns() const -> QVariantList {
  884. return m_available_campaigns;
  885. }
  886. void GameEngine::load_campaigns() {
  887. if (!m_saveLoadService) {
  888. return;
  889. }
  890. QString error;
  891. auto campaigns = m_saveLoadService->list_campaigns(&error);
  892. if (!error.isEmpty()) {
  893. qWarning() << "Failed to load campaigns:" << error;
  894. return;
  895. }
  896. m_available_campaigns = campaigns;
  897. emit available_campaigns_changed();
  898. }
  899. void GameEngine::start_campaign_mission(const QString &campaign_id) {
  900. clear_error();
  901. if (!m_saveLoadService) {
  902. set_error("Save/Load service not initialized");
  903. return;
  904. }
  905. QString error;
  906. auto campaigns = m_saveLoadService->list_campaigns(&error);
  907. if (!error.isEmpty()) {
  908. set_error("Failed to load campaign: " + error);
  909. return;
  910. }
  911. QVariantMap selected_campaign;
  912. for (const auto &campaign : campaigns) {
  913. auto campaign_map = campaign.toMap();
  914. if (campaign_map.value("id").toString() == campaign_id) {
  915. selected_campaign = campaign_map;
  916. break;
  917. }
  918. }
  919. if (selected_campaign.isEmpty()) {
  920. set_error("Campaign not found: " + campaign_id);
  921. return;
  922. }
  923. m_current_campaign_id = campaign_id;
  924. QString map_path = selected_campaign.value("mapPath").toString();
  925. QVariantList playerConfigs;
  926. QVariantMap player1;
  927. player1.insert("player_id", 1);
  928. player1.insert("playerName", "Carthage");
  929. player1.insert("colorIndex", 0);
  930. player1.insert("team_id", 0);
  931. player1.insert("nationId", "carthage");
  932. player1.insert("isHuman", true);
  933. playerConfigs.append(player1);
  934. QVariantMap player2;
  935. player2.insert("player_id", 2);
  936. player2.insert("playerName", "Rome");
  937. player2.insert("colorIndex", 1);
  938. player2.insert("team_id", 1);
  939. player2.insert("nationId", "roman_republic");
  940. player2.insert("isHuman", false);
  941. playerConfigs.append(player2);
  942. start_skirmish(map_path, playerConfigs);
  943. }
  944. void GameEngine::mark_current_mission_completed() {
  945. if (m_current_campaign_id.isEmpty()) {
  946. qWarning() << "No active campaign mission to mark as completed";
  947. return;
  948. }
  949. if (!m_saveLoadService) {
  950. qWarning() << "Save/Load service not initialized";
  951. return;
  952. }
  953. QString error;
  954. bool success =
  955. m_saveLoadService->mark_campaign_completed(m_current_campaign_id, &error);
  956. if (!success) {
  957. qWarning() << "Failed to mark campaign as completed:" << error;
  958. } else {
  959. qInfo() << "Campaign mission" << m_current_campaign_id
  960. << "marked as completed";
  961. load_campaigns();
  962. }
  963. }
  964. void GameEngine::start_skirmish(const QString &map_path,
  965. const QVariantList &playerConfigs) {
  966. clear_error();
  967. m_level.map_path = map_path;
  968. m_level.map_name = map_path;
  969. if (!m_runtime.victory_state.isEmpty()) {
  970. m_runtime.victory_state = "";
  971. emit victory_state_changed();
  972. }
  973. if (m_victoryService) {
  974. m_victoryService->reset();
  975. }
  976. m_enemyTroopsDefeated = 0;
  977. if (!m_runtime.initialized) {
  978. ensure_initialized();
  979. return;
  980. }
  981. if (m_world && m_renderer && m_camera) {
  982. m_runtime.loading = true;
  983. if (m_hoverTracker) {
  984. m_hoverTracker->update_hover(-1, -1, *m_world, *m_camera, 0, 0);
  985. }
  986. LevelOrchestrator orchestrator;
  987. LevelOrchestrator::RendererRefs renderers{
  988. m_renderer.get(), m_camera.get(), m_ground.get(), m_terrain.get(),
  989. m_biome.get(), m_river.get(), m_road.get(), m_riverbank.get(),
  990. m_bridge.get(), m_fog.get(), m_stone.get(), m_plant.get(),
  991. m_pine.get(), m_olive.get(), m_firecamp.get()};
  992. auto visibility_ready = [this]() {
  993. m_runtime.visibility_version =
  994. Game::Map::VisibilityService::instance().version();
  995. m_runtime.visibility_update_accumulator = 0.0F;
  996. };
  997. auto owner_update = [this]() { emit owner_info_changed(); };
  998. auto load_result = orchestrator.load_skirmish(
  999. map_path, playerConfigs, m_selected_player_id, *m_world, renderers,
  1000. m_level, m_entity_cache, m_victoryService.get(),
  1001. m_minimap_manager.get(), visibility_ready, owner_update);
  1002. if (load_result.updated_player_id != m_selected_player_id) {
  1003. m_selected_player_id = load_result.updated_player_id;
  1004. emit selected_player_id_changed();
  1005. }
  1006. if (!load_result.success) {
  1007. set_error(load_result.error_message);
  1008. m_runtime.loading = false;
  1009. return;
  1010. }
  1011. m_runtime.local_owner_id = load_result.updated_player_id;
  1012. if (m_victoryService) {
  1013. m_victoryService->setVictoryCallback([this](const QString &state) {
  1014. if (m_runtime.victory_state != state) {
  1015. m_runtime.victory_state = state;
  1016. emit victory_state_changed();
  1017. if (state == "victory" && !m_current_campaign_id.isEmpty()) {
  1018. mark_current_mission_completed();
  1019. }
  1020. }
  1021. });
  1022. }
  1023. m_runtime.loading = false;
  1024. GameStateRestorer::rebuild_entity_cache(m_world.get(), m_entity_cache,
  1025. m_runtime.local_owner_id);
  1026. m_ambient_state_manager = std::make_unique<AmbientStateManager>();
  1027. Engine::Core::EventManager::instance().publish(
  1028. Engine::Core::AmbientStateChangedEvent(
  1029. Engine::Core::AmbientState::PEACEFUL,
  1030. Engine::Core::AmbientState::PEACEFUL));
  1031. emit owner_info_changed();
  1032. }
  1033. }
  1034. void GameEngine::open_settings() {
  1035. if (m_saveLoadService) {
  1036. m_saveLoadService->open_settings();
  1037. }
  1038. }
  1039. void GameEngine::load_save() { load_from_slot("savegame"); }
  1040. void GameEngine::save_game(const QString &filename) {
  1041. save_to_slot(filename, filename);
  1042. }
  1043. void GameEngine::save_game_to_slot(const QString &slotName) {
  1044. save_to_slot(slotName, slotName);
  1045. }
  1046. void GameEngine::load_game_from_slot(const QString &slotName) {
  1047. load_from_slot(slotName);
  1048. }
  1049. auto GameEngine::load_from_slot(const QString &slot) -> bool {
  1050. if (!m_saveLoadService || !m_world) {
  1051. set_error("Load: not initialized");
  1052. return false;
  1053. }
  1054. m_runtime.loading = true;
  1055. if (!m_saveLoadService->load_game_from_slot(*m_world, slot)) {
  1056. set_error(m_saveLoadService->get_last_error());
  1057. m_runtime.loading = false;
  1058. return false;
  1059. }
  1060. const QJsonObject meta = m_saveLoadService->get_last_metadata();
  1061. Game::Systems::GameStateSerializer::restoreLevelFromMetadata(meta, m_level);
  1062. Game::Systems::GameStateSerializer::restoreCameraFromMetadata(
  1063. meta, m_camera.get(), m_viewport.width, m_viewport.height);
  1064. Game::Systems::RuntimeSnapshot runtime_snap = to_runtime_snapshot();
  1065. Game::Systems::GameStateSerializer::restoreRuntimeFromMetadata(meta,
  1066. runtime_snap);
  1067. apply_runtime_snapshot(runtime_snap);
  1068. GameStateRestorer::RendererRefs renderers{
  1069. m_renderer.get(), m_camera.get(), m_ground.get(), m_terrain.get(),
  1070. m_biome.get(), m_river.get(), m_road.get(), m_riverbank.get(),
  1071. m_bridge.get(), m_fog.get(), m_stone.get(), m_plant.get(),
  1072. m_pine.get(), m_olive.get(), m_firecamp.get()};
  1073. GameStateRestorer::restore_environment_from_metadata(
  1074. meta, m_world.get(), renderers, m_level, m_runtime.local_owner_id,
  1075. m_viewport);
  1076. auto unit_reg = std::make_shared<Game::Units::UnitFactoryRegistry>();
  1077. Game::Units::registerBuiltInUnits(*unit_reg);
  1078. Game::Map::MapTransformer::setFactoryRegistry(unit_reg);
  1079. qInfo() << "Factory registry reinitialized after loading saved game";
  1080. GameStateRestorer::rebuild_registries_after_load(
  1081. m_world.get(), m_selected_player_id, m_level, m_runtime.local_owner_id);
  1082. GameStateRestorer::rebuild_entity_cache(m_world.get(), m_entity_cache,
  1083. m_runtime.local_owner_id);
  1084. if (auto *ai_system = m_world->get_system<Game::Systems::AISystem>()) {
  1085. qInfo() << "Reinitializing AI system after loading saved game";
  1086. ai_system->reinitialize();
  1087. }
  1088. if (m_victoryService) {
  1089. m_victoryService->configure(Game::Map::VictoryConfig(),
  1090. m_runtime.local_owner_id);
  1091. }
  1092. m_runtime.loading = false;
  1093. qInfo() << "Game load complete, victory/defeat checks re-enabled";
  1094. emit selected_units_changed();
  1095. emit owner_info_changed();
  1096. return true;
  1097. }
  1098. auto GameEngine::save_to_slot(const QString &slot,
  1099. const QString &title) -> bool {
  1100. if (!m_saveLoadService || !m_world) {
  1101. set_error("Save: not initialized");
  1102. return false;
  1103. }
  1104. Game::Systems::RuntimeSnapshot const runtime_snap = to_runtime_snapshot();
  1105. QJsonObject meta = Game::Systems::GameStateSerializer::buildMetadata(
  1106. *m_world, m_camera.get(), m_level, runtime_snap);
  1107. meta["title"] = title;
  1108. const QByteArray screenshot = capture_screenshot();
  1109. if (!m_saveLoadService->save_game_to_slot(*m_world, slot, title,
  1110. m_level.map_name, meta, screenshot)) {
  1111. set_error(m_saveLoadService->get_last_error());
  1112. return false;
  1113. }
  1114. emit save_slots_changed();
  1115. return true;
  1116. }
  1117. auto GameEngine::get_save_slots() const -> QVariantList {
  1118. if (!m_saveLoadService) {
  1119. qWarning() << "Cannot get save slots: service not initialized";
  1120. return {};
  1121. }
  1122. return m_saveLoadService->get_save_slots();
  1123. }
  1124. void GameEngine::refresh_save_slots() { emit save_slots_changed(); }
  1125. auto GameEngine::delete_save_slot(const QString &slotName) -> bool {
  1126. if (!m_saveLoadService) {
  1127. qWarning() << "Cannot delete save slot: service not initialized";
  1128. return false;
  1129. }
  1130. bool const success = m_saveLoadService->delete_save_slot(slotName);
  1131. if (!success) {
  1132. QString const error = m_saveLoadService->get_last_error();
  1133. qWarning() << "Failed to delete save slot:" << error;
  1134. set_error(error);
  1135. } else {
  1136. emit save_slots_changed();
  1137. }
  1138. return success;
  1139. }
  1140. auto GameEngine::to_runtime_snapshot() const -> Game::Systems::RuntimeSnapshot {
  1141. Game::Systems::RuntimeSnapshot snapshot;
  1142. snapshot.paused = m_runtime.paused;
  1143. snapshot.time_scale = m_runtime.time_scale;
  1144. snapshot.local_owner_id = m_runtime.local_owner_id;
  1145. snapshot.victory_state = m_runtime.victory_state;
  1146. snapshot.cursor_mode = static_cast<int>(m_runtime.cursor_mode);
  1147. snapshot.selected_player_id = m_selected_player_id;
  1148. snapshot.follow_selection = m_followSelectionEnabled;
  1149. return snapshot;
  1150. }
  1151. void GameEngine::apply_runtime_snapshot(
  1152. const Game::Systems::RuntimeSnapshot &snapshot) {
  1153. m_runtime.paused = snapshot.paused;
  1154. m_runtime.time_scale = snapshot.time_scale;
  1155. m_runtime.local_owner_id = snapshot.local_owner_id;
  1156. m_runtime.victory_state = snapshot.victory_state;
  1157. m_selected_player_id = snapshot.selected_player_id;
  1158. m_followSelectionEnabled = snapshot.follow_selection;
  1159. m_runtime.cursor_mode = static_cast<CursorMode>(snapshot.cursor_mode);
  1160. if (m_cursorManager) {
  1161. m_cursorManager->setMode(m_runtime.cursor_mode);
  1162. }
  1163. }
  1164. auto GameEngine::capture_screenshot() const -> QByteArray { return {}; }
  1165. void GameEngine::exit_game() {
  1166. if (m_saveLoadService) {
  1167. m_saveLoadService->exit_game();
  1168. }
  1169. }
  1170. auto GameEngine::get_owner_info() const -> QVariantList {
  1171. QVariantList result;
  1172. const auto &owner_registry = Game::Systems::OwnerRegistry::instance();
  1173. const auto &owners = owner_registry.get_all_owners();
  1174. for (const auto &owner : owners) {
  1175. QVariantMap owner_map;
  1176. owner_map["id"] = owner.owner_id;
  1177. owner_map["name"] = QString::fromStdString(owner.name);
  1178. owner_map["team_id"] = owner.team_id;
  1179. QString type_str;
  1180. switch (owner.type) {
  1181. case Game::Systems::OwnerType::Player:
  1182. type_str = "Player";
  1183. break;
  1184. case Game::Systems::OwnerType::AI:
  1185. type_str = "AI";
  1186. break;
  1187. case Game::Systems::OwnerType::Neutral:
  1188. type_str = "Neutral";
  1189. break;
  1190. }
  1191. owner_map["type"] = type_str;
  1192. owner_map["isLocal"] = (owner.owner_id == m_runtime.local_owner_id);
  1193. result.append(owner_map);
  1194. }
  1195. return result;
  1196. }
  1197. void GameEngine::get_selected_unit_ids(
  1198. std::vector<Engine::Core::EntityID> &out) const {
  1199. out.clear();
  1200. if (!m_selectionController) {
  1201. return;
  1202. }
  1203. m_selectionController->get_selected_unit_ids(out);
  1204. }
  1205. auto GameEngine::get_unit_info(Engine::Core::EntityID id, QString &name,
  1206. int &health, int &max_health, bool &isBuilding,
  1207. bool &alive, QString &nation) const -> bool {
  1208. if (!m_world) {
  1209. return false;
  1210. }
  1211. auto *e = m_world->get_entity(id);
  1212. if (e == nullptr) {
  1213. return false;
  1214. }
  1215. isBuilding = e->has_component<Engine::Core::BuildingComponent>();
  1216. if (auto *u = e->get_component<Engine::Core::UnitComponent>()) {
  1217. name =
  1218. QString::fromStdString(Game::Units::spawn_typeToString(u->spawn_type));
  1219. health = u->health;
  1220. max_health = u->max_health;
  1221. alive = (u->health > 0);
  1222. nation = Game::Systems::nationIDToQString(u->nation_id);
  1223. return true;
  1224. }
  1225. name = QStringLiteral("Entity");
  1226. health = max_health = 0;
  1227. alive = true;
  1228. nation = QStringLiteral("");
  1229. return true;
  1230. }
  1231. void GameEngine::on_unit_spawned(const Engine::Core::UnitSpawnedEvent &event) {
  1232. auto &owners = Game::Systems::OwnerRegistry::instance();
  1233. if (event.owner_id == m_runtime.local_owner_id) {
  1234. if (event.spawn_type == Game::Units::SpawnType::Barracks) {
  1235. m_entity_cache.player_barracks_alive = true;
  1236. } else {
  1237. int const production_cost =
  1238. Game::Units::TroopConfig::instance().getProductionCost(
  1239. event.spawn_type);
  1240. m_entity_cache.player_troop_count += production_cost;
  1241. }
  1242. } else if (owners.is_ai(event.owner_id)) {
  1243. if (event.spawn_type == Game::Units::SpawnType::Barracks) {
  1244. m_entity_cache.enemy_barracks_count++;
  1245. m_entity_cache.enemy_barracks_alive = true;
  1246. }
  1247. }
  1248. auto emit_if_changed = [&] {
  1249. if (m_entity_cache.player_troop_count != m_runtime.last_troop_count) {
  1250. m_runtime.last_troop_count = m_entity_cache.player_troop_count;
  1251. emit troop_count_changed();
  1252. }
  1253. };
  1254. emit_if_changed();
  1255. }
  1256. void GameEngine::on_unit_died(const Engine::Core::UnitDiedEvent &event) {
  1257. auto &owners = Game::Systems::OwnerRegistry::instance();
  1258. if (event.owner_id == m_runtime.local_owner_id) {
  1259. if (event.spawn_type == Game::Units::SpawnType::Barracks) {
  1260. m_entity_cache.player_barracks_alive = false;
  1261. } else {
  1262. int const production_cost =
  1263. Game::Units::TroopConfig::instance().getProductionCost(
  1264. event.spawn_type);
  1265. m_entity_cache.player_troop_count -= production_cost;
  1266. m_entity_cache.player_troop_count =
  1267. std::max(0, m_entity_cache.player_troop_count);
  1268. }
  1269. } else if (owners.is_ai(event.owner_id)) {
  1270. if (event.spawn_type == Game::Units::SpawnType::Barracks) {
  1271. m_entity_cache.enemy_barracks_count--;
  1272. m_entity_cache.enemy_barracks_count =
  1273. std::max(0, m_entity_cache.enemy_barracks_count);
  1274. m_entity_cache.enemy_barracks_alive =
  1275. (m_entity_cache.enemy_barracks_count > 0);
  1276. }
  1277. }
  1278. }
  1279. auto GameEngine::minimap_image() const -> QImage {
  1280. if (m_minimap_manager) {
  1281. return m_minimap_manager->get_image();
  1282. }
  1283. return QImage();
  1284. }