WorldmapModule.cpp 119 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666
  1. /*
  2. * Copyright (C) 2022 The V-Gears Team
  3. *
  4. * This file is part of V-Gears
  5. static bool IsJunonTexture(uint16 texture_id){
  6. const size_t texture_count = sizeof(textures) / sizeof(textures[0]);
  7. if (texture_id >= texture_count) return false;
  8. const std::string texture_name = textures[texture_id].name;
  9. return texture_name.compare(0, 3, "jun") == 0
  10. || texture_name == "jutmpl01";
  11. }
  12. *
  13. * V-Gears is free software: you can redistribute it and/or modify it under
  14. * terms of the GNU General Public License as published by the Free Software
  15. * Foundation, version 3.0 (GPLv3) of the License.
  16. *
  17. * V-Gears is distributed in the hope that it will be useful,
  18. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  19. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  20. * GNU General Public License for more details.
  21. */
  22. #include "WorldmapModule.h"
  23. #include <algorithm>
  24. #include <map>
  25. #include <memory>
  26. #include <limits>
  27. #include <set>
  28. #include <string>
  29. #include <vector>
  30. #include <sstream>
  31. #include <cstdlib>
  32. #include <tinyxml.h>
  33. #include <OgreEntity.h>
  34. #include <OgreSceneManager.h>
  35. #include <OgreManualObject.h>
  36. #include <OgreRoot.h>
  37. #include <OgreException.h>
  38. #include <OgreHardwarePixelBuffer.h>
  39. #include <OgreLogManager.h>
  40. #include <OgreTextureManager.h>
  41. #include "app/VGearsApplication.h"
  42. #include <Overlay/OgreOverlay.h>
  43. #include <Overlay/OgreOverlayContainer.h>
  44. #include <Overlay/OgreOverlayManager.h>
  45. #include <Overlay/OgrePanelOverlayElement.h>
  46. #include <OgreMaterialManager.h>
  47. #include <OgreResourceGroupManager.h>
  48. #include "data/VGearsTexFile.h"
  49. #include "core/InputManager.h"
  50. #include "common/Logger.h"
  51. #include "engine/entity/EntityManager.h"
  52. #include "engine/entity/EntityModel.h"
  53. #include "core/DialogsManager.h"
  54. #include "core/ScriptManager.h"
  55. #include "data/worldmap/WorldmapFile.h"
  56. #include "data/worldmap/WorldmapFileManager.h"
  57. #include "data/worldmap/WorldmapFileSerializer.h"
  58. #include "core/CameraManager.h"
  59. #include "core/UiManager.h"
  60. #include "core/UiWidget.h"
  61. /**
  62. * World map module singleton.
  63. */
  64. template<> VGears::WorldmapModule *Ogre::Singleton< VGears::WorldmapModule >::msSingleton = nullptr;
  65. namespace VGears {
  66. using namespace Ogre;
  67. /**
  68. * World map hardcoded texture information.
  69. */
  70. struct HarcodedTextureInfo{
  71. /**
  72. * Texture id.
  73. */
  74. uint32 id;
  75. /**
  76. * Texture name.
  77. */
  78. const char* name;
  79. /**
  80. * Texture width.
  81. */
  82. uint32 width;
  83. /**
  84. * Texture height.
  85. */
  86. uint32 height;
  87. /**
  88. * Texture U component.
  89. */
  90. uint32 u;
  91. /**
  92. * Texture V component
  93. */
  94. uint32 v;
  95. };
  96. /**
  97. * World map hardcoded textures
  98. */
  99. static HarcodedTextureInfo textures[] ={
  100. {0, "pond", 32, 32, 0, 352},
  101. {1, "riv_m2", 32, 32, 128, 64},
  102. {2, "was_gs", 64, 64, 64, 192},
  103. {3, "wpcltr", 32, 128, 0, 256},
  104. {4, "wpcltr2", 32, 32, 160, 64},
  105. {5, "bzdun", 64, 64, 192, 192},
  106. {6, "bone", 32, 32, 224, 384},
  107. {7, "bone2", 32, 32, 224, 416},
  108. {8, "bornwd", 64, 64, 160, 320},
  109. {9, "bridge", 32, 64, 192, 0},
  110. {10, "bridge2", 32, 32, 224, 0},
  111. {11, "cave", 32, 32, 224, 448},
  112. {12, "cave2", 32, 32, 224, 320},
  113. {13, "cave_s", 32, 32, 160, 224},
  114. {14, "cdl_cl2", 64, 32, 96, 96},
  115. {15, "cf01", 64, 32, 192, 288},
  116. {16, "clf_bgs", 64, 32, 192, 384},
  117. {17, "clf_ggl", 64, 64, 128, 256},
  118. {18, "clf_ggs", 64, 32, 192, 352},
  119. {19, "clf_l", 64, 64, 0, 0},
  120. {20, "clf_ld", 64, 64, 64, 0},
  121. {21, "clf_lf", 64, 64, 128, 0},
  122. {22, "clf_lg", 32, 64, 0, 96},
  123. {23, "clf_lr", 32, 64, 128, 0},
  124. {24, "clf_lsg", 32, 64, 64, 64},
  125. {25, "clf_r", 32, 32, 0, 96},
  126. {26, "clf_s", 64, 32, 192, 0},
  127. {27, "clf_sd", 64, 32, 192, 32},
  128. {28, "clf_sf", 64, 32, 0, 64},
  129. {29, "clf_sg", 32, 32, 32, 96},
  130. {30, "clf_sg2", 32, 32, 0, 160},
  131. {31, "clf_sr", 32, 32, 32, 96},
  132. {32, "clf_ss", 32, 32, 32, 128},
  133. {33, "clf_ssd", 32, 32, 0, 224},
  134. {34, "clf_ssw", 32, 32, 224, 32},
  135. {35, "clf_sw", 32, 32, 192, 32},
  136. {36, "clf_w02", 64, 64, 128, 64},
  137. {37, "clf_w03", 64, 64, 192, 64},
  138. {38, "clf_was", 64, 32, 64, 64},
  139. {39, "clfeg", 32, 32, 192, 320},
  140. {40, "clfegd", 32, 32, 0, 320},
  141. {41, "clftop", 64, 32, 192, 64},
  142. {42, "clftop2", 32, 32, 128, 64},
  143. {43, "cndl_cl", 64, 32, 96, 128},
  144. {44, "cndlf", 64, 64, 160, 64},
  145. {45, "cndlf02", 64, 64, 208, 64},
  146. {46, "comtr", 16, 32, 144, 96},
  147. {47, "cosinn", 32, 32, 224, 416},
  148. {48, "cosinn2", 32, 32, 192, 448},
  149. {49, "csmk", 32, 32, 64, 64},
  150. {50, "csmk2", 32, 32, 96, 64},
  151. {51, "cstds01", 32, 32, 224, 160},
  152. {52, "cstds02", 64, 64, 0, 448},
  153. {53, "des01", 32, 32, 160, 320},
  154. {54, "desert", 64, 64, 128, 128},
  155. {55, "desor", 64, 32, 160, 64},
  156. {56, "ds1", 32, 32, 0, 256},
  157. {57, "ds_s1", 32, 32, 192, 288},
  158. {58, "dsee1", 32, 32, 96, 288},
  159. {59, "dsrt_d", 32, 32, 224, 0},
  160. {60, "dsrt_e", 64, 128, 64, 128},
  161. {61, "edes01", 32, 32, 224, 320},
  162. {62, "elm01", 32, 32, 160, 0},
  163. {63, "elm02", 32, 32, 64, 96},
  164. {64, "elm_gro", 64, 64, 0, 96},
  165. {65, "elm_r", 32, 32, 192, 0},
  166. {66, "elm_r2", 32, 32, 224, 0},
  167. {67, "fall1", 32, 32, 128, 256},
  168. {68, "farm01", 32, 32, 160, 32},
  169. {69, "farm02", 32, 32, 192, 32},
  170. {70, "farm_g", 32, 32, 128, 64},
  171. {71, "farm_r", 32, 16, 128, 48},
  172. {72, "fld", 64, 64, 64, 96},
  173. {73, "fld_02", 64, 64, 0, 64},
  174. {74, "fld_s", 64, 64, 0, 160},
  175. {75, "fld_s2", 32, 32, 224, 256},
  176. {76, "fld_sw", 64, 64, 128, 192},
  177. {77, "fld_v", 128, 128, 0, 128},
  178. {78, "fld_vd", 32, 64, 96, 128},
  179. {79, "fld_vd2", 32, 64, 192, 416},
  180. {80, "fvedge", 32, 64, 0, 0},
  181. {81, "gclf_d", 128, 64, 128, 128},
  182. {82, "gclf_g", 32, 64, 224, 128},
  183. {83, "gclfwa", 128, 64, 64, 320},
  184. {84, "gclfwa2", 32, 64, 160, 320},
  185. {85, "gclfwag", 32, 64, 32, 320},
  186. {86, "gg_gro", 64, 64, 64, 448},
  187. {87, "gg_mts", 64, 128, 0, 128},
  188. {88, "ggmk", 64, 64, 128, 448},
  189. {89, "ggmt", 128, 128, 0, 0},
  190. {90, "ggmt_e", 128, 32, 0, 96},
  191. {91, "ggmt_ed", 128, 32, 128, 96},
  192. {92, "ggmt_eg", 32, 32, 96, 224},
  193. {93, "ggmtd", 128, 128, 128, 0},
  194. {94, "ggs_g", 32, 32, 32, 64},
  195. {95, "ggshr", 32, 32, 192, 96},
  196. {96, "ggshrg", 32, 32, 224, 96},
  197. {97, "gia", 64, 32, 64, 224},
  198. {98, "gia2", 64, 32, 0, 224},
  199. {99, "gia_d", 64, 32, 128, 224},
  200. {100, "gia_d2", 64, 32, 64, 224},
  201. {101, "gia_g", 32, 32, 192, 224},
  202. {102, "gia_g2", 32, 32, 128, 224},
  203. {103, "gmt_eda", 32, 32, 0, 352},
  204. {104, "gonclf", 128, 64, 96, 64},
  205. {105, "gredge", 32, 32, 192, 192},
  206. {106, "hyouga", 64, 64, 192, 64},
  207. {107, "iceclf", 64, 32, 64, 96},
  208. {108, "iceclfd", 64, 32, 128, 96},
  209. {109, "iceclfg", 32, 32, 32, 224},
  210. {110, "jun", 64, 64, 192, 192},
  211. {111, "jun_d", 64, 64, 128, 192},
  212. {112, "jun_e", 64, 16, 0, 240},
  213. {113, "jun_gro", 64, 64, 0, 64},
  214. {114, "junmk", 32, 32, 0, 96},
  215. {115, "junn01", 32, 32, 160, 112},
  216. {116, "junn02", 32, 32, 192, 112},
  217. {117, "junn03", 32, 32, 224, 112},
  218. {118, "junn04", 32, 32, 64, 128},
  219. {119, "jutmpl01", 64, 64, 128, 192},
  220. {120, "lake-e", 32, 32, 96, 192},
  221. {121, "lake_ef", 32, 32, 128, 224},
  222. {122, "lake_fl", 128, 32, 160, 224},
  223. {123, "lostclf", 32, 64, 128, 384},
  224. {124, "lostmt", 128, 32, 128, 448},
  225. {125, "lostmtd", 128, 32, 128, 480},
  226. {126, "lostmts", 64, 32, 160, 384},
  227. {127, "lostwd_e", 32, 32, 64, 480},
  228. {128, "lostwod", 64, 64, 0, 448},
  229. {129, "lst1", 32, 32, 192, 256},
  230. {130, "lstwd_e2", 32, 32, 96, 480},
  231. {131, "mzes", 32, 32, 224, 128},
  232. {132, "mzmt_e", 128, 64, 128, 64},
  233. {133, "mzmt_ed", 128, 32, 128, 128},
  234. {134, "mzmt_edw", 128, 32, 128, 160},
  235. {135, "mzmt_ew", 128, 32, 0, 128},
  236. {136, "mzmt_o", 128, 32, 64, 416},
  237. {137, "mzmt_od", 128, 32, 64, 448},
  238. {138, "mzmt_s", 128, 32, 0, 192},
  239. {139, "mzmt_sd", 128, 32, 0, 160},
  240. {140, "md01", 32, 32, 96, 16},
  241. {141, "md02", 128, 128, 0, 0},
  242. {142, "md03", 16, 16, 112, 64},
  243. {143, "md04", 32, 32, 128, 16},
  244. {144, "md05", 64, 16, 96, 0},
  245. {145, "md06", 16, 32, 96, 48},
  246. {146, "md07", 16, 16, 112, 48},
  247. {147, "md_mt", 128, 128, 128, 0},
  248. {148, "md_mtd", 128, 128, 0, 0},
  249. {149, "md_mts", 64, 128, 64, 160},
  250. {150, "md_snow", 128, 32, 128, 0},
  251. {151, "md_snw2", 128, 32, 128, 32},
  252. {152, "md_snwd", 128, 64, 0, 128},
  253. {153, "md_snwe", 64, 64, 96, 320},
  254. {154, "md_snws", 64, 64, 128, 128},
  255. {155, "md_snwt", 128, 32, 0, 192},
  256. {156, "md_snww", 32, 32, 224, 224},
  257. {157, "md_sw_s", 128, 128, 0, 0},
  258. {158, "md_swd2", 32, 32, 192, 256},
  259. {159, "md_swnp", 128, 128, 0, 96},
  260. {160, "mdsrt_e", 128, 32, 128, 192},
  261. {161, "mdsrt_ed", 128, 32, 128, 224},
  262. {162, "mdsrt_eg", 32, 32, 64, 224},
  263. {163, "midil", 32, 32, 32, 192},
  264. {164, "midild", 32, 32, 224, 192},
  265. {165, "mt_ewg", 32, 32, 64, 96},
  266. {166, "mt_road", 64, 64, 192, 128},
  267. {167, "mt_se", 32, 32, 160, 416},
  268. {168, "mt_se2", 64, 64, 128, 256},
  269. {169, "mt_sg01", 32, 32, 0, 224},
  270. {170, "mt_sg02", 32, 32, 32, 224},
  271. {171, "mt_sg03", 32, 32, 0, 192},
  272. {172, "mt_sg04", 32, 32, 160, 384},
  273. {173, "mtcoin", 64, 64, 0, 256},
  274. {174, "mtwas_e", 128, 32, 0, 224},
  275. {175, "mtwas_ed", 128, 32, 0, 224},
  276. {176, "ncol_gro", 64, 64, 64, 384},
  277. {177, "ncole01", 32, 32, 224, 384},
  278. {178, "ncole02", 32, 32, 192, 416},
  279. {179, "nivl_gro", 64, 64, 128, 384},
  280. {180, "nivl_mt", 128, 64, 0, 0},
  281. {181, "nivl_top", 32, 32, 0, 64},
  282. {182, "nivlr", 32, 32, 192, 384},
  283. {183, "port", 32, 32, 96, 224},
  284. {184, "port_d", 32, 32, 160, 0},
  285. {185, "rzclf02", 64, 64, 128, 128},
  286. {186, "rct_gro", 64, 128, 0, 416},
  287. {187, "riv_cls", 64, 64, 64, 0},
  288. {188, "riv_l1", 32, 32, 96, 320},
  289. {189, "riv_m", 32, 32, 0, 224},
  290. {190, "rivr", 32, 32, 64, 224},
  291. {191, "rivrclf", 64, 64, 128, 192},
  292. {192, "rivs1", 32, 32, 128, 320},
  293. {193, "rivshr", 64, 64, 192, 192},
  294. {194, "rivssr", 64, 32, 192, 224},
  295. {195, "rivstrt", 32, 32, 192, 160},
  296. {196, "rm1", 32, 32, 32, 288},
  297. {197, "rocet", 32, 32, 128, 160},
  298. {198, "rs_ss", 32, 32, 96, 224},
  299. {199, "sango", 32, 32, 224, 320},
  300. {200, "sango2", 32, 32, 224, 352},
  301. {201, "sango3", 32, 32, 128, 384},
  302. {202, "sango4", 64, 64, 0, 384},
  303. {203, "sdun", 64, 64, 0, 160},
  304. {204, "sdun02", 64, 64, 64, 160},
  305. {205, "sh1", 32, 32, 32, 256},
  306. {206, "sh_s1", 32, 32, 224, 288},
  307. {207, "shedge", 32, 64, 160, 160},
  308. {208, "shlm_1", 32, 32, 192, 320},
  309. {209, "shol", 128, 128, 128, 96},
  310. {210, "shol_s", 64, 64, 192, 192},
  311. {211, "shor", 128, 128, 0, 0},
  312. {212, "shor_s", 64, 64, 128, 192},
  313. {213, "shor_s2", 32, 32, 224, 416},
  314. {214, "shor_v", 32, 32, 192, 0},
  315. {215, "silo", 32, 32, 224, 32},
  316. {216, "slope", 128, 32, 0, 384},
  317. {217, "snow_es", 32, 32, 192, 480},
  318. {218, "snow_es2", 32, 32, 224, 480},
  319. {219, "snow_es3", 32, 32, 224, 448},
  320. {220, "snw_mt", 128, 128, 0, 0},
  321. {221, "snw_mtd", 128, 128, 128, 0},
  322. {222, "snw_mte", 64, 32, 0, 96},
  323. {223, "snw_mted", 64, 32, 64, 96},
  324. {224, "snw_mts", 64, 128, 64, 0},
  325. {225, "snw_mts2", 64, 32, 128, 192},
  326. {226, "snwfld", 64, 64, 0, 64},
  327. {227, "snwfld_s", 64, 32, 128, 128},
  328. {228, "snwgra", 64, 64, 192, 192},
  329. {229, "snwhm01", 32, 32, 32, 0},
  330. {230, "snwhm02", 32, 32, 32, 32},
  331. {231, "snwods", 32, 32, 224, 192},
  332. {232, "snwood", 64, 64, 192, 128},
  333. {233, "snwtrk", 32, 64, 96, 256},
  334. {234, "sse_s1", 32, 32, 32, 320},
  335. {235, "ssee1", 32, 32, 64, 288},
  336. {236, "sst1", 32, 32, 224, 256},
  337. {237, "stown_r", 32, 32, 192, 256},
  338. {238, "stw_gro", 64, 64, 0, 384},
  339. {239, "subrg2", 32, 32, 224, 160},
  340. {240, "susbrg", 64, 64, 192, 96},
  341. {241, "sw_se", 64, 64, 0, 0},
  342. {242, "swclf_l", 64, 64, 64, 128},
  343. {243, "swclf_ld", 64, 64, 192, 128},
  344. {244, "swclf_lg", 32, 64, 0, 192},
  345. {245, "swclf_s", 64, 32, 128, 96},
  346. {246, "swclf_sd", 64, 32, 192, 96},
  347. {247, "swclf_sg", 32, 32, 32, 192},
  348. {248, "swclf_wg", 32, 32, 192, 192},
  349. {249, "swfld_s2", 64, 32, 128, 160},
  350. {250, "swfld_s3", 32, 32, 160, 192},
  351. {251, "swmd_cg", 32, 32, 128, 192},
  352. {252, "swmd_clf", 64, 32, 64, 192},
  353. {253, "swp1", 32, 32, 0, 288},
  354. {254, "trk", 64, 64, 128, 0},
  355. {255, "tyo_f", 128, 128, 128, 128},
  356. {256, "tyosnw", 64, 128, 64, 384},
  357. {257, "uf1", 32, 32, 160, 256},
  358. {258, "utai01", 32, 32, 32, 96},
  359. {259, "utai02", 32, 32, 224, 64},
  360. {260, "utai_gro", 64, 64, 128, 96},
  361. {261, "utaimt", 32, 32, 0, 128},
  362. {262, "utaimtd", 32, 32, 96, 96},
  363. {263, "utaimtg", 32, 32, 96, 128},
  364. {264, "wa1", 32, 32, 192, 320},
  365. {265, "wzs1", 32, 32, 128, 288},
  366. {266, "wzshr", 32, 32, 160, 32},
  367. {267, "wzshr2", 32, 32, 32, 128},
  368. {268, "wzshrs", 32, 32, 32, 160},
  369. {269, "was", 128, 128, 0, 96},
  370. {270, "was_d", 64, 32, 0, 224},
  371. {271, "was_g", 64, 64, 0, 192},
  372. {272, "was_s", 128, 128, 128, 0},
  373. {273, "wasfld", 64, 64, 64, 256},
  374. {274, "wdedge", 64, 64, 64, 160},
  375. {275, "we1", 32, 32, 96, 256},
  376. {276, "we_s1", 32, 32, 160, 288},
  377. {277, "wedged", 32, 64, 128, 160},
  378. {278, "wod-e2", 32, 32, 64, 224},
  379. {279, "wood", 64, 64, 192, 0},
  380. {280, "wood_d", 64, 64, 192, 160},
  381. {281, "wtrk", 32, 64, 64, 96},
  382. // The ids 282-293 (ff7.exe table of u, v at 0x95b9f0) are the ones that WM2 uses (its ids + 282).
  383. {282, "cltr", 128, 128, 0, 0},
  384. {283, "lake_a", 128, 256, 0, 0},
  385. {284, "rock", 256, 256, 0, 0},
  386. {285, "scave", 256, 256, 0, 0},
  387. {286, "ssand", 256, 256, 0, 0},
  388. {287, "swall02", 256, 256, 0, 0},
  389. {288, "sng01", 128, 128, 128, 0},
  390. {289, "sng02", 128, 128, 128, 0},
  391. {290, "hokola01", 64, 64, 0, 0},
  392. {291, "hokola02", 64, 64, 0, 128},
  393. {292, "snwfldl", 64, 64, 0, 64},
  394. {293, "snwfld2", 64, 64, 0, 192}
  395. };
  396. /**
  397. * The ids of the textures of WM2 and WM3 start after the ones of WM0 in the table of the game:
  398. * WM2 uses 0-7 as 282-289 and WM3 0-3 as 290-293 (checked with the ranges of their UVs).
  399. */
  400. static uint16 GetTextureIdOffset(const uint8 map_id){
  401. return map_id == 1 ? 282 : (map_id == 2 ? 290 : 0);
  402. }
  403. static const char* WORLD_MAP_RESOURCE_GROUP = "WORLD_MAP";
  404. static bool IsFootWalkable(uint8 walkability_type){
  405. using WalkType = VGears::WorldmapFileSerializer::TriangleWalkMapTypes;
  406. switch (walkability_type){
  407. case WalkType::GRASS:
  408. case WalkType::FOREST:
  409. case WalkType::SWAMP:
  410. case WalkType::DESERT:
  411. case WalkType::WASTELAND:
  412. case WalkType::SNOW:
  413. case WalkType::RIVERSIDE:
  414. case WalkType::COREL_BRIDGE:
  415. case WalkType::WUTAI_BRIDGE:
  416. case WalkType::HILL_SIDE:
  417. case WalkType::BEACH:
  418. case WalkType::CANYON:
  419. case WalkType::MOUNTAIN_PASS:
  420. case WalkType::GOLD_SAUCER_DESERT:
  421. case WalkType::JUNGLE:
  422. case WalkType::NORTHERND_CAVE:
  423. case WalkType::GOLD_SAUCER_DESERT_BORDER:
  424. case WalkType::BRIDGE_HEAD:
  425. case WalkType::BACK_ENTRANCE:
  426. return true;
  427. default:
  428. return false;
  429. }
  430. }
  431. static const std::map<Ogre::String, uint8>& GetWorldMapTerrainTypes(){
  432. using WalkType = VGears::WorldmapFileSerializer::TriangleWalkMapTypes;
  433. static const std::map<Ogre::String, uint8> terrain_types = {
  434. {"GRASS", static_cast<uint8>(WalkType::GRASS)},
  435. {"FOREST", static_cast<uint8>(WalkType::FOREST)},
  436. {"MOUNTAIN", static_cast<uint8>(WalkType::MOUNTAIN)},
  437. {"SEA_DEEP_WATER", static_cast<uint8>(WalkType::SEA_DEEP_WATER)},
  438. {"RIVER_CROSSING", static_cast<uint8>(WalkType::RIVER_CROSSING)},
  439. {"RIVER", static_cast<uint8>(WalkType::RIVER)},
  440. {"WATER", static_cast<uint8>(WalkType::WATER)},
  441. {"SWAMP", static_cast<uint8>(WalkType::SWAMP)},
  442. {"DESERT", static_cast<uint8>(WalkType::DESERT)},
  443. {"WASTELAND", static_cast<uint8>(WalkType::WASTELAND)},
  444. {"SNOW", static_cast<uint8>(WalkType::SNOW)},
  445. {"RIVERSIDE", static_cast<uint8>(WalkType::RIVERSIDE)},
  446. {"CLIFF", static_cast<uint8>(WalkType::CLIFF)},
  447. {"COREL_BRIDGE", static_cast<uint8>(WalkType::COREL_BRIDGE)},
  448. {"WUTAI_BRIDGE", static_cast<uint8>(WalkType::WUTAI_BRIDGE)},
  449. {"UNUSED_1", static_cast<uint8>(WalkType::UNUSED_1)},
  450. {"HILL_SIDE", static_cast<uint8>(WalkType::HILL_SIDE)},
  451. {"BEACH", static_cast<uint8>(WalkType::BEACH)},
  452. {"SUBMARINE_PEN", static_cast<uint8>(WalkType::SUBMARINE_PEN)},
  453. {"CANYON", static_cast<uint8>(WalkType::CANYON)},
  454. {"MOUNTAIN_PASS", static_cast<uint8>(WalkType::MOUNTAIN_PASS)},
  455. {"UNKNOWN_1", static_cast<uint8>(WalkType::UNKNOWN_1)},
  456. {"WATERFALL", static_cast<uint8>(WalkType::WATERFALL)},
  457. {"UNUSED_2", static_cast<uint8>(WalkType::UNUSED_2)},
  458. {"GOLD_SAUCER_DESERT", static_cast<uint8>(WalkType::GOLD_SAUCER_DESERT)},
  459. {"JUNGLE", static_cast<uint8>(WalkType::JUNGLE)},
  460. {"SEA", static_cast<uint8>(WalkType::SEA)},
  461. {"NORTHERND_CAVE", static_cast<uint8>(WalkType::NORTHERND_CAVE)},
  462. {"GOLD_SAUCER_DESERT_BORDER", static_cast<uint8>(WalkType::GOLD_SAUCER_DESERT_BORDER)},
  463. {"BRIDGE_HEAD", static_cast<uint8>(WalkType::BRIDGE_HEAD)},
  464. {"BACK_ENTRANCE", static_cast<uint8>(WalkType::BACK_ENTRANCE)},
  465. {"UNUSED_3", static_cast<uint8>(WalkType::UNUSED_3)}
  466. };
  467. return terrain_types;
  468. }
  469. static Ogre::String GetWorldMapTerrainName(const uint8 walkability_type){
  470. for (const auto& terrain : GetWorldMapTerrainTypes()){
  471. if (terrain.second == walkability_type) return terrain.first;
  472. }
  473. return "";
  474. }
  475. /**
  476. * World map IDs and the files of the original game they load. The original game has no WM1.
  477. * 0 is the overworld, 1 is WM2 and 2 is WM3.
  478. */
  479. static const int WORLD_MAP_FILE_NUMBERS[] = {0, 2, 3};
  480. static const int WORLD_MAP_COUNT = sizeof(WORLD_MAP_FILE_NUMBERS) / sizeof(int);
  481. /**
  482. * Size and position of a map in blocks. The blocks of a MAP file are stored in order, row by
  483. * row. The maps are placed in the 9x7 block grid of the world, since the scripts index the
  484. * meshes with the position in that grid, and the maps share coordinates: the underwater map
  485. * WM2 is a part of the world of WM0, so a position of WM0 inside it is the same in WM2.
  486. *
  487. * The layout of WM2 was deduced from the edges of its blocks and the mesh coordinates in its
  488. * script. The one of WM3 is a guess.
  489. */
  490. struct MapLayout{
  491. int width;
  492. int height;
  493. int origin_x;
  494. int origin_y;
  495. };
  496. static MapLayout GetMapLayout(const int map_id){
  497. switch (map_id){
  498. case 1: return {3, 4, 3, 2};
  499. case 2: return {2, 2, 0, 0};
  500. default: return {9, 7, 0, 0};
  501. }
  502. }
  503. /**
  504. * Gets if a position of the world is inside the blocks of a map.
  505. */
  506. static bool IsInsideMap(const int map_id, const float x, const float z){
  507. const MapLayout layout = GetMapLayout(map_id);
  508. const float block_size = (8182.0f / 4096.0f) * 4.0f;
  509. const float bx = x / block_size - layout.origin_x;
  510. const float bz = z / block_size - layout.origin_y;
  511. return bx >= 0 && bz >= 0 && bx < layout.width && bz < layout.height;
  512. }
  513. /// Rotation speed of the camera with L1 and R1, in radians per second.
  514. static const float CAMERA_ROTATION_SPEED = 1.5f;
  515. /// Snow map (WM3): the camera turns by itself after this many seconds (random in the range) ...
  516. static const float SNOW_CAMERA_MIN_WAIT = 6.0f;
  517. static const float SNOW_CAMERA_MAX_WAIT = 12.0f;
  518. /// ... by this many degrees (random in the range, to any side), at the speed of the manual rotation.
  519. static const float SNOW_CAMERA_MIN_DEGREES = 30.0f;
  520. static const float SNOW_CAMERA_MAX_DEGREES = 160.0f;
  521. /// Snow map (WM3): how many poles can exist at the same time.
  522. static const size_t SNOW_MAX_POLES = 4;
  523. /** Distances (from the camera, 1 map block = 2 units) where the black fog of WM2 starts and is total. */
  524. static const float UNDERWATER_FOG_START = 2.0f;
  525. static const float UNDERWATER_FOG_END = 6.0f;
  526. /// Turning speed of the flying vehicles, in radians per second.
  527. static const float FLIGHT_TURN_SPEED = 1.5f;
  528. /// Speed up and down of the flying vehicles, in world units per second.
  529. static const float FLIGHT_CLIMB_SPEED = 1.0f;
  530. /// Closest distance of the flying vehicles to the ground.
  531. static const float FLIGHT_MIN_CLEARANCE = 0.1f;
  532. /// How much the model of the submarine is under the surface of the water in WM0, in world
  533. /// units. Found by looking at it.
  534. static const float SUBMARINE_SUBMERGED_DEPTH = 0.09f;
  535. /**
  536. * Moves the model of an entity up or down, without moving the entity.
  537. *
  538. * The model is scaled to the size of the world, so the offset has to be divided by that scale
  539. * to be in world units.
  540. *
  541. * @param[in] entity The entity.
  542. * @param[in] offset Distance in world units. Negative is down.
  543. */
  544. static void SetModelHeightOffset(EntityModel* entity, const float offset){
  545. Ogre::SceneNode* model_node = entity->GetModel()->getParentSceneNode();
  546. float scale = 1.0f;
  547. if (model_node->getParentSceneNode() != nullptr){
  548. scale = model_node->getParentSceneNode()->_getDerivedScale().y;
  549. }
  550. if (scale <= 0.0f) scale = 1.0f;
  551. model_node->setPosition(Ogre::Vector3(0.0f, offset / scale, 0.0f));
  552. }
  553. /// Height over the ground where the submarine starts, so it floats.
  554. static const float SUBMARINE_START_CLEARANCE = 0.3f;
  555. /// Highest height over the ground where the Highwind can be unboarded. It lands there.
  556. static const float HIGHWIND_MAX_LANDING_HEIGHT = 1.0f;
  557. /// Highest point the Highwind can reach.
  558. static const float HIGHWIND_MAX_HEIGHT = 1.0f;
  559. /// How deep the submarine goes under the surface of WM0 when diving, in world units.
  560. static const float DIVE_SINK_DEPTH = 0.5f;
  561. /// Time the submarine takes to go under the surface of WM0, or to come up to it.
  562. static const float DIVE_SINK_TIME = 1.0f;
  563. /// Height where the submarine appears in WM2 when diving, and where it goes when surfacing.
  564. /// It's over the top layer of the map.
  565. static const float DIVE_HIGH_HEIGHT = 1.0f;
  566. /// Time the submarine takes to go down from, or up to, the height above.
  567. static const float DIVE_HIGH_TIME = 1.5f;
  568. /// Time of the fade to black before the map changes.
  569. static const float DIVE_FADE_OUT_TIME = 0.5f;
  570. /**
  571. * Highest terrain height the submarine can reach in WM2. The terrain above it is the top
  572. * layer. The submarine can move over all terrain types below this height.
  573. *
  574. * @todo The value was chosen from the height distribution of the WM2 triangles, and not
  575. * verified against the original game.
  576. */
  577. static const float UNDERWATER_MAX_HEIGHT = -0.3f;
  578. /**
  579. * Enables the submarine height limit of WM2.
  580. *
  581. * The submarine can't go over terrain that is closer than FLIGHT_MIN_CLEARANCE to the
  582. * ceiling.
  583. */
  584. static const bool UNDERWATER_HEIGHT_LIMIT_ENABLED = true;
  585. /**
  586. * Width in meshes of the grid that the world map scripts use to index meshes (mesh_y * 36 +
  587. * mesh_x). It is the same in every map, regardless of the size of the map.
  588. */
  589. static const int WORLD_MAP_SCRIPT_MESH_STRIDE = 36;
  590. /**
  591. * Loads and parses an installed world map file.
  592. *
  593. * @param[in] file_name Name of the MAP file, like "WM0.MAP".
  594. * @return The map blocks.
  595. */
  596. static std::vector<VGears::WorldmapFileSerializer::Block> LoadWorldMap(
  597. const Ogre::String& file_name
  598. ){
  599. /**
  600. * The serializer retains its parsed blocks; the resource argument is
  601. * currently unused by the MAP serializer.
  602. */
  603. class TestFile : public VGears::WorldmapFile{
  604. public:
  605. TestFile() : VGears::WorldmapFile(nullptr, "", 0, "") {}
  606. };
  607. Ogre::DataStreamPtr stream
  608. = Ogre::ResourceGroupManager::getSingleton().openResource(
  609. file_name, WORLD_MAP_RESOURCE_GROUP, nullptr, true
  610. );
  611. TestFile file;
  612. VGears::WorldmapFileSerializer serializer;
  613. serializer.ImportWorldmapFile(stream, file);
  614. Ogre::LogManager::getSingleton().logMessage(
  615. "Loaded " + file_name + " with " + std::to_string(serializer.blocks.size())
  616. + " blocks."
  617. );
  618. return serializer.blocks;
  619. }
  620. /**
  621. * Creates a 16 bit point from coordinates.
  622. *
  623. * @param[in] coord The coordinates.
  624. * @return Coordinate point.
  625. */
  626. static float From16BitFixedPoint(VGears::sint16 coord){
  627. // return float(coord);
  628. return (float(coord) / 4096.0f);
  629. }
  630. /**
  631. * Converts a coordinate to a texture U component coordinate.
  632. *
  633. * @param[in] coord The coordinate to convert.
  634. * @param[in] id Texture ID.
  635. * @return Texture coordinate U component.
  636. * @todo Understand and document properly.
  637. */
  638. static float ToTextureCoordU(uint8 coord, uint16 id){
  639. return (float(coord) - float(textures[id].u)) / float(textures[id].width);
  640. //return (float(textures[id].u) + float(coord)) / 256.0f;
  641. }
  642. /**
  643. * Converts a coordinate to a texture V component coordinate.
  644. *
  645. * @param[in] coord The coordinate to convert.
  646. * @param[in] id Texture ID.
  647. * @return Texture coordinate V component.
  648. * @todo Understand and document properly.
  649. */
  650. static float ToTextureCoordV(uint8 coord, uint16 id){
  651. return (float(coord) - float(textures[id].v)) / float(textures[id].height);
  652. //return (float(textures[id].v) + float(coord)) / 640.0f;
  653. }
  654. struct ImageDataDeleter{
  655. void operator()(Ogre::ImageCodec::ImageData* image_data) const{
  656. OGRE_DELETE image_data;
  657. }
  658. };
  659. static TexturePtr LoadWorldMapTexture(const std::string& name){
  660. const std::string texture_name = name + ".tex";
  661. Ogre::DataStreamPtr stream
  662. = ResourceGroupManager::getSingleton().openResource(
  663. texture_name, WORLD_MAP_RESOURCE_GROUP, nullptr, true
  664. );
  665. VGears::TexFile tex_file;
  666. tex_file.Read(stream);
  667. Ogre::MemoryDataStreamPtr pixel_data(tex_file.GetPixelData());
  668. std::unique_ptr<Ogre::ImageCodec::ImageData, ImageDataDeleter> image_data(
  669. tex_file.GetImageData()
  670. );
  671. TexturePtr texture = Ogre::TextureManager::getSingleton().createManual(
  672. std::string("WorldMapTex_") + name,
  673. ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, TEX_TYPE_2D,
  674. image_data->width, image_data->height, 0, image_data->format, TU_STATIC
  675. );
  676. texture->getBuffer()->blitFromMemory(Ogre::PixelBox(
  677. image_data->width, image_data->height, 1, image_data->format,
  678. pixel_data->getPtr()
  679. ));
  680. return texture;
  681. }
  682. /**
  683. * Animated textures (water, shores, rivers, waterfalls, swamps). The original game has sets of
  684. * frames named by the first one plus a number (ff7.exe 0x95b880: fall1-8, riv_l1-4, ...). The
  685. * triangles use the first frame, and the material of it shows the frames in turn.
  686. */
  687. struct AnimatedTextureSet{
  688. const char* prefix;
  689. int frames;
  690. };
  691. static const AnimatedTextureSet ANIMATED_TEXTURES[] = {
  692. {"we_s", 8}, {"fall", 8}, {"uf", 4}, {"lst", 4}, {"sst", 4}, {"rm", 4}, {"ds", 4}, {"sh", 4},
  693. {"ssee", 4}, {"riv_l", 4}, {"ds_s", 4}, {"sh_s", 4}, {"sse_s", 4}, {"swp", 4}, {"dsee", 4},
  694. {"shlm_", 4}, {"des0", 4}, {"edes0", 4}, {"rivs", 4}
  695. };
  696. /** Seconds that each frame of the animated textures lasts (the original timing is not known). */
  697. static const float ANIMATED_TEXTURE_FRAME_SECONDS = 0.125f;
  698. static void AnimateWorldMapTextures(const float delta_time){
  699. static float elapsed = 0;
  700. static long last_step = -1;
  701. elapsed += delta_time;
  702. const long step = static_cast<long>(elapsed / ANIMATED_TEXTURE_FRAME_SECONDS);
  703. if (step == last_step) return;
  704. last_step = step;
  705. for (const AnimatedTextureSet& set : ANIMATED_TEXTURES){
  706. MaterialPtr material = Ogre::MaterialManager::getSingleton().getByName(
  707. std::string("WorldMap_") + set.prefix + "1"
  708. );
  709. if (material.isNull()) continue;
  710. const std::string frame_name = std::string(set.prefix) + std::to_string(step % set.frames + 1);
  711. const std::string texture_name = std::string("WorldMapTex_") + frame_name;
  712. try{
  713. if (!Ogre::TextureManager::getSingleton().resourceExists(texture_name)){
  714. if (!ResourceGroupManager::getSingleton().resourceExists(
  715. WORLD_MAP_RESOURCE_GROUP, frame_name + ".tex"
  716. )) continue;
  717. LoadWorldMapTexture(frame_name);
  718. }
  719. material->getTechnique(0)->getPass(0)->getTextureUnitState(0)->setTextureName(texture_name);
  720. }
  721. catch (const Ogre::Exception&){}
  722. }
  723. }
  724. /**
  725. * The blizzard of WM3: two layers of the unused textures snow4 (cloud mist) and snow5 (dark blotches)
  726. * drift over the screen at different speeds. How the original draws it is not known.
  727. */
  728. struct SnowLayer{
  729. const char* texture;
  730. float alpha;
  731. float scroll_u;
  732. float scroll_v;
  733. float tiles_x;
  734. float tiles_y;
  735. };
  736. static const SnowLayer SNOW_LAYERS[] = {
  737. // The same texture three times, with other size, speed and direction (the opacities add up).
  738. {"snow4", 0.28f, 0.030f, 0.150f, 0.6f, 0.45f},
  739. {"snow4", 0.22f, -0.070f, 0.240f, 0.5f, 0.4f},
  740. {"snow4", 0.18f, 0.105f, 0.345f, 0.8f, 0.6f}
  741. // HIDDEN: {"snow5", 0.30f, -0.015f, 0.090f, 1.0f, 0.75f}
  742. };
  743. static void SetSnowOverlay(const bool visible){
  744. Ogre::OverlayManager& manager = Ogre::OverlayManager::getSingleton();
  745. Ogre::Overlay* overlay = manager.getByName("WorldMapSnow");
  746. if (overlay == nullptr){
  747. if (!visible) return;
  748. // The engine doesn't draw the overlays of Ogre unless its system listens to the scene.
  749. Ogre::OverlaySystem* overlay_system = VGears::Application::getSingleton().GetOverlaySystem();
  750. if (overlay_system != nullptr){
  751. Root::getSingleton().getSceneManager("Scene")->addRenderQueueListener(overlay_system);
  752. }
  753. overlay = manager.create("WorldMapSnow");
  754. overlay->setZOrder(100);
  755. int index = 0;
  756. for (const SnowLayer& layer : SNOW_LAYERS){
  757. // The same texture can be in several layers: the materials and panels are by index.
  758. const std::string name = std::string("WorldMapSnow_") + std::to_string(index) + "_" + layer.texture;
  759. try{
  760. if (!Ogre::TextureManager::getSingleton().resourceExists(std::string("WorldMapTex_") + layer.texture)){
  761. LoadWorldMapTexture(layer.texture);
  762. }
  763. }
  764. catch (const Ogre::Exception& exception){
  765. LogManager::getSingleton().logMessage(
  766. "Failed to load the snow texture " + std::string(layer.texture) + ": " + exception.getDescription()
  767. );
  768. continue;
  769. }
  770. MaterialPtr material = Ogre::MaterialManager::getSingleton().create(
  771. name, ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME
  772. );
  773. Pass* pass = material->getTechnique(0)->getPass(0);
  774. pass->setLightingEnabled(false);
  775. pass->setDepthCheckEnabled(false);
  776. pass->setDepthWriteEnabled(false);
  777. pass->setSceneBlending(Ogre::SBT_TRANSPARENT_ALPHA);
  778. Ogre::TextureUnitState* unit = pass->createTextureUnitState(std::string("WorldMapTex_") + layer.texture);
  779. unit->setTextureAddressingMode(Ogre::TextureUnitState::TAM_WRAP);
  780. unit->setAlphaOperation(Ogre::LBX_MODULATE, Ogre::LBS_TEXTURE, Ogre::LBS_MANUAL, 1.0f, layer.alpha);
  781. unit->setScrollAnimation(layer.scroll_u, layer.scroll_v);
  782. Ogre::PanelOverlayElement* panel = static_cast<Ogre::PanelOverlayElement*>(
  783. manager.createOverlayElement("Panel", name + "_panel")
  784. );
  785. panel->setMetricsMode(Ogre::GMM_RELATIVE);
  786. panel->setPosition(0.0f, 0.0f);
  787. panel->setDimensions(1.0f, 1.0f);
  788. panel->setMaterialName(name);
  789. panel->setTiling(layer.tiles_x, layer.tiles_y);
  790. overlay->add2D(panel);
  791. ++index;
  792. }
  793. }
  794. if (visible) overlay->show();
  795. else overlay->hide();
  796. LogManager::getSingleton().logMessage(
  797. std::string("World map snow overlay ") + (visible ? "shown" : "hidden") + ", layers: "
  798. + std::to_string(overlay->get2DElements().size())
  799. );
  800. }
  801. static MaterialPtr LoadTextureMaterial(uint16 texture_id){
  802. const std::string material_name
  803. = std::string("WorldMap_") + textures[texture_id].name;
  804. MaterialPtr material
  805. = Ogre::MaterialManager::getSingleton().getByName(material_name);
  806. // The textures and materials are kept when a map is replaced, and the maps share them.
  807. if (material.isNull()){
  808. TexturePtr texture = LoadWorldMapTexture(textures[texture_id].name);
  809. material = Ogre::MaterialManager::getSingleton().create(
  810. material_name, ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME
  811. );
  812. Pass* pass = material->getTechnique(0)->getPass(0);
  813. pass->createTextureUnitState(texture->getName());
  814. pass->setTextureFiltering(TFO_NONE);
  815. pass->setLightingEnabled(false);
  816. }
  817. return material;
  818. }
  819. /**
  820. * Gets if a position of the overworld (WM0) is over deep water. Used when the submarine
  821. * comes back from WM2, when WM0 is not loaded. Only the part of the world that WM2 covers is
  822. * read, and it's done once.
  823. */
  824. static bool IsOverworldDeepWater(const float x, const float z){
  825. struct Triangle{
  826. float x[3];
  827. float z[3];
  828. };
  829. static std::vector<Triangle> triangles;
  830. static bool loaded = false;
  831. if (!loaded){
  832. loaded = true;
  833. const MapLayout overworld = GetMapLayout(0);
  834. const MapLayout underwater = GetMapLayout(1);
  835. const float space = From16BitFixedPoint(8182);
  836. const std::vector<VGears::WorldmapFileSerializer::Block> blocks = LoadWorldMap("WM0.MAP");
  837. for (size_t block_index = 0; block_index < std::min(blocks.size(), size_t(63)); ++block_index){
  838. const int map_x = block_index % overworld.width;
  839. const int map_y = block_index / overworld.width;
  840. if (map_x < underwater.origin_x || map_x >= underwater.origin_x + underwater.width
  841. || map_y < underwater.origin_y || map_y >= underwater.origin_y + underwater.height){
  842. continue;
  843. }
  844. const VGears::WorldmapFileSerializer::Block& block = blocks[block_index];
  845. for (size_t mesh_index = 0; mesh_index < block.meshes.size(); ++mesh_index){
  846. const VGears::WorldmapFileSerializer::BlockPart& part = block.meshes[mesh_index];
  847. const float pos_x = ((mesh_index % 4) + map_x * 4) * space;
  848. const float pos_z = ((mesh_index / 4) + map_y * 4) * space;
  849. for (const VGears::WorldmapFileSerializer::BlockTriangle& triangle : part.triangles){
  850. if (triangle.walkability_info_ != VGears::WorldmapFileSerializer::SEA_DEEP_WATER){
  851. continue;
  852. }
  853. const size_t indices[3] = {
  854. triangle.vertex_0_index, triangle.vertex_1_index, triangle.vertex_2_index
  855. };
  856. Triangle result;
  857. for (int i = 0; i < 3; ++i){
  858. const VGears::WorldmapFileSerializer::Vertex& vertex = part.vertices.at(indices[i]);
  859. result.x[i] = From16BitFixedPoint(vertex.x) + pos_x;
  860. result.z[i] = From16BitFixedPoint(vertex.z) + pos_z;
  861. }
  862. triangles.push_back(result);
  863. }
  864. }
  865. }
  866. }
  867. for (const Triangle& t : triangles){
  868. const float denominator
  869. = (t.z[1] - t.z[2]) * (t.x[0] - t.x[2]) + (t.x[2] - t.x[1]) * (t.z[0] - t.z[2]);
  870. if (Ogre::Math::Abs(denominator) < 1e-6f) continue;
  871. const float a = ((t.z[1] - t.z[2]) * (x - t.x[2]) + (t.x[2] - t.x[1]) * (z - t.z[2]))
  872. / denominator;
  873. const float b = ((t.z[2] - t.z[0]) * (x - t.x[2]) + (t.x[0] - t.x[2]) * (z - t.z[2]))
  874. / denominator;
  875. const float c = 1.0f - a - b;
  876. if (a >= -1e-4f && b >= -1e-4f && c >= -1e-4f) return true;
  877. }
  878. return false;
  879. }
  880. WorldmapModule::WorldmapModule():
  881. scene_manager_(nullptr),
  882. world_map_node_(nullptr),
  883. player_entity_(nullptr),
  884. highwind_entity_(nullptr),
  885. buggy_entity_(nullptr),
  886. chocobo_entity_(nullptr),
  887. submarine_entity_(nullptr),
  888. tiny_bronco_entity_(nullptr),
  889. current_vehicle_(VehicleType::ON_FOOT),
  890. map_id_(-1),
  891. grid_width_(9),
  892. grid_height_(7),
  893. camera_yaw_(0),
  894. flight_active_(false),
  895. flight_entity_(nullptr),
  896. flight_heading_(0),
  897. flight_y_(0),
  898. origin_x_(0),
  899. origin_y_(0),
  900. player_height_offset_(0),
  901. active_function_mesh_index_(-1),
  902. active_function_id_(-1),
  903. initialized_(false),
  904. frame_listener_attached_(false),
  905. cancel_was_pressed_(false),
  906. confirm_was_pressed_(false),
  907. transition_stage_(TransitionStage::NONE),
  908. transition_dive_(true),
  909. transition_timer_(0),
  910. transition_start_y_(0),
  911. transition_target_y_(0),
  912. surface_requested_(false),
  913. surface_position_(Ogre::Vector3::ZERO),
  914. surface_heading_(0),
  915. dive_requested_(false),
  916. dive_position_(Ogre::Vector3::ZERO),
  917. dive_heading_(0),
  918. encounter_frames_(0),
  919. encounter_accumulator_(0),
  920. encounter_last_battle_(-1),
  921. encounters_locked_(false),
  922. paused_for_battle_(false)
  923. {}
  924. WorldmapModule::~WorldmapModule(){
  925. if (frame_listener_attached_) Root::getSingleton().removeFrameListener(this);
  926. if (scene_manager_ != nullptr && world_map_node_ != nullptr){
  927. scene_manager_->getRootSceneNode()->removeAndDestroyChild("WorldMapTerrain");
  928. }
  929. }
  930. void WorldmapModule::CreateWorldMap(SceneManager* scene_manager){
  931. scene_manager_ = scene_manager;
  932. // The node is kept when a map is replaced.
  933. if (world_map_node_ == nullptr){
  934. world_map_node_ = scene_manager_->getRootSceneNode()
  935. ->createChildSceneNode("WorldMapTerrain");
  936. }
  937. world_map_node_->setVisible(true);
  938. std::vector<VGears::WorldmapFileSerializer::Block> blocks
  939. = LoadWorldMap("WM" + std::to_string(WORLD_MAP_FILE_NUMBERS[map_id_]) + ".MAP");
  940. if (GetTextureIdOffset(map_id_) != 0){
  941. for (auto& block : blocks) for (auto& mesh : block.meshes) for (auto& triangle : mesh.triangles){
  942. triangle.TextureInfo += GetTextureIdOffset(map_id_);
  943. }
  944. }
  945. const size_t texture_count = sizeof(textures) / sizeof(textures[0]);
  946. // WM0 has extra blocks after the 9x7 grid: the alternate shapes of the story progress.
  947. const size_t base_block_count = map_id_ == 0
  948. ? std::min(blocks.size(), size_t(63)) : blocks.size();
  949. const float space = From16BitFixedPoint(8182);
  950. std::map<uint16, ManualObject*> texture_objects;
  951. std::set<uint16> unavailable_texture_ids;
  952. unsigned int manual_index = 0;
  953. for (size_t block_index = 0; block_index < base_block_count; ++block_index){
  954. const VGears::WorldmapFileSerializer::Block& block = blocks[block_index];
  955. const size_t map_x = origin_x_ + block_index % grid_width_;
  956. const size_t map_y = origin_y_ + block_index / grid_width_;
  957. for (size_t mesh_index = 0; mesh_index < block.meshes.size(); ++mesh_index){
  958. const VGears::WorldmapFileSerializer::BlockPart& part
  959. = block.meshes[mesh_index];
  960. const size_t mesh_x = mesh_index % 4;
  961. const size_t mesh_y = mesh_index / 4;
  962. const float pos_x = (mesh_x * space) + (map_x * space * 4);
  963. const float pos_z = (mesh_y * space) + (map_y * space * 4);
  964. for (const VGears::WorldmapFileSerializer::BlockTriangle& triangle
  965. : part.triangles){
  966. const VGears::WorldmapFileSerializer::Vertex& vertex_0
  967. = part.vertices.at(triangle.vertex_0_index);
  968. const VGears::WorldmapFileSerializer::Vertex& vertex_1
  969. = part.vertices.at(triangle.vertex_1_index);
  970. const VGears::WorldmapFileSerializer::Vertex& vertex_2
  971. = part.vertices.at(triangle.vertex_2_index);
  972. TerrainTriangle terrain_triangle;
  973. terrain_triangle.vertices[0] = Ogre::Vector3(
  974. From16BitFixedPoint(vertex_0.x) + pos_x,
  975. From16BitFixedPoint(vertex_0.y),
  976. From16BitFixedPoint(vertex_0.z) + pos_z
  977. );
  978. terrain_triangle.vertices[1] = Ogre::Vector3(
  979. From16BitFixedPoint(vertex_1.x) + pos_x,
  980. From16BitFixedPoint(vertex_1.y),
  981. From16BitFixedPoint(vertex_1.z) + pos_z
  982. );
  983. terrain_triangle.vertices[2] = Ogre::Vector3(
  984. From16BitFixedPoint(vertex_2.x) + pos_x,
  985. From16BitFixedPoint(vertex_2.y),
  986. From16BitFixedPoint(vertex_2.z) + pos_z
  987. );
  988. terrain_triangle.walkability_type = triangle.walkability_info_;
  989. terrain_triangle.function_id = triangle.function_id;
  990. terrain_triangle.mesh_x = static_cast<int>(map_x * 4 + mesh_x);
  991. terrain_triangle.mesh_y = static_cast<int>(map_y * 4 + mesh_y);
  992. // The 5 lower bits of the location are the region of the random encounters.
  993. terrain_triangle.region = std::min<int>(triangle.Location & 0x1F, 15);
  994. terrain_triangles_.push_back(terrain_triangle);
  995. if (unavailable_texture_ids.find(triangle.TextureInfo)
  996. != unavailable_texture_ids.end()){
  997. continue;
  998. }
  999. if (triangle.TextureInfo >= texture_count){
  1000. if (unavailable_texture_ids.insert(triangle.TextureInfo).second){
  1001. LogManager::getSingleton().logMessage(
  1002. "Skipping world-map texture ID "
  1003. + std::to_string(triangle.TextureInfo)
  1004. + ": no PC texture mapping is available."
  1005. );
  1006. }
  1007. continue;
  1008. }
  1009. ManualObject* manual = nullptr;
  1010. auto object = texture_objects.find(triangle.TextureInfo);
  1011. if (object == texture_objects.end()){
  1012. MaterialPtr material;
  1013. try{
  1014. material = LoadTextureMaterial(triangle.TextureInfo);
  1015. }
  1016. catch (const Ogre::Exception& exception){
  1017. unavailable_texture_ids.insert(triangle.TextureInfo);
  1018. LogManager::getSingleton().logMessage(
  1019. "Failed to load world-map texture "
  1020. + std::string(textures[triangle.TextureInfo].name)
  1021. + ": " + exception.getDescription()
  1022. );
  1023. continue;
  1024. }
  1025. manual = scene_manager->createManualObject(
  1026. "world_map_surface_" + std::to_string(++manual_index)
  1027. );
  1028. manual->begin(material->getName(), RenderOperation::OT_TRIANGLE_LIST);
  1029. manual->setDebugDisplayEnabled(false);
  1030. manual->setDynamic(false);
  1031. texture_objects[triangle.TextureInfo] = manual;
  1032. }
  1033. else manual = object->second;
  1034. manual->position(
  1035. terrain_triangle.vertices[2].x,
  1036. terrain_triangle.vertices[2].y,
  1037. terrain_triangle.vertices[2].z
  1038. );
  1039. manual->textureCoord(
  1040. ToTextureCoordU(triangle.vertex_2_u, triangle.TextureInfo),
  1041. ToTextureCoordV(triangle.vertex_2_v, triangle.TextureInfo)
  1042. );
  1043. manual->position(
  1044. terrain_triangle.vertices[1].x,
  1045. terrain_triangle.vertices[1].y,
  1046. terrain_triangle.vertices[1].z
  1047. );
  1048. manual->textureCoord(
  1049. ToTextureCoordU(triangle.vertex_1_u, triangle.TextureInfo),
  1050. ToTextureCoordV(triangle.vertex_1_v, triangle.TextureInfo)
  1051. );
  1052. manual->position(
  1053. terrain_triangle.vertices[0].x,
  1054. terrain_triangle.vertices[0].y,
  1055. terrain_triangle.vertices[0].z
  1056. );
  1057. manual->textureCoord(
  1058. ToTextureCoordU(triangle.vertex_0_u, triangle.TextureInfo),
  1059. ToTextureCoordV(triangle.vertex_0_v, triangle.TextureInfo)
  1060. );
  1061. }
  1062. }
  1063. }
  1064. for (const auto& texture_object : texture_objects){
  1065. texture_object.second->end();
  1066. world_map_node_->attachObject(texture_object.second);
  1067. }
  1068. BuildTerrainIndex();
  1069. const float map_center_x = space * (origin_x_ * 4.0f + grid_width_ * 2.0f);
  1070. const float map_center_z = space * (origin_y_ * 4.0f + grid_height_ * 2.0f);
  1071. Ogre::Camera* camera = CameraManager::getSingleton().GetCurrentCamera();
  1072. camera->setPosition(Ogre::Vector3(map_center_x, 80.0f, map_center_z + 90.0f));
  1073. camera->lookAt(Ogre::Vector3(map_center_x, 0.0f, map_center_z));
  1074. }
  1075. void WorldmapModule::CreatePlayer(){
  1076. Ogre::Vector3 requested_spawn = GetSpawn("Cloud", Ogre::Vector3(42.0f, 0.0f, 36.5f));
  1077. Ogre::Vector3 spawn_position;
  1078. bool spawn_found;
  1079. if (map_id_ == 0){
  1080. // A given spawn point (from a field exit) can be on any terrain, like a town or a forest.
  1081. const bool given_spawn = spawn_overrides_.find("Cloud") != spawn_overrides_.end();
  1082. spawn_found = given_spawn
  1083. ? FindWalkableSurface(requested_spawn, spawn_position, false, false)
  1084. : FindWalkableSurface(requested_spawn, spawn_position, true);
  1085. }
  1086. else{
  1087. // Spawn points of the other maps are unknown: use the walkable triangle closest to the
  1088. // center of the map, or to the position where the submarine dived.
  1089. const Ogre::Real space = From16BitFixedPoint(8182);
  1090. const Ogre::Vector3 center = dive_requested_ ? dive_position_ : Ogre::Vector3(
  1091. space * (origin_x_ * 4.0f + grid_width_ * 2.0f), 0.0f,
  1092. space * (origin_y_ * 4.0f + grid_height_ * 2.0f)
  1093. );
  1094. Ogre::Real best_distance = std::numeric_limits<Ogre::Real>::max();
  1095. // The exact position of the dive, if the submarine can be there.
  1096. const bool exact_dive_position = dive_requested_
  1097. && FindWalkableSurface(dive_position_, spawn_position, false, true);
  1098. if (exact_dive_position) best_distance = 0;
  1099. else for (const TerrainTriangle& triangle : terrain_triangles_){
  1100. const Ogre::Vector3 centroid
  1101. = (triangle.vertices[0] + triangle.vertices[1] + triangle.vertices[2]) / 3.0f;
  1102. if (map_id_ == 1 ? (UNDERWATER_HEIGHT_LIMIT_ENABLED
  1103. && centroid.y + FLIGHT_MIN_CLEARANCE > UNDERWATER_MAX_HEIGHT)
  1104. : !IsActiveTerrainAllowed(triangle.walkability_type)) continue;
  1105. const Ogre::Real distance = Ogre::Vector2(
  1106. centroid.x - center.x, centroid.z - center.z
  1107. ).squaredLength();
  1108. if (distance < best_distance){
  1109. best_distance = distance;
  1110. requested_spawn = centroid;
  1111. }
  1112. }
  1113. spawn_found = exact_dive_position || (
  1114. best_distance < std::numeric_limits<Ogre::Real>::max()
  1115. && FindWalkableSurface(requested_spawn, spawn_position, false)
  1116. );
  1117. }
  1118. if (!spawn_found){
  1119. LogManager::getSingleton().logMessage(
  1120. "World map " + std::to_string(map_id_) + " has no walkable surface for Cloud's spawn."
  1121. );
  1122. return;
  1123. }
  1124. if (map_id_ == 1){
  1125. // The underwater map is played with the submarine only.
  1126. AddWorldModel(
  1127. "Submarine", "ddd.mesh", spawn_position, From16BitFixedPoint(8182) * 0.1125f,
  1128. Ogre::Quaternion::IDENTITY, 1.0f, false
  1129. );
  1130. submarine_entity_ = static_cast<EntityModel*>(
  1131. EntityManager::getSingleton().GetEntity("WorldMapSubmarine")
  1132. );
  1133. if (submarine_entity_ == nullptr) return;
  1134. player_entity_ = submarine_entity_;
  1135. player_height_offset_ = 0;
  1136. if (dive_requested_){
  1137. // Same heading as in WM0.
  1138. submarine_entity_->GetModel()->getParentSceneNode()->getParentSceneNode()
  1139. ->setOrientation(Ogre::Quaternion(Ogre::Radian(dive_heading_), Ogre::Vector3::UNIT_Y));
  1140. dive_requested_ = false;
  1141. }
  1142. // It floats over the seabed.
  1143. submarine_entity_->SetPosition(
  1144. submarine_entity_->GetPosition() + Ogre::Vector3(0, SUBMARINE_START_CLEARANCE, 0)
  1145. );
  1146. EntityManager::getSingleton().ScriptSetPlayerEntity("WorldMapSubmarine");
  1147. UpdateCamera(0, true);
  1148. return;
  1149. }
  1150. LogManager::getSingleton().logMessage(
  1151. "Spawning Cloud at "
  1152. + Ogre::StringConverter::toString(spawn_position.x) + ", "
  1153. + Ogre::StringConverter::toString(spawn_position.z)
  1154. );
  1155. player_entity_ = EntityManager::getSingleton().AddWorldMapEntity(
  1156. "WorldMapCloud", "cloud.mesh", spawn_position, Ogre::Degree(0),
  1157. Ogre::Vector3::UNIT_SCALE, "FIELD_MODELS"
  1158. );
  1159. if (player_entity_ == nullptr) return;
  1160. // Cloud's bounds without animations. The bounds in the mesh can't be used for sizing: the
  1161. // installer enlarges them with the animations' movement, so the model is not culled.
  1162. const Ogre::AxisAlignedBox bounds(
  1163. -8.7473f, -8.1671f, -4.1878f, 7.8685f, 5.6837f, 22.8135f
  1164. );
  1165. const Ogre::Vector3 model_size = bounds.getSize();
  1166. const Ogre::Real model_height = model_size.y;
  1167. if (model_height > 0){
  1168. const Ogre::Real scale = From16BitFixedPoint(8182) * 0.45f * 0.25f * 0.25f
  1169. / model_height;
  1170. player_entity_->setScale(Ogre::Vector3::UNIT_SCALE * scale);
  1171. player_entity_->SetHeight(model_height * scale);
  1172. player_entity_->SetSolidRadius(
  1173. std::max(model_size.x, model_size.z) * scale * 0.5f
  1174. );
  1175. player_entity_->SetCollisionDebugOrientation(
  1176. Ogre::Quaternion(Ogre::Degree(-90), Ogre::Vector3::UNIT_X)
  1177. );
  1178. // Only solid entities can interact with the vehicles.
  1179. player_entity_->SetSolid(true);
  1180. player_height_offset_ = -bounds.getMinimum().y * scale;
  1181. spawn_position.y += player_height_offset_;
  1182. player_entity_->SetPosition(spawn_position);
  1183. Ogre::AnimationStateSet* animations
  1184. = player_entity_->GetModel()->getAllAnimationStates();
  1185. if (animations == nullptr || !animations->hasAnimationState("Walk")){
  1186. LogManager::getSingleton().logMessage(
  1187. "Cloud model has no Walk animation state."
  1188. );
  1189. }
  1190. EntityManager::getSingleton().ScriptSetPlayerEntity("WorldMapCloud");
  1191. player_entity_->PlayAnimationContinue("Idle");
  1192. // Vehicles and companions are only placed in the overworld.
  1193. if (map_id_ == 0){
  1194. CreateCompanionModels();
  1195. // Coming back from WM2: everything is where it was, except for the submarine.
  1196. if (surface_requested_){
  1197. RestoreOverworldSnapshot();
  1198. PlaceSurfacedSubmarine();
  1199. }
  1200. overworld_snapshot_.clear();
  1201. }
  1202. UpdateCamera(0, true);
  1203. }
  1204. }
  1205. void WorldmapModule::AddWorldModel(
  1206. const Ogre::String& name, const Ogre::String& mesh_name,
  1207. const Ogre::Vector3& desired_position, Ogre::Real target_size,
  1208. const Ogre::Quaternion& orientation, Ogre::Real collision_radius_scale,
  1209. bool talkable, Ogre::Real explicit_scale
  1210. ){
  1211. Ogre::Vector3 surface_position;
  1212. if (!FindWalkableSurface(desired_position, surface_position, false, false)){
  1213. LogManager::getSingleton().logMessage(
  1214. "No terrain surface found for world-map model '" + name + "'."
  1215. );
  1216. return;
  1217. }
  1218. EntityModel* entity = nullptr;
  1219. try{
  1220. entity = EntityManager::getSingleton().AddWorldMapEntity(
  1221. "WorldMap" + name, mesh_name, surface_position,
  1222. Ogre::Degree(0), Ogre::Vector3::UNIT_SCALE, "WORLD_MODELS"
  1223. );
  1224. }
  1225. catch (const Ogre::Exception& exception){
  1226. LogManager::getSingleton().logMessage(
  1227. "Failed to load world-map model '" + mesh_name + "': "
  1228. + exception.getDescription()
  1229. );
  1230. return;
  1231. }
  1232. if (entity == nullptr) return;
  1233. const Ogre::Vector3 bounds_size = entity->GetModel()->getBoundingBox().getSize();
  1234. const Ogre::Real largest_dimension = std::max(
  1235. bounds_size.x, std::max(bounds_size.y, bounds_size.z)
  1236. );
  1237. if (largest_dimension <= 0){
  1238. LogManager::getSingleton().logMessage(
  1239. "World-map model '" + mesh_name + "' has empty bounds."
  1240. );
  1241. return;
  1242. }
  1243. // The scale of the model: the size of its largest dimension, or the one that is given.
  1244. const Ogre::Real model_scale = explicit_scale > 0 ? explicit_scale
  1245. : target_size / largest_dimension;
  1246. const Ogre::Vector3 oriented_x = orientation * Ogre::Vector3::UNIT_X;
  1247. const Ogre::Vector3 oriented_y = orientation * Ogre::Vector3::UNIT_Y;
  1248. const Ogre::Vector3 oriented_z = orientation * Ogre::Vector3::UNIT_Z;
  1249. const Ogre::Real world_width =
  1250. Ogre::Math::Abs(oriented_x.x) * bounds_size.x
  1251. + Ogre::Math::Abs(oriented_y.x) * bounds_size.y
  1252. + Ogre::Math::Abs(oriented_z.x) * bounds_size.z;
  1253. const Ogre::Real world_height =
  1254. Ogre::Math::Abs(oriented_x.y) * bounds_size.x
  1255. + Ogre::Math::Abs(oriented_y.y) * bounds_size.y
  1256. + Ogre::Math::Abs(oriented_z.y) * bounds_size.z;
  1257. const Ogre::Real world_depth =
  1258. Ogre::Math::Abs(oriented_x.z) * bounds_size.x
  1259. + Ogre::Math::Abs(oriented_y.z) * bounds_size.y
  1260. + Ogre::Math::Abs(oriented_z.z) * bounds_size.z;
  1261. entity->setRootOrientation(orientation);
  1262. entity->setScale(Ogre::Vector3::UNIT_SCALE * model_scale);
  1263. entity->SetSolid(true);
  1264. entity->SetHeight(world_height * model_scale);
  1265. entity->SetSolidRadius(
  1266. std::max(world_width, world_depth) * model_scale * 0.5f
  1267. * collision_radius_scale
  1268. );
  1269. entity->SetTalkable(talkable);
  1270. if (talkable) entity->SetTalkRadius(entity->GetSolidRadius());
  1271. // The submarine of the overworld is partially under the surface of the water. Only the
  1272. // model is lowered, so its position and collision are the same.
  1273. if (map_id_ == 0 && name == "Submarine"){
  1274. SetModelHeightOffset(entity, -SUBMARINE_SUBMERGED_DEPTH);
  1275. }
  1276. entity->SetCollisionDebugOrientation(
  1277. Ogre::Quaternion(Ogre::Degree(-90), Ogre::Vector3::UNIT_X)
  1278. );
  1279. LogManager::getSingleton().logMessage(
  1280. "Placed world-map model '" + name + "' at "
  1281. + Ogre::StringConverter::toString(surface_position.x) + ", "
  1282. + Ogre::StringConverter::toString(surface_position.z)
  1283. );
  1284. }
  1285. void WorldmapModule::CreateCompanionModels(){
  1286. // These models and their spawn points are now hardcoded, they mmust be
  1287. // loaded according to the story point and save game data.
  1288. const Ogre::Real space = From16BitFixedPoint(8182);
  1289. AddWorldModel(
  1290. "Chocobo", "aja.mesh",
  1291. GetSpawn("Chocobo", Ogre::Vector3(42.5f, 0.0f, 37.5f)),
  1292. space * 0.14f,
  1293. // The animations of the model (asc) already have it the right way up.
  1294. Ogre::Quaternion::IDENTITY, 1.0f, true
  1295. );
  1296. AddWorldModel(
  1297. "Highwind", "cgd.mesh",
  1298. GetSpawn("Highwind", Ogre::Vector3(43.0f, 0.0f, 36.5f)),
  1299. space * 0.25f,
  1300. // The animation of the model (cic) already has it the right way up.
  1301. Ogre::Quaternion::IDENTITY, 0.5f, true
  1302. );
  1303. AddWorldModel(
  1304. "Buggy", "aba.mesh",
  1305. GetSpawn("Buggy", Ogre::Vector3(42.0f, 0.0f, 36.0f)),
  1306. space * 0.3f, Ogre::Quaternion::IDENTITY, 0.5f, true
  1307. );
  1308. AddWorldModel(
  1309. "Submarine", "ddd.mesh",
  1310. GetSpawn("Submarine", Ogre::Vector3(41.5f, 0.0f, 36.5f)),
  1311. space * 0.1125f, Ogre::Quaternion::IDENTITY, 1.0f, true
  1312. );
  1313. AddWorldModel(
  1314. "TinyBronco", "dva.mesh",
  1315. GetSpawn("TinyBronco", Ogre::Vector3(42.0f, 0.0f, 37.37f)),
  1316. space * 0.15f, Ogre::Quaternion::IDENTITY, 0.75f, true
  1317. );
  1318. highwind_entity_ = static_cast<EntityModel*>(
  1319. EntityManager::getSingleton().GetEntity("WorldMapHighwind")
  1320. );
  1321. buggy_entity_ = static_cast<EntityModel*>(
  1322. EntityManager::getSingleton().GetEntity("WorldMapBuggy")
  1323. );
  1324. chocobo_entity_ = static_cast<EntityModel*>(
  1325. EntityManager::getSingleton().GetEntity("WorldMapChocobo")
  1326. );
  1327. submarine_entity_ = static_cast<EntityModel*>(
  1328. EntityManager::getSingleton().GetEntity("WorldMapSubmarine")
  1329. );
  1330. tiny_bronco_entity_ = static_cast<EntityModel*>(
  1331. EntityManager::getSingleton().GetEntity("WorldMapTinyBronco")
  1332. );
  1333. for (const Ogre::String& name : hidden_vehicles_){
  1334. ::Entity* entity = EntityManager::getSingleton().GetEntity("WorldMap" + name);
  1335. if (entity == nullptr) continue;
  1336. entity->SetVisible(false);
  1337. entity->SetSolid(false);
  1338. entity->SetTalkable(false);
  1339. }
  1340. }
  1341. void WorldmapModule::BuildTerrainIndex(){
  1342. terrain_grid_.clear();
  1343. terrain_grid_columns_ = 0;
  1344. terrain_grid_rows_ = 0;
  1345. if (terrain_triangles_.empty()) return;
  1346. float min_x = std::numeric_limits<float>::max(), min_z = min_x;
  1347. float max_x = -min_x, max_z = -min_x;
  1348. for (const TerrainTriangle& triangle : terrain_triangles_){
  1349. for (const Ogre::Vector3& vertex : triangle.vertices){
  1350. min_x = std::min(min_x, vertex.x); max_x = std::max(max_x, vertex.x);
  1351. min_z = std::min(min_z, vertex.z); max_z = std::max(max_z, vertex.z);
  1352. }
  1353. }
  1354. // A cell is as big as a mesh of the map (a triangle almost always touches only one).
  1355. terrain_grid_cell_ = From16BitFixedPoint(8182);
  1356. terrain_grid_min_x_ = min_x;
  1357. terrain_grid_min_z_ = min_z;
  1358. terrain_grid_columns_ = static_cast<int>((max_x - min_x) / terrain_grid_cell_) + 1;
  1359. terrain_grid_rows_ = static_cast<int>((max_z - min_z) / terrain_grid_cell_) + 1;
  1360. terrain_grid_.resize(static_cast<size_t>(terrain_grid_columns_) * terrain_grid_rows_);
  1361. // The tolerance of the search (a point a little outside of the edge still counts).
  1362. const float margin = 0.01f;
  1363. for (size_t i = 0; i < terrain_triangles_.size(); ++i){
  1364. const TerrainTriangle& triangle = terrain_triangles_[i];
  1365. float t_min_x = triangle.vertices[0].x, t_max_x = t_min_x;
  1366. float t_min_z = triangle.vertices[0].z, t_max_z = t_min_z;
  1367. for (const Ogre::Vector3& vertex : triangle.vertices){
  1368. t_min_x = std::min(t_min_x, vertex.x); t_max_x = std::max(t_max_x, vertex.x);
  1369. t_min_z = std::min(t_min_z, vertex.z); t_max_z = std::max(t_max_z, vertex.z);
  1370. }
  1371. const int column_0 = std::max(0, static_cast<int>(std::floor((t_min_x - margin - min_x) / terrain_grid_cell_)));
  1372. const int column_1 = std::min(terrain_grid_columns_ - 1, static_cast<int>(std::floor((t_max_x + margin - min_x) / terrain_grid_cell_)));
  1373. const int row_0 = std::max(0, static_cast<int>(std::floor((t_min_z - margin - min_z) / terrain_grid_cell_)));
  1374. const int row_1 = std::min(terrain_grid_rows_ - 1, static_cast<int>(std::floor((t_max_z + margin - min_z) / terrain_grid_cell_)));
  1375. for (int row = row_0; row <= row_1; ++row){
  1376. for (int column = column_0; column <= column_1; ++column){
  1377. terrain_grid_[static_cast<size_t>(row) * terrain_grid_columns_ + column].push_back(static_cast<uint32>(i));
  1378. }
  1379. }
  1380. }
  1381. size_t entries = 0;
  1382. for (const auto& cell : terrain_grid_) entries += cell.size();
  1383. LogManager::getSingleton().logMessage(
  1384. "World map terrain index: " + std::to_string(terrain_triangles_.size()) + " triangles in "
  1385. + std::to_string(terrain_grid_columns_) + "x" + std::to_string(terrain_grid_rows_) + " cells, "
  1386. + std::to_string(entries) + " entries"
  1387. );
  1388. }
  1389. bool WorldmapModule::FindWalkableSurface(
  1390. const Ogre::Vector3& position, Ogre::Vector3& surface, bool grass_only,
  1391. bool require_walkable, uint8* walkability_type, size_t* triangle_index, bool use_index
  1392. ) const{
  1393. bool found = false;
  1394. Ogre::Real closest_height_distance = std::numeric_limits<Ogre::Real>::max();
  1395. // Only the triangles of the cell of the position (the index is in ascending order, so the result
  1396. // is the same as with all of them).
  1397. const std::vector<uint32>* cell_triangles = nullptr;
  1398. if (use_index && !terrain_grid_.empty()){
  1399. const int column = static_cast<int>(std::floor((position.x - terrain_grid_min_x_) / terrain_grid_cell_));
  1400. const int row = static_cast<int>(std::floor((position.z - terrain_grid_min_z_) / terrain_grid_cell_));
  1401. if (column < 0 || row < 0 || column >= terrain_grid_columns_ || row >= terrain_grid_rows_) return false;
  1402. cell_triangles = &terrain_grid_[static_cast<size_t>(row) * terrain_grid_columns_ + column];
  1403. }
  1404. const size_t candidate_count = cell_triangles != nullptr ? cell_triangles->size() : terrain_triangles_.size();
  1405. for (size_t candidate = 0; candidate < candidate_count; ++candidate){
  1406. const size_t i = cell_triangles != nullptr ? (*cell_triangles)[candidate] : candidate;
  1407. const TerrainTriangle& triangle = terrain_triangles_[i];
  1408. if (grass_only
  1409. && triangle.walkability_type != VGears::WorldmapFileSerializer::GRASS){
  1410. continue;
  1411. }
  1412. const Ogre::Vector3& a = triangle.vertices[0];
  1413. const Ogre::Vector3& b = triangle.vertices[1];
  1414. const Ogre::Vector3& c = triangle.vertices[2];
  1415. const Ogre::Real denominator
  1416. = (b.z - c.z) * (a.x - c.x) + (c.x - b.x) * (a.z - c.z);
  1417. if (Ogre::Math::Abs(denominator) < 1e-6f) continue;
  1418. const Ogre::Real weight_a
  1419. = ((b.z - c.z) * (position.x - c.x)
  1420. + (c.x - b.x) * (position.z - c.z)) / denominator;
  1421. const Ogre::Real weight_b
  1422. = ((c.z - a.z) * (position.x - c.x)
  1423. + (a.x - c.x) * (position.z - c.z)) / denominator;
  1424. const Ogre::Real weight_c = 1.0f - weight_a - weight_b;
  1425. if (weight_a < -1e-4f || weight_b < -1e-4f || weight_c < -1e-4f){
  1426. continue;
  1427. }
  1428. const Ogre::Real height
  1429. = weight_a * a.y + weight_b * b.y + weight_c * c.y;
  1430. const Ogre::Real height_distance = Ogre::Math::Abs(height - position.y);
  1431. if (height_distance >= closest_height_distance) continue;
  1432. closest_height_distance = height_distance;
  1433. found = !require_walkable || (map_id_ == 1
  1434. // Underwater: every terrain type is allowed, but there is a height limit.
  1435. ? (!UNDERWATER_HEIGHT_LIMIT_ENABLED
  1436. || height + FLIGHT_MIN_CLEARANCE <= UNDERWATER_MAX_HEIGHT)
  1437. : IsActiveTerrainAllowed(triangle.walkability_type));
  1438. surface = Ogre::Vector3(position.x, height, position.z);
  1439. if (walkability_type != nullptr) *walkability_type = triangle.walkability_type;
  1440. if (triangle_index != nullptr) *triangle_index = i;
  1441. }
  1442. return found;
  1443. }
  1444. void WorldmapModule::ClearVehicleTerrains(){
  1445. active_vehicle_terrain_types_.clear();
  1446. }
  1447. void WorldmapModule::AddVehicleTerrain(const char* terrain_name){
  1448. if (terrain_name == nullptr) return;
  1449. const auto terrain = GetWorldMapTerrainTypes().find(terrain_name);
  1450. if (terrain == GetWorldMapTerrainTypes().end()){
  1451. LogManager::getSingleton().logMessage(
  1452. "Unknown world-map vehicle terrain '" + Ogre::String(terrain_name) + "'."
  1453. );
  1454. return;
  1455. }
  1456. if (std::find(
  1457. active_vehicle_terrain_types_.begin(), active_vehicle_terrain_types_.end(),
  1458. terrain->second
  1459. ) == active_vehicle_terrain_types_.end()){
  1460. active_vehicle_terrain_types_.push_back(terrain->second);
  1461. }
  1462. }
  1463. bool WorldmapModule::IsActiveTerrainAllowed(uint8 walkability_type) const{
  1464. if (current_vehicle_ == VehicleType::ON_FOOT){
  1465. return IsFootWalkable(walkability_type);
  1466. }
  1467. return std::find(
  1468. active_vehicle_terrain_types_.begin(), active_vehicle_terrain_types_.end(),
  1469. walkability_type
  1470. ) != active_vehicle_terrain_types_.end();
  1471. }
  1472. bool WorldmapModule::DiveToUnderwaterMap(EntityModel* submarine){
  1473. const Ogre::Vector3 position = submarine->GetPosition();
  1474. Ogre::Vector3 surface;
  1475. uint8 walkability_type = 0;
  1476. if (!FindWalkableSurface(position, surface, false, false, &walkability_type)
  1477. || walkability_type != VGears::WorldmapFileSerializer::SEA_DEEP_WATER){
  1478. return false;
  1479. }
  1480. // WM2 only covers a part of the world.
  1481. if (!IsInsideMap(1, position.x, position.z)){
  1482. LogManager::getSingleton().logMessage(
  1483. "The submarine can't dive here: it's outside the underwater map."
  1484. );
  1485. return false;
  1486. }
  1487. dive_requested_ = true;
  1488. dive_position_ = position;
  1489. dive_heading_ = submarine->GetModel()->getParentSceneNode()->getParentSceneNode()
  1490. ->getOrientation().getYaw().valueRadians();
  1491. BeginTransition(true, submarine);
  1492. return true;
  1493. }
  1494. /**
  1495. * Sets how opaque the black cover of the screen is.
  1496. *
  1497. * @param[in] alpha 0 shows the world map, 1 is all black.
  1498. */
  1499. static void SetScreenCover(const float alpha){
  1500. UiWidget* cover = UiManager::getSingleton().GetWidget("Fade.Screen");
  1501. if (cover == nullptr) return;
  1502. cover->SetColour(0, 0, 0);
  1503. cover->SetAlpha(std::max(0.0f, std::min(1.0f, alpha)));
  1504. }
  1505. /// Eases a progress from 0 to 1.
  1506. static float Smooth(const float t){
  1507. const float clamped = std::max(0.0f, std::min(1.0f, t));
  1508. return clamped * clamped * (3.0f - 2.0f * clamped);
  1509. }
  1510. void WorldmapModule::BeginTransition(const bool dive, EntityModel* submarine){
  1511. transition_stage_ = TransitionStage::LEAVING;
  1512. transition_dive_ = dive;
  1513. transition_timer_ = 0;
  1514. transition_start_y_ = submarine->GetPosition().y;
  1515. // Diving: it sinks under the surface. Surfacing: it goes up, out of the map.
  1516. transition_target_y_ = dive ? transition_start_y_ - DIVE_SINK_DEPTH : DIVE_HIGH_HEIGHT;
  1517. EntityManager::getSingleton().ScriptPlayerLock(true);
  1518. }
  1519. void WorldmapModule::EndTransition(){
  1520. transition_stage_ = TransitionStage::NONE;
  1521. SetScreenCover(0);
  1522. EntityManager::getSingleton().ScriptPlayerLock(false);
  1523. }
  1524. void WorldmapModule::UpdateTransition(const Ogre::Real delta_time){
  1525. transition_timer_ += delta_time;
  1526. ::Entity* submarine = EntityManager::getSingleton().ScriptGetPlayerEntity();
  1527. if (submarine == nullptr){
  1528. EndTransition();
  1529. return;
  1530. }
  1531. const auto set_height = [submarine](const float y){
  1532. Ogre::Vector3 position = submarine->GetPosition();
  1533. position.y = y;
  1534. submarine->SetPosition(position);
  1535. };
  1536. if (transition_stage_ == TransitionStage::LEAVING){
  1537. const float duration = transition_dive_ ? DIVE_SINK_TIME : DIVE_HIGH_TIME;
  1538. set_height(
  1539. transition_start_y_
  1540. + (transition_target_y_ - transition_start_y_) * Smooth(transition_timer_ / duration)
  1541. );
  1542. if (transition_timer_ >= duration){
  1543. transition_stage_ = TransitionStage::FADING_OUT;
  1544. transition_timer_ = 0;
  1545. }
  1546. }
  1547. else if (transition_stage_ == TransitionStage::FADING_OUT){
  1548. SetScreenCover(transition_timer_ / DIVE_FADE_OUT_TIME);
  1549. if (transition_timer_ >= DIVE_FADE_OUT_TIME){
  1550. // The map changes under the black screen. The entities are not valid after it.
  1551. Init(transition_dive_ ? 1 : 0);
  1552. ::Entity* arrived = EntityManager::getSingleton().GetEntity("WorldMapSubmarine");
  1553. if (arrived == nullptr){
  1554. EndTransition();
  1555. return;
  1556. }
  1557. transition_target_y_ = arrived->GetPosition().y;
  1558. // Diving: it comes from high up. Surfacing: it comes from under the surface.
  1559. transition_start_y_ = transition_dive_
  1560. ? DIVE_HIGH_HEIGHT : transition_target_y_ - DIVE_SINK_DEPTH;
  1561. Ogre::Vector3 position = arrived->GetPosition();
  1562. position.y = transition_start_y_;
  1563. arrived->SetPosition(position);
  1564. transition_stage_ = TransitionStage::ARRIVING;
  1565. transition_timer_ = 0;
  1566. EntityManager::getSingleton().ScriptPlayerLock(true);
  1567. UpdateCamera(0, true);
  1568. }
  1569. }
  1570. else if (transition_stage_ == TransitionStage::ARRIVING){
  1571. const float duration = transition_dive_ ? DIVE_HIGH_TIME : DIVE_SINK_TIME;
  1572. set_height(
  1573. transition_start_y_
  1574. + (transition_target_y_ - transition_start_y_) * Smooth(transition_timer_ / duration)
  1575. );
  1576. // The screen is shown again by the time the submarine is at its height.
  1577. SetScreenCover(1.0f - transition_timer_ / duration);
  1578. if (transition_timer_ >= duration){
  1579. set_height(transition_target_y_);
  1580. EndTransition();
  1581. }
  1582. }
  1583. }
  1584. /**
  1585. * Animations of a vehicle in the world map, from the A files of the model: when it's parked,
  1586. * when it's boarded, and when it's boarded and moving. An empty name is no animation (the
  1587. * model in its pose). The roles were found by playing them, and for the models with only one
  1588. * animation it's the one of the model.
  1589. */
  1590. struct VehicleAnimations{
  1591. const char* parked;
  1592. const char* boarded;
  1593. const char* moving;
  1594. /// The parked animation shows its first frame and doesn't move.
  1595. bool parked_paused;
  1596. };
  1597. static const VehicleAnimations CHOCOBO_ANIMATIONS = {"asc", "asc", "asd", false};
  1598. static const VehicleAnimations BUGGY_ANIMATIONS = {"age", "aha", "aha", false};
  1599. static const VehicleAnimations TINY_BRONCO_ANIMATIONS = {"dya", "dya", "dya", true};
  1600. static const VehicleAnimations HIGHWIND_ANIMATIONS = {"cic", "cic", "cic", true};
  1601. static const VehicleAnimations SUBMARINE_ANIMATIONS = {"dfe", "dfe", "dfe", true};
  1602. /**
  1603. * Plays the animation of a vehicle in its current state.
  1604. */
  1605. static void PlayVehicleAnimation(
  1606. EntityModel* vehicle, const ::Entity* active_entity, const bool moving,
  1607. const VehicleAnimations& animations
  1608. ){
  1609. if (vehicle == nullptr) return;
  1610. const bool parked = vehicle != active_entity;
  1611. const char* name = parked ? animations.parked
  1612. : (moving ? animations.moving : animations.boarded);
  1613. if (name[0] == '\0'){
  1614. vehicle->StopAnimation();
  1615. return;
  1616. }
  1617. if (parked && animations.parked_paused){
  1618. vehicle->PlayAnimationPaused(name);
  1619. return;
  1620. }
  1621. vehicle->UnfreezeAnimation();
  1622. if (vehicle->HasAnimation(name)) vehicle->PlayAnimationContinue(name);
  1623. }
  1624. void WorldmapModule::UpdateVehicleAnimations(const bool moving){
  1625. const ::Entity* active_entity = EntityManager::getSingleton().ScriptGetPlayerEntity();
  1626. PlayVehicleAnimation(chocobo_entity_, active_entity, moving, CHOCOBO_ANIMATIONS);
  1627. PlayVehicleAnimation(buggy_entity_, active_entity, moving, BUGGY_ANIMATIONS);
  1628. PlayVehicleAnimation(tiny_bronco_entity_, active_entity, moving, TINY_BRONCO_ANIMATIONS);
  1629. PlayVehicleAnimation(highwind_entity_, active_entity, moving, HIGHWIND_ANIMATIONS);
  1630. PlayVehicleAnimation(submarine_entity_, active_entity, moving, SUBMARINE_ANIMATIONS);
  1631. }
  1632. void WorldmapModule::AddWorldModelFromScript(
  1633. const char* name, const char* hrc, const float x, const float z, const int raw_scale,
  1634. const int direction, const float rotation_x, const float rotation_y, const float rotation_z
  1635. ){
  1636. if (name == nullptr || hrc == nullptr) return;
  1637. // The game scale is for coordinates of 4096 units per world unit, and 0x200 is 1 (15.2).
  1638. // The 1.1 is what the models that were adjusted by looking at them have more.
  1639. const Ogre::Real scale = (static_cast<Ogre::Real>(raw_scale) / 512.0f) * 15.2f / 4096.0f * 1.1f;
  1640. AddWorldModel(
  1641. name, Ogre::String(hrc) + ".mesh", Ogre::Vector3(x, 0.0f, z), 1.0f,
  1642. Ogre::Quaternion::IDENTITY, 1.0f, false, scale
  1643. );
  1644. ::Entity* entity = EntityManager::getSingleton().GetEntity(Ogre::String("WorldMap") + name);
  1645. if (entity == nullptr) return;
  1646. entity->SetSolid(false);
  1647. // The rotation of the model itself.
  1648. entity->setRootOrientation(
  1649. Ogre::Quaternion(Ogre::Degree(rotation_x), Ogre::Vector3::UNIT_X)
  1650. * Ogre::Quaternion(Ogre::Degree(rotation_y), Ogre::Vector3::UNIT_Y)
  1651. * Ogre::Quaternion(Ogre::Degree(rotation_z), Ogre::Vector3::UNIT_Z)
  1652. );
  1653. // The direction of the script is a full turn in 256: 0 faces +Z (south), 64 east (+X), 128 north and
  1654. // 192 west. Checked with the sea around Junon in the scene of the Warship, which sails at 192.
  1655. const Ogre::Radian heading(Ogre::Degree(direction * 360.0f / 256.0f));
  1656. static_cast<EntityModel*>(entity)->GetModel()->getParentSceneNode()->getParentSceneNode()
  1657. ->setOrientation(Ogre::Quaternion(heading, Ogre::Vector3::UNIT_Y));
  1658. }
  1659. void WorldmapModule::SetVehicleHidden(const char* entity_name){
  1660. if (entity_name != nullptr) hidden_vehicles_.insert(entity_name);
  1661. }
  1662. void WorldmapModule::SetSpeed(const char* name, const float speed){
  1663. if (name != nullptr && speed > 0.0f) speeds_[name] = speed;
  1664. }
  1665. void WorldmapModule::SetCamera(const char* name, const float distance, const float pitch_degrees){
  1666. if (name != nullptr && distance > 0.0f) camera_settings_[name] = {distance, pitch_degrees};
  1667. }
  1668. float WorldmapModule::GetSpeed(const char* name, const float default_speed) const{
  1669. const auto speed = speeds_.find(name);
  1670. return speed == speeds_.end() ? default_speed : speed->second;
  1671. }
  1672. void WorldmapModule::SetSpawn(const char* entity_name, const float x, const float z){
  1673. if (entity_name == nullptr) return;
  1674. spawn_overrides_[entity_name] = Ogre::Vector2(x, z);
  1675. }
  1676. Ogre::Vector3 WorldmapModule::GetSpawn(
  1677. const Ogre::String& entity_name, const Ogre::Vector3& default_spawn
  1678. ) const{
  1679. const auto spawn = spawn_overrides_.find(entity_name);
  1680. if (spawn == spawn_overrides_.end()) return default_spawn;
  1681. return Ogre::Vector3(spawn->second.x, 0.0f, spawn->second.y);
  1682. }
  1683. void WorldmapModule::SetModelOffset(const char* entity_name, const float y){
  1684. if (entity_name == nullptr) return;
  1685. ::Entity* entity = EntityManager::getSingleton().GetEntity(entity_name);
  1686. if (entity == nullptr) return;
  1687. SetModelHeightOffset(static_cast<EntityModel*>(entity), y);
  1688. }
  1689. void WorldmapModule::SetEntityAltitude(const char* entity_name, const float y){
  1690. if (entity_name == nullptr) return;
  1691. ::Entity* entity = EntityManager::getSingleton().GetEntity(entity_name);
  1692. if (entity == nullptr) return;
  1693. const Ogre::Vector3 position = entity->GetPosition();
  1694. entity->SetPosition(Ogre::Vector3(position.x, y, position.z));
  1695. }
  1696. void WorldmapModule::SetModelOrientation(
  1697. const char* entity_name, const float x, const float y, const float z
  1698. ){
  1699. if (entity_name == nullptr) return;
  1700. ::Entity* entity = EntityManager::getSingleton().GetEntity(entity_name);
  1701. if (entity == nullptr) return;
  1702. entity->setRootOrientation(
  1703. Ogre::Quaternion(Ogre::Degree(x), Ogre::Vector3::UNIT_X)
  1704. * Ogre::Quaternion(Ogre::Degree(y), Ogre::Vector3::UNIT_Y)
  1705. * Ogre::Quaternion(Ogre::Degree(z), Ogre::Vector3::UNIT_Z)
  1706. );
  1707. }
  1708. void WorldmapModule::SetModelHeading(const char* entity_name, const float direction){
  1709. if (entity_name == nullptr) return;
  1710. ::Entity* entity = EntityManager::getSingleton().GetEntity(entity_name);
  1711. if (entity == nullptr) return;
  1712. // The same heading as AddWorldModelFromScript.
  1713. const Ogre::Radian heading(Ogre::Degree(direction * 360.0f / 256.0f));
  1714. static_cast<EntityModel*>(entity)->GetModel()->getParentSceneNode()->getParentSceneNode()
  1715. ->setOrientation(Ogre::Quaternion(heading, Ogre::Vector3::UNIT_Y));
  1716. }
  1717. int WorldmapModule::GetModelHeading(const char* entity_name){
  1718. if (entity_name == nullptr) return 0;
  1719. ::Entity* entity = EntityManager::getSingleton().GetEntity(entity_name);
  1720. if (entity == nullptr) return 0;
  1721. const Ogre::Quaternion orientation = static_cast<EntityModel*>(entity)->GetModel()
  1722. ->getParentSceneNode()->getParentSceneNode()->getOrientation();
  1723. const Ogre::Vector3 forward = orientation * Ogre::Vector3(0.0f, 0.0f, 1.0f);
  1724. const float turns = std::atan2(forward.x, forward.z) / Ogre::Math::TWO_PI;
  1725. return static_cast<int>(std::floor(turns * 256.0f + 0.5f)) & 255;
  1726. }
  1727. bool WorldmapModule::SurfaceToOverworld(EntityModel* submarine){
  1728. const Ogre::Vector3 position = submarine->GetPosition();
  1729. // The same position of WM0 has to be deep water.
  1730. if (!IsOverworldDeepWater(position.x, position.z)){
  1731. LogManager::getSingleton().logMessage(
  1732. "The submarine can't surface here: it's not deep water in the overworld."
  1733. );
  1734. return false;
  1735. }
  1736. surface_requested_ = true;
  1737. surface_position_ = position;
  1738. surface_heading_ = submarine->GetModel()->getParentSceneNode()->getParentSceneNode()
  1739. ->getOrientation().getYaw().valueRadians();
  1740. BeginTransition(false, submarine);
  1741. return true;
  1742. }
  1743. void WorldmapModule::PlaceSurfacedSubmarine(){
  1744. surface_requested_ = false;
  1745. if (submarine_entity_ == nullptr) return;
  1746. Ogre::Vector3 surface;
  1747. if (!FindWalkableSurface(surface_position_, surface, false, false)) return;
  1748. submarine_entity_->SetPosition(surface);
  1749. submarine_entity_->GetModel()->getParentSceneNode()->getParentSceneNode()->setOrientation(
  1750. Ogre::Quaternion(Ogre::Radian(surface_heading_), Ogre::Vector3::UNIT_Y)
  1751. );
  1752. // Cloud boards the submarine, like the boarding script does.
  1753. player_entity_->SetVisible(false);
  1754. player_entity_->SetSolid(false);
  1755. player_entity_->SetTalkable(false);
  1756. ClearVehicleTerrains();
  1757. for (const char* terrain : {"SEA_DEEP_WATER", "SEA", "SUBMARINE_PEN"}) AddVehicleTerrain(terrain);
  1758. EntityManager::getSingleton().ScriptSetPlayerEntity("WorldMapSubmarine");
  1759. UpdateCamera(0, true);
  1760. }
  1761. void WorldmapModule::EnterTriangle(const TerrainTriangle& triangle){
  1762. const int mesh_index = triangle.mesh_y * WORLD_MAP_SCRIPT_MESH_STRIDE + triangle.mesh_x;
  1763. if (triangle.function_id >= 3){
  1764. if (mesh_index != active_function_mesh_index_
  1765. || triangle.function_id != active_function_id_){
  1766. TriggerTriangleFunction(triangle);
  1767. }
  1768. active_function_mesh_index_ = mesh_index;
  1769. active_function_id_ = triangle.function_id;
  1770. }
  1771. else{
  1772. active_function_mesh_index_ = -1;
  1773. active_function_id_ = -1;
  1774. }
  1775. }
  1776. void WorldmapModule::UpdateFlight(
  1777. EntityModel* entity, const Ogre::Real delta_time, const bool highwind
  1778. ){
  1779. Ogre::SceneNode* node = entity->GetModel()->getParentSceneNode()->getParentSceneNode();
  1780. if (flight_entity_ != entity){
  1781. // Starts flying: continue from the current heading and height.
  1782. flight_entity_ = entity;
  1783. flight_heading_ = node->getOrientation().getYaw().valueRadians();
  1784. flight_y_ = entity->GetPosition().y;
  1785. camera_yaw_ = 0;
  1786. }
  1787. float turn = 0;
  1788. float climb = 0;
  1789. bool forward = false;
  1790. // Scripts lock the player during events and transitions.
  1791. if (!EntityManager::getSingleton().IsPlayerLocked()){
  1792. InputManager& input = InputManager::getSingleton();
  1793. // The heading decreases to turn right: the model faces +Z at heading 0 and the
  1794. // right side of the camera behind it is -X.
  1795. if (input.IsGameEventPressed("walk_left")) turn += 1.0f;
  1796. if (input.IsGameEventPressed("walk_right")) turn -= 1.0f;
  1797. // Inverted, like the controls of a plane: down climbs and up descends.
  1798. if (input.IsGameEventPressed("walk_up")) climb -= 1.0f;
  1799. if (input.IsGameEventPressed("walk_down")) climb += 1.0f;
  1800. forward = input.IsGameEventPressed("CONFIRM");
  1801. }
  1802. flight_heading_ += turn * FLIGHT_TURN_SPEED * delta_time;
  1803. if (flight_heading_ > Ogre::Math::PI) flight_heading_ -= Ogre::Math::TWO_PI;
  1804. else if (flight_heading_ < -Ogre::Math::PI) flight_heading_ += Ogre::Math::TWO_PI;
  1805. node->setOrientation(Ogre::Quaternion(Ogre::Radian(flight_heading_), Ogre::Vector3::UNIT_Y));
  1806. const Ogre::Vector3 current_position = entity->GetPosition();
  1807. Ogre::Vector3 requested_position = current_position;
  1808. if (forward){
  1809. const Ogre::Vector3 direction(
  1810. Ogre::Math::Sin(Ogre::Radian(flight_heading_)), 0.0f,
  1811. Ogre::Math::Cos(Ogre::Radian(flight_heading_))
  1812. );
  1813. requested_position += direction * delta_time * GetSpeed(
  1814. highwind ? "highwind" : "submarine", From16BitFixedPoint(8182) * 0.45f * 2.0f
  1815. );
  1816. }
  1817. // The terrain below. If the vehicle can't go there, it stays but can still go up or down.
  1818. Ogre::Vector3 surface;
  1819. size_t triangle_index = 0;
  1820. if (!FindWalkableSurface(requested_position, surface, false, true, nullptr, &triangle_index)){
  1821. requested_position = current_position;
  1822. if (!FindWalkableSurface(
  1823. requested_position, surface, false, false, nullptr, &triangle_index
  1824. )) return;
  1825. forward = false;
  1826. }
  1827. // The ground has priority over the maximum height, so the vehicle never goes through it.
  1828. const Ogre::Real ceiling = highwind ? HIGHWIND_MAX_HEIGHT : UNDERWATER_MAX_HEIGHT;
  1829. Ogre::Real new_y = flight_y_ + climb * FLIGHT_CLIMB_SPEED * delta_time;
  1830. new_y = std::min(new_y, ceiling);
  1831. new_y = std::max(new_y, surface.y + FLIGHT_MIN_CLEARANCE);
  1832. const Ogre::Vector3 new_position(requested_position.x, new_y, requested_position.z);
  1833. if (EntityManager::getSingleton().IsWorldPositionBlocked(entity, new_position)) return;
  1834. flight_y_ = new_y;
  1835. entity->SetPosition(new_position);
  1836. if (forward) EnterTriangle(terrain_triangles_[triangle_index]);
  1837. }
  1838. /// Name of a vehicle in the scripts (WorldMapSettings).
  1839. static const char* GetVehicleScriptName(const WorldmapModule::VehicleType vehicle){
  1840. switch (vehicle){
  1841. case WorldmapModule::VehicleType::CHOCOBO: return "chocobo";
  1842. case WorldmapModule::VehicleType::BUGGY: return "buggy";
  1843. case WorldmapModule::VehicleType::HIGHWIND: return "highwind";
  1844. case WorldmapModule::VehicleType::SUBMARINE: return "submarine";
  1845. case WorldmapModule::VehicleType::TINY_BRONCO: return "tiny_bronco";
  1846. default: return "walk";
  1847. }
  1848. }
  1849. void WorldmapModule::TriggerTriangleFunction(const TerrainTriangle& triangle){
  1850. ScriptEntity* world_map_script
  1851. = ScriptManager::getSingleton().GetScriptEntityByName(
  1852. ScriptManager::SYSTEM, "WorldMap"
  1853. );
  1854. if (world_map_script == nullptr) return;
  1855. const int mesh_index = triangle.mesh_y * WORLD_MAP_SCRIPT_MESH_STRIDE + triangle.mesh_x;
  1856. // What the function can know about who entered the triangle (see WorldVM.can_enter).
  1857. ScriptManager::getSingleton().RunString(
  1858. std::string("System.WorldMap.vehicle = \"") + GetVehicleScriptName(current_vehicle_)
  1859. + "\"; System.WorldMap.landing = " + (landing_trigger_ ? "true" : "false")
  1860. );
  1861. ScriptManager::getSingleton().ScriptRequest(
  1862. world_map_script, "on_triangle_enter", 1,
  1863. std::to_string(mesh_index), std::to_string(triangle.function_id - 3), false, false
  1864. );
  1865. }
  1866. Ogre::String WorldmapModule::GetTerrainTypeUnderEntity(const char* entity_name) const{
  1867. if (entity_name == nullptr) return "";
  1868. const ::Entity* entity = EntityManager::getSingleton().GetEntity(entity_name);
  1869. if (entity == nullptr) return "";
  1870. Ogre::Vector3 surface;
  1871. uint8 walkability_type = 0;
  1872. if (!FindWalkableSurface(entity->GetPosition(), surface, false, false, &walkability_type)){
  1873. return "";
  1874. }
  1875. return GetWorldMapTerrainName(walkability_type);
  1876. }
  1877. int WorldmapModule::GetTerrainTriangleUnderEntity(const char* entity_name) const{
  1878. if (entity_name == nullptr) return -1;
  1879. const ::Entity* entity = EntityManager::getSingleton().GetEntity(entity_name);
  1880. if (entity == nullptr) return -1;
  1881. Ogre::Vector3 surface;
  1882. size_t triangle_index = 0;
  1883. if (!FindWalkableSurface(entity->GetPosition(), surface, false, false, nullptr, &triangle_index)){
  1884. return -1;
  1885. }
  1886. return static_cast<int>(triangle_index);
  1887. }
  1888. bool WorldmapModule::UnboardVehicle(const char* vehicle_name){
  1889. if (vehicle_name == nullptr) return false;
  1890. EntityManager& entity_manager = EntityManager::getSingleton();
  1891. ::Entity* player_entity = entity_manager.ScriptGetPlayerEntity();
  1892. ::Entity* vehicle_entity = entity_manager.GetEntity(vehicle_name);
  1893. if (
  1894. player_entity == nullptr || vehicle_entity == nullptr
  1895. || player_entity != vehicle_entity || player_entity == player_entity_
  1896. ){
  1897. return false;
  1898. }
  1899. const Ogre::Vector3 vehicle_position = vehicle_entity->GetPosition();
  1900. const Ogre::Real unboard_distance
  1901. = vehicle_entity->GetSolidRadius() + player_entity_->GetSolidRadius() + 0.1f;
  1902. const Ogre::Real diagonal_distance = unboard_distance * 0.70710678f;
  1903. const Ogre::Vector3 directions[] = {
  1904. Ogre::Vector3(1, 0, 0), Ogre::Vector3(-1, 0, 0),
  1905. Ogre::Vector3(0, 0, 1), Ogre::Vector3(0, 0, -1),
  1906. Ogre::Vector3(1, 0, 1), Ogre::Vector3(-1, 0, 1),
  1907. Ogre::Vector3(1, 0, -1), Ogre::Vector3(-1, 0, -1)
  1908. };
  1909. for (size_t i = 0; i < sizeof(directions) / sizeof(directions[0]); ++i){
  1910. const Ogre::Real distance = i < 4 ? unboard_distance : diagonal_distance;
  1911. const Ogre::Vector3 requested_position
  1912. = vehicle_position + directions[i] * distance;
  1913. Ogre::Vector3 surface;
  1914. uint8 walkability_type = 0;
  1915. if (!FindWalkableSurface(
  1916. requested_position, surface, false, false, &walkability_type
  1917. ) || !IsFootWalkable(walkability_type)){
  1918. continue;
  1919. }
  1920. surface.y += player_height_offset_;
  1921. if (entity_manager.IsWorldPositionBlocked(player_entity_, surface)) continue;
  1922. if (vehicle_entity == highwind_entity_){
  1923. // The Highwind lands. It can't be left higher up, Cloud couldn't board it again.
  1924. Ogre::Vector3 ground;
  1925. if (!FindWalkableSurface(vehicle_position, ground, false, false)) return false;
  1926. if (vehicle_position.y - ground.y > HIGHWIND_MAX_LANDING_HEIGHT) return false;
  1927. vehicle_entity->SetPosition(Ogre::Vector3(vehicle_position.x, ground.y, vehicle_position.z));
  1928. // Landing on the terrain of the northern cave enters it (the function of the triangle runs).
  1929. uint8 landing_terrain = 0;
  1930. size_t landing_triangle = 0;
  1931. if (FindWalkableSurface(vehicle_position, ground, false, false, &landing_terrain, &landing_triangle)
  1932. && landing_terrain == VGears::WorldmapFileSerializer::NORTHERND_CAVE
  1933. && terrain_triangles_[landing_triangle].function_id >= 3){
  1934. landing_after_unboard_ = &terrain_triangles_[landing_triangle];
  1935. }
  1936. }
  1937. player_entity_->SetPosition(surface);
  1938. // The boarding scripts hide Cloud and make him non-solid.
  1939. player_entity_->SetVisible(true);
  1940. player_entity_->SetSolid(true);
  1941. vehicle_entity->SetTalkable(true);
  1942. entity_manager.ScriptSetPlayerEntity("WorldMapCloud");
  1943. ClearVehicleTerrains();
  1944. if (landing_after_unboard_ != nullptr){
  1945. // The Highwind is what entered (the vehicle of the trigger).
  1946. current_vehicle_ = VehicleType::HIGHWIND;
  1947. landing_trigger_ = true;
  1948. TriggerTriangleFunction(*landing_after_unboard_);
  1949. landing_trigger_ = false;
  1950. landing_after_unboard_ = nullptr;
  1951. }
  1952. current_vehicle_ = VehicleType::ON_FOOT;
  1953. return true;
  1954. }
  1955. return false;
  1956. }
  1957. bool WorldmapModule::frameStarted(const Ogre::FrameEvent& event){
  1958. if (!initialized_ || player_entity_ == nullptr || paused_for_battle_) return true;
  1959. AnimateWorldMapTextures(event.timeSinceLastFrame);
  1960. // Diving or surfacing: the submarine moves by itself and the screen fades.
  1961. if (transition_stage_ != TransitionStage::NONE){
  1962. UpdateTransition(event.timeSinceLastFrame);
  1963. if (initialized_ && player_entity_ != nullptr){
  1964. UpdateVehicleAnimations(false);
  1965. UpdateCamera(event.timeSinceLastFrame, false);
  1966. }
  1967. return true;
  1968. }
  1969. ::Entity* active_entity = EntityManager::getSingleton().ScriptGetPlayerEntity();
  1970. if (active_entity == player_entity_){
  1971. current_vehicle_ = VehicleType::ON_FOOT;
  1972. }
  1973. else if (active_entity == chocobo_entity_){
  1974. current_vehicle_ = VehicleType::CHOCOBO;
  1975. }
  1976. else if (active_entity == buggy_entity_){
  1977. current_vehicle_ = VehicleType::BUGGY;
  1978. }
  1979. else if (active_entity == highwind_entity_){
  1980. current_vehicle_ = VehicleType::HIGHWIND;
  1981. }
  1982. else if (active_entity == submarine_entity_){
  1983. current_vehicle_ = VehicleType::SUBMARINE;
  1984. }
  1985. else if (active_entity == tiny_bronco_entity_){
  1986. current_vehicle_ = VehicleType::TINY_BRONCO;
  1987. }
  1988. else{
  1989. // An entity of a scripted scene (the Warship): the camera follows it and nothing else happens.
  1990. if (active_entity != nullptr){
  1991. UpdateCamera(event.timeSinceLastFrame, false);
  1992. }
  1993. return true;
  1994. }
  1995. // The music of the map (WorldMusic in world_music.lua): when the vehicle changes and every half second.
  1996. music_timer_ += event.timeSinceLastFrame;
  1997. if (music_timer_ >= 0.5f || music_vehicle_ != current_vehicle_){
  1998. music_timer_ = 0.0f;
  1999. music_vehicle_ = current_vehicle_;
  2000. const char* music_vehicle = "walk";
  2001. switch (current_vehicle_){
  2002. case VehicleType::CHOCOBO: music_vehicle = "chocobo"; break;
  2003. case VehicleType::BUGGY: music_vehicle = "buggy"; break;
  2004. case VehicleType::HIGHWIND: music_vehicle = "highwind"; break;
  2005. case VehicleType::SUBMARINE: music_vehicle = "submarine"; break;
  2006. case VehicleType::TINY_BRONCO: music_vehicle = "tiny_bronco"; break;
  2007. default: break;
  2008. }
  2009. ScriptManager::getSingleton().RunString(
  2010. "if WorldMusic then WorldMusic.update(" + std::to_string(map_id_) + ", \"" + music_vehicle + "\") end"
  2011. );
  2012. }
  2013. const bool highwind_active = active_entity == highwind_entity_;
  2014. const bool vehicle_active = current_vehicle_ != VehicleType::ON_FOOT;
  2015. const bool cancel_pressed = InputManager::getSingleton().IsGameEventPressed("CANCEL");
  2016. const bool cancel_edge = cancel_pressed && !cancel_was_pressed_;
  2017. // The cancel button makes the submarine of WM2 go back to the surface.
  2018. if (
  2019. cancel_edge && map_id_ == 1 && active_entity == submarine_entity_
  2020. && !EntityManager::getSingleton().IsPlayerLocked()
  2021. ){
  2022. cancel_was_pressed_ = true;
  2023. // Changes the map: the entities are not valid after it.
  2024. if (SurfaceToOverworld(submarine_entity_)) return true;
  2025. }
  2026. if (vehicle_active && cancel_pressed && !cancel_was_pressed_){
  2027. ScriptManager::getSingleton().ScriptRequest(
  2028. ScriptManager::ENTITY, active_entity->GetName().c_str(), "unboard", 0
  2029. );
  2030. }
  2031. cancel_was_pressed_ = cancel_pressed;
  2032. // The action button makes the submarine dive from WM0 to WM2.
  2033. const bool confirm_pressed = InputManager::getSingleton().IsGameEventPressed("CONFIRM");
  2034. const bool dive_pressed = confirm_pressed && !confirm_was_pressed_;
  2035. confirm_was_pressed_ = confirm_pressed;
  2036. if (
  2037. dive_pressed && map_id_ == 2 && active_entity == player_entity_
  2038. && !EntityManager::getSingleton().IsPlayerLocked()
  2039. ){
  2040. PlaceSnowPole();
  2041. }
  2042. if (
  2043. dive_pressed && map_id_ == 0 && active_entity == submarine_entity_
  2044. && !EntityManager::getSingleton().IsPlayerLocked()
  2045. ){
  2046. // Changes the map: the entities are not valid after it.
  2047. if (DiveToUnderwaterMap(submarine_entity_)) return true;
  2048. }
  2049. EntityModel* active_model = active_entity == player_entity_ ? player_entity_
  2050. : (current_vehicle_ == VehicleType::CHOCOBO ? chocobo_entity_
  2051. : (current_vehicle_ == VehicleType::BUGGY ? buggy_entity_
  2052. : (highwind_active ? highwind_entity_
  2053. : (current_vehicle_ == VehicleType::SUBMARINE
  2054. ? submarine_entity_ : tiny_bronco_entity_))));
  2055. // Flying vehicles (the Highwind, and the submarine of WM2) have their own controls.
  2056. flight_active_ = highwind_active || (map_id_ == 1 && active_entity == player_entity_);
  2057. if (flight_active_){
  2058. UpdateFlight(active_model, event.timeSinceLastFrame, highwind_active);
  2059. UpdateVehicleAnimations(false);
  2060. UpdateCamera(event.timeSinceLastFrame, false);
  2061. return true;
  2062. }
  2063. flight_entity_ = nullptr;
  2064. // L1 and R1 rotate the camera around the active entity.
  2065. {
  2066. InputManager& camera_input = InputManager::getSingleton();
  2067. // The camera of the snow map (WM3) can't be moved by hand: it turns by itself.
  2068. if (map_id_ == 2) UpdateSnowCamera(event.timeSinceLastFrame);
  2069. else{
  2070. if (camera_input.IsGameEventPressed("L1")) camera_yaw_ -= CAMERA_ROTATION_SPEED * event.timeSinceLastFrame;
  2071. if (camera_input.IsGameEventPressed("R1")) camera_yaw_ += CAMERA_ROTATION_SPEED * event.timeSinceLastFrame;
  2072. }
  2073. if (camera_yaw_ > Ogre::Math::PI) camera_yaw_ -= Ogre::Math::TWO_PI;
  2074. else if (camera_yaw_ < -Ogre::Math::PI) camera_yaw_ += Ogre::Math::TWO_PI;
  2075. }
  2076. Ogre::Vector3 movement = Ogre::Vector3::ZERO;
  2077. // Scripts lock the player during events and transitions.
  2078. if (EntityManager::getSingleton().IsPlayerLocked()){
  2079. // Nothing: no movement.
  2080. }
  2081. else{
  2082. // The game events of the movement, so the keys of the controller settings are used.
  2083. InputManager& input = InputManager::getSingleton();
  2084. if (input.IsGameEventPressed("walk_left")) movement.x -= 1.0f;
  2085. if (input.IsGameEventPressed("walk_right")) movement.x += 1.0f;
  2086. if (input.IsGameEventPressed("walk_up")) movement.z -= 1.0f;
  2087. if (input.IsGameEventPressed("walk_down")) movement.z += 1.0f;
  2088. }
  2089. bool is_walking = false;
  2090. if (!movement.isZeroLength()){
  2091. movement.normalise();
  2092. // The movement is relative to the camera.
  2093. movement = Ogre::Quaternion(Ogre::Radian(camera_yaw_), Ogre::Vector3::UNIT_Y) * movement;
  2094. const Ogre::Vector3 current_position = active_entity->GetPosition();
  2095. const char* speed_name = "walk";
  2096. switch (current_vehicle_){
  2097. case VehicleType::CHOCOBO: speed_name = "chocobo"; break;
  2098. case VehicleType::BUGGY: speed_name = "buggy"; break;
  2099. case VehicleType::HIGHWIND: speed_name = "highwind"; break;
  2100. case VehicleType::SUBMARINE: speed_name = "submarine"; break;
  2101. case VehicleType::TINY_BRONCO: speed_name = "tiny_bronco"; break;
  2102. default: break;
  2103. }
  2104. const Ogre::Real speed = GetSpeed(
  2105. speed_name, From16BitFixedPoint(8182) * 0.45f * (vehicle_active ? 2.0f : 1.0f)
  2106. );
  2107. Ogre::Vector3 requested_position = current_position
  2108. + movement * speed * event.timeSinceLastFrame;
  2109. Ogre::Vector3 surface;
  2110. size_t triangle_index = 0;
  2111. if (FindWalkableSurface(requested_position, surface, false, true, nullptr,
  2112. &triangle_index)){
  2113. if (highwind_active){
  2114. Ogre::Vector3 current_surface;
  2115. if (FindWalkableSurface(current_position, current_surface, false, false)){
  2116. surface.y += current_position.y - current_surface.y;
  2117. }
  2118. }
  2119. else if (active_entity == player_entity_){
  2120. surface.y += player_height_offset_;
  2121. }
  2122. if (!EntityManager::getSingleton().IsWorldPositionBlocked(
  2123. active_entity, surface
  2124. )){
  2125. active_entity->SetPosition(surface);
  2126. const TerrainTriangle& triangle = terrain_triangles_[triangle_index];
  2127. EnterTriangle(triangle);
  2128. // There are no encounters underwater.
  2129. if (current_vehicle_ == VehicleType::ON_FOOT && map_id_ != 1){
  2130. UpdateEncounters(event.timeSinceLastFrame, triangle);
  2131. }
  2132. const Ogre::Vector3 model_forward(0.0f, 0.0f, 1.0f);
  2133. const Ogre::Vector3 move_direction(movement.x, 0.0f, movement.z);
  2134. const Ogre::Quaternion heading
  2135. = model_forward.getRotationTo(move_direction, Ogre::Vector3::UNIT_Y);
  2136. active_model->GetModel()->getParentSceneNode()
  2137. ->getParentSceneNode()->setOrientation(heading);
  2138. is_walking = true;
  2139. }
  2140. }
  2141. }
  2142. // The submarine of WM2 has no walking animations.
  2143. if (!vehicle_active && map_id_ != 1){
  2144. player_entity_->PlayAnimationContinue(is_walking ? "Walk" : "Idle");
  2145. }
  2146. UpdateVehicleAnimations(is_walking);
  2147. UpdateCamera(event.timeSinceLastFrame, false);
  2148. return true;
  2149. }
  2150. void WorldmapModule::UpdateCamera(Ogre::Real delta_time, bool snap_to_player){
  2151. ::Entity* active_entity = EntityManager::getSingleton().ScriptGetPlayerEntity();
  2152. if (active_entity == nullptr) return;
  2153. const Ogre::Vector3 target
  2154. = active_entity->GetPosition() + Ogre::Vector3(0, active_entity->GetHeight() * 0.5f, 0);
  2155. // The camera of a flying vehicle stays behind it. L1 and R1 rotate it from there.
  2156. const float yaw = camera_yaw_ + (flight_active_ ? flight_heading_ + Ogre::Math::PI : 0.0f);
  2157. // The camera of the entity: distance and angle over the ground (the default one is the offset 1.5, 2.25).
  2158. const char* camera_name = "walk";
  2159. if (map_id_ == 1) camera_name = "submarine_underwater";
  2160. else if (active_entity == chocobo_entity_) camera_name = "chocobo";
  2161. else if (active_entity == buggy_entity_) camera_name = "buggy";
  2162. else if (active_entity == highwind_entity_) camera_name = "highwind";
  2163. else if (active_entity == submarine_entity_) camera_name = "submarine";
  2164. else if (active_entity == tiny_bronco_entity_) camera_name = "tiny_bronco";
  2165. else if (active_entity != player_entity_) camera_name = "scene";
  2166. float distance = std::sqrt(1.5f * 1.5f + 2.25f * 2.25f);
  2167. float pitch = std::atan2(1.5f, 2.25f);
  2168. const auto camera_settings = camera_settings_.find(camera_name);
  2169. if (camera_settings != camera_settings_.end()){
  2170. distance = camera_settings->second.distance;
  2171. pitch = Ogre::Math::DegreesToRadians(camera_settings->second.pitch_degrees);
  2172. }
  2173. const Ogre::Vector3 camera_offset
  2174. = Ogre::Quaternion(Ogre::Radian(yaw), Ogre::Vector3::UNIT_Y)
  2175. * Ogre::Vector3(0.0f, distance * std::sin(pitch), distance * std::cos(pitch));
  2176. Ogre::Camera* camera = CameraManager::getSingleton().GetCurrentCamera();
  2177. const Ogre::Vector3 desired_position = target + camera_offset;
  2178. if (snap_to_player){
  2179. camera->setPosition(desired_position);
  2180. }
  2181. else{
  2182. const Ogre::Real follow_amount = std::min(1.0f, delta_time * 8.0f);
  2183. camera->setPosition(
  2184. camera->getPosition()
  2185. + (desired_position - camera->getPosition()) * follow_amount
  2186. );
  2187. }
  2188. camera->lookAt(target);
  2189. }
  2190. void WorldmapModule::LoadEncounters(){
  2191. encounter_records_.clear();
  2192. TiXmlDocument document("./data/gamedata/world_encounters.xml");
  2193. if (!document.LoadFile()){
  2194. LOG_WARNING("World map encounters were not found. There will be no random battles.");
  2195. return;
  2196. }
  2197. TiXmlHandle handle(&document);
  2198. for (
  2199. TiXmlElement* record = handle.FirstChildElement("world_encounters")
  2200. .FirstChildElement("record").ToElement();
  2201. record != nullptr; record = record->NextSiblingElement("record")
  2202. ){
  2203. EncounterRecord data;
  2204. int enabled = 0;
  2205. data.rate = 0;
  2206. data.terrain = 0;
  2207. record->QueryIntAttribute("enabled", &enabled);
  2208. record->QueryIntAttribute("rate", &data.rate);
  2209. record->QueryIntAttribute("terrain", &data.terrain);
  2210. data.enabled = enabled != 0;
  2211. for (unsigned int i = 0; i < 15; ++ i) data.words[i] = 0;
  2212. std::istringstream words(record->Attribute("words") ? record->Attribute("words") : "");
  2213. for (unsigned int i = 0; i < 15; ++ i){
  2214. unsigned int word = 0;
  2215. if (!(words >> word)) break;
  2216. data.words[i] = static_cast<uint16>(word);
  2217. }
  2218. encounter_records_.push_back(data);
  2219. }
  2220. LOG_TRIVIAL("World map encounters loaded: " + std::to_string(encounter_records_.size()));
  2221. }
  2222. int WorldmapModule::RollEncounterBattle(const EncounterRecord& record) const{
  2223. // Same order as the original game: the special battles first, then the standard ones. The
  2224. // chance of a word is its probability out of 64, as the roll is a 16 bit value and the
  2225. // probability sits in the 6 highest bits.
  2226. const uint16* w = record.words;
  2227. int battle = -1;
  2228. int roll = (std::rand() % 256) << 8;
  2229. // Words 7 and 8 (indices 6 and 7): back attacks.
  2230. if (w[6] > roll) battle = w[6] & 0x3FF;
  2231. else if (w[6] + w[7] > roll) battle = w[7] & 0x3FF;
  2232. // Word 9: side attack. Needs a party of more than one member.
  2233. if (battle < 0){
  2234. roll = (std::rand() % 256) << 8;
  2235. if (w[8] > roll) battle = w[8] & 0x3FF;
  2236. }
  2237. // Word 10: pincer attack.
  2238. if (battle < 0){
  2239. roll = (std::rand() % 256) << 8;
  2240. if (w[9] > roll) battle = w[9] & 0x3FF;
  2241. }
  2242. // Words 1-6: standard battles. The last battle is not repeated (one reroll).
  2243. for (unsigned int attempt = 0; battle < 0 && attempt < 2; ++ attempt){
  2244. roll = (std::rand() % 256) << 8;
  2245. int sum = 0;
  2246. for (unsigned int i = 0; i < 6; ++ i){
  2247. sum += w[i];
  2248. if (sum > roll){
  2249. battle = w[i] & 0x3FF;
  2250. break;
  2251. }
  2252. }
  2253. if (battle == encounter_last_battle_ && attempt == 0) battle = -1;
  2254. }
  2255. return battle;
  2256. }
  2257. void WorldmapModule::UpdateEncounters(const float delta_time, const TerrainTriangle& triangle){
  2258. if (encounters_locked_ || encounter_records_.size() < 64) return;
  2259. // The original game checks every 16 frames of walking, at 30 frames per second.
  2260. encounter_frames_ += delta_time * 30.0f;
  2261. if (encounter_frames_ < 16.0f) return;
  2262. encounter_frames_ -= 16.0f;
  2263. // Region and terrain group. The terrain types 0x10 and 0x18 count as 0 and 8.
  2264. const int region = std::min<int>(triangle.region, 15);
  2265. int terrain = triangle.walkability_type;
  2266. if (terrain == 0x10) terrain = 0;
  2267. else if (terrain == 0x18) terrain = 8;
  2268. int group = 0;
  2269. for (int i = 0; i < 4; ++ i){
  2270. if (encounter_records_[region * 4 + i].terrain == terrain){
  2271. group = i;
  2272. break;
  2273. }
  2274. }
  2275. const EncounterRecord& record = encounter_records_[region * 4 + group];
  2276. // The accumulator grows on every check, so the chance gets higher until a battle starts.
  2277. const float multiplier = EntityManager::getSingleton().GetEncounterMultiplier();
  2278. if (multiplier <= 0.0f) return;
  2279. const int speed = static_cast<int>(16 * multiplier);
  2280. encounter_accumulator_ += (record.rate != 0) ? (speed << 10) / record.rate : 0x7FFF;
  2281. const int check = std::rand() % 256;
  2282. if (EntityManager::getSingleton().IsDebugEncounters()){
  2283. LOG_TRIVIAL(
  2284. "World encounter check: region " + std::to_string(region) + ", terrain "
  2285. + std::to_string(terrain) + ", group " + std::to_string(group) + ", rate "
  2286. + std::to_string(record.rate) + ", chance " + std::to_string(encounter_accumulator_ >> 8)
  2287. + "/256, roll " + std::to_string(check)
  2288. );
  2289. }
  2290. if (check >= (encounter_accumulator_ >> 8) || !record.enabled) return;
  2291. encounter_accumulator_ = 0;
  2292. const int battle = RollEncounterBattle(record);
  2293. if (battle < 0) return;
  2294. encounter_last_battle_ = battle;
  2295. LOG_TRIVIAL("World random encounter: battle " + std::to_string(battle));
  2296. ScriptManager::getSingleton().RunString("Encounter.start(" + std::to_string(battle) + ")");
  2297. }
  2298. void WorldmapModule::PauseForBattle(){
  2299. paused_for_battle_ = true;
  2300. if (world_map_node_ != nullptr) world_map_node_->setVisible(false);
  2301. }
  2302. void WorldmapModule::ResumeAfterBattle(){
  2303. paused_for_battle_ = false;
  2304. encounter_frames_ = 0;
  2305. // The battle had its own music: the one of the map starts again.
  2306. music_timer_ = 1.0f;
  2307. ScriptManager::getSingleton().RunString("if WorldMusic then WorldMusic.reset() end");
  2308. if (world_map_node_ != nullptr) world_map_node_->setVisible(true);
  2309. if (player_entity_ != nullptr) UpdateCamera(0, true);
  2310. }
  2311. void WorldmapModule::SetEncountersLocked(const bool locked){encounters_locked_ = locked;}
  2312. /// Names of the entities of the overworld whose state is kept when the map is replaced.
  2313. static const char* const OVERWORLD_ENTITY_NAMES[] = {
  2314. "WorldMapCloud", "WorldMapChocobo", "WorldMapHighwind", "WorldMapBuggy",
  2315. "WorldMapSubmarine", "WorldMapTinyBronco"
  2316. };
  2317. void WorldmapModule::SaveOverworldSnapshot(){
  2318. overworld_snapshot_.clear();
  2319. for (const char* name : OVERWORLD_ENTITY_NAMES){
  2320. ::Entity* entity = EntityManager::getSingleton().GetEntity(name);
  2321. if (entity == nullptr) continue;
  2322. EntityState state;
  2323. state.name = name;
  2324. state.position = entity->GetPosition();
  2325. state.orientation = static_cast<EntityModel*>(entity)->GetModel()->getParentSceneNode()
  2326. ->getParentSceneNode()->getOrientation();
  2327. state.visible = entity->IsVisible();
  2328. state.solid = entity->IsSolid();
  2329. state.talkable = entity->IsTalkable();
  2330. overworld_snapshot_.push_back(state);
  2331. }
  2332. }
  2333. void WorldmapModule::RestoreOverworldSnapshot(){
  2334. for (const EntityState& state : overworld_snapshot_){
  2335. ::Entity* entity = EntityManager::getSingleton().GetEntity(state.name);
  2336. if (entity == nullptr) continue;
  2337. entity->SetPosition(state.position);
  2338. static_cast<EntityModel*>(entity)->GetModel()->getParentSceneNode()->getParentSceneNode()
  2339. ->setOrientation(state.orientation);
  2340. entity->SetVisible(state.visible);
  2341. entity->SetSolid(state.solid);
  2342. entity->SetTalkable(state.talkable);
  2343. }
  2344. overworld_snapshot_.clear();
  2345. }
  2346. void WorldmapModule::DestroyWorldMap(){
  2347. // The overworld is built again when the submarine surfaces: keep where everything was.
  2348. if (map_id_ == 0) SaveOverworldSnapshot();
  2349. Suspend();
  2350. if (world_map_node_ != nullptr && scene_manager_ != nullptr){
  2351. // Destroy the surfaces. The node is kept and reused.
  2352. while (world_map_node_->numAttachedObjects() > 0){
  2353. Ogre::MovableObject* object = world_map_node_->detachObject(static_cast<unsigned short>(0));
  2354. scene_manager_->destroyMovableObject(object);
  2355. }
  2356. }
  2357. terrain_triangles_.clear();
  2358. terrain_grid_.clear();
  2359. encounter_records_.clear();
  2360. // The entities of the old map (player, vehicles, models and scripts).
  2361. EntityManager::getSingleton().ClearWorld();
  2362. initialized_ = false;
  2363. map_id_ = -1;
  2364. }
  2365. void WorldmapModule::Enter(const int map_id){
  2366. if (initialized_) DestroyWorldMap();
  2367. Init(map_id);
  2368. }
  2369. void WorldmapModule::Init(const int map_id){
  2370. if (map_id < 0 || map_id >= WORLD_MAP_COUNT){
  2371. LogManager::getSingleton().logMessage(
  2372. "Invalid world map " + std::to_string(map_id) + ". Valid maps are 0 to "
  2373. + std::to_string(WORLD_MAP_COUNT - 1) + "."
  2374. );
  2375. return;
  2376. }
  2377. if (initialized_ && map_id != map_id_){
  2378. DestroyWorldMap();
  2379. }
  2380. if (initialized_){
  2381. if (frame_listener_attached_) return;
  2382. EntityManager::getSingleton().SetWorldModule();
  2383. DialogsManager::getSingleton().SetWorldModule();
  2384. world_map_node_->setVisible(true);
  2385. // The music starts again (a field or a battle had its own).
  2386. music_timer_ = 1.0f;
  2387. ScriptManager::getSingleton().RunString("if WorldMusic then WorldMusic.reset() end");
  2388. CreatePlayer();
  2389. Root::getSingleton().addFrameListener(this);
  2390. frame_listener_attached_ = true;
  2391. return;
  2392. }
  2393. map_id_ = map_id;
  2394. camera_yaw_ = 0;
  2395. const MapLayout layout = GetMapLayout(map_id_);
  2396. grid_width_ = layout.width;
  2397. grid_height_ = layout.height;
  2398. origin_x_ = layout.origin_x;
  2399. origin_y_ = layout.origin_y;
  2400. EntityManager::getSingleton().SetWorldModule();
  2401. DialogsManager::getSingleton().SetWorldModule();
  2402. CreateWorldMap(Root::getSingleton().getSceneManager("Scene"));
  2403. // Underwater (WM2): everything fades to black with the distance to the camera.
  2404. if (map_id_ == 1){
  2405. Root::getSingleton().getSceneManager("Scene")->setFog(
  2406. Ogre::FOG_LINEAR, Ogre::ColourValue::Black, 0.0f, UNDERWATER_FOG_START, UNDERWATER_FOG_END
  2407. );
  2408. }
  2409. else Root::getSingleton().getSceneManager("Scene")->setFog(Ogre::FOG_NONE);
  2410. // Snow map (WM3): it always snows.
  2411. SetSnowOverlay(map_id_ == 2);
  2412. // The music of the map starts in the first frame.
  2413. music_timer_ = 1.0f;
  2414. ScriptManager::getSingleton().RunString("if WorldMusic then WorldMusic.reset() end");
  2415. snow_poles_.clear();
  2416. snow_pole_counter_ = 0;
  2417. // The button that was used to get here (a menu, a field) must not count as the first pole.
  2418. confirm_was_pressed_ = InputManager::getSingleton().IsGameEventPressed("CONFIRM");
  2419. snow_camera_remaining_ = 0.0f;
  2420. snow_camera_timer_ = Ogre::Math::RangeRandom(SNOW_CAMERA_MIN_WAIT, SNOW_CAMERA_MAX_WAIT);
  2421. ScriptManager::getSingleton().RunFile(
  2422. "scripts/worldmap/wm" + std::to_string(WORLD_MAP_FILE_NUMBERS[map_id_]) + ".lua"
  2423. );
  2424. // The debug spawn points, if debug_data.lua has them.
  2425. spawn_overrides_.clear();
  2426. hidden_vehicles_.clear();
  2427. ScriptManager::getSingleton().RunString(
  2428. "if WorldMapDebug and WorldMapDebug.spawn then "
  2429. "for name, point in pairs(WorldMapDebug.spawn) do "
  2430. "world_map_module:set_spawn(name, point[1], point[2]) end end"
  2431. );
  2432. // The positions that the scripts give to the vehicles, for the story (debug ones have priority).
  2433. ScriptManager::getSingleton().RunString(
  2434. "if WorldVM then WorldVM.prepare(" + std::to_string(map_id_) + ") end"
  2435. );
  2436. CreatePlayer();
  2437. // The models that the scripts place (scenery).
  2438. ScriptManager::getSingleton().RunString(
  2439. "if WorldVM then WorldVM.place_models(" + std::to_string(map_id_) + ") end"
  2440. );
  2441. LoadEncounters();
  2442. initialized_ = true;
  2443. Root::getSingleton().addFrameListener(this);
  2444. frame_listener_attached_ = true;
  2445. }
  2446. void WorldmapModule::UpdateSnowCamera(Ogre::Real delta_time){
  2447. if (snow_camera_remaining_ == 0.0f){
  2448. snow_camera_timer_ -= delta_time;
  2449. if (snow_camera_timer_ > 0.0f) return;
  2450. const float degrees = Ogre::Math::RangeRandom(SNOW_CAMERA_MIN_DEGREES, SNOW_CAMERA_MAX_DEGREES);
  2451. const float direction = Ogre::Math::UnitRandom() < 0.5f ? -1.0f : 1.0f;
  2452. snow_camera_remaining_ = direction * Ogre::Math::DegreesToRadians(degrees);
  2453. snow_camera_timer_ = Ogre::Math::RangeRandom(SNOW_CAMERA_MIN_WAIT, SNOW_CAMERA_MAX_WAIT);
  2454. }
  2455. const float step = std::min(std::abs(snow_camera_remaining_), CAMERA_ROTATION_SPEED * delta_time);
  2456. const float signed_step = snow_camera_remaining_ < 0.0f ? -step : step;
  2457. camera_yaw_ += signed_step;
  2458. snow_camera_remaining_ -= signed_step;
  2459. if (std::abs(snow_camera_remaining_) < 0.0001f) snow_camera_remaining_ = 0.0f;
  2460. }
  2461. void WorldmapModule::PlaceSnowPole(){
  2462. if (player_entity_ == nullptr) return;
  2463. // The oldest pole goes away when there is no room for another one.
  2464. while (snow_poles_.size() >= SNOW_MAX_POLES){
  2465. EntityManager::getSingleton().RemoveWorldMapEntity(snow_poles_.front());
  2466. snow_poles_.pop_front();
  2467. }
  2468. const Ogre::Vector3 position = player_entity_->GetPosition();
  2469. const std::string name = "snowpole_" + std::to_string(snow_pole_counter_++);
  2470. // The model and scale of the snow poles of the game (WorldMapModels: djc, 0x300).
  2471. AddWorldModelFromScript(name.c_str(), "djc", position.x, position.z, 0x300, 0, 0.0f, 0.0f, 0.0f);
  2472. if (EntityManager::getSingleton().GetEntity("WorldMap" + name) != nullptr){
  2473. snow_poles_.push_back("WorldMap" + name);
  2474. }
  2475. }
  2476. void WorldmapModule::Suspend(){
  2477. if (!frame_listener_attached_) return;
  2478. Root::getSingleton().removeFrameListener(this);
  2479. frame_listener_attached_ = false;
  2480. if (world_map_node_ != nullptr) world_map_node_->setVisible(false);
  2481. SetSnowOverlay(false);
  2482. player_entity_ = nullptr;
  2483. highwind_entity_ = nullptr;
  2484. buggy_entity_ = nullptr;
  2485. chocobo_entity_ = nullptr;
  2486. submarine_entity_ = nullptr;
  2487. tiny_bronco_entity_ = nullptr;
  2488. current_vehicle_ = VehicleType::ON_FOOT;
  2489. active_vehicle_terrain_types_.clear();
  2490. active_function_mesh_index_ = -1;
  2491. active_function_id_ = -1;
  2492. flight_active_ = false;
  2493. flight_entity_ = nullptr;
  2494. cancel_was_pressed_ = false;
  2495. confirm_was_pressed_ = false;
  2496. }
  2497. } // namespace VGears