campaign_map_view.cpp 50 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742
  1. #include "campaign_map_view.h"
  2. #include "../utils/resource_utils.h"
  3. #include <QDateTime>
  4. #include <QDebug>
  5. #include <QFile>
  6. #include <QJsonArray>
  7. #include <QJsonDocument>
  8. #include <QJsonObject>
  9. #include <QMatrix4x4>
  10. #include <QOpenGLContext>
  11. #include <QOpenGLFramebufferObject>
  12. #include <QOpenGLFramebufferObjectFormat>
  13. #include <QOpenGLFunctions_3_3_Core>
  14. #include <QOpenGLShaderProgram>
  15. #include <QOpenGLTexture>
  16. #include <QVariantMap>
  17. #include <QVector2D>
  18. #include <QVector3D>
  19. #include <QVector4D>
  20. #include <QtGlobal>
  21. #include <QtMath>
  22. #include <cmath>
  23. #include <cstring>
  24. #include <unordered_map>
  25. #include <utility>
  26. #include <vector>
  27. namespace {
  28. auto build_mvp_matrix(float width, float height, float yaw_deg, float pitch_deg,
  29. float distance, float pan_u, float pan_v) -> QMatrix4x4 {
  30. const float view_w = qMax(1.0F, width);
  31. const float view_h = qMax(1.0F, height);
  32. const float aspect = view_w / view_h;
  33. QMatrix4x4 projection;
  34. projection.perspective(45.0F, aspect, 0.1F, 10.0F);
  35. const float clamped_pan_u = qBound(-0.5F, pan_u, 0.5F);
  36. const float clamped_pan_v = qBound(-0.5F, pan_v, 0.5F);
  37. const QVector3D center(0.5F + clamped_pan_u, 0.0F, 0.5F + clamped_pan_v);
  38. const float yaw_rad = qDegreesToRadians(yaw_deg);
  39. const float pitch_rad = qDegreesToRadians(pitch_deg);
  40. const float clamped_distance =
  41. qMax(CampaignMapView::k_min_orbit_distance, distance);
  42. const float cos_pitch = std::cos(pitch_rad);
  43. const float sin_pitch = std::sin(pitch_rad);
  44. const float cos_yaw = std::cos(yaw_rad);
  45. const float sin_yaw = std::sin(yaw_rad);
  46. QVector3D eye(center.x() + clamped_distance * sin_yaw * cos_pitch,
  47. center.y() + clamped_distance * sin_pitch,
  48. center.z() + clamped_distance * cos_yaw * cos_pitch);
  49. QMatrix4x4 view;
  50. view.lookAt(eye, center, QVector3D(0.0F, 0.0F, 1.0F));
  51. QMatrix4x4 model;
  52. return projection * view * model;
  53. }
  54. auto point_in_triangle(const QVector2D &p, const QVector2D &a,
  55. const QVector2D &b, const QVector2D &c) -> bool {
  56. const QVector2D v0 = c - a;
  57. const QVector2D v1 = b - a;
  58. const QVector2D v2 = p - a;
  59. const float dot00 = QVector2D::dotProduct(v0, v0);
  60. const float dot01 = QVector2D::dotProduct(v0, v1);
  61. const float dot02 = QVector2D::dotProduct(v0, v2);
  62. const float dot11 = QVector2D::dotProduct(v1, v1);
  63. const float dot12 = QVector2D::dotProduct(v1, v2);
  64. const float denom = dot00 * dot11 - dot01 * dot01;
  65. if (qFuzzyIsNull(denom)) {
  66. return false;
  67. }
  68. const float inv_denom = 1.0F / denom;
  69. const float u = (dot11 * dot02 - dot01 * dot12) * inv_denom;
  70. const float v = (dot00 * dot12 - dot01 * dot02) * inv_denom;
  71. return (u >= 0.0F) && (v >= 0.0F) && (u + v <= 1.0F);
  72. }
  73. struct LineSpan {
  74. int start = 0;
  75. int count = 0;
  76. };
  77. struct LineLayer {
  78. GLuint vao = 0;
  79. GLuint vbo = 0;
  80. std::vector<LineSpan> spans;
  81. QVector4D color = QVector4D(1.0F, 1.0F, 1.0F, 1.0F);
  82. float width = 1.0F;
  83. bool ready = false;
  84. };
  85. struct StrokeMesh {
  86. GLuint vao = 0;
  87. GLuint vbo = 0;
  88. int vertex_count = 0;
  89. float width = 0.0F;
  90. bool ready = false;
  91. };
  92. struct PathLine {
  93. std::vector<QVector2D> points;
  94. StrokeMesh border;
  95. StrokeMesh highlight;
  96. StrokeMesh core;
  97. };
  98. struct PathLayer {
  99. std::vector<PathLine> lines;
  100. bool ready = false;
  101. };
  102. struct ProvinceSpan {
  103. int start = 0;
  104. int count = 0;
  105. QVector4D color = QVector4D(0.0F, 0.0F, 0.0F, 0.0F);
  106. QVector4D base_color = QVector4D(0.0F, 0.0F, 0.0F, 0.0F);
  107. QString id;
  108. };
  109. struct ProvinceLayer {
  110. GLuint vao = 0;
  111. GLuint vbo = 0;
  112. std::vector<ProvinceSpan> spans;
  113. bool ready = false;
  114. };
  115. struct QStringHash {
  116. std::size_t operator()(const QString &s) const noexcept { return qHash(s); }
  117. };
  118. struct CampaignMapTextureCache {
  119. static CampaignMapTextureCache &instance() {
  120. static CampaignMapTextureCache s_instance;
  121. return s_instance;
  122. }
  123. QOpenGLTexture *get_or_load(const QString &resource_path) {
  124. if (!m_allow_loading) {
  125. qWarning() << "CampaignMapTextureCache: Attempted to load texture after "
  126. "initialization:"
  127. << resource_path;
  128. return nullptr;
  129. }
  130. auto it = m_textures.find(resource_path);
  131. if (it != m_textures.end() && it->second != nullptr) {
  132. return it->second;
  133. }
  134. const QString path = Utils::Resources::resolveResourcePath(resource_path);
  135. QImage image(path);
  136. if (image.isNull()) {
  137. qWarning() << "CampaignMapTextureCache: Failed to load texture" << path;
  138. return nullptr;
  139. }
  140. QImage rgba = image.convertToFormat(QImage::Format_RGBA8888);
  141. auto *texture = new QOpenGLTexture(rgba);
  142. texture->setWrapMode(QOpenGLTexture::ClampToEdge);
  143. texture->setMinMagFilters(QOpenGLTexture::Linear, QOpenGLTexture::Linear);
  144. m_textures[resource_path] = texture;
  145. return texture;
  146. }
  147. void set_loading_allowed(bool allowed) { m_allow_loading = allowed; }
  148. void clear() {
  149. QOpenGLContext *ctx = QOpenGLContext::currentContext();
  150. if (ctx != nullptr && ctx->isValid()) {
  151. for (auto &pair : m_textures) {
  152. delete pair.second;
  153. }
  154. }
  155. m_textures.clear();
  156. }
  157. private:
  158. CampaignMapTextureCache() = default;
  159. ~CampaignMapTextureCache() { clear(); }
  160. std::unordered_map<QString, QOpenGLTexture *, QStringHash> m_textures;
  161. bool m_allow_loading = true;
  162. };
  163. class CampaignMapRenderer : public QQuickFramebufferObject::Renderer,
  164. protected QOpenGLFunctions_3_3_Core {
  165. public:
  166. CampaignMapRenderer() = default;
  167. ~CampaignMapRenderer() override { cleanup(); }
  168. void render() override {
  169. if (!ensure_initialized()) {
  170. return;
  171. }
  172. glViewport(0, 0, m_size.width(), m_size.height());
  173. glEnable(GL_DEPTH_TEST);
  174. glDisable(GL_CULL_FACE);
  175. glEnable(GL_BLEND);
  176. glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
  177. glClearColor(0.157F, 0.267F, 0.361F, 1.0F);
  178. glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
  179. QMatrix4x4 mvp;
  180. compute_mvp(mvp);
  181. draw_textured_layer(m_water_texture, m_quad_vao, 6, mvp, 1.0F, -0.01F);
  182. if (m_land_vertex_count > 0) {
  183. draw_textured_layer(m_base_texture, m_land_vao, m_land_vertex_count, mvp,
  184. 1.0F, 0.0F);
  185. } else {
  186. draw_textured_layer(m_base_texture, m_quad_vao, 6, mvp, 1.0F, 0.0F);
  187. }
  188. glDisable(GL_DEPTH_TEST);
  189. draw_province_layer(m_province_layer, mvp, 0.002F);
  190. draw_line_layer(m_province_border_layer, mvp, 0.0045F);
  191. draw_line_layer(m_coast_layer, mvp, 0.004F);
  192. draw_line_layer(m_river_layer, mvp, 0.003F);
  193. draw_progressive_path_layers(m_path_layer, mvp, 0.006F);
  194. if (!m_hover_province_id.isEmpty()) {
  195. qint64 now = QDateTime::currentMSecsSinceEpoch();
  196. if (now - m_last_update_time >= 16) {
  197. m_last_update_time = now;
  198. update();
  199. }
  200. }
  201. }
  202. auto createFramebufferObject(const QSize &size)
  203. -> QOpenGLFramebufferObject * override {
  204. m_size = size;
  205. QOpenGLFramebufferObjectFormat fmt;
  206. fmt.setAttachment(QOpenGLFramebufferObject::Depth);
  207. fmt.setSamples(0);
  208. return new QOpenGLFramebufferObject(size, fmt);
  209. }
  210. void synchronize(QQuickFramebufferObject *item) override {
  211. auto *view = dynamic_cast<CampaignMapView *>(item);
  212. if (view == nullptr) {
  213. return;
  214. }
  215. m_orbit_yaw = view->orbit_yaw();
  216. m_orbit_pitch = view->orbit_pitch();
  217. m_orbit_distance = view->orbit_distance();
  218. m_pan_u = view->pan_u();
  219. m_pan_v = view->pan_v();
  220. QString new_hover_id = view->hover_province_id();
  221. if (m_hover_province_id != new_hover_id) {
  222. m_hover_start_time = QDateTime::currentMSecsSinceEpoch();
  223. m_hover_province_id = new_hover_id;
  224. }
  225. m_current_mission = view->current_mission();
  226. if (m_province_state_version != view->province_state_version() &&
  227. m_province_layer.ready) {
  228. apply_province_overrides(view->province_overrides());
  229. m_province_state_version = view->province_state_version();
  230. }
  231. }
  232. private:
  233. QSize m_size;
  234. bool m_initialized = false;
  235. QOpenGLShaderProgram m_texture_program;
  236. QOpenGLShaderProgram m_line_program;
  237. GLuint m_quad_vao = 0;
  238. GLuint m_quad_vbo = 0;
  239. GLuint m_land_vao = 0;
  240. GLuint m_land_vbo = 0;
  241. int m_land_vertex_count = 0;
  242. QOpenGLTexture *m_base_texture = nullptr;
  243. QOpenGLTexture *m_water_texture = nullptr;
  244. LineLayer m_coast_layer;
  245. LineLayer m_river_layer;
  246. PathLayer m_path_layer;
  247. LineLayer m_province_border_layer;
  248. ProvinceLayer m_province_layer;
  249. float m_orbit_yaw = 180.0F;
  250. float m_orbit_pitch = 55.0F;
  251. float m_orbit_distance = 2.4F;
  252. float m_pan_u = 0.0F;
  253. float m_pan_v = 0.0F;
  254. QString m_hover_province_id;
  255. int m_province_state_version = 0;
  256. int m_current_mission = 7;
  257. qint64 m_hover_start_time = 0;
  258. qint64 m_last_update_time = 0;
  259. auto ensure_initialized() -> bool {
  260. if (m_initialized) {
  261. return true;
  262. }
  263. QOpenGLContext *ctx = QOpenGLContext::currentContext();
  264. if (ctx == nullptr || !ctx->isValid()) {
  265. qWarning() << "CampaignMapRenderer: No valid OpenGL context";
  266. return false;
  267. }
  268. initializeOpenGLFunctions();
  269. if (!init_shaders()) {
  270. return false;
  271. }
  272. init_quad();
  273. auto &tex_cache = CampaignMapTextureCache::instance();
  274. tex_cache.set_loading_allowed(true);
  275. m_water_texture = tex_cache.get_or_load(
  276. QStringLiteral(":/assets/campaign_map/campaign_water.png"));
  277. m_base_texture = tex_cache.get_or_load(
  278. QStringLiteral(":/assets/campaign_map/campaign_base_color.png"));
  279. tex_cache.set_loading_allowed(false);
  280. init_land_mesh();
  281. init_line_layer(m_coast_layer,
  282. QStringLiteral(":/assets/campaign_map/coastlines_uv.json"),
  283. QVector4D(0.15F, 0.13F, 0.11F, 1.0F), 2.0F);
  284. init_line_layer(m_river_layer,
  285. QStringLiteral(":/assets/campaign_map/rivers_uv.json"),
  286. QVector4D(0.35F, 0.45F, 0.55F, 0.85F), 1.5F);
  287. init_path_layer(m_path_layer,
  288. QStringLiteral(":/assets/campaign_map/hannibal_path.json"));
  289. init_province_layer(m_province_layer,
  290. QStringLiteral(":/assets/campaign_map/provinces.json"));
  291. init_borders_layer(m_province_border_layer,
  292. QStringLiteral(":/assets/campaign_map/provinces.json"),
  293. QVector4D(0.25F, 0.22F, 0.20F, 0.65F), 1.2F);
  294. m_initialized = true;
  295. return true;
  296. }
  297. auto init_shaders() -> bool {
  298. static const char *kTexVert = R"(
  299. #version 330 core
  300. layout(location = 0) in vec2 a_pos;
  301. uniform mat4 u_mvp;
  302. uniform float u_z;
  303. out vec2 v_uv;
  304. void main() {
  305. vec3 world = vec3(1.0 - a_pos.x, u_z, a_pos.y);
  306. gl_Position = u_mvp * vec4(world, 1.0);
  307. v_uv = a_pos;
  308. }
  309. )";
  310. static const char *kTexFrag = R"(
  311. #version 330 core
  312. in vec2 v_uv;
  313. uniform sampler2D u_tex;
  314. uniform float u_alpha;
  315. out vec4 fragColor;
  316. void main() {
  317. vec2 uv = vec2(v_uv.x, 1.0 - v_uv.y);
  318. vec4 texel = texture(u_tex, uv);
  319. fragColor = vec4(texel.rgb, texel.a * u_alpha);
  320. }
  321. )";
  322. static const char *kLineVert = R"(
  323. #version 330 core
  324. layout(location = 0) in vec2 a_pos;
  325. uniform mat4 u_mvp;
  326. uniform float u_z;
  327. void main() {
  328. vec3 world = vec3(1.0 - a_pos.x, u_z, a_pos.y);
  329. gl_Position = u_mvp * vec4(world, 1.0);
  330. }
  331. )";
  332. static const char *kLineFrag = R"(
  333. #version 330 core
  334. uniform vec4 u_color;
  335. out vec4 fragColor;
  336. void main() {
  337. fragColor = u_color;
  338. }
  339. )";
  340. if (!m_texture_program.addShaderFromSourceCode(QOpenGLShader::Vertex,
  341. kTexVert)) {
  342. qWarning()
  343. << "CampaignMapRenderer: Failed to compile texture vertex shader";
  344. return false;
  345. }
  346. if (!m_texture_program.addShaderFromSourceCode(QOpenGLShader::Fragment,
  347. kTexFrag)) {
  348. qWarning()
  349. << "CampaignMapRenderer: Failed to compile texture fragment shader";
  350. return false;
  351. }
  352. if (!m_texture_program.link()) {
  353. qWarning() << "CampaignMapRenderer: Failed to link texture shader";
  354. return false;
  355. }
  356. if (!m_line_program.addShaderFromSourceCode(QOpenGLShader::Vertex,
  357. kLineVert)) {
  358. qWarning() << "CampaignMapRenderer: Failed to compile line vertex shader";
  359. return false;
  360. }
  361. if (!m_line_program.addShaderFromSourceCode(QOpenGLShader::Fragment,
  362. kLineFrag)) {
  363. qWarning()
  364. << "CampaignMapRenderer: Failed to compile line fragment shader";
  365. return false;
  366. }
  367. if (!m_line_program.link()) {
  368. qWarning() << "CampaignMapRenderer: Failed to link line shader";
  369. return false;
  370. }
  371. return true;
  372. }
  373. void init_quad() {
  374. if (m_quad_vao != 0) {
  375. return;
  376. }
  377. static const float kQuadVerts[] = {
  378. 0.0F, 0.0F, 1.0F, 0.0F, 1.0F, 1.0F, 0.0F, 0.0F, 1.0F, 1.0F, 0.0F, 1.0F,
  379. };
  380. glGenVertexArrays(1, &m_quad_vao);
  381. glGenBuffers(1, &m_quad_vbo);
  382. glBindVertexArray(m_quad_vao);
  383. glBindBuffer(GL_ARRAY_BUFFER, m_quad_vbo);
  384. glBufferData(GL_ARRAY_BUFFER, sizeof(kQuadVerts), kQuadVerts,
  385. GL_STATIC_DRAW);
  386. glEnableVertexAttribArray(0);
  387. glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 2 * sizeof(float),
  388. reinterpret_cast<void *>(0));
  389. glBindVertexArray(0);
  390. }
  391. void init_land_mesh() {
  392. const QString path = Utils::Resources::resolveResourcePath(
  393. QStringLiteral(":/assets/campaign_map/land_mesh.bin"));
  394. QFile file(path);
  395. if (!file.open(QIODevice::ReadOnly)) {
  396. qWarning() << "CampaignMapRenderer: Failed to open land mesh" << path;
  397. return;
  398. }
  399. const QByteArray data = file.readAll();
  400. if (data.isEmpty() || (data.size() % sizeof(float) != 0)) {
  401. qWarning() << "CampaignMapRenderer: Land mesh is empty or invalid";
  402. return;
  403. }
  404. const int floatCount = data.size() / static_cast<int>(sizeof(float));
  405. if (floatCount % 2 != 0) {
  406. qWarning() << "CampaignMapRenderer: Land mesh float count is odd";
  407. return;
  408. }
  409. std::vector<float> verts(static_cast<size_t>(floatCount));
  410. memcpy(verts.data(), data.constData(), static_cast<size_t>(data.size()));
  411. m_land_vertex_count = floatCount / 2;
  412. if (m_land_vertex_count == 0) {
  413. return;
  414. }
  415. glGenVertexArrays(1, &m_land_vao);
  416. glGenBuffers(1, &m_land_vbo);
  417. glBindVertexArray(m_land_vao);
  418. glBindBuffer(GL_ARRAY_BUFFER, m_land_vbo);
  419. glBufferData(GL_ARRAY_BUFFER, static_cast<GLsizeiptr>(data.size()),
  420. verts.data(), GL_STATIC_DRAW);
  421. glEnableVertexAttribArray(0);
  422. glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 2 * sizeof(float),
  423. reinterpret_cast<void *>(0));
  424. glBindVertexArray(0);
  425. }
  426. void init_line_layer(LineLayer &layer, const QString &resource_path,
  427. const QVector4D &color, float width) {
  428. const QString path = Utils::Resources::resolveResourcePath(resource_path);
  429. QFile file(path);
  430. if (!file.open(QIODevice::ReadOnly)) {
  431. qWarning() << "CampaignMapRenderer: Failed to open line layer" << path;
  432. return;
  433. }
  434. const QJsonDocument doc = QJsonDocument::fromJson(file.readAll());
  435. if (!doc.isObject()) {
  436. qWarning() << "CampaignMapRenderer: Line layer JSON invalid" << path;
  437. return;
  438. }
  439. const QJsonArray lines = doc.object().value("lines").toArray();
  440. std::vector<float> verts;
  441. verts.reserve(lines.size() * 8);
  442. std::vector<LineSpan> spans;
  443. int cursor = 0;
  444. for (const auto &line_val : lines) {
  445. const QJsonArray line = line_val.toArray();
  446. if (line.isEmpty()) {
  447. continue;
  448. }
  449. const int start = cursor;
  450. int count = 0;
  451. for (const auto &pt_val : line) {
  452. const QJsonArray pt = pt_val.toArray();
  453. if (pt.size() < 2) {
  454. continue;
  455. }
  456. verts.push_back(static_cast<float>(pt.at(0).toDouble()));
  457. verts.push_back(static_cast<float>(pt.at(1).toDouble()));
  458. ++count;
  459. ++cursor;
  460. }
  461. if (count >= 2) {
  462. spans.push_back({start, count});
  463. }
  464. }
  465. if (verts.empty() || spans.empty()) {
  466. return;
  467. }
  468. glGenVertexArrays(1, &layer.vao);
  469. glGenBuffers(1, &layer.vbo);
  470. glBindVertexArray(layer.vao);
  471. glBindBuffer(GL_ARRAY_BUFFER, layer.vbo);
  472. glBufferData(GL_ARRAY_BUFFER,
  473. static_cast<GLsizeiptr>(verts.size() * sizeof(float)),
  474. verts.data(), GL_STATIC_DRAW);
  475. glEnableVertexAttribArray(0);
  476. glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 2 * sizeof(float),
  477. reinterpret_cast<void *>(0));
  478. glBindVertexArray(0);
  479. layer.color = color;
  480. layer.width = width;
  481. layer.spans = std::move(spans);
  482. layer.ready = true;
  483. }
  484. void init_province_layer(ProvinceLayer &layer, const QString &resource_path) {
  485. const QString path = Utils::Resources::resolveResourcePath(resource_path);
  486. QFile file(path);
  487. if (!file.open(QIODevice::ReadOnly)) {
  488. qWarning() << "CampaignMapRenderer: Failed to open provinces" << path;
  489. return;
  490. }
  491. const QJsonDocument doc = QJsonDocument::fromJson(file.readAll());
  492. if (!doc.isObject()) {
  493. qWarning() << "CampaignMapRenderer: Provinces JSON invalid" << path;
  494. return;
  495. }
  496. const QJsonArray provinces = doc.object().value("provinces").toArray();
  497. if (provinces.isEmpty()) {
  498. return;
  499. }
  500. std::vector<float> verts;
  501. std::vector<ProvinceSpan> spans;
  502. int cursor = 0;
  503. for (const auto &prov_val : provinces) {
  504. const QJsonObject prov = prov_val.toObject();
  505. const QString province_id = prov.value("id").toString();
  506. const QJsonArray tri = prov.value("triangles").toArray();
  507. if (tri.isEmpty()) {
  508. continue;
  509. }
  510. const int start = cursor;
  511. int count = 0;
  512. for (const auto &pt_val : tri) {
  513. const QJsonArray pt = pt_val.toArray();
  514. if (pt.size() < 2) {
  515. continue;
  516. }
  517. verts.push_back(static_cast<float>(pt.at(0).toDouble()));
  518. verts.push_back(static_cast<float>(pt.at(1).toDouble()));
  519. ++count;
  520. ++cursor;
  521. }
  522. if (count >= 3) {
  523. QVector4D color(0.0F, 0.0F, 0.0F, 0.0F);
  524. const QJsonArray color_arr = prov.value("color").toArray();
  525. if (color_arr.size() >= 4) {
  526. color = QVector4D(static_cast<float>(color_arr.at(0).toDouble()),
  527. static_cast<float>(color_arr.at(1).toDouble()),
  528. static_cast<float>(color_arr.at(2).toDouble()),
  529. static_cast<float>(color_arr.at(3).toDouble()));
  530. }
  531. spans.push_back({start, count, color, color, province_id});
  532. }
  533. }
  534. if (verts.empty() || spans.empty()) {
  535. return;
  536. }
  537. glGenVertexArrays(1, &layer.vao);
  538. glGenBuffers(1, &layer.vbo);
  539. glBindVertexArray(layer.vao);
  540. glBindBuffer(GL_ARRAY_BUFFER, layer.vbo);
  541. glBufferData(GL_ARRAY_BUFFER,
  542. static_cast<GLsizeiptr>(verts.size() * sizeof(float)),
  543. verts.data(), GL_STATIC_DRAW);
  544. glEnableVertexAttribArray(0);
  545. glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 2 * sizeof(float),
  546. reinterpret_cast<void *>(0));
  547. glBindVertexArray(0);
  548. layer.spans = std::move(spans);
  549. layer.ready = true;
  550. }
  551. void init_borders_layer(LineLayer &layer, const QString &resource_path,
  552. const QVector4D &color, float width) {
  553. const QString path = Utils::Resources::resolveResourcePath(resource_path);
  554. QFile file(path);
  555. if (!file.open(QIODevice::ReadOnly)) {
  556. qWarning() << "CampaignMapRenderer: Failed to open borders" << path;
  557. return;
  558. }
  559. const QJsonDocument doc = QJsonDocument::fromJson(file.readAll());
  560. if (!doc.isObject()) {
  561. qWarning() << "CampaignMapRenderer: Borders JSON invalid" << path;
  562. return;
  563. }
  564. const QJsonArray lines = doc.object().value("borders").toArray();
  565. std::vector<float> verts;
  566. verts.reserve(lines.size() * 8);
  567. std::vector<LineSpan> spans;
  568. int cursor = 0;
  569. for (const auto &line_val : lines) {
  570. const QJsonArray line = line_val.toArray();
  571. if (line.isEmpty()) {
  572. continue;
  573. }
  574. const int start = cursor;
  575. int count = 0;
  576. for (const auto &pt_val : line) {
  577. const QJsonArray pt = pt_val.toArray();
  578. if (pt.size() < 2) {
  579. continue;
  580. }
  581. verts.push_back(static_cast<float>(pt.at(0).toDouble()));
  582. verts.push_back(static_cast<float>(pt.at(1).toDouble()));
  583. ++count;
  584. ++cursor;
  585. }
  586. if (count >= 2) {
  587. spans.push_back({start, count});
  588. }
  589. }
  590. if (verts.empty() || spans.empty()) {
  591. return;
  592. }
  593. glGenVertexArrays(1, &layer.vao);
  594. glGenBuffers(1, &layer.vbo);
  595. glBindVertexArray(layer.vao);
  596. glBindBuffer(GL_ARRAY_BUFFER, layer.vbo);
  597. glBufferData(GL_ARRAY_BUFFER,
  598. static_cast<GLsizeiptr>(verts.size() * sizeof(float)),
  599. verts.data(), GL_STATIC_DRAW);
  600. glEnableVertexAttribArray(0);
  601. glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 2 * sizeof(float),
  602. reinterpret_cast<void *>(0));
  603. glBindVertexArray(0);
  604. layer.color = color;
  605. layer.width = width;
  606. layer.spans = std::move(spans);
  607. layer.ready = true;
  608. }
  609. void init_path_layer(PathLayer &layer, const QString &resource_path) {
  610. const QString path = Utils::Resources::resolveResourcePath(resource_path);
  611. QFile file(path);
  612. if (!file.open(QIODevice::ReadOnly)) {
  613. qWarning() << "CampaignMapRenderer: Failed to open path layer" << path;
  614. return;
  615. }
  616. const QJsonDocument doc = QJsonDocument::fromJson(file.readAll());
  617. if (!doc.isObject()) {
  618. qWarning() << "CampaignMapRenderer: Path layer JSON invalid" << path;
  619. return;
  620. }
  621. const QJsonArray lines = doc.object().value("lines").toArray();
  622. for (const auto &line_val : lines) {
  623. const QJsonArray line = line_val.toArray();
  624. if (line.isEmpty()) {
  625. continue;
  626. }
  627. PathLine entry;
  628. entry.points.reserve(static_cast<size_t>(line.size()));
  629. for (const auto &pt_val : line) {
  630. const QJsonArray pt = pt_val.toArray();
  631. if (pt.size() < 2) {
  632. continue;
  633. }
  634. entry.points.emplace_back(static_cast<float>(pt.at(0).toDouble()),
  635. static_cast<float>(pt.at(1).toDouble()));
  636. }
  637. if (entry.points.size() >= 2) {
  638. layer.lines.push_back(std::move(entry));
  639. }
  640. }
  641. layer.ready = !layer.lines.empty();
  642. }
  643. auto load_texture(const QString &resource_path) -> QOpenGLTexture * {
  644. const QString path = Utils::Resources::resolveResourcePath(resource_path);
  645. QImage image(path);
  646. if (image.isNull()) {
  647. qWarning() << "CampaignMapRenderer: Failed to load texture" << path;
  648. return nullptr;
  649. }
  650. QImage rgba = image.convertToFormat(QImage::Format_RGBA8888);
  651. auto *texture = new QOpenGLTexture(rgba);
  652. texture->setWrapMode(QOpenGLTexture::ClampToEdge);
  653. texture->setMinMagFilters(QOpenGLTexture::Linear, QOpenGLTexture::Linear);
  654. return texture;
  655. }
  656. void compute_mvp(QMatrix4x4 &out_mvp) const {
  657. out_mvp = build_mvp_matrix(
  658. static_cast<float>(m_size.width()), static_cast<float>(m_size.height()),
  659. m_orbit_yaw, m_orbit_pitch, m_orbit_distance, m_pan_u, m_pan_v);
  660. }
  661. void draw_textured_layer(QOpenGLTexture *texture, GLuint vao,
  662. int vertex_count, const QMatrix4x4 &mvp, float alpha,
  663. float z_offset) {
  664. if (texture == nullptr || vao == 0 || vertex_count <= 0) {
  665. return;
  666. }
  667. m_texture_program.bind();
  668. m_texture_program.setUniformValue("u_mvp", mvp);
  669. m_texture_program.setUniformValue("u_z", z_offset);
  670. m_texture_program.setUniformValue("u_alpha", alpha);
  671. m_texture_program.setUniformValue("u_tex", 0);
  672. glActiveTexture(GL_TEXTURE0);
  673. texture->bind();
  674. glBindVertexArray(vao);
  675. glDrawArrays(GL_TRIANGLES, 0, vertex_count);
  676. glBindVertexArray(0);
  677. texture->release();
  678. m_texture_program.release();
  679. }
  680. void draw_line_layer(const LineLayer &layer, const QMatrix4x4 &mvp,
  681. float z_offset) {
  682. if (!layer.ready || layer.vao == 0 || layer.spans.empty()) {
  683. return;
  684. }
  685. glLineWidth(layer.width);
  686. m_line_program.bind();
  687. m_line_program.setUniformValue("u_mvp", mvp);
  688. m_line_program.setUniformValue("u_z", z_offset);
  689. m_line_program.setUniformValue("u_color", layer.color);
  690. glBindVertexArray(layer.vao);
  691. for (const auto &span : layer.spans) {
  692. glDrawArrays(GL_LINE_STRIP, span.start, span.count);
  693. }
  694. glBindVertexArray(0);
  695. m_line_program.release();
  696. }
  697. static auto safe_normalized(const QVector2D &v) -> QVector2D {
  698. const float len = v.length();
  699. if (len < 1e-5F) {
  700. return QVector2D(0.0F, 0.0F);
  701. }
  702. return v / len;
  703. }
  704. static auto perp(const QVector2D &v) -> QVector2D {
  705. return QVector2D(-v.y(), v.x());
  706. }
  707. void build_path_strip(const std::vector<QVector2D> &input, float half_width,
  708. std::vector<QVector2D> &out) const {
  709. out.clear();
  710. if (input.size() < 2 || half_width <= 0.0F) {
  711. return;
  712. }
  713. std::vector<QVector2D> points;
  714. points.reserve(input.size());
  715. for (const auto &pt : input) {
  716. if (points.empty()) {
  717. points.push_back(pt);
  718. continue;
  719. }
  720. const QVector2D delta = pt - points.back();
  721. if (QVector2D::dotProduct(delta, delta) > 1e-10F) {
  722. points.push_back(pt);
  723. }
  724. }
  725. if (points.size() < 2) {
  726. return;
  727. }
  728. out.reserve(points.size() * 2);
  729. for (size_t i = 0; i < points.size(); ++i) {
  730. QVector2D offset;
  731. if (i == 0) {
  732. const QVector2D dir = safe_normalized(points[1] - points[0]);
  733. offset = perp(dir) * half_width;
  734. } else if (i + 1 == points.size()) {
  735. const QVector2D dir = safe_normalized(points[i] - points[i - 1]);
  736. offset = perp(dir) * half_width;
  737. } else {
  738. QVector2D dir0 = safe_normalized(points[i] - points[i - 1]);
  739. QVector2D dir1 = safe_normalized(points[i + 1] - points[i]);
  740. if (dir0.isNull()) {
  741. dir0 = dir1;
  742. }
  743. if (dir1.isNull()) {
  744. dir1 = dir0;
  745. }
  746. const QVector2D n0 = perp(dir0);
  747. const QVector2D n1 = perp(dir1);
  748. QVector2D miter = safe_normalized(n0 + n1);
  749. if (miter.isNull()) {
  750. miter = n1;
  751. }
  752. float denom = QVector2D::dotProduct(miter, n1);
  753. if (std::abs(denom) < 0.2F) {
  754. denom = (denom >= 0.0F) ? 0.2F : -0.2F;
  755. }
  756. float miter_len = half_width / denom;
  757. const float max_miter = half_width * 3.0F;
  758. if (std::abs(miter_len) > max_miter) {
  759. miter_len = (miter_len < 0.0F) ? -max_miter : max_miter;
  760. }
  761. offset = miter * miter_len;
  762. }
  763. out.push_back(points[i] + offset);
  764. out.push_back(points[i] - offset);
  765. }
  766. }
  767. void update_path_mesh(StrokeMesh &mesh,
  768. const std::vector<QVector2D> &points, float width) {
  769. if (points.size() < 2) {
  770. mesh.ready = false;
  771. mesh.vertex_count = 0;
  772. return;
  773. }
  774. if (mesh.ready && qFuzzyCompare(mesh.width, width)) {
  775. return;
  776. }
  777. std::vector<QVector2D> strip;
  778. build_path_strip(points, width * 0.5F, strip);
  779. if (strip.size() < 4) {
  780. mesh.ready = false;
  781. mesh.vertex_count = 0;
  782. return;
  783. }
  784. std::vector<float> verts;
  785. verts.reserve(strip.size() * 2);
  786. for (const auto &v : strip) {
  787. verts.push_back(v.x());
  788. verts.push_back(v.y());
  789. }
  790. if (mesh.vao == 0) {
  791. glGenVertexArrays(1, &mesh.vao);
  792. glGenBuffers(1, &mesh.vbo);
  793. }
  794. glBindVertexArray(mesh.vao);
  795. glBindBuffer(GL_ARRAY_BUFFER, mesh.vbo);
  796. glBufferData(GL_ARRAY_BUFFER,
  797. static_cast<GLsizeiptr>(verts.size() * sizeof(float)),
  798. verts.data(), GL_DYNAMIC_DRAW);
  799. glEnableVertexAttribArray(0);
  800. glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 2 * sizeof(float),
  801. reinterpret_cast<void *>(0));
  802. glBindVertexArray(0);
  803. mesh.vertex_count = static_cast<int>(strip.size());
  804. mesh.width = width;
  805. mesh.ready = true;
  806. }
  807. auto uv_width_for_pixels(float px) const -> float {
  808. const float viewport_h = qMax(1.0F, static_cast<float>(m_size.height()));
  809. const float fov_rad = qDegreesToRadians(45.0F * 0.5F);
  810. const float view_h = 2.0F * m_orbit_distance * std::tan(fov_rad);
  811. const float uv_width = px * (view_h / viewport_h);
  812. return qMax(0.0005F, uv_width);
  813. }
  814. void draw_path_mesh(const StrokeMesh &mesh) {
  815. if (!mesh.ready || mesh.vao == 0 || mesh.vertex_count <= 0) {
  816. return;
  817. }
  818. glBindVertexArray(mesh.vao);
  819. glDrawArrays(GL_TRIANGLE_STRIP, 0, mesh.vertex_count);
  820. glBindVertexArray(0);
  821. }
  822. void draw_progressive_path_layers(PathLayer &layer, const QMatrix4x4 &mvp,
  823. float z_offset) {
  824. if (!layer.ready || layer.lines.empty()) {
  825. return;
  826. }
  827. const int max_mission =
  828. qBound(0, m_current_mission, static_cast<int>(layer.lines.size()) - 1);
  829. m_line_program.bind();
  830. m_line_program.setUniformValue("u_mvp", mvp);
  831. m_line_program.setUniformValue("u_z", z_offset);
  832. for (int i = 0; i <= max_mission; ++i) {
  833. if (i >= static_cast<int>(layer.lines.size())) {
  834. break;
  835. }
  836. auto &line = layer.lines[static_cast<size_t>(i)];
  837. QVector4D border_color;
  838. float border_width_px;
  839. if (i == max_mission) {
  840. border_color = QVector4D(0.15F, 0.08F, 0.05F, 0.85F);
  841. border_width_px = 18.0F;
  842. } else if (i == max_mission - 1) {
  843. border_color = QVector4D(0.15F, 0.08F, 0.05F, 0.70F);
  844. border_width_px = 16.0F;
  845. } else {
  846. const float age_factor = 1.0F - (max_mission - i) * 0.08F;
  847. border_color = QVector4D(0.15F * age_factor, 0.08F * age_factor,
  848. 0.05F * age_factor, 0.55F * age_factor);
  849. border_width_px = 14.0F;
  850. }
  851. update_path_mesh(line.border, line.points,
  852. uv_width_for_pixels(border_width_px));
  853. m_line_program.setUniformValue("u_color", border_color);
  854. draw_path_mesh(line.border);
  855. }
  856. for (int i = 0; i <= max_mission; ++i) {
  857. if (i >= static_cast<int>(layer.lines.size())) {
  858. break;
  859. }
  860. auto &line = layer.lines[static_cast<size_t>(i)];
  861. QVector4D highlight_color;
  862. float highlight_width_px;
  863. if (i == max_mission) {
  864. highlight_color = QVector4D(0.95F, 0.75F, 0.35F, 0.90F);
  865. highlight_width_px = 12.0F;
  866. } else if (i == max_mission - 1) {
  867. highlight_color = QVector4D(0.85F, 0.65F, 0.30F, 0.80F);
  868. highlight_width_px = 10.0F;
  869. } else {
  870. const float age_factor = 1.0F - (max_mission - i) * 0.08F;
  871. highlight_color = QVector4D(0.70F * age_factor, 0.50F * age_factor,
  872. 0.25F * age_factor, 0.65F * age_factor);
  873. highlight_width_px = 8.5F;
  874. }
  875. update_path_mesh(line.highlight, line.points,
  876. uv_width_for_pixels(highlight_width_px));
  877. m_line_program.setUniformValue("u_color", highlight_color);
  878. draw_path_mesh(line.highlight);
  879. }
  880. for (int i = 0; i <= max_mission; ++i) {
  881. if (i >= static_cast<int>(layer.lines.size())) {
  882. break;
  883. }
  884. auto &line = layer.lines[static_cast<size_t>(i)];
  885. QVector4D color;
  886. float width_px;
  887. if (i == max_mission) {
  888. color = QVector4D(0.80F, 0.15F, 0.10F, 1.0F);
  889. width_px = 7.0F;
  890. } else if (i == max_mission - 1) {
  891. color = QVector4D(0.70F, 0.15F, 0.10F, 0.95F);
  892. width_px = 6.0F;
  893. } else {
  894. const float age_factor = 1.0F - (max_mission - i) * 0.08F;
  895. color = QVector4D(0.55F * age_factor, 0.12F * age_factor,
  896. 0.08F * age_factor, 0.85F * age_factor);
  897. width_px = 5.0F;
  898. }
  899. update_path_mesh(line.core, line.points, uv_width_for_pixels(width_px));
  900. m_line_program.setUniformValue("u_color", color);
  901. draw_path_mesh(line.core);
  902. }
  903. m_line_program.release();
  904. }
  905. void apply_province_overrides(
  906. const QHash<QString, CampaignMapView::ProvinceVisual> &overrides) {
  907. if (!m_province_layer.ready || m_province_layer.spans.empty()) {
  908. return;
  909. }
  910. for (auto &span : m_province_layer.spans) {
  911. const auto it = overrides.find(span.id);
  912. if (it != overrides.end() && it->has_color) {
  913. span.color = it->color;
  914. } else {
  915. span.color = span.base_color;
  916. }
  917. }
  918. }
  919. void draw_province_layer(const ProvinceLayer &layer, const QMatrix4x4 &mvp,
  920. float z_offset) {
  921. if (!layer.ready || layer.vao == 0 || layer.spans.empty()) {
  922. return;
  923. }
  924. m_line_program.bind();
  925. m_line_program.setUniformValue("u_mvp", mvp);
  926. m_line_program.setUniformValue("u_z", z_offset);
  927. glBindVertexArray(layer.vao);
  928. for (const auto &span : layer.spans) {
  929. if (span.color.w() <= 0.0F) {
  930. continue;
  931. }
  932. QVector4D color = span.color;
  933. if (!m_hover_province_id.isEmpty() && span.id == m_hover_province_id) {
  934. qint64 elapsed =
  935. QDateTime::currentMSecsSinceEpoch() - m_hover_start_time;
  936. float pulse_cycle = 1200.0F;
  937. float pulse =
  938. 0.5F + 0.5F * std::sin(elapsed * 2.0F * M_PI / pulse_cycle);
  939. float brightness_boost = 0.3F + 0.15F * pulse;
  940. color = QVector4D(qMin(1.0F, color.x() + brightness_boost),
  941. qMin(1.0F, color.y() + brightness_boost),
  942. qMin(1.0F, color.z() + brightness_boost),
  943. qMin(1.0F, color.w() + 0.2F));
  944. }
  945. m_line_program.setUniformValue("u_color", color);
  946. glDrawArrays(GL_TRIANGLES, span.start, span.count);
  947. }
  948. glBindVertexArray(0);
  949. m_line_program.release();
  950. }
  951. void cleanup() {
  952. if (QOpenGLContext::currentContext() == nullptr) {
  953. return;
  954. }
  955. if (m_quad_vbo != 0) {
  956. glDeleteBuffers(1, &m_quad_vbo);
  957. m_quad_vbo = 0;
  958. }
  959. if (m_quad_vao != 0) {
  960. glDeleteVertexArrays(1, &m_quad_vao);
  961. m_quad_vao = 0;
  962. }
  963. if (m_land_vbo != 0) {
  964. glDeleteBuffers(1, &m_land_vbo);
  965. m_land_vbo = 0;
  966. }
  967. if (m_land_vao != 0) {
  968. glDeleteVertexArrays(1, &m_land_vao);
  969. m_land_vao = 0;
  970. }
  971. if (m_coast_layer.vbo != 0) {
  972. glDeleteBuffers(1, &m_coast_layer.vbo);
  973. m_coast_layer.vbo = 0;
  974. }
  975. if (m_coast_layer.vao != 0) {
  976. glDeleteVertexArrays(1, &m_coast_layer.vao);
  977. m_coast_layer.vao = 0;
  978. }
  979. if (m_river_layer.vbo != 0) {
  980. glDeleteBuffers(1, &m_river_layer.vbo);
  981. m_river_layer.vbo = 0;
  982. }
  983. if (m_river_layer.vao != 0) {
  984. glDeleteVertexArrays(1, &m_river_layer.vao);
  985. m_river_layer.vao = 0;
  986. }
  987. for (auto &line : m_path_layer.lines) {
  988. if (line.border.vbo != 0) {
  989. glDeleteBuffers(1, &line.border.vbo);
  990. line.border.vbo = 0;
  991. }
  992. if (line.border.vao != 0) {
  993. glDeleteVertexArrays(1, &line.border.vao);
  994. line.border.vao = 0;
  995. }
  996. if (line.highlight.vbo != 0) {
  997. glDeleteBuffers(1, &line.highlight.vbo);
  998. line.highlight.vbo = 0;
  999. }
  1000. if (line.highlight.vao != 0) {
  1001. glDeleteVertexArrays(1, &line.highlight.vao);
  1002. line.highlight.vao = 0;
  1003. }
  1004. if (line.core.vbo != 0) {
  1005. glDeleteBuffers(1, &line.core.vbo);
  1006. line.core.vbo = 0;
  1007. }
  1008. if (line.core.vao != 0) {
  1009. glDeleteVertexArrays(1, &line.core.vao);
  1010. line.core.vao = 0;
  1011. }
  1012. }
  1013. m_path_layer.lines.clear();
  1014. if (m_province_border_layer.vbo != 0) {
  1015. glDeleteBuffers(1, &m_province_border_layer.vbo);
  1016. m_province_border_layer.vbo = 0;
  1017. }
  1018. if (m_province_border_layer.vao != 0) {
  1019. glDeleteVertexArrays(1, &m_province_border_layer.vao);
  1020. m_province_border_layer.vao = 0;
  1021. }
  1022. if (m_province_layer.vbo != 0) {
  1023. glDeleteBuffers(1, &m_province_layer.vbo);
  1024. m_province_layer.vbo = 0;
  1025. }
  1026. if (m_province_layer.vao != 0) {
  1027. glDeleteVertexArrays(1, &m_province_layer.vao);
  1028. m_province_layer.vao = 0;
  1029. }
  1030. m_base_texture = nullptr;
  1031. m_water_texture = nullptr;
  1032. }
  1033. };
  1034. } // namespace
  1035. CampaignMapView::CampaignMapView() {
  1036. setMirrorVertically(true);
  1037. QOpenGLContext *ctx = QOpenGLContext::currentContext();
  1038. if (ctx == nullptr) {
  1039. qWarning() << "CampaignMapView: No OpenGL context available";
  1040. qWarning()
  1041. << "CampaignMapView: 3D rendering will not work in software mode";
  1042. qWarning()
  1043. << "CampaignMapView: Try running without QT_QUICK_BACKEND=software";
  1044. }
  1045. }
  1046. void CampaignMapView::load_provinces_for_hit_test() {
  1047. if (m_provinces_loaded) {
  1048. return;
  1049. }
  1050. m_provinces_loaded = true;
  1051. m_provinces.clear();
  1052. const QString path = Utils::Resources::resolveResourcePath(
  1053. QStringLiteral(":/assets/campaign_map/provinces.json"));
  1054. QFile file(path);
  1055. if (!file.open(QIODevice::ReadOnly)) {
  1056. return;
  1057. }
  1058. const QJsonDocument doc = QJsonDocument::fromJson(file.readAll());
  1059. if (!doc.isObject()) {
  1060. return;
  1061. }
  1062. const QJsonArray provinces = doc.object().value("provinces").toArray();
  1063. for (const auto &prov_val : provinces) {
  1064. const QJsonObject prov = prov_val.toObject();
  1065. const QJsonArray tri = prov.value("triangles").toArray();
  1066. if (tri.isEmpty()) {
  1067. continue;
  1068. }
  1069. ProvinceHit province;
  1070. province.id = prov.value("id").toString();
  1071. province.name = prov.value("name").toString();
  1072. province.owner = prov.value("owner").toString();
  1073. province.triangles.reserve(static_cast<size_t>(tri.size()));
  1074. for (const auto &pt_val : tri) {
  1075. const QJsonArray pt = pt_val.toArray();
  1076. if (pt.size() < 2) {
  1077. continue;
  1078. }
  1079. province.triangles.emplace_back(static_cast<float>(pt.at(0).toDouble()),
  1080. static_cast<float>(pt.at(1).toDouble()));
  1081. }
  1082. if (province.triangles.size() >= 3) {
  1083. m_provinces.push_back(std::move(province));
  1084. }
  1085. }
  1086. if (!m_province_overrides.isEmpty()) {
  1087. for (auto &province : m_provinces) {
  1088. const auto it = m_province_overrides.find(province.id);
  1089. if (it != m_province_overrides.end() && !it->owner.isEmpty()) {
  1090. province.owner = it->owner;
  1091. }
  1092. }
  1093. }
  1094. }
  1095. void CampaignMapView::load_province_labels() {
  1096. if (m_province_labels_loaded) {
  1097. return;
  1098. }
  1099. m_province_labels_loaded = true;
  1100. m_province_labels.clear();
  1101. const QString path = Utils::Resources::resolveResourcePath(
  1102. QStringLiteral(":/assets/campaign_map/provinces.json"));
  1103. QFile file(path);
  1104. if (!file.open(QIODevice::ReadOnly)) {
  1105. return;
  1106. }
  1107. const QJsonDocument doc = QJsonDocument::fromJson(file.readAll());
  1108. if (!doc.isObject()) {
  1109. return;
  1110. }
  1111. const QJsonArray provinces = doc.object().value("provinces").toArray();
  1112. for (const auto &prov_val : provinces) {
  1113. const QJsonObject prov = prov_val.toObject();
  1114. QVariantMap entry;
  1115. entry.insert(QStringLiteral("id"), prov.value("id").toString());
  1116. entry.insert(QStringLiteral("name"), prov.value("name").toString());
  1117. entry.insert(QStringLiteral("owner"), prov.value("owner").toString());
  1118. const QJsonArray label_uv = prov.value("label_uv").toArray();
  1119. if (label_uv.size() >= 2) {
  1120. QVariantList label_list;
  1121. label_list.reserve(2);
  1122. label_list.push_back(label_uv.at(0).toDouble());
  1123. label_list.push_back(label_uv.at(1).toDouble());
  1124. entry.insert(QStringLiteral("label_uv"), label_list);
  1125. }
  1126. const QJsonArray cities = prov.value("cities").toArray();
  1127. QVariantList city_list;
  1128. city_list.reserve(cities.size());
  1129. for (const auto &city_val : cities) {
  1130. const QJsonObject city = city_val.toObject();
  1131. const QString name = city.value("name").toString();
  1132. const QJsonArray uv = city.value("uv").toArray();
  1133. if (name.isEmpty() || uv.size() < 2) {
  1134. continue;
  1135. }
  1136. QVariantList uv_list;
  1137. uv_list.reserve(2);
  1138. uv_list.push_back(uv.at(0).toDouble());
  1139. uv_list.push_back(uv.at(1).toDouble());
  1140. QVariantMap city_entry;
  1141. city_entry.insert(QStringLiteral("name"), name);
  1142. city_entry.insert(QStringLiteral("uv"), uv_list);
  1143. city_list.push_back(city_entry);
  1144. }
  1145. entry.insert(QStringLiteral("cities"), city_list);
  1146. m_province_labels.push_back(entry);
  1147. }
  1148. if (!m_province_overrides.isEmpty()) {
  1149. QVariantList updated;
  1150. updated.reserve(m_province_labels.size());
  1151. for (const auto &entry_val : m_province_labels) {
  1152. QVariantMap entry = entry_val.toMap();
  1153. const QString id = entry.value(QStringLiteral("id")).toString();
  1154. const auto it = m_province_overrides.find(id);
  1155. if (it != m_province_overrides.end() && !it->owner.isEmpty()) {
  1156. entry.insert(QStringLiteral("owner"), it->owner);
  1157. }
  1158. updated.push_back(entry);
  1159. }
  1160. m_province_labels = std::move(updated);
  1161. }
  1162. emit province_labels_changed();
  1163. }
  1164. QVariantList CampaignMapView::province_labels() {
  1165. load_province_labels();
  1166. return m_province_labels;
  1167. }
  1168. void CampaignMapView::apply_province_state(const QVariantList &states) {
  1169. QHash<QString, ProvinceVisual> next_overrides;
  1170. next_overrides.reserve(states.size());
  1171. for (const auto &state_val : states) {
  1172. const QVariantMap state = state_val.toMap();
  1173. const QString id = state.value(QStringLiteral("id")).toString();
  1174. if (id.isEmpty()) {
  1175. continue;
  1176. }
  1177. ProvinceVisual visual;
  1178. visual.owner = state.value(QStringLiteral("owner")).toString();
  1179. const QVariantList color_list =
  1180. state.value(QStringLiteral("color")).toList();
  1181. if (color_list.size() >= 4) {
  1182. visual.color = QVector4D(static_cast<float>(color_list.at(0).toDouble()),
  1183. static_cast<float>(color_list.at(1).toDouble()),
  1184. static_cast<float>(color_list.at(2).toDouble()),
  1185. static_cast<float>(color_list.at(3).toDouble()));
  1186. visual.has_color = true;
  1187. }
  1188. next_overrides.insert(id, visual);
  1189. }
  1190. m_province_overrides = std::move(next_overrides);
  1191. ++m_province_state_version;
  1192. if (m_provinces_loaded) {
  1193. for (auto &province : m_provinces) {
  1194. const auto it = m_province_overrides.find(province.id);
  1195. if (it != m_province_overrides.end() && !it->owner.isEmpty()) {
  1196. province.owner = it->owner;
  1197. }
  1198. }
  1199. }
  1200. if (m_province_labels_loaded) {
  1201. QVariantList updated;
  1202. updated.reserve(m_province_labels.size());
  1203. for (const auto &entry_val : m_province_labels) {
  1204. QVariantMap entry = entry_val.toMap();
  1205. const QString id = entry.value(QStringLiteral("id")).toString();
  1206. const auto it = m_province_overrides.find(id);
  1207. if (it != m_province_overrides.end() && !it->owner.isEmpty()) {
  1208. entry.insert(QStringLiteral("owner"), it->owner);
  1209. }
  1210. updated.push_back(entry);
  1211. }
  1212. m_province_labels = std::move(updated);
  1213. emit province_labels_changed();
  1214. }
  1215. update();
  1216. }
  1217. QString CampaignMapView::province_at_screen(float x, float y) {
  1218. load_provinces_for_hit_test();
  1219. if (m_provinces.empty()) {
  1220. return {};
  1221. }
  1222. const float w = static_cast<float>(width());
  1223. const float h = static_cast<float>(height());
  1224. if (w <= 0.0F || h <= 0.0F) {
  1225. return {};
  1226. }
  1227. const float ndc_x = (2.0F * x / w) - 1.0F;
  1228. const float ndc_y = 1.0F - (2.0F * y / h);
  1229. const QMatrix4x4 mvp = build_mvp_matrix(w, h, m_orbit_yaw, m_orbit_pitch,
  1230. m_orbit_distance, m_pan_u, m_pan_v);
  1231. bool inverted = false;
  1232. const QMatrix4x4 inv = mvp.inverted(&inverted);
  1233. if (!inverted) {
  1234. return {};
  1235. }
  1236. QVector4D near_p = inv * QVector4D(ndc_x, ndc_y, -1.0F, 1.0F);
  1237. QVector4D far_p = inv * QVector4D(ndc_x, ndc_y, 1.0F, 1.0F);
  1238. if (qFuzzyIsNull(near_p.w()) || qFuzzyIsNull(far_p.w())) {
  1239. return {};
  1240. }
  1241. QVector3D near_v = QVector3D(near_p.x(), near_p.y(), near_p.z()) / near_p.w();
  1242. QVector3D far_v = QVector3D(far_p.x(), far_p.y(), far_p.z()) / far_p.w();
  1243. const QVector3D dir = far_v - near_v;
  1244. if (qFuzzyIsNull(dir.y())) {
  1245. return {};
  1246. }
  1247. const float t = -near_v.y() / dir.y();
  1248. if (t < 0.0F) {
  1249. return {};
  1250. }
  1251. const QVector3D hit = near_v + dir * t;
  1252. const float u = 1.0F - hit.x();
  1253. const float v = hit.z();
  1254. if (u < 0.0F || u > 1.0F || v < 0.0F || v > 1.0F) {
  1255. return {};
  1256. }
  1257. const QVector2D p(u, v);
  1258. for (const auto &province : m_provinces) {
  1259. const auto &triangles = province.triangles;
  1260. for (size_t i = 0; i + 2 < triangles.size(); i += 3) {
  1261. if (point_in_triangle(p, triangles[i], triangles[i + 1],
  1262. triangles[i + 2])) {
  1263. return province.id;
  1264. }
  1265. }
  1266. }
  1267. return {};
  1268. }
  1269. QVariantMap CampaignMapView::province_info_at_screen(float x, float y) {
  1270. load_provinces_for_hit_test();
  1271. QVariantMap info;
  1272. if (m_provinces.empty()) {
  1273. return info;
  1274. }
  1275. const float w = static_cast<float>(width());
  1276. const float h = static_cast<float>(height());
  1277. if (w <= 0.0F || h <= 0.0F) {
  1278. return info;
  1279. }
  1280. const float ndc_x = (2.0F * x / w) - 1.0F;
  1281. const float ndc_y = 1.0F - (2.0F * y / h);
  1282. const QMatrix4x4 mvp = build_mvp_matrix(w, h, m_orbit_yaw, m_orbit_pitch,
  1283. m_orbit_distance, m_pan_u, m_pan_v);
  1284. bool inverted = false;
  1285. const QMatrix4x4 inv = mvp.inverted(&inverted);
  1286. if (!inverted) {
  1287. return info;
  1288. }
  1289. QVector4D near_p = inv * QVector4D(ndc_x, ndc_y, -1.0F, 1.0F);
  1290. QVector4D far_p = inv * QVector4D(ndc_x, ndc_y, 1.0F, 1.0F);
  1291. if (qFuzzyIsNull(near_p.w()) || qFuzzyIsNull(far_p.w())) {
  1292. return info;
  1293. }
  1294. QVector3D near_v = QVector3D(near_p.x(), near_p.y(), near_p.z()) / near_p.w();
  1295. QVector3D far_v = QVector3D(far_p.x(), far_p.y(), far_p.z()) / far_p.w();
  1296. const QVector3D dir = far_v - near_v;
  1297. if (qFuzzyIsNull(dir.y())) {
  1298. return info;
  1299. }
  1300. const float t = -near_v.y() / dir.y();
  1301. if (t < 0.0F) {
  1302. return info;
  1303. }
  1304. const QVector3D hit = near_v + dir * t;
  1305. const float u = 1.0F - hit.x();
  1306. const float v = hit.z();
  1307. if (u < 0.0F || u > 1.0F || v < 0.0F || v > 1.0F) {
  1308. return info;
  1309. }
  1310. const QVector2D p(u, v);
  1311. for (const auto &province : m_provinces) {
  1312. const auto &triangles = province.triangles;
  1313. for (size_t i = 0; i + 2 < triangles.size(); i += 3) {
  1314. if (point_in_triangle(p, triangles[i], triangles[i + 1],
  1315. triangles[i + 2])) {
  1316. info.insert(QStringLiteral("id"), province.id);
  1317. info.insert(QStringLiteral("name"), province.name);
  1318. info.insert(QStringLiteral("owner"), province.owner);
  1319. return info;
  1320. }
  1321. }
  1322. }
  1323. return info;
  1324. }
  1325. QPointF CampaignMapView::screen_pos_for_uv(float u, float v) {
  1326. const float w = static_cast<float>(width());
  1327. const float h = static_cast<float>(height());
  1328. if (w <= 0.0F || h <= 0.0F) {
  1329. return {};
  1330. }
  1331. const float clamped_u = qBound(0.0F, u, 1.0F);
  1332. const float clamped_v = qBound(0.0F, v, 1.0F);
  1333. const QMatrix4x4 mvp = build_mvp_matrix(w, h, m_orbit_yaw, m_orbit_pitch,
  1334. m_orbit_distance, m_pan_u, m_pan_v);
  1335. const QVector4D world(1.0F - clamped_u, 0.0F, clamped_v, 1.0F);
  1336. const QVector4D clip = mvp * world;
  1337. if (qFuzzyIsNull(clip.w())) {
  1338. return {};
  1339. }
  1340. const float ndc_x = clip.x() / clip.w();
  1341. const float ndc_y = clip.y() / clip.w();
  1342. const float screen_x = (ndc_x + 1.0F) * 0.5F * w;
  1343. const float screen_y = (1.0F - (ndc_y + 1.0F) * 0.5F) * h;
  1344. return QPointF(screen_x, screen_y);
  1345. }
  1346. void CampaignMapView::load_hannibal_paths() {
  1347. if (m_hannibal_paths_loaded) {
  1348. return;
  1349. }
  1350. m_hannibal_paths_loaded = true;
  1351. m_hannibal_paths.clear();
  1352. const QString path = Utils::Resources::resolveResourcePath(
  1353. QStringLiteral(":/assets/campaign_map/hannibal_path.json"));
  1354. QFile file(path);
  1355. if (!file.open(QIODevice::ReadOnly)) {
  1356. qWarning() << "Failed to load Hannibal paths from" << path;
  1357. return;
  1358. }
  1359. const QJsonDocument doc = QJsonDocument::fromJson(file.readAll());
  1360. if (!doc.isObject()) {
  1361. return;
  1362. }
  1363. const QJsonArray lines = doc.object().value("lines").toArray();
  1364. for (const auto &line_val : lines) {
  1365. const QJsonArray line = line_val.toArray();
  1366. std::vector<QVector2D> path;
  1367. path.reserve(static_cast<size_t>(line.size()));
  1368. for (const auto &pt_val : line) {
  1369. const QJsonArray pt = pt_val.toArray();
  1370. if (pt.size() < 2) {
  1371. continue;
  1372. }
  1373. path.emplace_back(static_cast<float>(pt.at(0).toDouble()),
  1374. static_cast<float>(pt.at(1).toDouble()));
  1375. }
  1376. if (!path.empty()) {
  1377. m_hannibal_paths.push_back(std::move(path));
  1378. }
  1379. }
  1380. }
  1381. QPointF CampaignMapView::hannibal_icon_position() {
  1382. load_hannibal_paths();
  1383. if (m_hannibal_paths.empty()) {
  1384. return {};
  1385. }
  1386. const int mission_idx = qBound(0, m_current_mission,
  1387. static_cast<int>(m_hannibal_paths.size()) - 1);
  1388. const auto &path = m_hannibal_paths[static_cast<size_t>(mission_idx)];
  1389. if (path.empty()) {
  1390. return {};
  1391. }
  1392. const QVector2D &endpoint = path.back();
  1393. return screen_pos_for_uv(endpoint.x(), endpoint.y());
  1394. }
  1395. void CampaignMapView::set_orbit_yaw(float yaw) {
  1396. if (qFuzzyCompare(m_orbit_yaw, yaw)) {
  1397. return;
  1398. }
  1399. m_orbit_yaw = yaw;
  1400. emit orbit_yaw_changed();
  1401. update();
  1402. }
  1403. void CampaignMapView::set_orbit_pitch(float pitch) {
  1404. const float clamped = qBound(5.0F, pitch, 90.0F);
  1405. if (qFuzzyCompare(m_orbit_pitch, clamped)) {
  1406. return;
  1407. }
  1408. m_orbit_pitch = clamped;
  1409. emit orbit_pitch_changed();
  1410. update();
  1411. }
  1412. void CampaignMapView::set_orbit_distance(float distance) {
  1413. const float clamped =
  1414. qBound(k_min_orbit_distance, distance, k_max_orbit_distance);
  1415. if (qFuzzyCompare(m_orbit_distance, clamped)) {
  1416. return;
  1417. }
  1418. m_orbit_distance = clamped;
  1419. emit orbit_distance_changed();
  1420. update();
  1421. }
  1422. void CampaignMapView::set_pan_u(float pan) {
  1423. const float clamped = qBound(-0.5F, pan, 0.5F);
  1424. if (qFuzzyCompare(m_pan_u, clamped)) {
  1425. return;
  1426. }
  1427. m_pan_u = clamped;
  1428. emit pan_u_changed();
  1429. update();
  1430. }
  1431. void CampaignMapView::set_pan_v(float pan) {
  1432. const float clamped = qBound(-0.5F, pan, 0.5F);
  1433. if (qFuzzyCompare(m_pan_v, clamped)) {
  1434. return;
  1435. }
  1436. m_pan_v = clamped;
  1437. emit pan_v_changed();
  1438. update();
  1439. }
  1440. void CampaignMapView::set_hover_province_id(const QString &province_id) {
  1441. if (m_hover_province_id == province_id) {
  1442. return;
  1443. }
  1444. m_hover_province_id = province_id;
  1445. emit hover_province_id_changed();
  1446. update();
  1447. }
  1448. void CampaignMapView::set_current_mission(int mission) {
  1449. const int clamped = qBound(0, mission, 7);
  1450. if (m_current_mission == clamped) {
  1451. return;
  1452. }
  1453. m_current_mission = clamped;
  1454. emit current_mission_changed();
  1455. update();
  1456. }
  1457. auto CampaignMapView::createRenderer() const -> Renderer * {
  1458. QOpenGLContext *ctx = QOpenGLContext::currentContext();
  1459. if ((ctx == nullptr) || !ctx->isValid()) {
  1460. qCritical()
  1461. << "CampaignMapView::createRenderer() - No valid OpenGL context";
  1462. qCritical()
  1463. << "Running in software rendering mode - map view not available";
  1464. return nullptr;
  1465. }
  1466. return new CampaignMapRenderer();
  1467. }