campaign_map_view.cpp 83 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763
  1. #include "campaign_map_view.h"
  2. #include "campaign_map_render_utils.h"
  3. #include "../utils/resource_utils.h"
  4. #include <QDateTime>
  5. #include <QDebug>
  6. #include <QFile>
  7. #include <QImage>
  8. #include <QJsonArray>
  9. #include <QJsonDocument>
  10. #include <QJsonObject>
  11. #include <QMatrix4x4>
  12. #include <QOpenGLContext>
  13. #include <QOpenGLFramebufferObject>
  14. #include <QOpenGLFramebufferObjectFormat>
  15. #include <QOpenGLFunctions_3_3_Core>
  16. #include <QOpenGLShaderProgram>
  17. #include <QOpenGLTexture>
  18. #include <QVariantMap>
  19. #include <QVector2D>
  20. #include <QVector3D>
  21. #include <QVector4D>
  22. #include <QtGlobal>
  23. #include <QtMath>
  24. #include <cmath>
  25. #include <cstring>
  26. #include <unordered_map>
  27. #include <utility>
  28. #include <vector>
  29. namespace {
  30. auto build_mvp_matrix(float width, float height, float yaw_deg, float pitch_deg,
  31. float distance, float pan_u, float pan_v) -> QMatrix4x4 {
  32. const float view_w = qMax(1.0F, width);
  33. const float view_h = qMax(1.0F, height);
  34. const float aspect = view_w / view_h;
  35. QMatrix4x4 projection;
  36. projection.perspective(45.0F, aspect, 0.1F, 10.0F);
  37. const float clamped_pan_u = qBound(-0.5F, pan_u, 0.5F);
  38. const float clamped_pan_v = qBound(-0.5F, pan_v, 0.5F);
  39. const QVector3D center(0.5F + clamped_pan_u, 0.0F, 0.5F + clamped_pan_v);
  40. const float yaw_rad = qDegreesToRadians(yaw_deg);
  41. const float pitch_rad = qDegreesToRadians(pitch_deg);
  42. const float clamped_distance =
  43. qMax(CampaignMapView::k_min_orbit_distance, distance);
  44. const float cos_pitch = std::cos(pitch_rad);
  45. const float sin_pitch = std::sin(pitch_rad);
  46. const float cos_yaw = std::cos(yaw_rad);
  47. const float sin_yaw = std::sin(yaw_rad);
  48. QVector3D eye(center.x() + clamped_distance * sin_yaw * cos_pitch,
  49. center.y() + clamped_distance * sin_pitch,
  50. center.z() + clamped_distance * cos_yaw * cos_pitch);
  51. QMatrix4x4 view;
  52. view.lookAt(eye, center, QVector3D(0.0F, 0.0F, 1.0F));
  53. QMatrix4x4 model;
  54. return projection * view * model;
  55. }
  56. auto point_in_triangle(const QVector2D &p, const QVector2D &a,
  57. const QVector2D &b, const QVector2D &c) -> bool {
  58. const QVector2D v0 = c - a;
  59. const QVector2D v1 = b - a;
  60. const QVector2D v2 = p - a;
  61. const float dot00 = QVector2D::dotProduct(v0, v0);
  62. const float dot01 = QVector2D::dotProduct(v0, v1);
  63. const float dot02 = QVector2D::dotProduct(v0, v2);
  64. const float dot11 = QVector2D::dotProduct(v1, v1);
  65. const float dot12 = QVector2D::dotProduct(v1, v2);
  66. const float denom = dot00 * dot11 - dot01 * dot01;
  67. if (qFuzzyIsNull(denom)) {
  68. return false;
  69. }
  70. const float inv_denom = 1.0F / denom;
  71. const float u = (dot11 * dot02 - dot01 * dot12) * inv_denom;
  72. const float v = (dot00 * dot12 - dot01 * dot02) * inv_denom;
  73. return (u >= 0.0F) && (v >= 0.0F) && (u + v <= 1.0F);
  74. }
  75. struct LineSpan {
  76. int start = 0;
  77. int count = 0;
  78. };
  79. struct LineLayer {
  80. GLuint vao = 0;
  81. GLuint vbo = 0;
  82. std::vector<LineSpan> spans;
  83. QVector4D color = QVector4D(1.0F, 1.0F, 1.0F, 1.0F);
  84. float width = 1.0F;
  85. bool ready = false;
  86. bool double_stroke = false;
  87. QVector4D outer_color = QVector4D(0.12F, 0.10F, 0.08F, 0.95F);
  88. QVector4D inner_color = QVector4D(0.55F, 0.50F, 0.42F, 0.75F);
  89. float outer_width_ratio = 1.8F;
  90. float inner_width_ratio = 1.0F;
  91. };
  92. struct StrokeMesh {
  93. GLuint vao = 0;
  94. GLuint vbo = 0;
  95. int vertex_count = 0;
  96. float width = 0.0F;
  97. bool ready = false;
  98. };
  99. struct PathLine {
  100. std::vector<QVector2D> points;
  101. StrokeMesh border;
  102. StrokeMesh highlight;
  103. StrokeMesh core;
  104. };
  105. struct PathLayer {
  106. std::vector<PathLine> lines;
  107. bool ready = false;
  108. };
  109. struct ProvinceSpan {
  110. int start = 0;
  111. int count = 0;
  112. QVector4D color = QVector4D(0.0F, 0.0F, 0.0F, 0.0F);
  113. QVector4D base_color = QVector4D(0.0F, 0.0F, 0.0F, 0.0F);
  114. QString id;
  115. };
  116. struct ProvinceLayer {
  117. GLuint vao = 0;
  118. GLuint vbo = 0;
  119. std::vector<ProvinceSpan> spans;
  120. bool ready = false;
  121. };
  122. struct MissionBadge {
  123. GLuint vao = 0;
  124. GLuint vbo = 0;
  125. int vertex_count = 0;
  126. QVector2D position;
  127. bool ready = false;
  128. int style = 3;
  129. QVector4D primary_color = QVector4D(0.75F, 0.18F, 0.12F, 1.0F);
  130. QVector4D secondary_color = QVector4D(0.95F, 0.85F, 0.45F, 1.0F);
  131. QVector4D border_color = QVector4D(0.15F, 0.10F, 0.08F, 1.0F);
  132. QVector4D shadow_color = QVector4D(0.0F, 0.0F, 0.0F, 0.4F);
  133. float size = 0.025F;
  134. float border_width = 2.0F;
  135. bool show_shadow = true;
  136. };
  137. struct CartographicSymbolInstance {
  138. QVector2D position;
  139. int symbol_type;
  140. float size;
  141. int importance;
  142. };
  143. struct CartographicSymbolLayer {
  144. GLuint vao = 0;
  145. GLuint vbo = 0;
  146. std::vector<CartographicSymbolInstance> symbols;
  147. std::vector<LineSpan> spans;
  148. int total_vertices = 0;
  149. bool ready = false;
  150. QVector4D fill_color = QVector4D(0.35F, 0.30F, 0.25F, 0.85F);
  151. QVector4D stroke_color = QVector4D(0.18F, 0.15F, 0.12F, 0.95F);
  152. QVector4D shadow_color = QVector4D(0.0F, 0.0F, 0.0F, 0.35F);
  153. float stroke_width = 1.5F;
  154. bool show_shadow = true;
  155. };
  156. struct TerrainMesh {
  157. GLuint vao = 0;
  158. GLuint vbo = 0;
  159. int vertex_count = 0;
  160. bool ready = false;
  161. float height_scale = 0.05F;
  162. float z_base = 0.0F;
  163. };
  164. struct HillshadeLayer {
  165. GLuint texture_id = 0;
  166. int width = 0;
  167. int height = 0;
  168. bool ready = false;
  169. QVector3D light_direction{0.35F, 0.85F, 0.40F};
  170. float ambient = 0.25F;
  171. float intensity = 1.0F;
  172. };
  173. struct HeightmapData {
  174. std::vector<float> samples;
  175. int width = 0;
  176. int height = 0;
  177. float min_m = 0.0F;
  178. float max_m = 0.0F;
  179. bool ready = false;
  180. };
  181. struct ProvinceLabel {
  182. QString text;
  183. QVector2D position;
  184. int importance;
  185. bool is_sea = false;
  186. };
  187. struct LabelLayer {
  188. GLuint vao = 0;
  189. GLuint vbo = 0;
  190. std::vector<ProvinceLabel> labels;
  191. int total_vertices = 0;
  192. bool ready = false;
  193. GLuint font_texture = 0;
  194. };
  195. struct QStringHash {
  196. std::size_t operator()(const QString &s) const noexcept { return qHash(s); }
  197. };
  198. struct CampaignMapTextureCache {
  199. static CampaignMapTextureCache &instance() {
  200. static CampaignMapTextureCache s_instance;
  201. return s_instance;
  202. }
  203. QOpenGLTexture *get_or_load(const QString &resource_path) {
  204. if (!m_allow_loading) {
  205. qWarning() << "CampaignMapTextureCache: Attempted to load texture after "
  206. "initialization:"
  207. << resource_path;
  208. return nullptr;
  209. }
  210. auto it = m_textures.find(resource_path);
  211. if (it != m_textures.end() && it->second != nullptr) {
  212. return it->second;
  213. }
  214. const QString path = Utils::Resources::resolveResourcePath(resource_path);
  215. QImage image(path);
  216. if (image.isNull()) {
  217. qWarning() << "CampaignMapTextureCache: Failed to load texture" << path;
  218. return nullptr;
  219. }
  220. QImage rgba = image.convertToFormat(QImage::Format_RGBA8888);
  221. auto *texture = new QOpenGLTexture(rgba);
  222. texture->setWrapMode(QOpenGLTexture::ClampToEdge);
  223. texture->setMinMagFilters(QOpenGLTexture::Linear, QOpenGLTexture::Linear);
  224. m_textures[resource_path] = texture;
  225. return texture;
  226. }
  227. void set_loading_allowed(bool allowed) { m_allow_loading = allowed; }
  228. void clear() {
  229. QOpenGLContext *ctx = QOpenGLContext::currentContext();
  230. if (ctx != nullptr && ctx->isValid()) {
  231. for (auto &pair : m_textures) {
  232. delete pair.second;
  233. }
  234. }
  235. m_textures.clear();
  236. }
  237. private:
  238. CampaignMapTextureCache() = default;
  239. ~CampaignMapTextureCache() { clear(); }
  240. std::unordered_map<QString, QOpenGLTexture *, QStringHash> m_textures;
  241. bool m_allow_loading = true;
  242. };
  243. class CampaignMapRenderer : public QQuickFramebufferObject::Renderer,
  244. protected QOpenGLFunctions_3_3_Core {
  245. public:
  246. CampaignMapRenderer() = default;
  247. ~CampaignMapRenderer() override { cleanup(); }
  248. void render() override {
  249. if (!ensure_initialized()) {
  250. return;
  251. }
  252. glViewport(0, 0, m_size.width(), m_size.height());
  253. glEnable(GL_DEPTH_TEST);
  254. glDisable(GL_CULL_FACE);
  255. glEnable(GL_BLEND);
  256. glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
  257. glClearColor(0.157F, 0.267F, 0.361F, 1.0F);
  258. glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
  259. QMatrix4x4 mvp;
  260. compute_mvp(mvp);
  261. draw_textured_layer(m_water_texture, m_quad_vao, 6, mvp, 1.0F, -0.01F);
  262. if (m_terrain_mesh.ready && m_terrain_program.isLinked()) {
  263. draw_terrain_layer(m_terrain_mesh, mvp);
  264. } else if (m_land_vertex_count > 0) {
  265. draw_textured_layer(m_base_texture, m_land_vao, m_land_vertex_count, mvp,
  266. 1.0F, 0.0F);
  267. } else {
  268. draw_textured_layer(m_base_texture, m_quad_vao, 6, mvp, 1.0F, 0.0F);
  269. }
  270. glDisable(GL_DEPTH_TEST);
  271. if (m_show_province_fills) {
  272. draw_province_layer(m_province_layer, mvp, 0.002F);
  273. }
  274. draw_line_layer(m_province_border_layer, mvp, 0.0045F);
  275. draw_line_layer(m_coast_layer, mvp, 0.004F);
  276. draw_line_layer(m_river_layer, mvp, 0.003F);
  277. draw_progressive_path_layers(m_path_layer, mvp, 0.006F);
  278. draw_symbol_layer(m_symbol_layer, mvp, 0.007F);
  279. draw_mission_badge(m_mission_badge, mvp, 0.008F);
  280. draw_label_layer(m_label_layer, mvp, 0.009F);
  281. if (!m_hover_province_id.isEmpty()) {
  282. qint64 now = QDateTime::currentMSecsSinceEpoch();
  283. if (now - m_last_update_time >= 16) {
  284. m_last_update_time = now;
  285. update();
  286. }
  287. }
  288. }
  289. auto createFramebufferObject(const QSize &size)
  290. -> QOpenGLFramebufferObject * override {
  291. m_size = size;
  292. QOpenGLFramebufferObjectFormat fmt;
  293. fmt.setAttachment(QOpenGLFramebufferObject::Depth);
  294. fmt.setSamples(0);
  295. return new QOpenGLFramebufferObject(size, fmt);
  296. }
  297. void synchronize(QQuickFramebufferObject *item) override {
  298. auto *view = dynamic_cast<CampaignMapView *>(item);
  299. if (view == nullptr) {
  300. return;
  301. }
  302. m_orbit_yaw = view->orbit_yaw();
  303. m_orbit_pitch = view->orbit_pitch();
  304. m_orbit_distance = view->orbit_distance();
  305. m_pan_u = view->pan_u();
  306. m_pan_v = view->pan_v();
  307. m_terrain_height_scale = view->terrain_height_scale();
  308. m_show_province_fills = view->show_province_fills();
  309. QString new_hover_id = view->hover_province_id();
  310. if (m_hover_province_id != new_hover_id) {
  311. m_hover_start_time = QDateTime::currentMSecsSinceEpoch();
  312. m_hover_province_id = new_hover_id;
  313. }
  314. m_current_mission = view->current_mission();
  315. if (m_province_state_version != view->province_state_version() &&
  316. m_province_layer.ready) {
  317. apply_province_overrides(view->province_overrides());
  318. m_province_state_version = view->province_state_version();
  319. }
  320. }
  321. private:
  322. QSize m_size;
  323. bool m_initialized = false;
  324. QOpenGLShaderProgram m_texture_program;
  325. QOpenGLShaderProgram m_line_program;
  326. QOpenGLShaderProgram m_terrain_program;
  327. QOpenGLShaderProgram m_label_program;
  328. GLuint m_quad_vao = 0;
  329. GLuint m_quad_vbo = 0;
  330. GLuint m_land_vao = 0;
  331. GLuint m_land_vbo = 0;
  332. int m_land_vertex_count = 0;
  333. QOpenGLTexture *m_base_texture = nullptr;
  334. QOpenGLTexture *m_water_texture = nullptr;
  335. LineLayer m_coast_layer;
  336. LineLayer m_river_layer;
  337. PathLayer m_path_layer;
  338. LineLayer m_province_border_layer;
  339. ProvinceLayer m_province_layer;
  340. MissionBadge m_mission_badge;
  341. CartographicSymbolLayer m_symbol_layer;
  342. TerrainMesh m_terrain_mesh;
  343. HillshadeLayer m_hillshade;
  344. LabelLayer m_label_layer;
  345. float m_orbit_yaw = 185.0F;
  346. float m_orbit_pitch = 52.0F;
  347. float m_orbit_distance = 1.35F;
  348. float m_pan_u = 0.0F;
  349. float m_pan_v = 0.0F;
  350. QString m_hover_province_id;
  351. int m_province_state_version = 0;
  352. int m_current_mission = 7;
  353. float m_terrain_height_scale = 0.15F;
  354. bool m_show_province_fills = true;
  355. qint64 m_hover_start_time = 0;
  356. qint64 m_last_update_time = 0;
  357. auto ensure_initialized() -> bool {
  358. if (m_initialized) {
  359. return true;
  360. }
  361. QOpenGLContext *ctx = QOpenGLContext::currentContext();
  362. if (ctx == nullptr || !ctx->isValid()) {
  363. qWarning() << "CampaignMapRenderer: No valid OpenGL context";
  364. return false;
  365. }
  366. initializeOpenGLFunctions();
  367. if (!init_shaders()) {
  368. return false;
  369. }
  370. init_quad();
  371. auto &tex_cache = CampaignMapTextureCache::instance();
  372. tex_cache.set_loading_allowed(true);
  373. m_water_texture = tex_cache.get_or_load(
  374. QStringLiteral(":/assets/campaign_map/campaign_water.png"));
  375. m_base_texture = tex_cache.get_or_load(
  376. QStringLiteral(":/assets/campaign_map/campaign_base_color.png"));
  377. tex_cache.set_loading_allowed(false);
  378. init_land_mesh();
  379. init_line_layer(m_coast_layer,
  380. QStringLiteral(":/assets/campaign_map/coastlines_uv.json"),
  381. QVector4D(0.12F, 0.10F, 0.08F, 0.95F), 2.5F);
  382. m_coast_layer.double_stroke = true;
  383. m_coast_layer.outer_color = QVector4D(0.12F, 0.10F, 0.08F, 0.95F);
  384. m_coast_layer.inner_color = QVector4D(0.55F, 0.50F, 0.42F, 0.75F);
  385. init_line_layer(m_river_layer,
  386. QStringLiteral(":/assets/campaign_map/rivers_uv.json"),
  387. QVector4D(0.35F, 0.48F, 0.58F, 0.90F), 1.5F);
  388. init_path_layer(m_path_layer,
  389. QStringLiteral(":/assets/campaign_map/hannibal_path.json"));
  390. init_province_layer(m_province_layer,
  391. QStringLiteral(":/assets/campaign_map/provinces.json"));
  392. init_borders_layer(m_province_border_layer,
  393. QStringLiteral(":/assets/campaign_map/provinces.json"),
  394. QVector4D(0.25F, 0.22F, 0.20F, 0.65F), 1.2F);
  395. init_symbol_layer(m_symbol_layer,
  396. QStringLiteral(":/assets/campaign_map/provinces.json"));
  397. init_terrain_mesh(m_terrain_mesh, 128);
  398. init_hillshade_layer(m_hillshade, 256, 256);
  399. init_label_layer(m_label_layer,
  400. QStringLiteral(":/assets/campaign_map/provinces.json"));
  401. m_initialized = true;
  402. return true;
  403. }
  404. auto init_shaders() -> bool {
  405. static const char *kTexVert = R"(
  406. #version 330 core
  407. layout(location = 0) in vec2 a_pos;
  408. uniform mat4 u_mvp;
  409. uniform float u_z;
  410. out vec2 v_uv;
  411. void main() {
  412. vec3 world = vec3(1.0 - a_pos.x, u_z, a_pos.y);
  413. gl_Position = u_mvp * vec4(world, 1.0);
  414. v_uv = a_pos;
  415. }
  416. )";
  417. static const char *kTexFrag = R"(
  418. #version 330 core
  419. in vec2 v_uv;
  420. uniform sampler2D u_tex;
  421. uniform float u_alpha;
  422. out vec4 fragColor;
  423. void main() {
  424. vec2 uv = vec2(v_uv.x, 1.0 - v_uv.y);
  425. vec4 texel = texture(u_tex, uv);
  426. fragColor = vec4(texel.rgb, texel.a * u_alpha);
  427. }
  428. )";
  429. static const char *kLineVert = R"(
  430. #version 330 core
  431. layout(location = 0) in vec2 a_pos;
  432. uniform mat4 u_mvp;
  433. uniform float u_z;
  434. void main() {
  435. vec3 world = vec3(1.0 - a_pos.x, u_z, a_pos.y);
  436. gl_Position = u_mvp * vec4(world, 1.0);
  437. }
  438. )";
  439. static const char *kLineFrag = R"(
  440. #version 330 core
  441. uniform vec4 u_color;
  442. out vec4 fragColor;
  443. void main() {
  444. fragColor = u_color;
  445. }
  446. )";
  447. if (!m_texture_program.addShaderFromSourceCode(QOpenGLShader::Vertex,
  448. kTexVert)) {
  449. qWarning()
  450. << "CampaignMapRenderer: Failed to compile texture vertex shader";
  451. return false;
  452. }
  453. if (!m_texture_program.addShaderFromSourceCode(QOpenGLShader::Fragment,
  454. kTexFrag)) {
  455. qWarning()
  456. << "CampaignMapRenderer: Failed to compile texture fragment shader";
  457. return false;
  458. }
  459. if (!m_texture_program.link()) {
  460. qWarning() << "CampaignMapRenderer: Failed to link texture shader";
  461. return false;
  462. }
  463. if (!m_line_program.addShaderFromSourceCode(QOpenGLShader::Vertex,
  464. kLineVert)) {
  465. qWarning() << "CampaignMapRenderer: Failed to compile line vertex shader";
  466. return false;
  467. }
  468. if (!m_line_program.addShaderFromSourceCode(QOpenGLShader::Fragment,
  469. kLineFrag)) {
  470. qWarning()
  471. << "CampaignMapRenderer: Failed to compile line fragment shader";
  472. return false;
  473. }
  474. if (!m_line_program.link()) {
  475. qWarning() << "CampaignMapRenderer: Failed to link line shader";
  476. return false;
  477. }
  478. init_terrain_shader();
  479. return true;
  480. }
  481. void init_terrain_shader() {
  482. const QString vert_path = Utils::Resources::resolveResourcePath(
  483. QStringLiteral(":/assets/shaders/campaign_terrain.vert"));
  484. const QString frag_path = Utils::Resources::resolveResourcePath(
  485. QStringLiteral(":/assets/shaders/campaign_terrain.frag"));
  486. if (!m_terrain_program.addShaderFromSourceFile(QOpenGLShader::Vertex,
  487. vert_path)) {
  488. qWarning() << "CampaignMapRenderer: Failed to compile terrain vertex"
  489. << vert_path;
  490. m_terrain_program.removeAllShaders();
  491. return;
  492. }
  493. if (!m_terrain_program.addShaderFromSourceFile(QOpenGLShader::Fragment,
  494. frag_path)) {
  495. qWarning() << "CampaignMapRenderer: Failed to compile terrain fragment"
  496. << frag_path;
  497. m_terrain_program.removeAllShaders();
  498. return;
  499. }
  500. if (!m_terrain_program.link()) {
  501. qWarning() << "CampaignMapRenderer: Failed to link terrain shader";
  502. m_terrain_program.removeAllShaders();
  503. }
  504. }
  505. void init_quad() {
  506. if (m_quad_vao != 0) {
  507. return;
  508. }
  509. static const float kQuadVerts[] = {
  510. 0.0F, 0.0F, 1.0F, 0.0F, 1.0F, 1.0F, 0.0F, 0.0F, 1.0F, 1.0F, 0.0F, 1.0F,
  511. };
  512. glGenVertexArrays(1, &m_quad_vao);
  513. glGenBuffers(1, &m_quad_vbo);
  514. glBindVertexArray(m_quad_vao);
  515. glBindBuffer(GL_ARRAY_BUFFER, m_quad_vbo);
  516. glBufferData(GL_ARRAY_BUFFER, sizeof(kQuadVerts), kQuadVerts,
  517. GL_STATIC_DRAW);
  518. glEnableVertexAttribArray(0);
  519. glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 2 * sizeof(float),
  520. reinterpret_cast<void *>(0));
  521. glBindVertexArray(0);
  522. }
  523. void init_land_mesh() {
  524. const QString path = Utils::Resources::resolveResourcePath(
  525. QStringLiteral(":/assets/campaign_map/land_mesh.bin"));
  526. QFile file(path);
  527. if (!file.open(QIODevice::ReadOnly)) {
  528. qWarning() << "CampaignMapRenderer: Failed to open land mesh" << path;
  529. return;
  530. }
  531. const QByteArray data = file.readAll();
  532. if (data.isEmpty() || (data.size() % sizeof(float) != 0)) {
  533. qWarning() << "CampaignMapRenderer: Land mesh is empty or invalid";
  534. return;
  535. }
  536. const int floatCount = data.size() / static_cast<int>(sizeof(float));
  537. if (floatCount % 2 != 0) {
  538. qWarning() << "CampaignMapRenderer: Land mesh float count is odd";
  539. return;
  540. }
  541. std::vector<float> verts(static_cast<size_t>(floatCount));
  542. memcpy(verts.data(), data.constData(), static_cast<size_t>(data.size()));
  543. m_land_vertex_count = floatCount / 2;
  544. if (m_land_vertex_count == 0) {
  545. return;
  546. }
  547. glGenVertexArrays(1, &m_land_vao);
  548. glGenBuffers(1, &m_land_vbo);
  549. glBindVertexArray(m_land_vao);
  550. glBindBuffer(GL_ARRAY_BUFFER, m_land_vbo);
  551. glBufferData(GL_ARRAY_BUFFER, static_cast<GLsizeiptr>(data.size()),
  552. verts.data(), GL_STATIC_DRAW);
  553. glEnableVertexAttribArray(0);
  554. glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 2 * sizeof(float),
  555. reinterpret_cast<void *>(0));
  556. glBindVertexArray(0);
  557. }
  558. void init_line_layer(LineLayer &layer, const QString &resource_path,
  559. const QVector4D &color, float width) {
  560. const QString path = Utils::Resources::resolveResourcePath(resource_path);
  561. QFile file(path);
  562. if (!file.open(QIODevice::ReadOnly)) {
  563. qWarning() << "CampaignMapRenderer: Failed to open line layer" << path;
  564. return;
  565. }
  566. const QJsonDocument doc = QJsonDocument::fromJson(file.readAll());
  567. if (!doc.isObject()) {
  568. qWarning() << "CampaignMapRenderer: Line layer JSON invalid" << path;
  569. return;
  570. }
  571. const QJsonArray lines = doc.object().value("lines").toArray();
  572. std::vector<float> verts;
  573. verts.reserve(lines.size() * 8);
  574. std::vector<LineSpan> spans;
  575. int cursor = 0;
  576. for (const auto &line_val : lines) {
  577. const QJsonArray line = line_val.toArray();
  578. if (line.isEmpty()) {
  579. continue;
  580. }
  581. const int start = cursor;
  582. int count = 0;
  583. for (const auto &pt_val : line) {
  584. const QJsonArray pt = pt_val.toArray();
  585. if (pt.size() < 2) {
  586. continue;
  587. }
  588. verts.push_back(static_cast<float>(pt.at(0).toDouble()));
  589. verts.push_back(static_cast<float>(pt.at(1).toDouble()));
  590. ++count;
  591. ++cursor;
  592. }
  593. if (count >= 2) {
  594. spans.push_back({start, count});
  595. }
  596. }
  597. if (verts.empty() || spans.empty()) {
  598. return;
  599. }
  600. glGenVertexArrays(1, &layer.vao);
  601. glGenBuffers(1, &layer.vbo);
  602. glBindVertexArray(layer.vao);
  603. glBindBuffer(GL_ARRAY_BUFFER, layer.vbo);
  604. glBufferData(GL_ARRAY_BUFFER,
  605. static_cast<GLsizeiptr>(verts.size() * sizeof(float)),
  606. verts.data(), GL_STATIC_DRAW);
  607. glEnableVertexAttribArray(0);
  608. glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 2 * sizeof(float),
  609. reinterpret_cast<void *>(0));
  610. glBindVertexArray(0);
  611. layer.color = color;
  612. layer.width = width;
  613. layer.spans = std::move(spans);
  614. layer.ready = true;
  615. }
  616. void init_province_layer(ProvinceLayer &layer, const QString &resource_path) {
  617. const QString path = Utils::Resources::resolveResourcePath(resource_path);
  618. QFile file(path);
  619. if (!file.open(QIODevice::ReadOnly)) {
  620. qWarning() << "CampaignMapRenderer: Failed to open provinces" << path;
  621. return;
  622. }
  623. const QJsonDocument doc = QJsonDocument::fromJson(file.readAll());
  624. if (!doc.isObject()) {
  625. qWarning() << "CampaignMapRenderer: Provinces JSON invalid" << path;
  626. return;
  627. }
  628. const QJsonArray provinces = doc.object().value("provinces").toArray();
  629. if (provinces.isEmpty()) {
  630. return;
  631. }
  632. std::vector<float> verts;
  633. std::vector<ProvinceSpan> spans;
  634. int cursor = 0;
  635. for (const auto &prov_val : provinces) {
  636. const QJsonObject prov = prov_val.toObject();
  637. const QString province_id = prov.value("id").toString();
  638. const QJsonArray tri = prov.value("triangles").toArray();
  639. if (tri.isEmpty()) {
  640. continue;
  641. }
  642. const int start = cursor;
  643. int count = 0;
  644. for (const auto &pt_val : tri) {
  645. const QJsonArray pt = pt_val.toArray();
  646. if (pt.size() < 2) {
  647. continue;
  648. }
  649. verts.push_back(static_cast<float>(pt.at(0).toDouble()));
  650. verts.push_back(static_cast<float>(pt.at(1).toDouble()));
  651. ++count;
  652. ++cursor;
  653. }
  654. if (count >= 3) {
  655. QVector4D color(0.0F, 0.0F, 0.0F, 0.0F);
  656. const QJsonArray color_arr = prov.value("color").toArray();
  657. if (color_arr.size() >= 4) {
  658. color = QVector4D(static_cast<float>(color_arr.at(0).toDouble()),
  659. static_cast<float>(color_arr.at(1).toDouble()),
  660. static_cast<float>(color_arr.at(2).toDouble()),
  661. static_cast<float>(color_arr.at(3).toDouble()));
  662. }
  663. spans.push_back({start, count, color, color, province_id});
  664. }
  665. }
  666. if (verts.empty() || spans.empty()) {
  667. return;
  668. }
  669. glGenVertexArrays(1, &layer.vao);
  670. glGenBuffers(1, &layer.vbo);
  671. glBindVertexArray(layer.vao);
  672. glBindBuffer(GL_ARRAY_BUFFER, layer.vbo);
  673. glBufferData(GL_ARRAY_BUFFER,
  674. static_cast<GLsizeiptr>(verts.size() * sizeof(float)),
  675. verts.data(), GL_STATIC_DRAW);
  676. glEnableVertexAttribArray(0);
  677. glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 2 * sizeof(float),
  678. reinterpret_cast<void *>(0));
  679. glBindVertexArray(0);
  680. layer.spans = std::move(spans);
  681. layer.ready = true;
  682. }
  683. void init_borders_layer(LineLayer &layer, const QString &resource_path,
  684. const QVector4D &color, float width) {
  685. const QString path = Utils::Resources::resolveResourcePath(resource_path);
  686. QFile file(path);
  687. if (!file.open(QIODevice::ReadOnly)) {
  688. qWarning() << "CampaignMapRenderer: Failed to open borders" << path;
  689. return;
  690. }
  691. const QJsonDocument doc = QJsonDocument::fromJson(file.readAll());
  692. if (!doc.isObject()) {
  693. qWarning() << "CampaignMapRenderer: Borders JSON invalid" << path;
  694. return;
  695. }
  696. const QJsonArray lines = doc.object().value("borders").toArray();
  697. std::vector<float> verts;
  698. verts.reserve(lines.size() * 8);
  699. std::vector<LineSpan> spans;
  700. int cursor = 0;
  701. for (const auto &line_val : lines) {
  702. const QJsonArray line = line_val.toArray();
  703. if (line.isEmpty()) {
  704. continue;
  705. }
  706. const int start = cursor;
  707. int count = 0;
  708. for (const auto &pt_val : line) {
  709. const QJsonArray pt = pt_val.toArray();
  710. if (pt.size() < 2) {
  711. continue;
  712. }
  713. verts.push_back(static_cast<float>(pt.at(0).toDouble()));
  714. verts.push_back(static_cast<float>(pt.at(1).toDouble()));
  715. ++count;
  716. ++cursor;
  717. }
  718. if (count >= 2) {
  719. spans.push_back({start, count});
  720. }
  721. }
  722. if (verts.empty() || spans.empty()) {
  723. return;
  724. }
  725. glGenVertexArrays(1, &layer.vao);
  726. glGenBuffers(1, &layer.vbo);
  727. glBindVertexArray(layer.vao);
  728. glBindBuffer(GL_ARRAY_BUFFER, layer.vbo);
  729. glBufferData(GL_ARRAY_BUFFER,
  730. static_cast<GLsizeiptr>(verts.size() * sizeof(float)),
  731. verts.data(), GL_STATIC_DRAW);
  732. glEnableVertexAttribArray(0);
  733. glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 2 * sizeof(float),
  734. reinterpret_cast<void *>(0));
  735. glBindVertexArray(0);
  736. layer.color = color;
  737. layer.width = width;
  738. layer.spans = std::move(spans);
  739. layer.ready = true;
  740. }
  741. void init_path_layer(PathLayer &layer, const QString &resource_path) {
  742. const QString path = Utils::Resources::resolveResourcePath(resource_path);
  743. QFile file(path);
  744. if (!file.open(QIODevice::ReadOnly)) {
  745. qWarning() << "CampaignMapRenderer: Failed to open path layer" << path;
  746. return;
  747. }
  748. const QJsonDocument doc = QJsonDocument::fromJson(file.readAll());
  749. if (!doc.isObject()) {
  750. qWarning() << "CampaignMapRenderer: Path layer JSON invalid" << path;
  751. return;
  752. }
  753. const QJsonArray lines = doc.object().value("lines").toArray();
  754. for (const auto &line_val : lines) {
  755. const QJsonArray line = line_val.toArray();
  756. if (line.isEmpty()) {
  757. continue;
  758. }
  759. std::vector<QVector2D> raw_points;
  760. raw_points.reserve(static_cast<size_t>(line.size()));
  761. for (const auto &pt_val : line) {
  762. const QJsonArray pt = pt_val.toArray();
  763. if (pt.size() < 2) {
  764. continue;
  765. }
  766. raw_points.emplace_back(static_cast<float>(pt.at(0).toDouble()),
  767. static_cast<float>(pt.at(1).toDouble()));
  768. }
  769. if (raw_points.size() < 2) {
  770. continue;
  771. }
  772. PathLine entry;
  773. constexpr int k_spline_samples_per_segment = 8;
  774. entry.points = CampaignMapRender::smooth_catmull_rom(
  775. raw_points, k_spline_samples_per_segment);
  776. if (entry.points.size() >= 2) {
  777. layer.lines.push_back(std::move(entry));
  778. }
  779. }
  780. layer.ready = !layer.lines.empty();
  781. }
  782. void init_symbol_layer(CartographicSymbolLayer &layer,
  783. const QString &resource_path) {
  784. const QString path = Utils::Resources::resolveResourcePath(resource_path);
  785. QFile file(path);
  786. if (!file.open(QIODevice::ReadOnly)) {
  787. qWarning() << "CampaignMapRenderer: Failed to open symbols source"
  788. << path;
  789. return;
  790. }
  791. const QJsonDocument doc = QJsonDocument::fromJson(file.readAll());
  792. if (!doc.isObject()) {
  793. qWarning() << "CampaignMapRenderer: Symbols JSON invalid" << path;
  794. return;
  795. }
  796. const QJsonArray provinces = doc.object().value("provinces").toArray();
  797. for (const auto &prov_val : provinces) {
  798. const QJsonObject prov = prov_val.toObject();
  799. const QJsonArray cities = prov.value("cities").toArray();
  800. for (const auto &city_val : cities) {
  801. const QJsonObject city = city_val.toObject();
  802. const QJsonArray uv = city.value("uv").toArray();
  803. if (uv.size() < 2) {
  804. continue;
  805. }
  806. CartographicSymbolInstance symbol;
  807. symbol.position = QVector2D(static_cast<float>(uv.at(0).toDouble()),
  808. static_cast<float>(uv.at(1).toDouble()));
  809. const QString name = city.value("name").toString().toLower();
  810. const bool is_port = name.contains("port") || name.contains("harbor") ||
  811. city.value("is_port").toBool();
  812. const bool is_capital = city.value("is_capital").toBool();
  813. if (is_port) {
  814. symbol.symbol_type = 2;
  815. symbol.importance = 2;
  816. } else if (is_capital) {
  817. symbol.symbol_type = 1;
  818. symbol.importance = 3;
  819. } else {
  820. symbol.symbol_type = 1;
  821. symbol.importance = 1;
  822. }
  823. symbol.size = 0.012F + 0.004F * static_cast<float>(symbol.importance);
  824. layer.symbols.push_back(symbol);
  825. }
  826. const QString terrain = prov.value("terrain_type").toString().toLower();
  827. if (terrain.contains("mountain") || terrain.contains("alpine")) {
  828. const QJsonArray label_uv = prov.value("label_uv").toArray();
  829. if (label_uv.size() >= 2) {
  830. CartographicSymbolInstance mountain;
  831. mountain.position =
  832. QVector2D(static_cast<float>(label_uv.at(0).toDouble()),
  833. static_cast<float>(label_uv.at(1).toDouble()));
  834. mountain.symbol_type = 0;
  835. mountain.importance = 2;
  836. mountain.size = 0.018F;
  837. layer.symbols.push_back(mountain);
  838. }
  839. }
  840. }
  841. if (!layer.symbols.empty()) {
  842. build_symbol_geometry(layer);
  843. }
  844. }
  845. void build_symbol_geometry(CartographicSymbolLayer &layer) {
  846. std::vector<float> verts;
  847. verts.reserve(layer.symbols.size() * 20 * 4);
  848. layer.spans.clear();
  849. for (const auto &symbol : layer.symbols) {
  850. std::vector<QVector2D> outline;
  851. switch (symbol.symbol_type) {
  852. case 0:
  853. outline = CampaignMapRender::generate_mountain_icon(
  854. QVector2D(0.0F, 0.0F), 1.0F, symbol.importance);
  855. break;
  856. case 1:
  857. outline = CampaignMapRender::generate_city_marker(
  858. QVector2D(0.0F, 0.0F), 1.0F, symbol.importance);
  859. break;
  860. case 2:
  861. outline = CampaignMapRender::generate_anchor_icon(QVector2D(0.0F, 0.0F),
  862. 1.0F);
  863. break;
  864. default:
  865. outline = CampaignMapRender::generate_city_marker(QVector2D(0.0F, 0.0F),
  866. 1.0F, 1);
  867. break;
  868. }
  869. if (outline.size() < 2) {
  870. continue;
  871. }
  872. const int start = static_cast<int>(verts.size() / 4);
  873. const int count = static_cast<int>(outline.size());
  874. for (const auto &pt : outline) {
  875. float world_x = symbol.position.x() + pt.x() * symbol.size;
  876. float world_y = symbol.position.y() + pt.y() * symbol.size;
  877. verts.push_back(world_x);
  878. verts.push_back(world_y);
  879. verts.push_back(pt.x());
  880. verts.push_back(static_cast<float>(symbol.symbol_type));
  881. }
  882. layer.spans.push_back({start, count});
  883. }
  884. if (verts.empty() || layer.spans.empty()) {
  885. layer.ready = false;
  886. return;
  887. }
  888. if (layer.vao == 0) {
  889. glGenVertexArrays(1, &layer.vao);
  890. glGenBuffers(1, &layer.vbo);
  891. }
  892. glBindVertexArray(layer.vao);
  893. glBindBuffer(GL_ARRAY_BUFFER, layer.vbo);
  894. glBufferData(GL_ARRAY_BUFFER,
  895. static_cast<GLsizeiptr>(verts.size() * sizeof(float)),
  896. verts.data(), GL_STATIC_DRAW);
  897. glEnableVertexAttribArray(0);
  898. glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 4 * sizeof(float),
  899. reinterpret_cast<void *>(0));
  900. glEnableVertexAttribArray(1);
  901. glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 4 * sizeof(float),
  902. reinterpret_cast<void *>(2 * sizeof(float)));
  903. glBindVertexArray(0);
  904. layer.total_vertices = static_cast<int>(verts.size() / 4);
  905. layer.ready = true;
  906. }
  907. void draw_symbol_layer(const CartographicSymbolLayer &layer,
  908. const QMatrix4x4 &mvp, float z_offset) {
  909. if (!layer.ready || layer.vao == 0 || layer.spans.empty()) {
  910. return;
  911. }
  912. m_line_program.bind();
  913. m_line_program.setUniformValue("u_mvp", mvp);
  914. if (layer.show_shadow) {
  915. m_line_program.setUniformValue("u_z", z_offset);
  916. m_line_program.setUniformValue("u_color", layer.shadow_color);
  917. glBindVertexArray(layer.vao);
  918. for (const auto &span : layer.spans) {
  919. glDrawArrays(GL_LINE_STRIP, span.start, span.count);
  920. }
  921. glBindVertexArray(0);
  922. }
  923. m_line_program.setUniformValue("u_z", z_offset + 0.001F);
  924. m_line_program.setUniformValue("u_color", layer.fill_color);
  925. glBindVertexArray(layer.vao);
  926. for (const auto &span : layer.spans) {
  927. glDrawArrays(GL_LINE_STRIP, span.start, span.count);
  928. }
  929. glBindVertexArray(0);
  930. m_line_program.setUniformValue("u_z", z_offset + 0.002F);
  931. m_line_program.setUniformValue("u_color", layer.stroke_color);
  932. glBindVertexArray(layer.vao);
  933. for (const auto &span : layer.spans) {
  934. glDrawArrays(GL_LINE_STRIP, span.start, span.count);
  935. }
  936. glBindVertexArray(0);
  937. m_line_program.release();
  938. }
  939. void init_terrain_mesh(TerrainMesh &mesh, int resolution) {
  940. constexpr float k_height_scale = 1.0F;
  941. std::vector<float> vertices;
  942. HeightmapData heightmap = load_heightmap_data(
  943. QStringLiteral(":/assets/campaign_map/terrain_height.png"),
  944. QStringLiteral(":/assets/campaign_map/terrain_height.json"));
  945. if (heightmap.ready) {
  946. mesh.height_scale = k_height_scale;
  947. const int grid =
  948. qMax(resolution, qMax(heightmap.width, heightmap.height) / 4);
  949. if (grid > 1) {
  950. const float step = 1.0F / static_cast<float>(grid - 1);
  951. const float sample_dist =
  952. 1.0F / static_cast<float>(qMax(heightmap.width, heightmap.height));
  953. float land_max = 0.0F;
  954. for (float h : heightmap.samples) {
  955. if (h > land_max) {
  956. land_max = h;
  957. }
  958. }
  959. const float land_scale = (land_max > 1e-6F) ? (1.0F / land_max) : 1.0F;
  960. const float edge_margin = 0.03F;
  961. auto sample_height_raw = [&](float u, float v) -> float {
  962. const float cu = qBound(0.0F, u, 1.0F);
  963. const float cv = qBound(0.0F, v, 1.0F);
  964. const float x = cu * static_cast<float>(heightmap.width - 1);
  965. const float y =
  966. (1.0F - cv) * static_cast<float>(heightmap.height - 1);
  967. const int x0 = static_cast<int>(std::floor(x));
  968. const int y0 = static_cast<int>(std::floor(y));
  969. const int x1 = qMin(x0 + 1, heightmap.width - 1);
  970. const int y1 = qMin(y0 + 1, heightmap.height - 1);
  971. const float fx = x - static_cast<float>(x0);
  972. const float fy = y - static_cast<float>(y0);
  973. const float h00 =
  974. heightmap.samples[static_cast<size_t>(y0 * heightmap.width + x0)];
  975. const float h10 =
  976. heightmap.samples[static_cast<size_t>(y0 * heightmap.width + x1)];
  977. const float h01 =
  978. heightmap.samples[static_cast<size_t>(y1 * heightmap.width + x0)];
  979. const float h11 =
  980. heightmap.samples[static_cast<size_t>(y1 * heightmap.width + x1)];
  981. const float hx0 = h00 + (h10 - h00) * fx;
  982. const float hx1 = h01 + (h11 - h01) * fx;
  983. return hx0 + (hx1 - hx0) * fy;
  984. };
  985. auto sample_height = [&](float u, float v) -> float {
  986. const float h = sample_height_raw(u, v);
  987. float height = (h >= 0.0F) ? (h * land_scale) : 0.0F;
  988. const float edge_dist = qMin(qMin(u, 1.0F - u), qMin(v, 1.0F - v));
  989. if (edge_dist < edge_margin) {
  990. height *= qMax(0.0F, edge_dist / edge_margin);
  991. }
  992. return height;
  993. };
  994. auto sample_normal = [&](float u, float v) -> QVector3D {
  995. const float h_left = sample_height(u - sample_dist, v);
  996. const float h_right = sample_height(u + sample_dist, v);
  997. const float h_down = sample_height(u, v - sample_dist);
  998. const float h_up = sample_height(u, v + sample_dist);
  999. const float dx =
  1000. (h_right - h_left) / (2.0F * sample_dist) * mesh.height_scale;
  1001. const float dz =
  1002. (h_up - h_down) / (2.0F * sample_dist) * mesh.height_scale;
  1003. QVector3D normal(-dx, 1.0F, -dz);
  1004. normal.normalize();
  1005. return normal;
  1006. };
  1007. vertices.reserve(static_cast<size_t>(grid - 1) *
  1008. static_cast<size_t>(grid - 1) * 6 * 8);
  1009. auto add_vertex = [&](float u, float v, float h, const QVector3D &n) {
  1010. vertices.push_back(u);
  1011. vertices.push_back(v);
  1012. vertices.push_back(u);
  1013. vertices.push_back(v);
  1014. vertices.push_back(h);
  1015. vertices.push_back(n.x());
  1016. vertices.push_back(n.y());
  1017. vertices.push_back(n.z());
  1018. };
  1019. for (int y = 0; y < grid - 1; ++y) {
  1020. for (int x = 0; x < grid - 1; ++x) {
  1021. const float u0 = static_cast<float>(x) * step;
  1022. const float v0 = static_cast<float>(y) * step;
  1023. const float u1 = static_cast<float>(x + 1) * step;
  1024. const float v1 = static_cast<float>(y + 1) * step;
  1025. const float h00 = sample_height(u0, v0);
  1026. const float h10 = sample_height(u1, v0);
  1027. const float h01 = sample_height(u0, v1);
  1028. const float h11 = sample_height(u1, v1);
  1029. const QVector3D n00 = sample_normal(u0, v0);
  1030. const QVector3D n10 = sample_normal(u1, v0);
  1031. const QVector3D n01 = sample_normal(u0, v1);
  1032. const QVector3D n11 = sample_normal(u1, v1);
  1033. add_vertex(u0, v0, h00, n00);
  1034. add_vertex(u1, v0, h10, n10);
  1035. add_vertex(u0, v1, h01, n01);
  1036. add_vertex(u1, v0, h10, n10);
  1037. add_vertex(u1, v1, h11, n11);
  1038. add_vertex(u0, v1, h01, n01);
  1039. }
  1040. }
  1041. }
  1042. }
  1043. if (vertices.empty()) {
  1044. mesh.height_scale = k_height_scale;
  1045. vertices = CampaignMapRender::generate_terrain_mesh(resolution, 1.0F);
  1046. }
  1047. if (vertices.empty()) {
  1048. mesh.ready = false;
  1049. return;
  1050. }
  1051. if (mesh.vao == 0) {
  1052. glGenVertexArrays(1, &mesh.vao);
  1053. glGenBuffers(1, &mesh.vbo);
  1054. }
  1055. glBindVertexArray(mesh.vao);
  1056. glBindBuffer(GL_ARRAY_BUFFER, mesh.vbo);
  1057. glBufferData(GL_ARRAY_BUFFER,
  1058. static_cast<GLsizeiptr>(vertices.size() * sizeof(float)),
  1059. vertices.data(), GL_STATIC_DRAW);
  1060. const int stride = 8 * sizeof(float);
  1061. glEnableVertexAttribArray(0);
  1062. glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, stride,
  1063. reinterpret_cast<void *>(0));
  1064. glEnableVertexAttribArray(1);
  1065. glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, stride,
  1066. reinterpret_cast<void *>(2 * sizeof(float)));
  1067. glEnableVertexAttribArray(2);
  1068. glVertexAttribPointer(2, 1, GL_FLOAT, GL_FALSE, stride,
  1069. reinterpret_cast<void *>(4 * sizeof(float)));
  1070. glEnableVertexAttribArray(3);
  1071. glVertexAttribPointer(3, 3, GL_FLOAT, GL_FALSE, stride,
  1072. reinterpret_cast<void *>(5 * sizeof(float)));
  1073. glBindVertexArray(0);
  1074. mesh.vertex_count = static_cast<int>(vertices.size() / 8);
  1075. mesh.ready = true;
  1076. }
  1077. void init_hillshade_layer(HillshadeLayer &layer, int width, int height) {
  1078. CampaignMapRender::HillshadeConfig config;
  1079. config.light_direction = layer.light_direction;
  1080. config.ambient = layer.ambient;
  1081. config.intensity = layer.intensity;
  1082. std::vector<unsigned char> pixels =
  1083. CampaignMapRender::generate_hillshade_texture(width, height, config);
  1084. if (pixels.empty()) {
  1085. layer.ready = false;
  1086. return;
  1087. }
  1088. if (layer.texture_id == 0) {
  1089. glGenTextures(1, &layer.texture_id);
  1090. }
  1091. glBindTexture(GL_TEXTURE_2D, layer.texture_id);
  1092. glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA,
  1093. GL_UNSIGNED_BYTE, pixels.data());
  1094. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
  1095. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
  1096. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
  1097. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
  1098. glBindTexture(GL_TEXTURE_2D, 0);
  1099. layer.width = width;
  1100. layer.height = height;
  1101. layer.ready = true;
  1102. }
  1103. auto load_heightmap_data(const QString &image_path,
  1104. const QString &meta_path) -> HeightmapData {
  1105. HeightmapData data;
  1106. const QString resolved_image =
  1107. Utils::Resources::resolveResourcePath(image_path);
  1108. QImage image(resolved_image);
  1109. if (image.isNull()) {
  1110. qWarning() << "CampaignMapRenderer: Failed to load heightmap"
  1111. << resolved_image;
  1112. return data;
  1113. }
  1114. if (image.format() != QImage::Format_Grayscale16) {
  1115. image = image.convertToFormat(QImage::Format_Grayscale16);
  1116. }
  1117. if (image.isNull()) {
  1118. qWarning() << "CampaignMapRenderer: Heightmap conversion failed"
  1119. << resolved_image;
  1120. return data;
  1121. }
  1122. float min_m = -6000.0F;
  1123. float max_m = 4000.0F;
  1124. const QString resolved_meta =
  1125. Utils::Resources::resolveResourcePath(meta_path);
  1126. QFile meta_file(resolved_meta);
  1127. if (meta_file.open(QIODevice::ReadOnly)) {
  1128. const QJsonDocument doc = QJsonDocument::fromJson(meta_file.readAll());
  1129. if (doc.isObject()) {
  1130. const QJsonObject obj = doc.object();
  1131. if (obj.contains("min_m")) {
  1132. min_m = static_cast<float>(obj.value("min_m").toDouble());
  1133. }
  1134. if (obj.contains("max_m")) {
  1135. max_m = static_cast<float>(obj.value("max_m").toDouble());
  1136. }
  1137. }
  1138. }
  1139. if (!(min_m < max_m)) {
  1140. qWarning() << "CampaignMapRenderer: Heightmap metadata invalid"
  1141. << resolved_meta;
  1142. return data;
  1143. }
  1144. const int width = image.width();
  1145. const int height = image.height();
  1146. if (width <= 1 || height <= 1) {
  1147. qWarning() << "CampaignMapRenderer: Heightmap dimensions invalid" << width
  1148. << height;
  1149. return data;
  1150. }
  1151. const float range = max_m - min_m;
  1152. const float max_abs = qMax(std::abs(min_m), std::abs(max_m));
  1153. if (max_abs <= 0.0F) {
  1154. return data;
  1155. }
  1156. data.samples.resize(static_cast<size_t>(width * height));
  1157. for (int y = 0; y < height; ++y) {
  1158. const auto *row =
  1159. reinterpret_cast<const quint16 *>(image.constScanLine(y));
  1160. for (int x = 0; x < width; ++x) {
  1161. const float norm = static_cast<float>(row[x]) / 65535.0F;
  1162. const float height_m = min_m + norm * range;
  1163. data.samples[static_cast<size_t>(y * width + x)] = height_m / max_abs;
  1164. }
  1165. }
  1166. data.width = width;
  1167. data.height = height;
  1168. data.min_m = min_m;
  1169. data.max_m = max_m;
  1170. data.ready = true;
  1171. return data;
  1172. }
  1173. void init_label_layer(LabelLayer &layer, const QString &resource_path) {
  1174. const QString path = Utils::Resources::resolveResourcePath(resource_path);
  1175. QFile file(path);
  1176. if (!file.open(QIODevice::ReadOnly)) {
  1177. qWarning() << "CampaignMapRenderer: Failed to open labels source" << path;
  1178. return;
  1179. }
  1180. const QJsonDocument doc = QJsonDocument::fromJson(file.readAll());
  1181. if (!doc.isObject()) {
  1182. qWarning() << "CampaignMapRenderer: Labels JSON invalid" << path;
  1183. return;
  1184. }
  1185. const QJsonArray provinces = doc.object().value("provinces").toArray();
  1186. for (const auto &prov_val : provinces) {
  1187. const QJsonObject prov = prov_val.toObject();
  1188. const QString name = prov.value("name").toString();
  1189. const QJsonArray label_uv = prov.value("label_uv").toArray();
  1190. if (name.isEmpty() || label_uv.size() < 2) {
  1191. continue;
  1192. }
  1193. ProvinceLabel label;
  1194. label.text = name;
  1195. label.position = QVector2D(static_cast<float>(label_uv.at(0).toDouble()),
  1196. static_cast<float>(label_uv.at(1).toDouble()));
  1197. const QString id = prov.value("id").toString().toLower();
  1198. if (id.contains("core") || id.contains("capital")) {
  1199. label.importance = 3;
  1200. } else if (id.contains("major") ||
  1201. prov.value("cities").toArray().size() > 2) {
  1202. label.importance = 2;
  1203. } else {
  1204. label.importance = 1;
  1205. }
  1206. label.is_sea = id.contains("sea") || id.contains("mare") ||
  1207. id.contains("mediterranean");
  1208. layer.labels.push_back(label);
  1209. }
  1210. build_label_geometry(layer);
  1211. }
  1212. void build_label_geometry(LabelLayer &layer) {
  1213. std::vector<float> verts;
  1214. for (const auto &label : layer.labels) {
  1215. CampaignMapRender::LabelStyle style;
  1216. if (label.is_sea) {
  1217. style = CampaignMapRender::LabelStyles::sea_label();
  1218. } else if (label.importance >= 3) {
  1219. style = CampaignMapRender::LabelStyles::region_label();
  1220. } else if (label.importance >= 2) {
  1221. style = CampaignMapRender::LabelStyles::province_label();
  1222. } else {
  1223. style = CampaignMapRender::LabelStyles::city_label();
  1224. }
  1225. std::vector<float> label_verts = CampaignMapRender::generate_label_quads(
  1226. label.position, label.text.toStdString(), style);
  1227. verts.insert(verts.end(), label_verts.begin(), label_verts.end());
  1228. }
  1229. if (verts.empty()) {
  1230. layer.ready = false;
  1231. return;
  1232. }
  1233. if (layer.vao == 0) {
  1234. glGenVertexArrays(1, &layer.vao);
  1235. glGenBuffers(1, &layer.vbo);
  1236. }
  1237. glBindVertexArray(layer.vao);
  1238. glBindBuffer(GL_ARRAY_BUFFER, layer.vbo);
  1239. glBufferData(GL_ARRAY_BUFFER,
  1240. static_cast<GLsizeiptr>(verts.size() * sizeof(float)),
  1241. verts.data(), GL_STATIC_DRAW);
  1242. const int stride = 6 * sizeof(float);
  1243. glEnableVertexAttribArray(0);
  1244. glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, stride,
  1245. reinterpret_cast<void *>(0));
  1246. glEnableVertexAttribArray(1);
  1247. glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, stride,
  1248. reinterpret_cast<void *>(2 * sizeof(float)));
  1249. glEnableVertexAttribArray(2);
  1250. glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, stride,
  1251. reinterpret_cast<void *>(4 * sizeof(float)));
  1252. glBindVertexArray(0);
  1253. layer.total_vertices = static_cast<int>(verts.size() / 6);
  1254. layer.ready = true;
  1255. }
  1256. void draw_label_layer(const LabelLayer &layer, const QMatrix4x4 &mvp,
  1257. float z_offset) {
  1258. if (!layer.ready || layer.vao == 0 || layer.total_vertices <= 0) {
  1259. return;
  1260. }
  1261. if (layer.font_texture == 0) {
  1262. return;
  1263. }
  1264. m_line_program.bind();
  1265. m_line_program.setUniformValue("u_mvp", mvp);
  1266. m_line_program.setUniformValue("u_z", z_offset);
  1267. m_line_program.setUniformValue("u_color",
  1268. QVector4D(0.25F, 0.20F, 0.15F, 0.85F));
  1269. glBindVertexArray(layer.vao);
  1270. glDrawArrays(GL_TRIANGLES, 0, layer.total_vertices);
  1271. glBindVertexArray(0);
  1272. m_line_program.release();
  1273. }
  1274. auto load_texture(const QString &resource_path) -> QOpenGLTexture * {
  1275. const QString path = Utils::Resources::resolveResourcePath(resource_path);
  1276. QImage image(path);
  1277. if (image.isNull()) {
  1278. qWarning() << "CampaignMapRenderer: Failed to load texture" << path;
  1279. return nullptr;
  1280. }
  1281. QImage rgba = image.convertToFormat(QImage::Format_RGBA8888);
  1282. auto *texture = new QOpenGLTexture(rgba);
  1283. texture->setWrapMode(QOpenGLTexture::ClampToEdge);
  1284. texture->setMinMagFilters(QOpenGLTexture::Linear, QOpenGLTexture::Linear);
  1285. return texture;
  1286. }
  1287. void compute_mvp(QMatrix4x4 &out_mvp) const {
  1288. out_mvp = build_mvp_matrix(
  1289. static_cast<float>(m_size.width()), static_cast<float>(m_size.height()),
  1290. m_orbit_yaw, m_orbit_pitch, m_orbit_distance, m_pan_u, m_pan_v);
  1291. }
  1292. void draw_textured_layer(QOpenGLTexture *texture, GLuint vao,
  1293. int vertex_count, const QMatrix4x4 &mvp, float alpha,
  1294. float z_offset) {
  1295. if (texture == nullptr || vao == 0 || vertex_count <= 0) {
  1296. return;
  1297. }
  1298. m_texture_program.bind();
  1299. m_texture_program.setUniformValue("u_mvp", mvp);
  1300. m_texture_program.setUniformValue("u_z", z_offset);
  1301. m_texture_program.setUniformValue("u_alpha", alpha);
  1302. m_texture_program.setUniformValue("u_tex", 0);
  1303. glActiveTexture(GL_TEXTURE0);
  1304. texture->bind();
  1305. glBindVertexArray(vao);
  1306. glDrawArrays(GL_TRIANGLES, 0, vertex_count);
  1307. glBindVertexArray(0);
  1308. texture->release();
  1309. m_texture_program.release();
  1310. }
  1311. void draw_terrain_layer(const TerrainMesh &mesh, const QMatrix4x4 &mvp) {
  1312. if (!mesh.ready || mesh.vao == 0 || mesh.vertex_count <= 0 ||
  1313. m_base_texture == nullptr || !m_terrain_program.isLinked()) {
  1314. return;
  1315. }
  1316. m_terrain_program.bind();
  1317. m_terrain_program.setUniformValue("u_mvp", mvp);
  1318. m_terrain_program.setUniformValue(
  1319. "u_height_scale", mesh.height_scale * m_terrain_height_scale);
  1320. m_terrain_program.setUniformValue("u_z_base", mesh.z_base);
  1321. m_terrain_program.setUniformValue("u_light_direction",
  1322. QVector3D(0.35F, 0.85F, 0.40F));
  1323. m_terrain_program.setUniformValue("u_ambient_strength", 0.45F);
  1324. m_terrain_program.setUniformValue("u_hillshade_strength", 0.35F);
  1325. m_terrain_program.setUniformValue("u_ao_strength", 0.25F);
  1326. m_terrain_program.setUniformValue("u_use_hillshade", true);
  1327. m_terrain_program.setUniformValue("u_use_parchment", false);
  1328. m_terrain_program.setUniformValue("u_use_lighting", true);
  1329. m_terrain_program.setUniformValue("u_water_deep_color",
  1330. QVector3D(0.10F, 0.22F, 0.30F));
  1331. m_terrain_program.setUniformValue("u_water_shallow_color",
  1332. QVector3D(0.26F, 0.42F, 0.52F));
  1333. m_terrain_program.setUniformValue("u_lowland_tint",
  1334. QVector3D(0.96F, 0.92F, 0.86F));
  1335. m_terrain_program.setUniformValue("u_highland_tint",
  1336. QVector3D(0.82F, 0.74F, 0.64F));
  1337. m_terrain_program.setUniformValue("u_mountain_tint",
  1338. QVector3D(0.70F, 0.62F, 0.55F));
  1339. m_terrain_program.setUniformValue("u_elevation_scale", 1.2F);
  1340. m_terrain_program.setUniformValue("u_base_texture", 0);
  1341. glActiveTexture(GL_TEXTURE0);
  1342. m_base_texture->bind();
  1343. glBindVertexArray(mesh.vao);
  1344. glDrawArrays(GL_TRIANGLES, 0, mesh.vertex_count);
  1345. glBindVertexArray(0);
  1346. m_base_texture->release();
  1347. m_terrain_program.release();
  1348. }
  1349. void draw_line_layer(const LineLayer &layer, const QMatrix4x4 &mvp,
  1350. float z_offset) {
  1351. if (!layer.ready || layer.vao == 0 || layer.spans.empty()) {
  1352. return;
  1353. }
  1354. m_line_program.bind();
  1355. m_line_program.setUniformValue("u_mvp", mvp);
  1356. if (layer.double_stroke) {
  1357. glLineWidth(layer.width * layer.outer_width_ratio);
  1358. m_line_program.setUniformValue("u_z", z_offset);
  1359. m_line_program.setUniformValue("u_color", layer.outer_color);
  1360. glBindVertexArray(layer.vao);
  1361. for (const auto &span : layer.spans) {
  1362. glDrawArrays(GL_LINE_STRIP, span.start, span.count);
  1363. }
  1364. glLineWidth(layer.width * layer.inner_width_ratio);
  1365. m_line_program.setUniformValue("u_z", z_offset + 0.001F);
  1366. m_line_program.setUniformValue("u_color", layer.inner_color);
  1367. for (const auto &span : layer.spans) {
  1368. glDrawArrays(GL_LINE_STRIP, span.start, span.count);
  1369. }
  1370. glBindVertexArray(0);
  1371. } else {
  1372. glLineWidth(layer.width);
  1373. m_line_program.setUniformValue("u_z", z_offset);
  1374. m_line_program.setUniformValue("u_color", layer.color);
  1375. glBindVertexArray(layer.vao);
  1376. for (const auto &span : layer.spans) {
  1377. glDrawArrays(GL_LINE_STRIP, span.start, span.count);
  1378. }
  1379. glBindVertexArray(0);
  1380. }
  1381. m_line_program.release();
  1382. }
  1383. static auto safe_normalized(const QVector2D &v) -> QVector2D {
  1384. const float len = v.length();
  1385. if (len < 1e-5F) {
  1386. return QVector2D(0.0F, 0.0F);
  1387. }
  1388. return v / len;
  1389. }
  1390. static auto perp(const QVector2D &v) -> QVector2D {
  1391. return QVector2D(-v.y(), v.x());
  1392. }
  1393. void build_path_strip(const std::vector<QVector2D> &input, float half_width,
  1394. std::vector<QVector2D> &out) const {
  1395. out.clear();
  1396. if (input.size() < 2 || half_width <= 0.0F) {
  1397. return;
  1398. }
  1399. std::vector<QVector2D> points;
  1400. points.reserve(input.size());
  1401. for (const auto &pt : input) {
  1402. if (points.empty()) {
  1403. points.push_back(pt);
  1404. continue;
  1405. }
  1406. const QVector2D delta = pt - points.back();
  1407. if (QVector2D::dotProduct(delta, delta) > 1e-10F) {
  1408. points.push_back(pt);
  1409. }
  1410. }
  1411. if (points.size() < 2) {
  1412. return;
  1413. }
  1414. out.reserve(points.size() * 2);
  1415. for (size_t i = 0; i < points.size(); ++i) {
  1416. QVector2D offset;
  1417. if (i == 0) {
  1418. const QVector2D dir = safe_normalized(points[1] - points[0]);
  1419. offset = perp(dir) * half_width;
  1420. } else if (i + 1 == points.size()) {
  1421. const QVector2D dir = safe_normalized(points[i] - points[i - 1]);
  1422. offset = perp(dir) * half_width;
  1423. } else {
  1424. QVector2D dir0 = safe_normalized(points[i] - points[i - 1]);
  1425. QVector2D dir1 = safe_normalized(points[i + 1] - points[i]);
  1426. if (dir0.isNull()) {
  1427. dir0 = dir1;
  1428. }
  1429. if (dir1.isNull()) {
  1430. dir1 = dir0;
  1431. }
  1432. const QVector2D n0 = perp(dir0);
  1433. const QVector2D n1 = perp(dir1);
  1434. QVector2D miter = safe_normalized(n0 + n1);
  1435. if (miter.isNull()) {
  1436. miter = n1;
  1437. }
  1438. float denom = QVector2D::dotProduct(miter, n1);
  1439. if (std::abs(denom) < 0.2F) {
  1440. denom = (denom >= 0.0F) ? 0.2F : -0.2F;
  1441. }
  1442. float miter_len = half_width / denom;
  1443. const float max_miter = half_width * 3.0F;
  1444. if (std::abs(miter_len) > max_miter) {
  1445. miter_len = (miter_len < 0.0F) ? -max_miter : max_miter;
  1446. }
  1447. offset = miter * miter_len;
  1448. }
  1449. out.push_back(points[i] + offset);
  1450. out.push_back(points[i] - offset);
  1451. }
  1452. }
  1453. void update_path_mesh(StrokeMesh &mesh, const std::vector<QVector2D> &points,
  1454. float width) {
  1455. if (points.size() < 2) {
  1456. mesh.ready = false;
  1457. mesh.vertex_count = 0;
  1458. return;
  1459. }
  1460. if (mesh.ready && qFuzzyCompare(mesh.width, width)) {
  1461. return;
  1462. }
  1463. CampaignMapRender::StrokeMeshConfig config;
  1464. config.width = width;
  1465. config.start_cap = CampaignMapRender::CapStyle::Round;
  1466. config.end_cap = CampaignMapRender::CapStyle::Round;
  1467. config.join_style = CampaignMapRender::JoinStyle::Miter;
  1468. config.cap_segments = 6;
  1469. config.miter_params.max_miter_ratio = 3.0F;
  1470. std::vector<QVector2D> strip =
  1471. CampaignMapRender::build_stroke_mesh(points, config);
  1472. if (strip.size() < 4) {
  1473. mesh.ready = false;
  1474. mesh.vertex_count = 0;
  1475. return;
  1476. }
  1477. std::vector<float> verts;
  1478. verts.reserve(strip.size() * 2);
  1479. for (const auto &v : strip) {
  1480. verts.push_back(v.x());
  1481. verts.push_back(v.y());
  1482. }
  1483. if (mesh.vao == 0) {
  1484. glGenVertexArrays(1, &mesh.vao);
  1485. glGenBuffers(1, &mesh.vbo);
  1486. }
  1487. glBindVertexArray(mesh.vao);
  1488. glBindBuffer(GL_ARRAY_BUFFER, mesh.vbo);
  1489. glBufferData(GL_ARRAY_BUFFER,
  1490. static_cast<GLsizeiptr>(verts.size() * sizeof(float)),
  1491. verts.data(), GL_DYNAMIC_DRAW);
  1492. glEnableVertexAttribArray(0);
  1493. glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 2 * sizeof(float),
  1494. reinterpret_cast<void *>(0));
  1495. glBindVertexArray(0);
  1496. mesh.vertex_count = static_cast<int>(strip.size());
  1497. mesh.width = width;
  1498. mesh.ready = true;
  1499. }
  1500. auto uv_width_for_pixels(float px) const -> float {
  1501. const float viewport_h = qMax(1.0F, static_cast<float>(m_size.height()));
  1502. const float fov_rad = qDegreesToRadians(45.0F * 0.5F);
  1503. const float view_h = 2.0F * m_orbit_distance * std::tan(fov_rad);
  1504. const float uv_width = px * (view_h / viewport_h);
  1505. return qMax(0.0005F, uv_width);
  1506. }
  1507. void draw_path_mesh(const StrokeMesh &mesh) {
  1508. if (!mesh.ready || mesh.vao == 0 || mesh.vertex_count <= 0) {
  1509. return;
  1510. }
  1511. glBindVertexArray(mesh.vao);
  1512. glDrawArrays(GL_TRIANGLE_STRIP, 0, mesh.vertex_count);
  1513. glBindVertexArray(0);
  1514. }
  1515. void draw_progressive_path_layers(PathLayer &layer, const QMatrix4x4 &mvp,
  1516. float z_offset) {
  1517. if (!layer.ready || layer.lines.empty()) {
  1518. return;
  1519. }
  1520. const int max_mission =
  1521. qBound(0, m_current_mission, static_cast<int>(layer.lines.size()) - 1);
  1522. m_line_program.bind();
  1523. m_line_program.setUniformValue("u_mvp", mvp);
  1524. for (int i = 0; i <= max_mission; ++i) {
  1525. if (i >= static_cast<int>(layer.lines.size())) {
  1526. break;
  1527. }
  1528. auto &line = layer.lines[static_cast<size_t>(i)];
  1529. const int age = max_mission - i;
  1530. auto passes =
  1531. CampaignMapRender::CartographicStyles::get_inked_route_passes(1.0F,
  1532. age);
  1533. if (!passes.empty()) {
  1534. const auto &border_pass = passes[0];
  1535. float border_width_px = 6.0F * border_pass.width_multiplier;
  1536. if (i != max_mission) {
  1537. border_width_px *= 0.85F;
  1538. }
  1539. m_line_program.setUniformValue("u_z", z_offset + border_pass.z_offset);
  1540. update_path_mesh(line.border, line.points,
  1541. uv_width_for_pixels(border_width_px));
  1542. m_line_program.setUniformValue("u_color", border_pass.color);
  1543. draw_path_mesh(line.border);
  1544. }
  1545. }
  1546. for (int i = 0; i <= max_mission; ++i) {
  1547. if (i >= static_cast<int>(layer.lines.size())) {
  1548. break;
  1549. }
  1550. auto &line = layer.lines[static_cast<size_t>(i)];
  1551. const int age = max_mission - i;
  1552. auto passes =
  1553. CampaignMapRender::CartographicStyles::get_inked_route_passes(1.0F,
  1554. age);
  1555. if (passes.size() > 2) {
  1556. const auto &highlight_pass = passes[2];
  1557. float highlight_width_px = 4.0F * highlight_pass.width_multiplier;
  1558. if (i != max_mission) {
  1559. highlight_width_px *= 0.8F;
  1560. }
  1561. m_line_program.setUniformValue("u_z",
  1562. z_offset + highlight_pass.z_offset);
  1563. update_path_mesh(line.highlight, line.points,
  1564. uv_width_for_pixels(highlight_width_px));
  1565. m_line_program.setUniformValue("u_color", highlight_pass.color);
  1566. draw_path_mesh(line.highlight);
  1567. }
  1568. }
  1569. for (int i = 0; i <= max_mission; ++i) {
  1570. if (i >= static_cast<int>(layer.lines.size())) {
  1571. break;
  1572. }
  1573. auto &line = layer.lines[static_cast<size_t>(i)];
  1574. const int age = max_mission - i;
  1575. auto passes =
  1576. CampaignMapRender::CartographicStyles::get_inked_route_passes(1.0F,
  1577. age);
  1578. if (passes.size() > 3) {
  1579. const auto &core_pass = passes[3];
  1580. float core_width_px = 3.0F * core_pass.width_multiplier;
  1581. if (i != max_mission) {
  1582. core_width_px *= 0.75F;
  1583. }
  1584. m_line_program.setUniformValue("u_z", z_offset + core_pass.z_offset);
  1585. update_path_mesh(line.core, line.points,
  1586. uv_width_for_pixels(core_width_px));
  1587. m_line_program.setUniformValue("u_color", core_pass.color);
  1588. draw_path_mesh(line.core);
  1589. }
  1590. }
  1591. m_line_program.release();
  1592. }
  1593. void update_mission_badge_position(MissionBadge &badge,
  1594. const PathLayer &path_layer,
  1595. int mission_index) {
  1596. if (!path_layer.ready || path_layer.lines.empty()) {
  1597. badge.ready = false;
  1598. return;
  1599. }
  1600. const int clamped_mission =
  1601. qBound(0, mission_index, static_cast<int>(path_layer.lines.size()) - 1);
  1602. const auto &line = path_layer.lines[static_cast<size_t>(clamped_mission)];
  1603. if (line.points.empty()) {
  1604. badge.ready = false;
  1605. return;
  1606. }
  1607. badge.position = line.points.back();
  1608. badge.ready = true;
  1609. }
  1610. void build_badge_geometry(MissionBadge &badge) {
  1611. if (!badge.ready) {
  1612. return;
  1613. }
  1614. std::vector<QVector2D> outline = CampaignMapRender::generate_shield_badge(
  1615. QVector2D(0.0F, 0.0F), 1.0F, 16);
  1616. if (outline.size() < 3) {
  1617. badge.ready = false;
  1618. return;
  1619. }
  1620. std::vector<float> verts;
  1621. verts.reserve((outline.size() + 1) * 4);
  1622. verts.push_back(badge.position.x());
  1623. verts.push_back(badge.position.y());
  1624. verts.push_back(0.0F);
  1625. verts.push_back(0.0F);
  1626. for (const auto &pt : outline) {
  1627. verts.push_back(badge.position.x() + pt.x() * badge.size);
  1628. verts.push_back(badge.position.y() + pt.y() * badge.size);
  1629. verts.push_back(pt.x());
  1630. verts.push_back(pt.y());
  1631. }
  1632. if (badge.vao == 0) {
  1633. glGenVertexArrays(1, &badge.vao);
  1634. glGenBuffers(1, &badge.vbo);
  1635. }
  1636. glBindVertexArray(badge.vao);
  1637. glBindBuffer(GL_ARRAY_BUFFER, badge.vbo);
  1638. glBufferData(GL_ARRAY_BUFFER,
  1639. static_cast<GLsizeiptr>(verts.size() * sizeof(float)),
  1640. verts.data(), GL_DYNAMIC_DRAW);
  1641. glEnableVertexAttribArray(0);
  1642. glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 4 * sizeof(float),
  1643. reinterpret_cast<void *>(0));
  1644. glEnableVertexAttribArray(1);
  1645. glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 4 * sizeof(float),
  1646. reinterpret_cast<void *>(2 * sizeof(float)));
  1647. glBindVertexArray(0);
  1648. badge.vertex_count = static_cast<int>(outline.size() + 1);
  1649. }
  1650. void draw_mission_badge(MissionBadge &badge, const QMatrix4x4 &mvp,
  1651. float z_offset) {
  1652. if (!badge.ready) {
  1653. return;
  1654. }
  1655. update_mission_badge_position(badge, m_path_layer, m_current_mission);
  1656. build_badge_geometry(badge);
  1657. if (badge.vao == 0 || badge.vertex_count < 3) {
  1658. return;
  1659. }
  1660. m_line_program.bind();
  1661. m_line_program.setUniformValue("u_mvp", mvp);
  1662. if (badge.show_shadow) {
  1663. m_line_program.setUniformValue("u_z", z_offset);
  1664. m_line_program.setUniformValue("u_color", badge.shadow_color);
  1665. glBindVertexArray(badge.vao);
  1666. glDrawArrays(GL_TRIANGLE_FAN, 0, badge.vertex_count);
  1667. glBindVertexArray(0);
  1668. }
  1669. m_line_program.setUniformValue("u_z", z_offset + 0.001F);
  1670. m_line_program.setUniformValue("u_color", badge.border_color);
  1671. glBindVertexArray(badge.vao);
  1672. glDrawArrays(GL_TRIANGLE_FAN, 0, badge.vertex_count);
  1673. glBindVertexArray(0);
  1674. m_line_program.setUniformValue("u_z", z_offset + 0.002F);
  1675. m_line_program.setUniformValue("u_color", badge.primary_color);
  1676. glBindVertexArray(badge.vao);
  1677. glDrawArrays(GL_TRIANGLE_FAN, 0, badge.vertex_count);
  1678. glBindVertexArray(0);
  1679. m_line_program.release();
  1680. }
  1681. void apply_province_overrides(
  1682. const QHash<QString, CampaignMapView::ProvinceVisual> &overrides) {
  1683. if (!m_province_layer.ready || m_province_layer.spans.empty()) {
  1684. return;
  1685. }
  1686. for (auto &span : m_province_layer.spans) {
  1687. const auto it = overrides.find(span.id);
  1688. if (it != overrides.end() && it->has_color) {
  1689. span.color = it->color;
  1690. } else {
  1691. span.color = span.base_color;
  1692. }
  1693. }
  1694. }
  1695. void draw_province_layer(const ProvinceLayer &layer, const QMatrix4x4 &mvp,
  1696. float z_offset) {
  1697. if (!layer.ready || layer.vao == 0 || layer.spans.empty()) {
  1698. return;
  1699. }
  1700. m_line_program.bind();
  1701. m_line_program.setUniformValue("u_mvp", mvp);
  1702. m_line_program.setUniformValue("u_z", z_offset);
  1703. glBindVertexArray(layer.vao);
  1704. for (const auto &span : layer.spans) {
  1705. if (span.color.w() <= 0.0F) {
  1706. continue;
  1707. }
  1708. QVector4D color = span.color;
  1709. const float parchment_tint = 0.92F;
  1710. color.setX(color.x() * parchment_tint);
  1711. color.setY(color.y() * parchment_tint);
  1712. color.setZ(color.z() * parchment_tint * 0.98F);
  1713. if (m_terrain_mesh.ready && m_terrain_height_scale > 0.01F) {
  1714. float fade = 1.0F / (1.0F + 3.0F * m_terrain_height_scale);
  1715. color.setW(color.w() * fade);
  1716. }
  1717. if (!m_hover_province_id.isEmpty() && span.id == m_hover_province_id) {
  1718. qint64 elapsed =
  1719. QDateTime::currentMSecsSinceEpoch() - m_hover_start_time;
  1720. float pulse_cycle = 1200.0F;
  1721. float pulse =
  1722. 0.5F + 0.5F * std::sin(elapsed * 2.0F * M_PI / pulse_cycle);
  1723. float brightness_boost = 0.3F + 0.15F * pulse;
  1724. color = QVector4D(qMin(1.0F, color.x() + brightness_boost),
  1725. qMin(1.0F, color.y() + brightness_boost),
  1726. qMin(1.0F, color.z() + brightness_boost),
  1727. qMin(1.0F, color.w() + 0.2F));
  1728. }
  1729. m_line_program.setUniformValue("u_color", color);
  1730. glDrawArrays(GL_TRIANGLES, span.start, span.count);
  1731. }
  1732. glBindVertexArray(0);
  1733. m_line_program.release();
  1734. }
  1735. void cleanup() {
  1736. if (QOpenGLContext::currentContext() == nullptr) {
  1737. return;
  1738. }
  1739. if (m_quad_vbo != 0) {
  1740. glDeleteBuffers(1, &m_quad_vbo);
  1741. m_quad_vbo = 0;
  1742. }
  1743. if (m_quad_vao != 0) {
  1744. glDeleteVertexArrays(1, &m_quad_vao);
  1745. m_quad_vao = 0;
  1746. }
  1747. if (m_land_vbo != 0) {
  1748. glDeleteBuffers(1, &m_land_vbo);
  1749. m_land_vbo = 0;
  1750. }
  1751. if (m_land_vao != 0) {
  1752. glDeleteVertexArrays(1, &m_land_vao);
  1753. m_land_vao = 0;
  1754. }
  1755. if (m_coast_layer.vbo != 0) {
  1756. glDeleteBuffers(1, &m_coast_layer.vbo);
  1757. m_coast_layer.vbo = 0;
  1758. }
  1759. if (m_coast_layer.vao != 0) {
  1760. glDeleteVertexArrays(1, &m_coast_layer.vao);
  1761. m_coast_layer.vao = 0;
  1762. }
  1763. if (m_river_layer.vbo != 0) {
  1764. glDeleteBuffers(1, &m_river_layer.vbo);
  1765. m_river_layer.vbo = 0;
  1766. }
  1767. if (m_river_layer.vao != 0) {
  1768. glDeleteVertexArrays(1, &m_river_layer.vao);
  1769. m_river_layer.vao = 0;
  1770. }
  1771. for (auto &line : m_path_layer.lines) {
  1772. if (line.border.vbo != 0) {
  1773. glDeleteBuffers(1, &line.border.vbo);
  1774. line.border.vbo = 0;
  1775. }
  1776. if (line.border.vao != 0) {
  1777. glDeleteVertexArrays(1, &line.border.vao);
  1778. line.border.vao = 0;
  1779. }
  1780. if (line.highlight.vbo != 0) {
  1781. glDeleteBuffers(1, &line.highlight.vbo);
  1782. line.highlight.vbo = 0;
  1783. }
  1784. if (line.highlight.vao != 0) {
  1785. glDeleteVertexArrays(1, &line.highlight.vao);
  1786. line.highlight.vao = 0;
  1787. }
  1788. if (line.core.vbo != 0) {
  1789. glDeleteBuffers(1, &line.core.vbo);
  1790. line.core.vbo = 0;
  1791. }
  1792. if (line.core.vao != 0) {
  1793. glDeleteVertexArrays(1, &line.core.vao);
  1794. line.core.vao = 0;
  1795. }
  1796. }
  1797. m_path_layer.lines.clear();
  1798. if (m_province_border_layer.vbo != 0) {
  1799. glDeleteBuffers(1, &m_province_border_layer.vbo);
  1800. m_province_border_layer.vbo = 0;
  1801. }
  1802. if (m_province_border_layer.vao != 0) {
  1803. glDeleteVertexArrays(1, &m_province_border_layer.vao);
  1804. m_province_border_layer.vao = 0;
  1805. }
  1806. if (m_province_layer.vbo != 0) {
  1807. glDeleteBuffers(1, &m_province_layer.vbo);
  1808. m_province_layer.vbo = 0;
  1809. }
  1810. if (m_province_layer.vao != 0) {
  1811. glDeleteVertexArrays(1, &m_province_layer.vao);
  1812. m_province_layer.vao = 0;
  1813. }
  1814. if (m_mission_badge.vbo != 0) {
  1815. glDeleteBuffers(1, &m_mission_badge.vbo);
  1816. m_mission_badge.vbo = 0;
  1817. }
  1818. if (m_mission_badge.vao != 0) {
  1819. glDeleteVertexArrays(1, &m_mission_badge.vao);
  1820. m_mission_badge.vao = 0;
  1821. }
  1822. m_mission_badge.ready = false;
  1823. if (m_symbol_layer.vbo != 0) {
  1824. glDeleteBuffers(1, &m_symbol_layer.vbo);
  1825. m_symbol_layer.vbo = 0;
  1826. }
  1827. if (m_symbol_layer.vao != 0) {
  1828. glDeleteVertexArrays(1, &m_symbol_layer.vao);
  1829. m_symbol_layer.vao = 0;
  1830. }
  1831. m_symbol_layer.symbols.clear();
  1832. m_symbol_layer.ready = false;
  1833. if (m_terrain_mesh.vbo != 0) {
  1834. glDeleteBuffers(1, &m_terrain_mesh.vbo);
  1835. m_terrain_mesh.vbo = 0;
  1836. }
  1837. if (m_terrain_mesh.vao != 0) {
  1838. glDeleteVertexArrays(1, &m_terrain_mesh.vao);
  1839. m_terrain_mesh.vao = 0;
  1840. }
  1841. m_terrain_mesh.ready = false;
  1842. if (m_hillshade.texture_id != 0) {
  1843. glDeleteTextures(1, &m_hillshade.texture_id);
  1844. m_hillshade.texture_id = 0;
  1845. }
  1846. m_hillshade.ready = false;
  1847. if (m_label_layer.vbo != 0) {
  1848. glDeleteBuffers(1, &m_label_layer.vbo);
  1849. m_label_layer.vbo = 0;
  1850. }
  1851. if (m_label_layer.vao != 0) {
  1852. glDeleteVertexArrays(1, &m_label_layer.vao);
  1853. m_label_layer.vao = 0;
  1854. }
  1855. if (m_label_layer.font_texture != 0) {
  1856. glDeleteTextures(1, &m_label_layer.font_texture);
  1857. m_label_layer.font_texture = 0;
  1858. }
  1859. m_label_layer.labels.clear();
  1860. m_label_layer.ready = false;
  1861. m_base_texture = nullptr;
  1862. m_water_texture = nullptr;
  1863. }
  1864. };
  1865. } // namespace
  1866. CampaignMapView::CampaignMapView() {
  1867. setMirrorVertically(true);
  1868. QOpenGLContext *ctx = QOpenGLContext::currentContext();
  1869. if (ctx == nullptr) {
  1870. qWarning() << "CampaignMapView: No OpenGL context available";
  1871. qWarning()
  1872. << "CampaignMapView: 3D rendering will not work in software mode";
  1873. qWarning()
  1874. << "CampaignMapView: Try running without QT_QUICK_BACKEND=software";
  1875. }
  1876. }
  1877. void CampaignMapView::load_provinces_for_hit_test() {
  1878. if (m_provinces_loaded) {
  1879. return;
  1880. }
  1881. m_provinces_loaded = true;
  1882. m_provinces.clear();
  1883. const QString path = Utils::Resources::resolveResourcePath(
  1884. QStringLiteral(":/assets/campaign_map/provinces.json"));
  1885. QFile file(path);
  1886. if (!file.open(QIODevice::ReadOnly)) {
  1887. return;
  1888. }
  1889. const QJsonDocument doc = QJsonDocument::fromJson(file.readAll());
  1890. if (!doc.isObject()) {
  1891. return;
  1892. }
  1893. const QJsonArray provinces = doc.object().value("provinces").toArray();
  1894. for (const auto &prov_val : provinces) {
  1895. const QJsonObject prov = prov_val.toObject();
  1896. const QJsonArray tri = prov.value("triangles").toArray();
  1897. if (tri.isEmpty()) {
  1898. continue;
  1899. }
  1900. ProvinceHit province;
  1901. province.id = prov.value("id").toString();
  1902. province.name = prov.value("name").toString();
  1903. province.owner = prov.value("owner").toString();
  1904. province.triangles.reserve(static_cast<size_t>(tri.size()));
  1905. for (const auto &pt_val : tri) {
  1906. const QJsonArray pt = pt_val.toArray();
  1907. if (pt.size() < 2) {
  1908. continue;
  1909. }
  1910. province.triangles.emplace_back(static_cast<float>(pt.at(0).toDouble()),
  1911. static_cast<float>(pt.at(1).toDouble()));
  1912. }
  1913. if (province.triangles.size() >= 3) {
  1914. m_provinces.push_back(std::move(province));
  1915. }
  1916. }
  1917. if (!m_province_overrides.isEmpty()) {
  1918. for (auto &province : m_provinces) {
  1919. const auto it = m_province_overrides.find(province.id);
  1920. if (it != m_province_overrides.end() && !it->owner.isEmpty()) {
  1921. province.owner = it->owner;
  1922. }
  1923. }
  1924. }
  1925. }
  1926. void CampaignMapView::load_province_labels() {
  1927. if (m_province_labels_loaded) {
  1928. return;
  1929. }
  1930. m_province_labels_loaded = true;
  1931. m_province_labels.clear();
  1932. const QString path = Utils::Resources::resolveResourcePath(
  1933. QStringLiteral(":/assets/campaign_map/provinces.json"));
  1934. QFile file(path);
  1935. if (!file.open(QIODevice::ReadOnly)) {
  1936. return;
  1937. }
  1938. const QJsonDocument doc = QJsonDocument::fromJson(file.readAll());
  1939. if (!doc.isObject()) {
  1940. return;
  1941. }
  1942. const QJsonArray provinces = doc.object().value("provinces").toArray();
  1943. for (const auto &prov_val : provinces) {
  1944. const QJsonObject prov = prov_val.toObject();
  1945. QVariantMap entry;
  1946. entry.insert(QStringLiteral("id"), prov.value("id").toString());
  1947. entry.insert(QStringLiteral("name"), prov.value("name").toString());
  1948. entry.insert(QStringLiteral("owner"), prov.value("owner").toString());
  1949. const QJsonArray label_uv = prov.value("label_uv").toArray();
  1950. if (label_uv.size() >= 2) {
  1951. QVariantList label_list;
  1952. label_list.reserve(2);
  1953. label_list.push_back(label_uv.at(0).toDouble());
  1954. label_list.push_back(label_uv.at(1).toDouble());
  1955. entry.insert(QStringLiteral("label_uv"), label_list);
  1956. }
  1957. const QJsonArray cities = prov.value("cities").toArray();
  1958. QVariantList city_list;
  1959. city_list.reserve(cities.size());
  1960. for (const auto &city_val : cities) {
  1961. const QJsonObject city = city_val.toObject();
  1962. const QString name = city.value("name").toString();
  1963. const QJsonArray uv = city.value("uv").toArray();
  1964. if (name.isEmpty() || uv.size() < 2) {
  1965. continue;
  1966. }
  1967. QVariantList uv_list;
  1968. uv_list.reserve(2);
  1969. uv_list.push_back(uv.at(0).toDouble());
  1970. uv_list.push_back(uv.at(1).toDouble());
  1971. QVariantMap city_entry;
  1972. city_entry.insert(QStringLiteral("name"), name);
  1973. city_entry.insert(QStringLiteral("uv"), uv_list);
  1974. city_list.push_back(city_entry);
  1975. }
  1976. entry.insert(QStringLiteral("cities"), city_list);
  1977. m_province_labels.push_back(entry);
  1978. }
  1979. if (!m_province_overrides.isEmpty()) {
  1980. QVariantList updated;
  1981. updated.reserve(m_province_labels.size());
  1982. for (const auto &entry_val : m_province_labels) {
  1983. QVariantMap entry = entry_val.toMap();
  1984. const QString id = entry.value(QStringLiteral("id")).toString();
  1985. const auto it = m_province_overrides.find(id);
  1986. if (it != m_province_overrides.end() && !it->owner.isEmpty()) {
  1987. entry.insert(QStringLiteral("owner"), it->owner);
  1988. }
  1989. updated.push_back(entry);
  1990. }
  1991. m_province_labels = std::move(updated);
  1992. }
  1993. emit province_labels_changed();
  1994. }
  1995. QVariantList CampaignMapView::province_labels() {
  1996. load_province_labels();
  1997. return m_province_labels;
  1998. }
  1999. void CampaignMapView::apply_province_state(const QVariantList &states) {
  2000. QHash<QString, ProvinceVisual> next_overrides;
  2001. next_overrides.reserve(states.size());
  2002. for (const auto &state_val : states) {
  2003. const QVariantMap state = state_val.toMap();
  2004. const QString id = state.value(QStringLiteral("id")).toString();
  2005. if (id.isEmpty()) {
  2006. continue;
  2007. }
  2008. ProvinceVisual visual;
  2009. visual.owner = state.value(QStringLiteral("owner")).toString();
  2010. const QVariantList color_list =
  2011. state.value(QStringLiteral("color")).toList();
  2012. if (color_list.size() >= 4) {
  2013. visual.color = QVector4D(static_cast<float>(color_list.at(0).toDouble()),
  2014. static_cast<float>(color_list.at(1).toDouble()),
  2015. static_cast<float>(color_list.at(2).toDouble()),
  2016. static_cast<float>(color_list.at(3).toDouble()));
  2017. visual.has_color = true;
  2018. }
  2019. next_overrides.insert(id, visual);
  2020. }
  2021. m_province_overrides = std::move(next_overrides);
  2022. ++m_province_state_version;
  2023. if (m_provinces_loaded) {
  2024. for (auto &province : m_provinces) {
  2025. const auto it = m_province_overrides.find(province.id);
  2026. if (it != m_province_overrides.end() && !it->owner.isEmpty()) {
  2027. province.owner = it->owner;
  2028. }
  2029. }
  2030. }
  2031. if (m_province_labels_loaded) {
  2032. QVariantList updated;
  2033. updated.reserve(m_province_labels.size());
  2034. for (const auto &entry_val : m_province_labels) {
  2035. QVariantMap entry = entry_val.toMap();
  2036. const QString id = entry.value(QStringLiteral("id")).toString();
  2037. const auto it = m_province_overrides.find(id);
  2038. if (it != m_province_overrides.end() && !it->owner.isEmpty()) {
  2039. entry.insert(QStringLiteral("owner"), it->owner);
  2040. }
  2041. updated.push_back(entry);
  2042. }
  2043. m_province_labels = std::move(updated);
  2044. emit province_labels_changed();
  2045. }
  2046. update();
  2047. }
  2048. QString CampaignMapView::province_at_screen(float x, float y) {
  2049. load_provinces_for_hit_test();
  2050. if (m_provinces.empty()) {
  2051. return {};
  2052. }
  2053. const float w = static_cast<float>(width());
  2054. const float h = static_cast<float>(height());
  2055. if (w <= 0.0F || h <= 0.0F) {
  2056. return {};
  2057. }
  2058. const float ndc_x = (2.0F * x / w) - 1.0F;
  2059. const float ndc_y = 1.0F - (2.0F * y / h);
  2060. const QMatrix4x4 mvp = build_mvp_matrix(w, h, m_orbit_yaw, m_orbit_pitch,
  2061. m_orbit_distance, m_pan_u, m_pan_v);
  2062. bool inverted = false;
  2063. const QMatrix4x4 inv = mvp.inverted(&inverted);
  2064. if (!inverted) {
  2065. return {};
  2066. }
  2067. QVector4D near_p = inv * QVector4D(ndc_x, ndc_y, -1.0F, 1.0F);
  2068. QVector4D far_p = inv * QVector4D(ndc_x, ndc_y, 1.0F, 1.0F);
  2069. if (qFuzzyIsNull(near_p.w()) || qFuzzyIsNull(far_p.w())) {
  2070. return {};
  2071. }
  2072. QVector3D near_v = QVector3D(near_p.x(), near_p.y(), near_p.z()) / near_p.w();
  2073. QVector3D far_v = QVector3D(far_p.x(), far_p.y(), far_p.z()) / far_p.w();
  2074. const QVector3D dir = far_v - near_v;
  2075. if (qFuzzyIsNull(dir.y())) {
  2076. return {};
  2077. }
  2078. const float t = -near_v.y() / dir.y();
  2079. if (t < 0.0F) {
  2080. return {};
  2081. }
  2082. const QVector3D hit = near_v + dir * t;
  2083. const float u = 1.0F - hit.x();
  2084. const float v = hit.z();
  2085. if (u < 0.0F || u > 1.0F || v < 0.0F || v > 1.0F) {
  2086. return {};
  2087. }
  2088. const QVector2D p(u, v);
  2089. for (const auto &province : m_provinces) {
  2090. const auto &triangles = province.triangles;
  2091. for (size_t i = 0; i + 2 < triangles.size(); i += 3) {
  2092. if (point_in_triangle(p, triangles[i], triangles[i + 1],
  2093. triangles[i + 2])) {
  2094. return province.id;
  2095. }
  2096. }
  2097. }
  2098. return {};
  2099. }
  2100. QVariantMap CampaignMapView::province_info_at_screen(float x, float y) {
  2101. load_provinces_for_hit_test();
  2102. QVariantMap info;
  2103. if (m_provinces.empty()) {
  2104. return info;
  2105. }
  2106. const float w = static_cast<float>(width());
  2107. const float h = static_cast<float>(height());
  2108. if (w <= 0.0F || h <= 0.0F) {
  2109. return info;
  2110. }
  2111. const float ndc_x = (2.0F * x / w) - 1.0F;
  2112. const float ndc_y = 1.0F - (2.0F * y / h);
  2113. const QMatrix4x4 mvp = build_mvp_matrix(w, h, m_orbit_yaw, m_orbit_pitch,
  2114. m_orbit_distance, m_pan_u, m_pan_v);
  2115. bool inverted = false;
  2116. const QMatrix4x4 inv = mvp.inverted(&inverted);
  2117. if (!inverted) {
  2118. return info;
  2119. }
  2120. QVector4D near_p = inv * QVector4D(ndc_x, ndc_y, -1.0F, 1.0F);
  2121. QVector4D far_p = inv * QVector4D(ndc_x, ndc_y, 1.0F, 1.0F);
  2122. if (qFuzzyIsNull(near_p.w()) || qFuzzyIsNull(far_p.w())) {
  2123. return info;
  2124. }
  2125. QVector3D near_v = QVector3D(near_p.x(), near_p.y(), near_p.z()) / near_p.w();
  2126. QVector3D far_v = QVector3D(far_p.x(), far_p.y(), far_p.z()) / far_p.w();
  2127. const QVector3D dir = far_v - near_v;
  2128. if (qFuzzyIsNull(dir.y())) {
  2129. return info;
  2130. }
  2131. const float t = -near_v.y() / dir.y();
  2132. if (t < 0.0F) {
  2133. return info;
  2134. }
  2135. const QVector3D hit = near_v + dir * t;
  2136. const float u = 1.0F - hit.x();
  2137. const float v = hit.z();
  2138. if (u < 0.0F || u > 1.0F || v < 0.0F || v > 1.0F) {
  2139. return info;
  2140. }
  2141. const QVector2D p(u, v);
  2142. for (const auto &province : m_provinces) {
  2143. const auto &triangles = province.triangles;
  2144. for (size_t i = 0; i + 2 < triangles.size(); i += 3) {
  2145. if (point_in_triangle(p, triangles[i], triangles[i + 1],
  2146. triangles[i + 2])) {
  2147. info.insert(QStringLiteral("id"), province.id);
  2148. info.insert(QStringLiteral("name"), province.name);
  2149. info.insert(QStringLiteral("owner"), province.owner);
  2150. return info;
  2151. }
  2152. }
  2153. }
  2154. return info;
  2155. }
  2156. QPointF CampaignMapView::screen_pos_for_uv(float u, float v) {
  2157. const float w = static_cast<float>(width());
  2158. const float h = static_cast<float>(height());
  2159. if (w <= 0.0F || h <= 0.0F) {
  2160. return {};
  2161. }
  2162. const float clamped_u = qBound(0.0F, u, 1.0F);
  2163. const float clamped_v = qBound(0.0F, v, 1.0F);
  2164. const QMatrix4x4 mvp = build_mvp_matrix(w, h, m_orbit_yaw, m_orbit_pitch,
  2165. m_orbit_distance, m_pan_u, m_pan_v);
  2166. const QVector4D world(1.0F - clamped_u, 0.0F, clamped_v, 1.0F);
  2167. const QVector4D clip = mvp * world;
  2168. if (qFuzzyIsNull(clip.w())) {
  2169. return {};
  2170. }
  2171. const float ndc_x = clip.x() / clip.w();
  2172. const float ndc_y = clip.y() / clip.w();
  2173. const float screen_x = (ndc_x + 1.0F) * 0.5F * w;
  2174. const float screen_y = (1.0F - (ndc_y + 1.0F) * 0.5F) * h;
  2175. return QPointF(screen_x, screen_y);
  2176. }
  2177. void CampaignMapView::load_hannibal_paths() {
  2178. if (m_hannibal_paths_loaded) {
  2179. return;
  2180. }
  2181. m_hannibal_paths_loaded = true;
  2182. m_hannibal_paths.clear();
  2183. const QString path = Utils::Resources::resolveResourcePath(
  2184. QStringLiteral(":/assets/campaign_map/hannibal_path.json"));
  2185. QFile file(path);
  2186. if (!file.open(QIODevice::ReadOnly)) {
  2187. qWarning() << "Failed to load Hannibal paths from" << path;
  2188. return;
  2189. }
  2190. const QJsonDocument doc = QJsonDocument::fromJson(file.readAll());
  2191. if (!doc.isObject()) {
  2192. return;
  2193. }
  2194. const QJsonArray lines = doc.object().value("lines").toArray();
  2195. for (const auto &line_val : lines) {
  2196. const QJsonArray line = line_val.toArray();
  2197. std::vector<QVector2D> path;
  2198. path.reserve(static_cast<size_t>(line.size()));
  2199. for (const auto &pt_val : line) {
  2200. const QJsonArray pt = pt_val.toArray();
  2201. if (pt.size() < 2) {
  2202. continue;
  2203. }
  2204. path.emplace_back(static_cast<float>(pt.at(0).toDouble()),
  2205. static_cast<float>(pt.at(1).toDouble()));
  2206. }
  2207. if (!path.empty()) {
  2208. m_hannibal_paths.push_back(std::move(path));
  2209. }
  2210. }
  2211. }
  2212. QPointF CampaignMapView::hannibal_icon_position() {
  2213. load_hannibal_paths();
  2214. if (m_hannibal_paths.empty()) {
  2215. return {};
  2216. }
  2217. const int mission_idx = qBound(0, m_current_mission,
  2218. static_cast<int>(m_hannibal_paths.size()) - 1);
  2219. const auto &path = m_hannibal_paths[static_cast<size_t>(mission_idx)];
  2220. if (path.empty()) {
  2221. return {};
  2222. }
  2223. const QVector2D &endpoint = path.back();
  2224. return screen_pos_for_uv(endpoint.x(), endpoint.y());
  2225. }
  2226. void CampaignMapView::set_orbit_yaw(float yaw) {
  2227. if (qFuzzyCompare(m_orbit_yaw, yaw)) {
  2228. return;
  2229. }
  2230. m_orbit_yaw = yaw;
  2231. emit orbit_yaw_changed();
  2232. update();
  2233. }
  2234. void CampaignMapView::set_orbit_pitch(float pitch) {
  2235. const float clamped = qBound(5.0F, pitch, 90.0F);
  2236. if (qFuzzyCompare(m_orbit_pitch, clamped)) {
  2237. return;
  2238. }
  2239. m_orbit_pitch = clamped;
  2240. emit orbit_pitch_changed();
  2241. update();
  2242. }
  2243. void CampaignMapView::set_orbit_distance(float distance) {
  2244. const float clamped =
  2245. qBound(k_min_orbit_distance, distance, k_max_orbit_distance);
  2246. if (qFuzzyCompare(m_orbit_distance, clamped)) {
  2247. return;
  2248. }
  2249. m_orbit_distance = clamped;
  2250. emit orbit_distance_changed();
  2251. update();
  2252. }
  2253. void CampaignMapView::set_pan_u(float pan) {
  2254. const float clamped = qBound(-0.5F, pan, 0.5F);
  2255. if (qFuzzyCompare(m_pan_u, clamped)) {
  2256. return;
  2257. }
  2258. m_pan_u = clamped;
  2259. emit pan_u_changed();
  2260. update();
  2261. }
  2262. void CampaignMapView::set_pan_v(float pan) {
  2263. const float clamped = qBound(-0.5F, pan, 0.5F);
  2264. if (qFuzzyCompare(m_pan_v, clamped)) {
  2265. return;
  2266. }
  2267. m_pan_v = clamped;
  2268. emit pan_v_changed();
  2269. update();
  2270. }
  2271. void CampaignMapView::set_hover_province_id(const QString &province_id) {
  2272. if (m_hover_province_id == province_id) {
  2273. return;
  2274. }
  2275. m_hover_province_id = province_id;
  2276. emit hover_province_id_changed();
  2277. update();
  2278. }
  2279. void CampaignMapView::set_current_mission(int mission) {
  2280. const int clamped = qBound(0, mission, 7);
  2281. if (m_current_mission == clamped) {
  2282. return;
  2283. }
  2284. m_current_mission = clamped;
  2285. emit current_mission_changed();
  2286. update();
  2287. }
  2288. void CampaignMapView::set_terrain_height_scale(float scale) {
  2289. if (qFuzzyCompare(m_terrain_height_scale, scale)) {
  2290. return;
  2291. }
  2292. m_terrain_height_scale = scale;
  2293. emit terrain_height_scale_changed();
  2294. update();
  2295. }
  2296. void CampaignMapView::set_show_province_fills(bool show) {
  2297. if (m_show_province_fills == show) {
  2298. return;
  2299. }
  2300. m_show_province_fills = show;
  2301. emit show_province_fills_changed();
  2302. update();
  2303. }
  2304. auto CampaignMapView::createRenderer() const -> Renderer * {
  2305. QOpenGLContext *ctx = QOpenGLContext::currentContext();
  2306. if ((ctx == nullptr) || !ctx->isValid()) {
  2307. qCritical()
  2308. << "CampaignMapView::createRenderer() - No valid OpenGL context";
  2309. qCritical()
  2310. << "Running in software rendering mode - map view not available";
  2311. return nullptr;
  2312. }
  2313. return new CampaignMapRenderer();
  2314. }