game_engine.cpp 65 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110
  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 "app/models/cursor_mode.h"
  9. #include "app/utils/engine_view_helpers.h"
  10. #include "app/utils/movement_utils.h"
  11. #include "app/utils/selection_utils.h"
  12. #include "core/system.h"
  13. #include "game/audio/AudioSystem.h"
  14. #include "game/units/spawn_type.h"
  15. #include "game/units/troop_type.h"
  16. #include <QBuffer>
  17. #include <QCoreApplication>
  18. #include <QCursor>
  19. #include <QDebug>
  20. #include <QImage>
  21. #include <QOpenGLContext>
  22. #include <QQuickWindow>
  23. #include <QSize>
  24. #include <QVariant>
  25. #include <QVariantMap>
  26. #include <memory>
  27. #include <optional>
  28. #include <qbuffer.h>
  29. #include <qcoreapplication.h>
  30. #include <qdir.h>
  31. #include <qevent.h>
  32. #include <qglobal.h>
  33. #include <qimage.h>
  34. #include <qjsonobject.h>
  35. #include <qnamespace.h>
  36. #include <qobject.h>
  37. #include <qobjectdefs.h>
  38. #include <qpoint.h>
  39. #include <qsize.h>
  40. #include <qstringliteral.h>
  41. #include <qstringview.h>
  42. #include <qtmetamacros.h>
  43. #include <qvectornd.h>
  44. #include "../models/selected_units_model.h"
  45. #include "game/core/component.h"
  46. #include "game/core/event_manager.h"
  47. #include "game/core/world.h"
  48. #include "game/game_config.h"
  49. #include "game/map/environment.h"
  50. #include "game/map/level_loader.h"
  51. #include "game/map/map_catalog.h"
  52. #include "game/map/map_loader.h"
  53. #include "game/map/map_transformer.h"
  54. #include "game/map/skirmish_loader.h"
  55. #include "game/map/terrain_service.h"
  56. #include "game/map/visibility_service.h"
  57. #include "game/map/world_bootstrap.h"
  58. #include "game/systems/ai_system.h"
  59. #include "game/systems/arrow_system.h"
  60. #include "game/systems/building_collision_registry.h"
  61. #include "game/systems/camera_service.h"
  62. #include "game/systems/capture_system.h"
  63. #include "game/systems/cleanup_system.h"
  64. #include "game/systems/combat_system.h"
  65. #include "game/systems/command_service.h"
  66. #include "game/systems/formation_planner.h"
  67. #include "game/systems/game_state_serializer.h"
  68. #include "game/systems/global_stats_registry.h"
  69. #include "game/systems/healing_system.h"
  70. #include "game/systems/movement_system.h"
  71. #include "game/systems/nation_id.h"
  72. #include "game/systems/nation_registry.h"
  73. #include "game/systems/owner_registry.h"
  74. #include "game/systems/patrol_system.h"
  75. #include "game/systems/picking_service.h"
  76. #include "game/systems/production_service.h"
  77. #include "game/systems/production_system.h"
  78. #include "game/systems/save_load_service.h"
  79. #include "game/systems/selection_system.h"
  80. #include "game/systems/terrain_alignment_system.h"
  81. #include "game/systems/troop_count_registry.h"
  82. #include "game/systems/victory_service.h"
  83. #include "game/units/factory.h"
  84. #include "game/units/troop_config.h"
  85. #include "render/geom/arrow.h"
  86. #include "render/geom/patrol_flags.h"
  87. #include "render/gl/bootstrap.h"
  88. #include "render/gl/camera.h"
  89. #include "render/ground/biome_renderer.h"
  90. #include "render/ground/bridge_renderer.h"
  91. #include "render/ground/firecamp_renderer.h"
  92. #include "render/ground/fog_renderer.h"
  93. #include "render/ground/ground_renderer.h"
  94. #include "render/ground/olive_renderer.h"
  95. #include "render/ground/pine_renderer.h"
  96. #include "render/ground/plant_renderer.h"
  97. #include "render/ground/river_renderer.h"
  98. #include "render/ground/riverbank_renderer.h"
  99. #include "render/ground/road_renderer.h"
  100. #include "render/ground/stone_renderer.h"
  101. #include "render/ground/terrain_renderer.h"
  102. #include "render/scene_renderer.h"
  103. #include <QDir>
  104. #include <QFile>
  105. #include <QJsonArray>
  106. #include <QJsonDocument>
  107. #include <QJsonObject>
  108. #include <QSet>
  109. #include <algorithm>
  110. #include <cmath>
  111. #include <utility>
  112. #include <vector>
  113. GameEngine::GameEngine(QObject *parent)
  114. : QObject(parent),
  115. m_selectedUnitsModel(new SelectedUnitsModel(this, this)) {
  116. Game::Systems::NationRegistry::instance().initializeDefaults();
  117. Game::Systems::TroopCountRegistry::instance().initialize();
  118. Game::Systems::GlobalStatsRegistry::instance().initialize();
  119. m_world = std::make_unique<Engine::Core::World>();
  120. m_renderer = std::make_unique<Render::GL::Renderer>();
  121. m_camera = std::make_unique<Render::GL::Camera>();
  122. m_ground = std::make_unique<Render::GL::GroundRenderer>();
  123. m_terrain = std::make_unique<Render::GL::TerrainRenderer>();
  124. m_biome = std::make_unique<Render::GL::BiomeRenderer>();
  125. m_river = std::make_unique<Render::GL::RiverRenderer>();
  126. m_road = std::make_unique<Render::GL::RoadRenderer>();
  127. m_riverbank = std::make_unique<Render::GL::RiverbankRenderer>();
  128. m_bridge = std::make_unique<Render::GL::BridgeRenderer>();
  129. m_fog = std::make_unique<Render::GL::FogRenderer>();
  130. m_stone = std::make_unique<Render::GL::StoneRenderer>();
  131. m_plant = std::make_unique<Render::GL::PlantRenderer>();
  132. m_pine = std::make_unique<Render::GL::PineRenderer>();
  133. m_olive = std::make_unique<Render::GL::OliveRenderer>();
  134. m_firecamp = std::make_unique<Render::GL::FireCampRenderer>();
  135. m_passes = {m_ground.get(), m_terrain.get(), m_river.get(),
  136. m_road.get(), m_riverbank.get(), m_bridge.get(),
  137. m_biome.get(), m_stone.get(), m_plant.get(),
  138. m_pine.get(), m_olive.get(), m_firecamp.get(),
  139. m_fog.get()};
  140. std::unique_ptr<Engine::Core::System> arrow_sys =
  141. std::make_unique<Game::Systems::ArrowSystem>();
  142. m_world->add_system(std::move(arrow_sys));
  143. m_world->add_system(std::make_unique<Game::Systems::MovementSystem>());
  144. m_world->add_system(std::make_unique<Game::Systems::PatrolSystem>());
  145. m_world->add_system(std::make_unique<Game::Systems::CombatSystem>());
  146. m_world->add_system(std::make_unique<Game::Systems::HealingSystem>());
  147. m_world->add_system(std::make_unique<Game::Systems::CaptureSystem>());
  148. m_world->add_system(std::make_unique<Game::Systems::AISystem>());
  149. m_world->add_system(std::make_unique<Game::Systems::ProductionSystem>());
  150. m_world->add_system(
  151. std::make_unique<Game::Systems::TerrainAlignmentSystem>());
  152. m_world->add_system(std::make_unique<Game::Systems::CleanupSystem>());
  153. {
  154. std::unique_ptr<Engine::Core::System> sel_sys =
  155. std::make_unique<Game::Systems::SelectionSystem>();
  156. m_world->add_system(std::move(sel_sys));
  157. }
  158. m_pickingService = std::make_unique<Game::Systems::PickingService>();
  159. m_victoryService = std::make_unique<Game::Systems::VictoryService>();
  160. m_saveLoadService = std::make_unique<Game::Systems::SaveLoadService>();
  161. m_cameraService = std::make_unique<Game::Systems::CameraService>();
  162. auto *selection_system =
  163. m_world->get_system<Game::Systems::SelectionSystem>();
  164. m_selectionController = std::make_unique<Game::Systems::SelectionController>(
  165. m_world.get(), selection_system, m_pickingService.get());
  166. m_commandController = std::make_unique<App::Controllers::CommandController>(
  167. m_world.get(), selection_system, m_pickingService.get());
  168. m_cursorManager = std::make_unique<CursorManager>();
  169. m_hoverTracker = std::make_unique<HoverTracker>(m_pickingService.get());
  170. m_mapCatalog = std::make_unique<Game::Map::MapCatalog>(this);
  171. connect(m_mapCatalog.get(), &Game::Map::MapCatalog::mapLoaded, this,
  172. [this](const QVariantMap &mapData) {
  173. m_available_maps.append(mapData);
  174. emit available_maps_changed();
  175. });
  176. connect(m_mapCatalog.get(), &Game::Map::MapCatalog::loadingChanged, this,
  177. [this](bool loading) {
  178. m_maps_loading = loading;
  179. emit maps_loading_changed();
  180. });
  181. connect(m_mapCatalog.get(), &Game::Map::MapCatalog::allMapsLoaded, this,
  182. [this]() { emit available_maps_changed(); });
  183. if (AudioSystem::getInstance().initialize()) {
  184. qInfo() << "AudioSystem initialized successfully";
  185. load_audio_resources();
  186. } else {
  187. qWarning() << "Failed to initialize AudioSystem";
  188. }
  189. m_audio_systemProxy = std::make_unique<App::Models::AudioSystemProxy>(this);
  190. m_audioEventHandler =
  191. std::make_unique<Game::Audio::AudioEventHandler>(m_world.get());
  192. if (m_audioEventHandler->initialize()) {
  193. qInfo() << "AudioEventHandler initialized successfully";
  194. m_audioEventHandler->loadUnitVoiceMapping("archer", "archer_voice");
  195. m_audioEventHandler->loadUnitVoiceMapping("swordsman", "swordsman_voice");
  196. m_audioEventHandler->loadUnitVoiceMapping("swordsman", "swordsman_voice");
  197. m_audioEventHandler->loadUnitVoiceMapping("spearman", "spearman_voice");
  198. m_audioEventHandler->loadAmbientMusic(Engine::Core::AmbientState::PEACEFUL,
  199. "music_peaceful");
  200. m_audioEventHandler->loadAmbientMusic(Engine::Core::AmbientState::TENSE,
  201. "music_tense");
  202. m_audioEventHandler->loadAmbientMusic(Engine::Core::AmbientState::COMBAT,
  203. "music_combat");
  204. m_audioEventHandler->loadAmbientMusic(Engine::Core::AmbientState::VICTORY,
  205. "music_victory");
  206. m_audioEventHandler->loadAmbientMusic(Engine::Core::AmbientState::DEFEAT,
  207. "music_defeat");
  208. qInfo() << "Audio mappings configured";
  209. } else {
  210. qWarning() << "Failed to initialize AudioEventHandler";
  211. }
  212. connect(m_cursorManager.get(), &CursorManager::modeChanged, this,
  213. &GameEngine::cursor_mode_changed);
  214. connect(m_cursorManager.get(), &CursorManager::globalCursorChanged, this,
  215. &GameEngine::global_cursor_changed);
  216. connect(m_selectionController.get(),
  217. &Game::Systems::SelectionController::selection_changed, this,
  218. &GameEngine::selected_units_changed);
  219. connect(m_selectionController.get(),
  220. &Game::Systems::SelectionController::selection_changed, this,
  221. &GameEngine::sync_selection_flags);
  222. connect(
  223. m_selectionController.get(),
  224. &Game::Systems::SelectionController::selection_model_refresh_requested,
  225. this, &GameEngine::selected_units_data_changed);
  226. connect(m_commandController.get(),
  227. &App::Controllers::CommandController::attack_targetSelected,
  228. [this]() {
  229. if (auto *sel_sys =
  230. m_world->get_system<Game::Systems::SelectionSystem>()) {
  231. const auto &sel = sel_sys->get_selected_units();
  232. if (!sel.empty()) {
  233. auto *cam = m_camera.get();
  234. auto *picking = m_pickingService.get();
  235. if ((cam != nullptr) && (picking != nullptr)) {
  236. Engine::Core::EntityID const target_id =
  237. Game::Systems::PickingService::pick_unit_first(
  238. 0.0F, 0.0F, *m_world, *cam, m_viewport.width,
  239. m_viewport.height, 0);
  240. if (target_id != 0) {
  241. App::Controllers::ActionVFX::spawnAttackArrow(m_world.get(),
  242. target_id);
  243. }
  244. }
  245. }
  246. }
  247. });
  248. connect(m_commandController.get(),
  249. &App::Controllers::CommandController::troopLimitReached, [this]() {
  250. set_error(
  251. "Maximum troop limit reached. Cannot produce more units.");
  252. });
  253. connect(m_commandController.get(),
  254. &App::Controllers::CommandController::hold_modeChanged, this,
  255. &GameEngine::hold_mode_changed);
  256. connect(this, SIGNAL(selected_units_changed()), m_selectedUnitsModel,
  257. SLOT(refresh()));
  258. connect(this, SIGNAL(selected_units_data_changed()), m_selectedUnitsModel,
  259. SLOT(refresh()));
  260. emit selected_units_changed();
  261. m_unit_died_subscription =
  262. Engine::Core::ScopedEventSubscription<Engine::Core::UnitDiedEvent>(
  263. [this](const Engine::Core::UnitDiedEvent &e) {
  264. on_unit_died(e);
  265. if (e.owner_id != m_runtime.local_owner_id) {
  266. int const individuals_per_unit =
  267. Game::Units::TroopConfig::instance().getIndividualsPerUnit(
  268. e.spawn_type);
  269. m_enemyTroopsDefeated += individuals_per_unit;
  270. emit enemy_troops_defeated_changed();
  271. }
  272. });
  273. m_unit_spawned_subscription =
  274. Engine::Core::ScopedEventSubscription<Engine::Core::UnitSpawnedEvent>(
  275. [this](const Engine::Core::UnitSpawnedEvent &e) {
  276. on_unit_spawned(e);
  277. });
  278. }
  279. GameEngine::~GameEngine() {
  280. if (m_audioEventHandler) {
  281. m_audioEventHandler->shutdown();
  282. }
  283. AudioSystem::getInstance().shutdown();
  284. qInfo() << "AudioSystem shut down";
  285. }
  286. void GameEngine::cleanup_opengl_resources() {
  287. qInfo() << "Cleaning up OpenGL resources...";
  288. QOpenGLContext *context = QOpenGLContext::currentContext();
  289. const bool has_valid_context = (context != nullptr);
  290. if (!has_valid_context) {
  291. qInfo() << "No valid OpenGL context, skipping OpenGL cleanup";
  292. }
  293. if (m_renderer && has_valid_context) {
  294. m_renderer->shutdown();
  295. qInfo() << "Renderer shut down";
  296. }
  297. m_passes.clear();
  298. m_ground.reset();
  299. m_terrain.reset();
  300. m_biome.reset();
  301. m_river.reset();
  302. m_road.reset();
  303. m_riverbank.reset();
  304. m_bridge.reset();
  305. m_fog.reset();
  306. m_stone.reset();
  307. m_plant.reset();
  308. m_pine.reset();
  309. m_olive.reset();
  310. m_firecamp.reset();
  311. m_renderer.reset();
  312. m_resources.reset();
  313. qInfo() << "OpenGL resources cleaned up";
  314. }
  315. void GameEngine::on_map_clicked(qreal sx, qreal sy) {
  316. if (m_window == nullptr) {
  317. return;
  318. }
  319. ensure_initialized();
  320. if (m_selectionController && m_camera) {
  321. m_selectionController->on_click_select(sx, sy, false, m_viewport.width,
  322. m_viewport.height, m_camera.get(),
  323. m_runtime.local_owner_id);
  324. }
  325. }
  326. void GameEngine::on_right_click(qreal sx, qreal sy) {
  327. if (m_window == nullptr) {
  328. return;
  329. }
  330. ensure_initialized();
  331. auto *selection_system =
  332. m_world->get_system<Game::Systems::SelectionSystem>();
  333. if (selection_system == nullptr) {
  334. return;
  335. }
  336. if (m_cursorManager->mode() == CursorMode::Patrol ||
  337. m_cursorManager->mode() == CursorMode::Attack) {
  338. set_cursor_mode(CursorMode::Normal);
  339. return;
  340. }
  341. const auto &sel = selection_system->get_selected_units();
  342. if (sel.empty()) {
  343. return;
  344. }
  345. if (m_pickingService && m_camera) {
  346. Engine::Core::EntityID const target_id = m_pickingService->pick_unit_first(
  347. float(sx), float(sy), *m_world, *m_camera, m_viewport.width,
  348. m_viewport.height, 0);
  349. if (target_id != 0U) {
  350. auto *target_entity = m_world->get_entity(target_id);
  351. if (target_entity != nullptr) {
  352. auto *target_unit =
  353. target_entity->get_component<Engine::Core::UnitComponent>();
  354. if (target_unit != nullptr) {
  355. bool const is_enemy =
  356. (target_unit->owner_id != m_runtime.local_owner_id);
  357. if (is_enemy) {
  358. Game::Systems::CommandService::attack_target(*m_world, sel,
  359. target_id, true);
  360. return;
  361. }
  362. }
  363. }
  364. }
  365. }
  366. if (m_pickingService && m_camera) {
  367. QVector3D hit;
  368. if (m_pickingService->screen_to_ground(QPointF(sx, sy), *m_camera,
  369. m_viewport.width, m_viewport.height,
  370. hit)) {
  371. auto targets = Game::Systems::FormationPlanner::spreadFormation(
  372. int(sel.size()), hit,
  373. Game::GameConfig::instance().gameplay().formationSpacingDefault);
  374. Game::Systems::CommandService::MoveOptions opts;
  375. opts.group_move = sel.size() > 1;
  376. Game::Systems::CommandService::moveUnits(*m_world, sel, targets, opts);
  377. }
  378. }
  379. }
  380. void GameEngine::on_attack_click(qreal sx, qreal sy) {
  381. if (m_window == nullptr) {
  382. return;
  383. }
  384. ensure_initialized();
  385. if (!m_commandController || !m_camera) {
  386. return;
  387. }
  388. auto result = m_commandController->onAttackClick(
  389. sx, sy, m_viewport.width, m_viewport.height, m_camera.get());
  390. auto *selection_system =
  391. m_world->get_system<Game::Systems::SelectionSystem>();
  392. if ((selection_system == nullptr) || !m_pickingService || !m_camera ||
  393. !m_world) {
  394. return;
  395. }
  396. const auto &selected = selection_system->get_selected_units();
  397. if (!selected.empty()) {
  398. Engine::Core::EntityID const target_id = m_pickingService->pick_unit_first(
  399. float(sx), float(sy), *m_world, *m_camera, m_viewport.width,
  400. m_viewport.height, 0);
  401. if (target_id != 0) {
  402. auto *target_entity = m_world->get_entity(target_id);
  403. if (target_entity != nullptr) {
  404. auto *target_unit =
  405. target_entity->get_component<Engine::Core::UnitComponent>();
  406. if ((target_unit != nullptr) &&
  407. target_unit->owner_id != m_runtime.local_owner_id) {
  408. App::Controllers::ActionVFX::spawnAttackArrow(m_world.get(),
  409. target_id);
  410. }
  411. }
  412. }
  413. }
  414. if (result.resetCursorToNormal) {
  415. set_cursor_mode(CursorMode::Normal);
  416. }
  417. }
  418. void GameEngine::reset_movement(Engine::Core::Entity *entity) {
  419. App::Utils::reset_movement(entity);
  420. }
  421. void GameEngine::on_stop_command() {
  422. if (!m_commandController) {
  423. return;
  424. }
  425. ensure_initialized();
  426. auto result = m_commandController->onStopCommand();
  427. if (result.resetCursorToNormal) {
  428. set_cursor_mode(CursorMode::Normal);
  429. }
  430. }
  431. void GameEngine::on_hold_command() {
  432. if (!m_commandController) {
  433. return;
  434. }
  435. ensure_initialized();
  436. auto result = m_commandController->onHoldCommand();
  437. if (result.resetCursorToNormal) {
  438. set_cursor_mode(CursorMode::Normal);
  439. }
  440. }
  441. auto GameEngine::any_selected_in_hold_mode() const -> bool {
  442. if (!m_commandController) {
  443. return false;
  444. }
  445. return m_commandController->anySelectedInHoldMode();
  446. }
  447. void GameEngine::on_patrol_click(qreal sx, qreal sy) {
  448. if (!m_commandController || !m_camera) {
  449. return;
  450. }
  451. ensure_initialized();
  452. auto result = m_commandController->onPatrolClick(
  453. sx, sy, m_viewport.width, m_viewport.height, m_camera.get());
  454. if (result.resetCursorToNormal) {
  455. set_cursor_mode(CursorMode::Normal);
  456. }
  457. }
  458. void GameEngine::update_cursor(Qt::CursorShape newCursor) {
  459. if (m_window == nullptr) {
  460. return;
  461. }
  462. if (m_runtime.current_cursor != newCursor) {
  463. m_runtime.current_cursor = newCursor;
  464. m_window->setCursor(newCursor);
  465. }
  466. }
  467. void GameEngine::set_error(const QString &errorMessage) {
  468. if (m_runtime.last_error != errorMessage) {
  469. m_runtime.last_error = errorMessage;
  470. qCritical() << "GameEngine error:" << errorMessage;
  471. emit last_error_changed();
  472. }
  473. }
  474. void GameEngine::set_cursor_mode(CursorMode mode) {
  475. if (!m_cursorManager) {
  476. return;
  477. }
  478. m_cursorManager->setMode(mode);
  479. m_cursorManager->updateCursorShape(m_window);
  480. }
  481. void GameEngine::set_cursor_mode(const QString &mode) {
  482. set_cursor_mode(CursorModeUtils::fromString(mode));
  483. }
  484. auto GameEngine::cursor_mode() const -> QString {
  485. if (!m_cursorManager) {
  486. return "normal";
  487. }
  488. return m_cursorManager->modeString();
  489. }
  490. auto GameEngine::global_cursor_x() const -> qreal {
  491. if (!m_cursorManager) {
  492. return 0;
  493. }
  494. return m_cursorManager->global_cursor_x(m_window);
  495. }
  496. auto GameEngine::global_cursor_y() const -> qreal {
  497. if (!m_cursorManager) {
  498. return 0;
  499. }
  500. return m_cursorManager->global_cursor_y(m_window);
  501. }
  502. void GameEngine::set_hover_at_screen(qreal sx, qreal sy) {
  503. if (m_window == nullptr) {
  504. return;
  505. }
  506. ensure_initialized();
  507. if (!m_hoverTracker || !m_camera || !m_world) {
  508. return;
  509. }
  510. m_cursorManager->updateCursorShape(m_window);
  511. m_hoverTracker->update_hover(float(sx), float(sy), *m_world, *m_camera,
  512. m_viewport.width, m_viewport.height);
  513. }
  514. void GameEngine::on_click_select(qreal sx, qreal sy, bool additive) {
  515. if (m_window == nullptr) {
  516. return;
  517. }
  518. ensure_initialized();
  519. if (m_selectionController && m_camera) {
  520. m_selectionController->on_click_select(sx, sy, additive, m_viewport.width,
  521. m_viewport.height, m_camera.get(),
  522. m_runtime.local_owner_id);
  523. }
  524. }
  525. void GameEngine::on_area_selected(qreal x1, qreal y1, qreal x2, qreal y2,
  526. bool additive) {
  527. if (m_window == nullptr) {
  528. return;
  529. }
  530. ensure_initialized();
  531. if (m_selectionController && m_camera) {
  532. m_selectionController->on_area_selected(
  533. x1, y1, x2, y2, additive, m_viewport.width, m_viewport.height,
  534. m_camera.get(), m_runtime.local_owner_id);
  535. }
  536. }
  537. void GameEngine::select_all_troops() {
  538. ensure_initialized();
  539. if (m_selectionController) {
  540. m_selectionController->select_all_player_troops(m_runtime.local_owner_id);
  541. }
  542. }
  543. void GameEngine::select_unit_by_id(int unitId) {
  544. ensure_initialized();
  545. if (!m_selectionController || (unitId <= 0)) {
  546. return;
  547. }
  548. m_selectionController->select_single_unit(
  549. static_cast<Engine::Core::EntityID>(unitId), m_runtime.local_owner_id);
  550. }
  551. void GameEngine::ensure_initialized() {
  552. QString error;
  553. Game::Map::WorldBootstrap::ensure_initialized(
  554. m_runtime.initialized, *m_renderer, *m_camera, m_ground.get(), &error);
  555. if (!error.isEmpty()) {
  556. set_error(error);
  557. }
  558. }
  559. auto GameEngine::enemy_troops_defeated() const -> int {
  560. return m_enemyTroopsDefeated;
  561. }
  562. auto GameEngine::get_player_stats(int owner_id) -> QVariantMap {
  563. QVariantMap result;
  564. auto &stats_registry = Game::Systems::GlobalStatsRegistry::instance();
  565. const auto *stats = stats_registry.get_stats(owner_id);
  566. if (stats != nullptr) {
  567. result["troopsRecruited"] = stats->troops_recruited;
  568. result["enemiesKilled"] = stats->enemies_killed;
  569. result["barracksOwned"] = stats->barracks_owned;
  570. result["playTimeSec"] = stats->play_time_sec;
  571. result["gameEnded"] = stats->game_ended;
  572. } else {
  573. result["troopsRecruited"] = 0;
  574. result["enemiesKilled"] = 0;
  575. result["barracksOwned"] = 0;
  576. result["playTimeSec"] = 0.0F;
  577. result["gameEnded"] = false;
  578. }
  579. return result;
  580. }
  581. void GameEngine::update(float dt) {
  582. if (m_runtime.loading) {
  583. return;
  584. }
  585. if (m_runtime.paused) {
  586. dt = 0.0F;
  587. } else {
  588. dt *= m_runtime.time_scale;
  589. }
  590. if (!m_runtime.paused && !m_runtime.loading) {
  591. update_ambient_state(dt);
  592. }
  593. if (m_renderer) {
  594. m_renderer->update_animation_time(dt);
  595. }
  596. if (m_camera) {
  597. m_camera->update(dt);
  598. }
  599. if (m_world) {
  600. m_world->update(dt);
  601. auto &visibility_service = Game::Map::VisibilityService::instance();
  602. if (visibility_service.isInitialized()) {
  603. m_runtime.visibilityUpdateAccumulator += dt;
  604. const float visibility_update_interval =
  605. Game::GameConfig::instance().gameplay().visibility_update_interval;
  606. if (m_runtime.visibilityUpdateAccumulator >= visibility_update_interval) {
  607. m_runtime.visibilityUpdateAccumulator = 0.0F;
  608. visibility_service.update(*m_world, m_runtime.local_owner_id);
  609. }
  610. const auto new_version = visibility_service.version();
  611. if (new_version != m_runtime.visibilityVersion) {
  612. if (m_fog) {
  613. m_fog->updateMask(visibility_service.getWidth(),
  614. visibility_service.getHeight(),
  615. visibility_service.getTileSize(),
  616. visibility_service.snapshotCells());
  617. }
  618. m_runtime.visibilityVersion = new_version;
  619. }
  620. }
  621. }
  622. if (m_victoryService && m_world) {
  623. m_victoryService->update(*m_world, dt);
  624. }
  625. if (m_followSelectionEnabled && m_camera && m_world && m_cameraService) {
  626. m_cameraService->update_follow(*m_camera, *m_world,
  627. m_followSelectionEnabled);
  628. }
  629. if (m_selectedUnitsModel != nullptr) {
  630. auto *selection_system =
  631. m_world->get_system<Game::Systems::SelectionSystem>();
  632. if ((selection_system != nullptr) &&
  633. !selection_system->get_selected_units().empty()) {
  634. m_runtime.selectionRefreshCounter++;
  635. if (m_runtime.selectionRefreshCounter >= 15) {
  636. m_runtime.selectionRefreshCounter = 0;
  637. emit selected_units_data_changed();
  638. }
  639. }
  640. }
  641. }
  642. void GameEngine::render(int pixelWidth, int pixelHeight) {
  643. if (!m_renderer || !m_world || !m_runtime.initialized || m_runtime.loading) {
  644. return;
  645. }
  646. if (pixelWidth > 0 && pixelHeight > 0) {
  647. m_viewport.width = pixelWidth;
  648. m_viewport.height = pixelHeight;
  649. m_renderer->set_viewport(pixelWidth, pixelHeight);
  650. }
  651. if (auto *selection_system =
  652. m_world->get_system<Game::Systems::SelectionSystem>()) {
  653. const auto &sel = selection_system->get_selected_units();
  654. std::vector<unsigned int> const ids(sel.begin(), sel.end());
  655. m_renderer->set_selected_entities(ids);
  656. }
  657. m_renderer->begin_frame();
  658. if (auto *res = m_renderer->resources()) {
  659. for (auto *pass : m_passes) {
  660. if (pass != nullptr) {
  661. pass->submit(*m_renderer, res);
  662. }
  663. }
  664. }
  665. if (m_renderer && m_hoverTracker) {
  666. m_renderer->set_hovered_entity_id(m_hoverTracker->getLastHoveredEntity());
  667. }
  668. if (m_renderer) {
  669. m_renderer->set_local_owner_id(m_runtime.local_owner_id);
  670. }
  671. m_renderer->render_world(m_world.get());
  672. if (auto *arrow_system = m_world->get_system<Game::Systems::ArrowSystem>()) {
  673. if (auto *res = m_renderer->resources()) {
  674. Render::GL::renderArrows(m_renderer.get(), res, *arrow_system);
  675. }
  676. }
  677. if (auto *res = m_renderer->resources()) {
  678. std::optional<QVector3D> preview_waypoint;
  679. if (m_commandController && m_commandController->hasPatrolFirstWaypoint()) {
  680. preview_waypoint = m_commandController->getPatrolFirstWaypoint();
  681. }
  682. Render::GL::renderPatrolFlags(m_renderer.get(), res, *m_world,
  683. preview_waypoint);
  684. }
  685. m_renderer->end_frame();
  686. qreal const current_x = global_cursor_x();
  687. qreal const current_y = global_cursor_y();
  688. if (current_x != m_runtime.lastCursorX ||
  689. current_y != m_runtime.lastCursorY) {
  690. m_runtime.lastCursorX = current_x;
  691. m_runtime.lastCursorY = current_y;
  692. emit global_cursor_changed();
  693. }
  694. }
  695. auto GameEngine::screen_to_ground(const QPointF &screenPt,
  696. QVector3D &outWorld) -> bool {
  697. return App::Utils::screen_to_ground(m_pickingService.get(), m_camera.get(),
  698. m_window, m_viewport.width,
  699. m_viewport.height, screenPt, outWorld);
  700. }
  701. auto GameEngine::world_to_screen(const QVector3D &world,
  702. QPointF &outScreen) const -> bool {
  703. return App::Utils::world_to_screen(m_pickingService.get(), m_camera.get(),
  704. m_window, m_viewport.width,
  705. m_viewport.height, world, outScreen);
  706. }
  707. void GameEngine::sync_selection_flags() {
  708. auto *selection_system =
  709. m_world->get_system<Game::Systems::SelectionSystem>();
  710. if (!m_world || (selection_system == nullptr)) {
  711. return;
  712. }
  713. App::Utils::sanitize_selection(m_world.get(), selection_system);
  714. if (selection_system->get_selected_units().empty()) {
  715. if (m_cursorManager && m_cursorManager->mode() != CursorMode::Normal) {
  716. set_cursor_mode(CursorMode::Normal);
  717. }
  718. }
  719. }
  720. void GameEngine::camera_move(float dx, float dz) {
  721. ensure_initialized();
  722. if (!m_camera || !m_cameraService) {
  723. return;
  724. }
  725. m_cameraService->move(*m_camera, dx, dz);
  726. }
  727. void GameEngine::camera_elevate(float dy) {
  728. ensure_initialized();
  729. if (!m_camera || !m_cameraService) {
  730. return;
  731. }
  732. m_cameraService->elevate(*m_camera, dy);
  733. }
  734. void GameEngine::reset_camera() {
  735. ensure_initialized();
  736. if (!m_camera || !m_world || !m_cameraService) {
  737. return;
  738. }
  739. m_cameraService->resetCamera(*m_camera, *m_world, m_runtime.local_owner_id,
  740. m_level.player_unit_id);
  741. }
  742. void GameEngine::camera_zoom(float delta) {
  743. ensure_initialized();
  744. if (!m_camera || !m_cameraService) {
  745. return;
  746. }
  747. m_cameraService->zoom(*m_camera, delta);
  748. }
  749. auto GameEngine::camera_distance() const -> float {
  750. if (!m_camera || !m_cameraService) {
  751. return 0.0F;
  752. }
  753. return m_cameraService->get_distance(*m_camera);
  754. }
  755. void GameEngine::camera_yaw(float degrees) {
  756. ensure_initialized();
  757. if (!m_camera || !m_cameraService) {
  758. return;
  759. }
  760. m_cameraService->yaw(*m_camera, degrees);
  761. }
  762. void GameEngine::camera_orbit(float yaw_deg, float pitch_deg) {
  763. ensure_initialized();
  764. if (!m_camera || !m_cameraService) {
  765. return;
  766. }
  767. if (!std::isfinite(yaw_deg) || !std::isfinite(pitch_deg)) {
  768. qWarning() << "GameEngine::camera_orbit received invalid input, ignoring:"
  769. << yaw_deg << pitch_deg;
  770. return;
  771. }
  772. m_cameraService->orbit(*m_camera, yaw_deg, pitch_deg);
  773. }
  774. void GameEngine::camera_orbit_direction(int direction, bool shift) {
  775. if (!m_camera || !m_cameraService) {
  776. return;
  777. }
  778. m_cameraService->orbit_direction(*m_camera, direction, shift);
  779. }
  780. void GameEngine::camera_follow_selection(bool enable) {
  781. ensure_initialized();
  782. m_followSelectionEnabled = enable;
  783. if (!m_camera || !m_world || !m_cameraService) {
  784. return;
  785. }
  786. m_cameraService->follow_selection(*m_camera, *m_world, enable);
  787. }
  788. void GameEngine::camera_set_follow_lerp(float alpha) {
  789. ensure_initialized();
  790. if (!m_camera || !m_cameraService) {
  791. return;
  792. }
  793. m_cameraService->setFollowLerp(*m_camera, alpha);
  794. }
  795. auto GameEngine::selected_units_model() -> QAbstractItemModel * {
  796. return m_selectedUnitsModel;
  797. }
  798. auto GameEngine::audio_system() -> QObject * {
  799. return m_audio_systemProxy.get();
  800. }
  801. auto GameEngine::has_units_selected() const -> bool {
  802. if (!m_selectionController) {
  803. return false;
  804. }
  805. return m_selectionController->has_units_selected();
  806. }
  807. auto GameEngine::player_troop_count() const -> int {
  808. return m_entityCache.playerTroopCount;
  809. }
  810. auto GameEngine::has_selected_type(const QString &type) const -> bool {
  811. if (!m_selectionController) {
  812. return false;
  813. }
  814. return m_selectionController->has_selected_type(type);
  815. }
  816. void GameEngine::recruit_near_selected(const QString &unit_type) {
  817. ensure_initialized();
  818. if (!m_commandController) {
  819. return;
  820. }
  821. m_commandController->recruitNearSelected(unit_type, m_runtime.local_owner_id);
  822. }
  823. auto GameEngine::get_selected_production_state() const -> QVariantMap {
  824. QVariantMap m;
  825. m["has_barracks"] = false;
  826. m["in_progress"] = false;
  827. m["time_remaining"] = 0.0;
  828. m["build_time"] = 0.0;
  829. m["produced_count"] = 0;
  830. m["max_units"] = 0;
  831. m["villager_cost"] = 1;
  832. if (!m_world) {
  833. return m;
  834. }
  835. auto *selection_system =
  836. m_world->get_system<Game::Systems::SelectionSystem>();
  837. if (selection_system == nullptr) {
  838. return m;
  839. }
  840. Game::Systems::ProductionState st;
  841. Game::Systems::ProductionService::getSelectedBarracksState(
  842. *m_world, selection_system->get_selected_units(),
  843. m_runtime.local_owner_id, st);
  844. m["has_barracks"] = st.has_barracks;
  845. m["in_progress"] = st.in_progress;
  846. m["product_type"] =
  847. QString::fromStdString(Game::Units::troop_typeToString(st.product_type));
  848. m["time_remaining"] = st.time_remaining;
  849. m["build_time"] = st.build_time;
  850. m["produced_count"] = st.produced_count;
  851. m["max_units"] = st.max_units;
  852. m["villager_cost"] = st.villager_cost;
  853. m["queue_size"] = st.queue_size;
  854. m["nation_id"] =
  855. QString::fromStdString(Game::Systems::nationIDToString(st.nation_id));
  856. QVariantList queue_list;
  857. for (const auto &unit_type : st.production_queue) {
  858. queue_list.append(
  859. QString::fromStdString(Game::Units::troop_typeToString(unit_type)));
  860. }
  861. m["production_queue"] = queue_list;
  862. return m;
  863. }
  864. auto GameEngine::get_selected_units_command_mode() const -> QString {
  865. if (!m_world) {
  866. return "normal";
  867. }
  868. auto *selection_system =
  869. m_world->get_system<Game::Systems::SelectionSystem>();
  870. if (selection_system == nullptr) {
  871. return "normal";
  872. }
  873. const auto &sel = selection_system->get_selected_units();
  874. if (sel.empty()) {
  875. return "normal";
  876. }
  877. int attacking_count = 0;
  878. int patrolling_count = 0;
  879. int total_units = 0;
  880. for (auto id : sel) {
  881. auto *e = m_world->get_entity(id);
  882. if (e == nullptr) {
  883. continue;
  884. }
  885. auto *u = e->get_component<Engine::Core::UnitComponent>();
  886. if (u == nullptr) {
  887. continue;
  888. }
  889. if (u->spawn_type == Game::Units::SpawnType::Barracks) {
  890. continue;
  891. }
  892. total_units++;
  893. if (e->get_component<Engine::Core::AttackTargetComponent>() != nullptr) {
  894. attacking_count++;
  895. }
  896. auto *patrol = e->get_component<Engine::Core::PatrolComponent>();
  897. if ((patrol != nullptr) && patrol->patrolling) {
  898. patrolling_count++;
  899. }
  900. }
  901. if (total_units == 0) {
  902. return "normal";
  903. }
  904. if (patrolling_count == total_units) {
  905. return "patrol";
  906. }
  907. if (attacking_count == total_units) {
  908. return "attack";
  909. }
  910. return "normal";
  911. }
  912. void GameEngine::set_rally_at_screen(qreal sx, qreal sy) {
  913. ensure_initialized();
  914. if (!m_commandController || !m_camera) {
  915. return;
  916. }
  917. m_commandController->setRallyAtScreen(sx, sy, m_viewport.width,
  918. m_viewport.height, m_camera.get(),
  919. m_runtime.local_owner_id);
  920. }
  921. void GameEngine::start_loading_maps() {
  922. m_available_maps.clear();
  923. if (m_mapCatalog) {
  924. m_mapCatalog->loadMapsAsync();
  925. }
  926. load_campaigns();
  927. }
  928. auto GameEngine::available_maps() const -> QVariantList {
  929. return m_available_maps;
  930. }
  931. auto GameEngine::available_nations() const -> QVariantList {
  932. QVariantList nations;
  933. const auto &registry = Game::Systems::NationRegistry::instance();
  934. const auto &all = registry.getAllNations();
  935. QList<QVariantMap> ordered;
  936. ordered.reserve(static_cast<int>(all.size()));
  937. for (const auto &nation : all) {
  938. QVariantMap entry;
  939. entry.insert(
  940. QStringLiteral("id"),
  941. QString::fromStdString(Game::Systems::nationIDToString(nation.id)));
  942. entry.insert(QStringLiteral("name"),
  943. QString::fromStdString(nation.display_name));
  944. ordered.append(entry);
  945. }
  946. std::sort(ordered.begin(), ordered.end(),
  947. [](const QVariantMap &a, const QVariantMap &b) {
  948. return a.value(QStringLiteral("name"))
  949. .toString()
  950. .localeAwareCompare(
  951. b.value(QStringLiteral("name")).toString()) < 0;
  952. });
  953. for (const auto &entry : ordered) {
  954. nations.append(entry);
  955. }
  956. return nations;
  957. }
  958. auto GameEngine::available_campaigns() const -> QVariantList {
  959. return m_available_campaigns;
  960. }
  961. void GameEngine::load_campaigns() {
  962. if (!m_saveLoadService) {
  963. return;
  964. }
  965. QString error;
  966. auto campaigns = m_saveLoadService->list_campaigns(&error);
  967. if (!error.isEmpty()) {
  968. qWarning() << "Failed to load campaigns:" << error;
  969. return;
  970. }
  971. m_available_campaigns = campaigns;
  972. emit available_campaigns_changed();
  973. }
  974. void GameEngine::start_campaign_mission(const QString &campaign_id) {
  975. clear_error();
  976. if (!m_saveLoadService) {
  977. set_error("Save/Load service not initialized");
  978. return;
  979. }
  980. QString error;
  981. auto campaigns = m_saveLoadService->list_campaigns(&error);
  982. if (!error.isEmpty()) {
  983. set_error("Failed to load campaign: " + error);
  984. return;
  985. }
  986. QVariantMap selectedCampaign;
  987. for (const auto &campaign : campaigns) {
  988. auto campaignMap = campaign.toMap();
  989. if (campaignMap.value("id").toString() == campaign_id) {
  990. selectedCampaign = campaignMap;
  991. break;
  992. }
  993. }
  994. if (selectedCampaign.isEmpty()) {
  995. set_error("Campaign not found: " + campaign_id);
  996. return;
  997. }
  998. m_current_campaign_id = campaign_id;
  999. QString mapPath = selectedCampaign.value("mapPath").toString();
  1000. QVariantList playerConfigs;
  1001. QVariantMap player1;
  1002. player1.insert("player_id", 1);
  1003. player1.insert("playerName", "Carthage");
  1004. player1.insert("colorIndex", 0);
  1005. player1.insert("team_id", 0);
  1006. player1.insert("nationId", "carthage");
  1007. player1.insert("isHuman", true);
  1008. playerConfigs.append(player1);
  1009. QVariantMap player2;
  1010. player2.insert("player_id", 2);
  1011. player2.insert("playerName", "Rome");
  1012. player2.insert("colorIndex", 1);
  1013. player2.insert("team_id", 1);
  1014. player2.insert("nationId", "roman_republic");
  1015. player2.insert("isHuman", false);
  1016. playerConfigs.append(player2);
  1017. start_skirmish(mapPath, playerConfigs);
  1018. }
  1019. void GameEngine::mark_current_mission_completed() {
  1020. if (m_current_campaign_id.isEmpty()) {
  1021. qWarning() << "No active campaign mission to mark as completed";
  1022. return;
  1023. }
  1024. if (!m_saveLoadService) {
  1025. qWarning() << "Save/Load service not initialized";
  1026. return;
  1027. }
  1028. QString error;
  1029. bool success =
  1030. m_saveLoadService->mark_campaign_completed(m_current_campaign_id, &error);
  1031. if (!success) {
  1032. qWarning() << "Failed to mark campaign as completed:" << error;
  1033. } else {
  1034. qInfo() << "Campaign mission" << m_current_campaign_id
  1035. << "marked as completed";
  1036. load_campaigns();
  1037. }
  1038. }
  1039. void GameEngine::start_skirmish(const QString &map_path,
  1040. const QVariantList &playerConfigs) {
  1041. clear_error();
  1042. m_level.map_path = map_path;
  1043. m_level.map_name = map_path;
  1044. if (!m_runtime.victory_state.isEmpty()) {
  1045. m_runtime.victory_state = "";
  1046. emit victory_state_changed();
  1047. }
  1048. if (m_victoryService) {
  1049. m_victoryService->reset();
  1050. }
  1051. m_enemyTroopsDefeated = 0;
  1052. if (!m_runtime.initialized) {
  1053. ensure_initialized();
  1054. return;
  1055. }
  1056. if (m_world && m_renderer && m_camera) {
  1057. m_runtime.loading = true;
  1058. if (m_hoverTracker) {
  1059. m_hoverTracker->update_hover(-1, -1, *m_world, *m_camera, 0, 0);
  1060. }
  1061. m_entityCache.reset();
  1062. Game::Map::SkirmishLoader loader(*m_world, *m_renderer, *m_camera);
  1063. loader.setGroundRenderer(m_ground.get());
  1064. loader.setTerrainRenderer(m_terrain.get());
  1065. loader.setBiomeRenderer(m_biome.get());
  1066. loader.setRiverRenderer(m_river.get());
  1067. loader.setRoadRenderer(m_road.get());
  1068. loader.setRiverbankRenderer(m_riverbank.get());
  1069. loader.setBridgeRenderer(m_bridge.get());
  1070. loader.setFogRenderer(m_fog.get());
  1071. loader.setStoneRenderer(m_stone.get());
  1072. loader.setPlantRenderer(m_plant.get());
  1073. loader.setPineRenderer(m_pine.get());
  1074. loader.setOliveRenderer(m_olive.get());
  1075. loader.setFireCampRenderer(m_firecamp.get());
  1076. loader.setOnOwnersUpdated([this]() { emit owner_info_changed(); });
  1077. loader.setOnVisibilityMaskReady([this]() {
  1078. m_runtime.visibilityVersion =
  1079. Game::Map::VisibilityService::instance().version();
  1080. m_runtime.visibilityUpdateAccumulator = 0.0F;
  1081. });
  1082. int updated_player_id = m_selectedPlayerId;
  1083. auto result = loader.start(map_path, playerConfigs, m_selectedPlayerId,
  1084. updated_player_id);
  1085. if (updated_player_id != m_selectedPlayerId) {
  1086. m_selectedPlayerId = updated_player_id;
  1087. emit selected_player_id_changed();
  1088. }
  1089. if (!result.ok && !result.errorMessage.isEmpty()) {
  1090. set_error(result.errorMessage);
  1091. }
  1092. m_runtime.local_owner_id = updated_player_id;
  1093. m_level.map_name = result.map_name;
  1094. m_level.player_unit_id = result.player_unit_id;
  1095. m_level.cam_fov = result.cam_fov;
  1096. m_level.cam_near = result.cam_near;
  1097. m_level.cam_far = result.cam_far;
  1098. m_level.max_troops_per_player = result.max_troops_per_player;
  1099. Game::GameConfig::instance().setMaxTroopsPerPlayer(
  1100. result.max_troops_per_player);
  1101. if (m_victoryService) {
  1102. m_victoryService->configure(result.victoryConfig,
  1103. m_runtime.local_owner_id);
  1104. m_victoryService->setVictoryCallback([this](const QString &state) {
  1105. if (m_runtime.victory_state != state) {
  1106. m_runtime.victory_state = state;
  1107. emit victory_state_changed();
  1108. if (state == "victory" && !m_current_campaign_id.isEmpty()) {
  1109. mark_current_mission_completed();
  1110. }
  1111. }
  1112. });
  1113. }
  1114. if (result.hasFocusPosition && m_camera) {
  1115. const auto &cam_config = Game::GameConfig::instance().camera();
  1116. m_camera->setRTSView(result.focusPosition, cam_config.defaultDistance,
  1117. cam_config.defaultPitch, cam_config.defaultYaw);
  1118. }
  1119. m_runtime.loading = false;
  1120. if (auto *ai_system = m_world->get_system<Game::Systems::AISystem>()) {
  1121. ai_system->reinitialize();
  1122. }
  1123. rebuild_entity_cache();
  1124. auto &troops = Game::Systems::TroopCountRegistry::instance();
  1125. troops.rebuild_from_world(*m_world);
  1126. auto &stats_registry = Game::Systems::GlobalStatsRegistry::instance();
  1127. stats_registry.rebuild_from_world(*m_world);
  1128. auto &owner_registry = Game::Systems::OwnerRegistry::instance();
  1129. const auto &all_owners = owner_registry.getAllOwners();
  1130. for (const auto &owner : all_owners) {
  1131. if (owner.type == Game::Systems::OwnerType::Player ||
  1132. owner.type == Game::Systems::OwnerType::AI) {
  1133. stats_registry.mark_game_start(owner.owner_id);
  1134. }
  1135. }
  1136. m_currentAmbientState = Engine::Core::AmbientState::PEACEFUL;
  1137. m_ambientCheckTimer = 0.0F;
  1138. Engine::Core::EventManager::instance().publish(
  1139. Engine::Core::AmbientStateChangedEvent(
  1140. Engine::Core::AmbientState::PEACEFUL,
  1141. Engine::Core::AmbientState::PEACEFUL));
  1142. emit owner_info_changed();
  1143. }
  1144. }
  1145. void GameEngine::open_settings() {
  1146. if (m_saveLoadService) {
  1147. m_saveLoadService->openSettings();
  1148. }
  1149. }
  1150. void GameEngine::load_save() { load_from_slot("savegame"); }
  1151. void GameEngine::save_game(const QString &filename) {
  1152. save_to_slot(filename, filename);
  1153. }
  1154. void GameEngine::save_game_to_slot(const QString &slotName) {
  1155. save_to_slot(slotName, slotName);
  1156. }
  1157. void GameEngine::load_game_from_slot(const QString &slotName) {
  1158. load_from_slot(slotName);
  1159. }
  1160. auto GameEngine::load_from_slot(const QString &slot) -> bool {
  1161. if (!m_saveLoadService || !m_world) {
  1162. set_error("Load: not initialized");
  1163. return false;
  1164. }
  1165. m_runtime.loading = true;
  1166. if (!m_saveLoadService->loadGameFromSlot(*m_world, slot)) {
  1167. set_error(m_saveLoadService->getLastError());
  1168. m_runtime.loading = false;
  1169. return false;
  1170. }
  1171. const QJsonObject meta = m_saveLoadService->getLastMetadata();
  1172. Game::Systems::GameStateSerializer::restoreLevelFromMetadata(meta, m_level);
  1173. Game::Systems::GameStateSerializer::restoreCameraFromMetadata(
  1174. meta, m_camera.get(), m_viewport.width, m_viewport.height);
  1175. Game::Systems::RuntimeSnapshot runtime_snap = to_runtime_snapshot();
  1176. Game::Systems::GameStateSerializer::restoreRuntimeFromMetadata(meta,
  1177. runtime_snap);
  1178. apply_runtime_snapshot(runtime_snap);
  1179. restore_environment_from_metadata(meta);
  1180. auto unit_reg = std::make_shared<Game::Units::UnitFactoryRegistry>();
  1181. Game::Units::registerBuiltInUnits(*unit_reg);
  1182. Game::Map::MapTransformer::setFactoryRegistry(unit_reg);
  1183. qInfo() << "Factory registry reinitialized after loading saved game";
  1184. rebuild_registries_after_load();
  1185. rebuild_entity_cache();
  1186. if (auto *ai_system = m_world->get_system<Game::Systems::AISystem>()) {
  1187. qInfo() << "Reinitializing AI system after loading saved game";
  1188. ai_system->reinitialize();
  1189. }
  1190. if (m_victoryService) {
  1191. m_victoryService->configure(Game::Map::VictoryConfig(),
  1192. m_runtime.local_owner_id);
  1193. }
  1194. m_runtime.loading = false;
  1195. qInfo() << "Game load complete, victory/defeat checks re-enabled";
  1196. emit selected_units_changed();
  1197. emit owner_info_changed();
  1198. return true;
  1199. }
  1200. auto GameEngine::save_to_slot(const QString &slot,
  1201. const QString &title) -> bool {
  1202. if (!m_saveLoadService || !m_world) {
  1203. set_error("Save: not initialized");
  1204. return false;
  1205. }
  1206. Game::Systems::RuntimeSnapshot const runtime_snap = to_runtime_snapshot();
  1207. QJsonObject meta = Game::Systems::GameStateSerializer::buildMetadata(
  1208. *m_world, m_camera.get(), m_level, runtime_snap);
  1209. meta["title"] = title;
  1210. const QByteArray screenshot = capture_screenshot();
  1211. if (!m_saveLoadService->saveGameToSlot(*m_world, slot, title,
  1212. m_level.map_name, meta, screenshot)) {
  1213. set_error(m_saveLoadService->getLastError());
  1214. return false;
  1215. }
  1216. emit save_slots_changed();
  1217. return true;
  1218. }
  1219. auto GameEngine::get_save_slots() const -> QVariantList {
  1220. if (!m_saveLoadService) {
  1221. qWarning() << "Cannot get save slots: service not initialized";
  1222. return {};
  1223. }
  1224. return m_saveLoadService->getSaveSlots();
  1225. }
  1226. void GameEngine::refresh_save_slots() { emit save_slots_changed(); }
  1227. auto GameEngine::delete_save_slot(const QString &slotName) -> bool {
  1228. if (!m_saveLoadService) {
  1229. qWarning() << "Cannot delete save slot: service not initialized";
  1230. return false;
  1231. }
  1232. bool const success = m_saveLoadService->deleteSaveSlot(slotName);
  1233. if (!success) {
  1234. QString const error = m_saveLoadService->getLastError();
  1235. qWarning() << "Failed to delete save slot:" << error;
  1236. set_error(error);
  1237. } else {
  1238. emit save_slots_changed();
  1239. }
  1240. return success;
  1241. }
  1242. void GameEngine::exit_game() {
  1243. if (m_saveLoadService) {
  1244. m_saveLoadService->exitGame();
  1245. }
  1246. }
  1247. auto GameEngine::get_owner_info() const -> QVariantList {
  1248. QVariantList result;
  1249. const auto &owner_registry = Game::Systems::OwnerRegistry::instance();
  1250. const auto &owners = owner_registry.getAllOwners();
  1251. for (const auto &owner : owners) {
  1252. QVariantMap owner_map;
  1253. owner_map["id"] = owner.owner_id;
  1254. owner_map["name"] = QString::fromStdString(owner.name);
  1255. owner_map["team_id"] = owner.team_id;
  1256. QString type_str;
  1257. switch (owner.type) {
  1258. case Game::Systems::OwnerType::Player:
  1259. type_str = "Player";
  1260. break;
  1261. case Game::Systems::OwnerType::AI:
  1262. type_str = "AI";
  1263. break;
  1264. case Game::Systems::OwnerType::Neutral:
  1265. type_str = "Neutral";
  1266. break;
  1267. }
  1268. owner_map["type"] = type_str;
  1269. owner_map["isLocal"] = (owner.owner_id == m_runtime.local_owner_id);
  1270. result.append(owner_map);
  1271. }
  1272. return result;
  1273. }
  1274. void GameEngine::get_selected_unit_ids(
  1275. std::vector<Engine::Core::EntityID> &out) const {
  1276. out.clear();
  1277. if (!m_selectionController) {
  1278. return;
  1279. }
  1280. m_selectionController->get_selected_unit_ids(out);
  1281. }
  1282. auto GameEngine::get_unit_info(Engine::Core::EntityID id, QString &name,
  1283. int &health, int &max_health, bool &isBuilding,
  1284. bool &alive, QString &nation) const -> bool {
  1285. if (!m_world) {
  1286. return false;
  1287. }
  1288. auto *e = m_world->get_entity(id);
  1289. if (e == nullptr) {
  1290. return false;
  1291. }
  1292. isBuilding = e->has_component<Engine::Core::BuildingComponent>();
  1293. if (auto *u = e->get_component<Engine::Core::UnitComponent>()) {
  1294. name =
  1295. QString::fromStdString(Game::Units::spawn_typeToString(u->spawn_type));
  1296. health = u->health;
  1297. max_health = u->max_health;
  1298. alive = (u->health > 0);
  1299. nation = Game::Systems::nationIDToQString(u->nation_id);
  1300. return true;
  1301. }
  1302. name = QStringLiteral("Entity");
  1303. health = max_health = 0;
  1304. alive = true;
  1305. nation = QStringLiteral("");
  1306. return true;
  1307. }
  1308. void GameEngine::on_unit_spawned(const Engine::Core::UnitSpawnedEvent &event) {
  1309. auto &owners = Game::Systems::OwnerRegistry::instance();
  1310. if (event.owner_id == m_runtime.local_owner_id) {
  1311. if (event.spawn_type == Game::Units::SpawnType::Barracks) {
  1312. m_entityCache.playerBarracksAlive = true;
  1313. } else {
  1314. int const individuals_per_unit =
  1315. Game::Units::TroopConfig::instance().getIndividualsPerUnit(
  1316. event.spawn_type);
  1317. m_entityCache.playerTroopCount += individuals_per_unit;
  1318. }
  1319. } else if (owners.isAI(event.owner_id)) {
  1320. if (event.spawn_type == Game::Units::SpawnType::Barracks) {
  1321. m_entityCache.enemyBarracksCount++;
  1322. m_entityCache.enemyBarracksAlive = true;
  1323. }
  1324. }
  1325. auto emit_if_changed = [&] {
  1326. if (m_entityCache.playerTroopCount != m_runtime.lastTroopCount) {
  1327. m_runtime.lastTroopCount = m_entityCache.playerTroopCount;
  1328. emit troop_count_changed();
  1329. }
  1330. };
  1331. emit_if_changed();
  1332. }
  1333. void GameEngine::on_unit_died(const Engine::Core::UnitDiedEvent &event) {
  1334. auto &owners = Game::Systems::OwnerRegistry::instance();
  1335. if (event.owner_id == m_runtime.local_owner_id) {
  1336. if (event.spawn_type == Game::Units::SpawnType::Barracks) {
  1337. m_entityCache.playerBarracksAlive = false;
  1338. } else {
  1339. int const individuals_per_unit =
  1340. Game::Units::TroopConfig::instance().getIndividualsPerUnit(
  1341. event.spawn_type);
  1342. m_entityCache.playerTroopCount -= individuals_per_unit;
  1343. m_entityCache.playerTroopCount =
  1344. std::max(0, m_entityCache.playerTroopCount);
  1345. }
  1346. } else if (owners.isAI(event.owner_id)) {
  1347. if (event.spawn_type == Game::Units::SpawnType::Barracks) {
  1348. m_entityCache.enemyBarracksCount--;
  1349. m_entityCache.enemyBarracksCount =
  1350. std::max(0, m_entityCache.enemyBarracksCount);
  1351. m_entityCache.enemyBarracksAlive = (m_entityCache.enemyBarracksCount > 0);
  1352. }
  1353. }
  1354. sync_selection_flags();
  1355. auto emit_if_changed = [&] {
  1356. if (m_entityCache.playerTroopCount != m_runtime.lastTroopCount) {
  1357. m_runtime.lastTroopCount = m_entityCache.playerTroopCount;
  1358. emit troop_count_changed();
  1359. }
  1360. };
  1361. emit_if_changed();
  1362. }
  1363. void GameEngine::rebuild_entity_cache() {
  1364. if (!m_world) {
  1365. m_entityCache.reset();
  1366. return;
  1367. }
  1368. m_entityCache.reset();
  1369. auto &owners = Game::Systems::OwnerRegistry::instance();
  1370. auto entities = m_world->get_entities_with<Engine::Core::UnitComponent>();
  1371. for (auto *e : entities) {
  1372. auto *unit = e->get_component<Engine::Core::UnitComponent>();
  1373. if ((unit == nullptr) || unit->health <= 0) {
  1374. continue;
  1375. }
  1376. if (unit->owner_id == m_runtime.local_owner_id) {
  1377. if (unit->spawn_type == Game::Units::SpawnType::Barracks) {
  1378. m_entityCache.playerBarracksAlive = true;
  1379. } else {
  1380. int const individuals_per_unit =
  1381. Game::Units::TroopConfig::instance().getIndividualsPerUnit(
  1382. unit->spawn_type);
  1383. m_entityCache.playerTroopCount += individuals_per_unit;
  1384. }
  1385. } else if (owners.isAI(unit->owner_id)) {
  1386. if (unit->spawn_type == Game::Units::SpawnType::Barracks) {
  1387. m_entityCache.enemyBarracksCount++;
  1388. m_entityCache.enemyBarracksAlive = true;
  1389. }
  1390. }
  1391. }
  1392. auto emit_if_changed = [&] {
  1393. if (m_entityCache.playerTroopCount != m_runtime.lastTroopCount) {
  1394. m_runtime.lastTroopCount = m_entityCache.playerTroopCount;
  1395. emit troop_count_changed();
  1396. }
  1397. };
  1398. emit_if_changed();
  1399. }
  1400. void GameEngine::rebuild_registries_after_load() {
  1401. if (!m_world) {
  1402. return;
  1403. }
  1404. auto &owner_registry = Game::Systems::OwnerRegistry::instance();
  1405. m_runtime.local_owner_id = owner_registry.getLocalPlayerId();
  1406. auto &troops = Game::Systems::TroopCountRegistry::instance();
  1407. troops.rebuild_from_world(*m_world);
  1408. auto &stats_registry = Game::Systems::GlobalStatsRegistry::instance();
  1409. stats_registry.rebuild_from_world(*m_world);
  1410. const auto &all_owners = owner_registry.getAllOwners();
  1411. for (const auto &owner : all_owners) {
  1412. if (owner.type == Game::Systems::OwnerType::Player ||
  1413. owner.type == Game::Systems::OwnerType::AI) {
  1414. stats_registry.mark_game_start(owner.owner_id);
  1415. }
  1416. }
  1417. rebuild_building_collisions();
  1418. m_level.player_unit_id = 0;
  1419. auto units = m_world->get_entities_with<Engine::Core::UnitComponent>();
  1420. for (auto *entity : units) {
  1421. auto *unit = entity->get_component<Engine::Core::UnitComponent>();
  1422. if (unit == nullptr) {
  1423. continue;
  1424. }
  1425. if (unit->owner_id == m_runtime.local_owner_id) {
  1426. m_level.player_unit_id = entity->get_id();
  1427. break;
  1428. }
  1429. }
  1430. if (m_selectedPlayerId != m_runtime.local_owner_id) {
  1431. m_selectedPlayerId = m_runtime.local_owner_id;
  1432. emit selected_player_id_changed();
  1433. }
  1434. }
  1435. void GameEngine::rebuild_building_collisions() {
  1436. auto &registry = Game::Systems::BuildingCollisionRegistry::instance();
  1437. registry.clear();
  1438. if (!m_world) {
  1439. return;
  1440. }
  1441. auto buildings =
  1442. m_world->get_entities_with<Engine::Core::BuildingComponent>();
  1443. for (auto *entity : buildings) {
  1444. auto *transform = entity->get_component<Engine::Core::TransformComponent>();
  1445. auto *unit = entity->get_component<Engine::Core::UnitComponent>();
  1446. if ((transform == nullptr) || (unit == nullptr)) {
  1447. continue;
  1448. }
  1449. registry.registerBuilding(
  1450. entity->get_id(), Game::Units::spawn_typeToString(unit->spawn_type),
  1451. transform->position.x, transform->position.z, unit->owner_id);
  1452. }
  1453. }
  1454. auto GameEngine::to_runtime_snapshot() const -> Game::Systems::RuntimeSnapshot {
  1455. Game::Systems::RuntimeSnapshot snap;
  1456. snap.paused = m_runtime.paused;
  1457. snap.time_scale = m_runtime.time_scale;
  1458. snap.local_owner_id = m_runtime.local_owner_id;
  1459. snap.victory_state = m_runtime.victory_state;
  1460. snap.cursor_mode = CursorModeUtils::toInt(m_runtime.cursor_mode);
  1461. snap.selected_player_id = m_selectedPlayerId;
  1462. snap.follow_selection = m_followSelectionEnabled;
  1463. return snap;
  1464. }
  1465. void GameEngine::apply_runtime_snapshot(
  1466. const Game::Systems::RuntimeSnapshot &snapshot) {
  1467. m_runtime.local_owner_id = snapshot.local_owner_id;
  1468. set_paused(snapshot.paused);
  1469. set_game_speed(snapshot.time_scale);
  1470. if (snapshot.victory_state != m_runtime.victory_state) {
  1471. m_runtime.victory_state = snapshot.victory_state;
  1472. emit victory_state_changed();
  1473. }
  1474. set_cursor_mode(CursorModeUtils::fromInt(snapshot.cursor_mode));
  1475. if (snapshot.selected_player_id != m_selectedPlayerId) {
  1476. m_selectedPlayerId = snapshot.selected_player_id;
  1477. emit selected_player_id_changed();
  1478. }
  1479. if (snapshot.follow_selection != m_followSelectionEnabled) {
  1480. m_followSelectionEnabled = snapshot.follow_selection;
  1481. if (m_camera && m_cameraService && m_world) {
  1482. m_cameraService->follow_selection(*m_camera, *m_world,
  1483. m_followSelectionEnabled);
  1484. }
  1485. }
  1486. }
  1487. auto GameEngine::capture_screenshot() const -> QByteArray {
  1488. if (m_window == nullptr) {
  1489. return {};
  1490. }
  1491. QImage const image = m_window->grabWindow();
  1492. if (image.isNull()) {
  1493. return {};
  1494. }
  1495. const QSize target_size(320, 180);
  1496. QImage const scaled =
  1497. image.scaled(target_size, Qt::KeepAspectRatio, Qt::SmoothTransformation);
  1498. QByteArray buffer;
  1499. QBuffer q_buffer(&buffer);
  1500. if (!q_buffer.open(QIODevice::WriteOnly)) {
  1501. return {};
  1502. }
  1503. if (!scaled.save(&q_buffer, "PNG")) {
  1504. return {};
  1505. }
  1506. return buffer;
  1507. }
  1508. void GameEngine::restore_environment_from_metadata(
  1509. const QJsonObject &metadata) {
  1510. if (!m_world) {
  1511. return;
  1512. }
  1513. const auto fallback_grid_width = metadata.value("grid_width").toInt(50);
  1514. const auto fallback_grid_height = metadata.value("grid_height").toInt(50);
  1515. const float fallback_tile_size =
  1516. static_cast<float>(metadata.value("tile_size").toDouble(1.0));
  1517. auto &terrain_service = Game::Map::TerrainService::instance();
  1518. bool const terrain_already_restored = terrain_service.isInitialized();
  1519. Game::Map::MapDefinition def;
  1520. QString map_error;
  1521. bool loaded_definition = false;
  1522. const QString &map_path = m_level.map_path;
  1523. if (!terrain_already_restored && !map_path.isEmpty()) {
  1524. loaded_definition =
  1525. Game::Map::MapLoader::loadFromJsonFile(map_path, def, &map_error);
  1526. if (!loaded_definition) {
  1527. qWarning() << "GameEngine: Failed to load map definition from" << map_path
  1528. << "during save load:" << map_error;
  1529. }
  1530. }
  1531. if (!terrain_already_restored && loaded_definition) {
  1532. terrain_service.initialize(def);
  1533. if (!def.name.isEmpty()) {
  1534. m_level.map_name = def.name;
  1535. }
  1536. m_level.cam_fov = def.camera.fovY;
  1537. m_level.cam_near = def.camera.near_plane;
  1538. m_level.cam_far = def.camera.far_plane;
  1539. }
  1540. if (m_renderer && m_camera) {
  1541. if (loaded_definition) {
  1542. Game::Map::Environment::apply(def, *m_renderer, *m_camera);
  1543. } else {
  1544. Game::Map::Environment::applyDefault(*m_renderer, *m_camera);
  1545. }
  1546. }
  1547. if (terrain_service.isInitialized()) {
  1548. const auto *height_map = terrain_service.getHeightMap();
  1549. const int grid_width =
  1550. (height_map != nullptr) ? height_map->getWidth() : fallback_grid_width;
  1551. const int grid_height = (height_map != nullptr) ? height_map->getHeight()
  1552. : fallback_grid_height;
  1553. const float tile_size = (height_map != nullptr) ? height_map->getTileSize()
  1554. : fallback_tile_size;
  1555. if (m_ground) {
  1556. m_ground->configure(tile_size, grid_width, grid_height);
  1557. m_ground->setBiome(terrain_service.biomeSettings());
  1558. }
  1559. if (height_map != nullptr) {
  1560. if (m_terrain) {
  1561. m_terrain->configure(*height_map, terrain_service.biomeSettings());
  1562. }
  1563. if (m_river) {
  1564. m_river->configure(height_map->getRiverSegments(),
  1565. height_map->getTileSize());
  1566. }
  1567. if (m_road) {
  1568. m_road->configure(terrain_service.road_segments(),
  1569. height_map->getTileSize());
  1570. }
  1571. if (m_riverbank) {
  1572. m_riverbank->configure(height_map->getRiverSegments(), *height_map);
  1573. }
  1574. if (m_bridge) {
  1575. m_bridge->configure(height_map->getBridges(),
  1576. height_map->getTileSize());
  1577. }
  1578. if (m_biome) {
  1579. m_biome->configure(*height_map, terrain_service.biomeSettings());
  1580. m_biome->refreshGrass();
  1581. }
  1582. if (m_stone) {
  1583. m_stone->configure(*height_map, terrain_service.biomeSettings());
  1584. }
  1585. if (m_plant) {
  1586. m_plant->configure(*height_map, terrain_service.biomeSettings());
  1587. }
  1588. if (m_pine) {
  1589. m_pine->configure(*height_map, terrain_service.biomeSettings());
  1590. }
  1591. if (m_olive) {
  1592. m_olive->configure(*height_map, terrain_service.biomeSettings());
  1593. }
  1594. if (m_firecamp) {
  1595. m_firecamp->configure(*height_map, terrain_service.biomeSettings());
  1596. }
  1597. }
  1598. Game::Systems::CommandService::initialize(grid_width, grid_height);
  1599. auto &visibility_service = Game::Map::VisibilityService::instance();
  1600. visibility_service.initialize(grid_width, grid_height, tile_size);
  1601. visibility_service.computeImmediate(*m_world, m_runtime.local_owner_id);
  1602. if (m_fog && visibility_service.isInitialized()) {
  1603. m_fog->updateMask(
  1604. visibility_service.getWidth(), visibility_service.getHeight(),
  1605. visibility_service.getTileSize(), visibility_service.snapshotCells());
  1606. }
  1607. m_runtime.visibilityVersion = visibility_service.version();
  1608. m_runtime.visibilityUpdateAccumulator = 0.0F;
  1609. } else {
  1610. if (m_renderer && m_camera) {
  1611. Game::Map::Environment::applyDefault(*m_renderer, *m_camera);
  1612. }
  1613. Game::Map::MapDefinition fallback_def;
  1614. fallback_def.grid.width = fallback_grid_width;
  1615. fallback_def.grid.height = fallback_grid_height;
  1616. fallback_def.grid.tile_size = fallback_tile_size;
  1617. fallback_def.max_troops_per_player = m_level.max_troops_per_player;
  1618. terrain_service.initialize(fallback_def);
  1619. if (m_ground) {
  1620. m_ground->configure(fallback_tile_size, fallback_grid_width,
  1621. fallback_grid_height);
  1622. }
  1623. Game::Systems::CommandService::initialize(fallback_grid_width,
  1624. fallback_grid_height);
  1625. auto &visibility_service = Game::Map::VisibilityService::instance();
  1626. visibility_service.initialize(fallback_grid_width, fallback_grid_height,
  1627. fallback_tile_size);
  1628. visibility_service.computeImmediate(*m_world, m_runtime.local_owner_id);
  1629. if (m_fog && visibility_service.isInitialized()) {
  1630. m_fog->updateMask(
  1631. visibility_service.getWidth(), visibility_service.getHeight(),
  1632. visibility_service.getTileSize(), visibility_service.snapshotCells());
  1633. }
  1634. m_runtime.visibilityVersion = visibility_service.version();
  1635. m_runtime.visibilityUpdateAccumulator = 0.0F;
  1636. }
  1637. }
  1638. auto GameEngine::has_patrol_preview_waypoint() const -> bool {
  1639. return m_commandController && m_commandController->hasPatrolFirstWaypoint();
  1640. }
  1641. auto GameEngine::get_patrol_preview_waypoint() const -> QVector3D {
  1642. if (!m_commandController) {
  1643. return {};
  1644. }
  1645. return m_commandController->getPatrolFirstWaypoint();
  1646. }
  1647. void GameEngine::update_ambient_state(float dt) {
  1648. m_ambientCheckTimer += dt;
  1649. const float check_interval = 2.0F;
  1650. if (m_ambientCheckTimer < check_interval) {
  1651. return;
  1652. }
  1653. m_ambientCheckTimer = 0.0F;
  1654. Engine::Core::AmbientState new_state = Engine::Core::AmbientState::PEACEFUL;
  1655. if (!m_runtime.victory_state.isEmpty()) {
  1656. if (m_runtime.victory_state == "victory") {
  1657. new_state = Engine::Core::AmbientState::VICTORY;
  1658. } else if (m_runtime.victory_state == "defeat") {
  1659. new_state = Engine::Core::AmbientState::DEFEAT;
  1660. }
  1661. } else if (is_player_in_combat()) {
  1662. new_state = Engine::Core::AmbientState::COMBAT;
  1663. } else if (m_entityCache.enemyBarracksAlive &&
  1664. m_entityCache.playerBarracksAlive) {
  1665. new_state = Engine::Core::AmbientState::TENSE;
  1666. }
  1667. if (new_state != m_currentAmbientState) {
  1668. Engine::Core::AmbientState const previous_state = m_currentAmbientState;
  1669. m_currentAmbientState = new_state;
  1670. Engine::Core::EventManager::instance().publish(
  1671. Engine::Core::AmbientStateChangedEvent(new_state, previous_state));
  1672. qInfo() << "Ambient state changed from" << static_cast<int>(previous_state)
  1673. << "to" << static_cast<int>(new_state);
  1674. }
  1675. }
  1676. auto GameEngine::is_player_in_combat() const -> bool {
  1677. if (!m_world) {
  1678. return false;
  1679. }
  1680. auto units = m_world->get_entities_with<Engine::Core::UnitComponent>();
  1681. const float combat_check_radius = 15.0F;
  1682. for (auto *entity : units) {
  1683. auto *unit = entity->get_component<Engine::Core::UnitComponent>();
  1684. if ((unit == nullptr) || unit->owner_id != m_runtime.local_owner_id ||
  1685. unit->health <= 0) {
  1686. continue;
  1687. }
  1688. if (entity->has_component<Engine::Core::AttackTargetComponent>()) {
  1689. return true;
  1690. }
  1691. auto *transform = entity->get_component<Engine::Core::TransformComponent>();
  1692. if (transform == nullptr) {
  1693. continue;
  1694. }
  1695. for (auto *other_entity : units) {
  1696. auto *other_unit =
  1697. other_entity->get_component<Engine::Core::UnitComponent>();
  1698. if ((other_unit == nullptr) ||
  1699. other_unit->owner_id == m_runtime.local_owner_id ||
  1700. other_unit->health <= 0) {
  1701. continue;
  1702. }
  1703. auto *other_transform =
  1704. other_entity->get_component<Engine::Core::TransformComponent>();
  1705. if (other_transform == nullptr) {
  1706. continue;
  1707. }
  1708. float const dx = transform->position.x - other_transform->position.x;
  1709. float const dz = transform->position.z - other_transform->position.z;
  1710. float const dist_sq = dx * dx + dz * dz;
  1711. if (dist_sq < combat_check_radius * combat_check_radius) {
  1712. return true;
  1713. }
  1714. }
  1715. }
  1716. return false;
  1717. }
  1718. void GameEngine::load_audio_resources() {
  1719. auto &audio_sys = AudioSystem::getInstance();
  1720. QString const base_path =
  1721. QCoreApplication::applicationDirPath() + "/assets/audio/";
  1722. qInfo() << "Loading audio resources from:" << base_path;
  1723. QDir const audio_dir(base_path);
  1724. if (!audio_dir.exists()) {
  1725. qWarning() << "Audio assets directory does not exist:" << base_path;
  1726. qWarning() << "Application directory:"
  1727. << QCoreApplication::applicationDirPath();
  1728. return;
  1729. }
  1730. if (audio_sys.loadSound("archer_voice",
  1731. (base_path + "voices/archer_voice.wav").toStdString(),
  1732. AudioCategory::VOICE)) {
  1733. qInfo() << "Loaded archer voice";
  1734. } else {
  1735. qWarning() << "Failed to load archer voice from:"
  1736. << (base_path + "voices/archer_voice.wav");
  1737. }
  1738. if (audio_sys.loadSound(
  1739. "swordsman_voice",
  1740. (base_path + "voices/swordsman_voice.wav").toStdString(),
  1741. AudioCategory::VOICE)) {
  1742. qInfo() << "Loaded swordsman voice";
  1743. } else {
  1744. qWarning() << "Failed to load swordsman voice from:"
  1745. << (base_path + "voices/swordsman_voice.wav");
  1746. }
  1747. if (audio_sys.loadSound(
  1748. "spearman_voice",
  1749. (base_path + "voices/spearman_voice.wav").toStdString(),
  1750. AudioCategory::VOICE)) {
  1751. qInfo() << "Loaded spearman voice";
  1752. } else {
  1753. qWarning() << "Failed to load spearman voice from:"
  1754. << (base_path + "voices/spearman_voice.wav");
  1755. }
  1756. if (audio_sys.loadMusic("music_peaceful",
  1757. (base_path + "music/peaceful.wav").toStdString())) {
  1758. qInfo() << "Loaded peaceful music";
  1759. } else {
  1760. qWarning() << "Failed to load peaceful music from:"
  1761. << (base_path + "music/peaceful.wav");
  1762. }
  1763. if (audio_sys.loadMusic("music_tense",
  1764. (base_path + "music/tense.wav").toStdString())) {
  1765. qInfo() << "Loaded tense music";
  1766. } else {
  1767. qWarning() << "Failed to load tense music from:"
  1768. << (base_path + "music/tense.wav");
  1769. }
  1770. if (audio_sys.loadMusic("music_combat",
  1771. (base_path + "music/combat.wav").toStdString())) {
  1772. qInfo() << "Loaded combat music";
  1773. } else {
  1774. qWarning() << "Failed to load combat music from:"
  1775. << (base_path + "music/combat.wav");
  1776. }
  1777. if (audio_sys.loadMusic("music_victory",
  1778. (base_path + "music/victory.wav").toStdString())) {
  1779. qInfo() << "Loaded victory music";
  1780. } else {
  1781. qWarning() << "Failed to load victory music from:"
  1782. << (base_path + "music/victory.wav");
  1783. }
  1784. if (audio_sys.loadMusic("music_defeat",
  1785. (base_path + "music/defeat.wav").toStdString())) {
  1786. qInfo() << "Loaded defeat music";
  1787. } else {
  1788. qWarning() << "Failed to load defeat music from:"
  1789. << (base_path + "music/defeat.wav");
  1790. }
  1791. qInfo() << "Audio resources loading complete";
  1792. }