mapHandler.cpp 45 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485
  1. /*
  2. * mapHandler.cpp, part of VCMI engine
  3. *
  4. * Authors: listed in file AUTHORS in main folder
  5. *
  6. * License: GNU General Public License v2.0 or later
  7. * Full text of license available in license.txt file, in main folder
  8. *
  9. */
  10. #include "StdInc.h"
  11. #include "mapHandler.h"
  12. #include "../render/CAnimation.h"
  13. #include "../render/CFadeAnimation.h"
  14. #include "../render/Colors.h"
  15. #include "../renderSDL/SDL_Extensions.h"
  16. #include "../CGameInfo.h"
  17. #include "../render/Graphics.h"
  18. #include "../render/IImage.h"
  19. #include "../CMusicHandler.h"
  20. #include "../../lib/mapObjects/CGHeroInstance.h"
  21. #include "../../lib/mapObjects/CObjectClassesHandler.h"
  22. #include "../../lib/mapping/CMap.h"
  23. #include "../../lib/CConfigHandler.h"
  24. #include "../../lib/CGeneralTextHandler.h"
  25. #include "../../lib/CStopWatch.h"
  26. #include "../../lib/CRandomGenerator.h"
  27. #include "../../lib/RoadHandler.h"
  28. #include "../../lib/RiverHandler.h"
  29. #include "../../lib/TerrainHandler.h"
  30. #define ADVOPT (conf.go()->ac)
  31. static bool objectBlitOrderSorter(const TerrainTileObject & a, const TerrainTileObject & b)
  32. {
  33. return CMapHandler::compareObjectBlitOrder(a.obj, b.obj);
  34. }
  35. struct NeighborTilesInfo
  36. {
  37. bool d7, //789
  38. d8, //456
  39. d9, //123
  40. d4,
  41. d5,
  42. d6,
  43. d1,
  44. d2,
  45. d3;
  46. NeighborTilesInfo(const int3 & pos, const int3 & sizes, std::shared_ptr<const boost::multi_array<ui8, 3>> visibilityMap)
  47. {
  48. auto getTile = [&](int dx, int dy)->bool
  49. {
  50. if ( dx + pos.x < 0 || dx + pos.x >= sizes.x
  51. || dy + pos.y < 0 || dy + pos.y >= sizes.y)
  52. return false;
  53. //FIXME: please do not read settings for every tile...
  54. return settings["session"]["spectate"].Bool() ? true : (*visibilityMap)[pos.z][dx+pos.x][dy+pos.y];
  55. };
  56. d7 = getTile(-1, -1); //789
  57. d8 = getTile( 0, -1); //456
  58. d9 = getTile(+1, -1); //123
  59. d4 = getTile(-1, 0);
  60. d5 = (*visibilityMap)[pos.z][pos.x][pos.y];
  61. d6 = getTile(+1, 0);
  62. d1 = getTile(-1, +1);
  63. d2 = getTile( 0, +1);
  64. d3 = getTile(+1, +1);
  65. }
  66. bool areAllHidden() const
  67. {
  68. return !(d1 || d2 || d3 || d4 || d5 || d6 || d7 || d8 || d9);
  69. }
  70. int getBitmapID() const
  71. {
  72. //NOTE: some images have unused in VCMI pair (same blockmap but a bit different look)
  73. // 0-1, 2-3, 4-5, 11-13, 12-14
  74. static const int visBitmaps[256] = {
  75. -1, 34, 4, 4, 22, 23, 4, 4, 36, 36, 38, 38, 47, 47, 38, 38, //16
  76. 3, 25, 12, 12, 3, 25, 12, 12, 9, 9, 6, 6, 9, 9, 6, 6, //32
  77. 35, 39, 48, 48, 41, 43, 48, 48, 36, 36, 38, 38, 47, 47, 38, 38, //48
  78. 26, 49, 28, 28, 26, 49, 28, 28, 9, 9, 6, 6, 9, 9, 6, 6, //64
  79. 0, 45, 29, 29, 24, 33, 29, 29, 37, 37, 7, 7, 50, 50, 7, 7, //80
  80. 13, 27, 44, 44, 13, 27, 44, 44, 8, 8, 10, 10, 8, 8, 10, 10, //96
  81. 0, 45, 29, 29, 24, 33, 29, 29, 37, 37, 7, 7, 50, 50, 7, 7, //112
  82. 13, 27, 44, 44, 13, 27, 44, 44, 8, 8, 10, 10, 8, 8, 10, 10, //128
  83. 15, 17, 30, 30, 16, 19, 30, 30, 46, 46, 40, 40, 32, 32, 40, 40, //144
  84. 2, 25, 12, 12, 2, 25, 12, 12, 9, 9, 6, 6, 9, 9, 6, 6, //160
  85. 18, 42, 31, 31, 20, 21, 31, 31, 46, 46, 40, 40, 32, 32, 40, 40, //176
  86. 26, 49, 28, 28, 26, 49, 28, 28, 9, 9, 6, 6, 9, 9, 6, 6, //192
  87. 0, 45, 29, 29, 24, 33, 29, 29, 37, 37, 7, 7, 50, 50, 7, 7, //208
  88. 13, 27, 44, 44, 13, 27, 44, 44, 8, 8, 10, 10, 8, 8, 10, 10, //224
  89. 0, 45, 29, 29, 24, 33, 29, 29, 37, 37, 7, 7, 50, 50, 7, 7, //240
  90. 13, 27, 44, 44, 13, 27, 44, 44, 8, 8, 10, 10, 8, 8, 10, 10 //256
  91. };
  92. return visBitmaps[d1 + d2 * 2 + d3 * 4 + d4 * 8 + d6 * 16 + d7 * 32 + d8 * 64 + d9 * 128]; // >=0 -> partial hide, <0 - full hide
  93. }
  94. };
  95. void CMapHandler::prepareFOWDefs()
  96. {
  97. //assume all frames in group 0
  98. size_t size = graphics->fogOfWarFullHide->size(0);
  99. FoWfullHide.resize(size);
  100. for(size_t frame = 0; frame < size; frame++)
  101. FoWfullHide[frame] = graphics->fogOfWarFullHide->getImage(frame);
  102. //initialization of type of full-hide image
  103. hideBitmap.resize(boost::extents[sizes.z][sizes.x][sizes.y]);
  104. for (int i = 0; i < hideBitmap.num_elements(); i++)
  105. hideBitmap.data()[i] = CRandomGenerator::getDefault().nextInt(size - 1);
  106. size = graphics->fogOfWarPartialHide->size(0);
  107. FoWpartialHide.resize(size);
  108. for(size_t frame = 0; frame < size; frame++)
  109. FoWpartialHide[frame] = graphics->fogOfWarPartialHide->getImage(frame);
  110. }
  111. EMapAnimRedrawStatus CMapHandler::drawTerrainRectNew(SDL_Surface * targetSurface, const MapDrawingInfo * info, bool redrawOnlyAnim)
  112. {
  113. assert(info);
  114. bool hasActiveFade = updateObjectsFade();
  115. resolveBlitter(info)->blit(targetSurface, info);
  116. return hasActiveFade ? EMapAnimRedrawStatus::REDRAW_REQUESTED : EMapAnimRedrawStatus::OK;
  117. }
  118. void CMapHandler::initTerrainGraphics()
  119. {
  120. auto loadFlipped = [](TFlippedAnimations & animation, TFlippedCache & cache, const std::map<std::string, std::string> & files)
  121. {
  122. //no rotation and basic setup
  123. for(auto & type : files)
  124. {
  125. animation[type.first][0] = std::make_unique<CAnimation>(type.second);
  126. animation[type.first][0]->preload();
  127. const size_t views = animation[type.first][0]->size(0);
  128. cache[type.first].resize(views);
  129. for(int j = 0; j < views; j++)
  130. cache[type.first][j][0] = animation[type.first][0]->getImage(j);
  131. }
  132. for(int rotation = 1; rotation < 4; rotation++)
  133. {
  134. for(auto & type : files)
  135. {
  136. animation[type.first][rotation] = std::make_unique<CAnimation>(type.second);
  137. animation[type.first][rotation]->preload();
  138. const size_t views = animation[type.first][rotation]->size(0);
  139. for(int j = 0; j < views; j++)
  140. {
  141. auto image = animation[type.first][rotation]->getImage(j);
  142. if(rotation == 2 || rotation == 3)
  143. image->horizontalFlip();
  144. if(rotation == 1 || rotation == 3)
  145. image->verticalFlip();
  146. cache[type.first][j][rotation] = image;
  147. }
  148. }
  149. }
  150. };
  151. std::map<std::string, std::string> terrainFiles;
  152. std::map<std::string, std::string> riverFiles;
  153. std::map<std::string, std::string> roadFiles;
  154. for(const auto & terrain : VLC->terrainTypeHandler->objects)
  155. {
  156. terrainFiles[terrain->getJsonKey()] = terrain->tilesFilename;
  157. }
  158. for(const auto & river : VLC->riverTypeHandler->objects)
  159. {
  160. riverFiles[river->getJsonKey()] = river->tilesFilename;
  161. }
  162. for(const auto & road : VLC->roadTypeHandler->objects)
  163. {
  164. roadFiles[road->getJsonKey()] = road->tilesFilename;
  165. }
  166. loadFlipped(terrainAnimations, terrainImages, terrainFiles);
  167. loadFlipped(riverAnimations, riverImages, riverFiles);
  168. loadFlipped(roadAnimations, roadImages, roadFiles);
  169. // Create enough room for the whole map and its frame
  170. //ttiles.resize(sizes.x, frameW, frameW);
  171. //FIXME: why do we even handle array with z (surface and undeground) at the same time?
  172. ttiles.resize(boost::extents[sizes.z][sizes.x + 2 * frameW][sizes.y + 2 * frameH]);
  173. ttiles.reindex(std::list<int>{ 0, -frameW, -frameH }); //need to move starting coordinates so that used index is always positive
  174. }
  175. void CMapHandler::initBorderGraphics()
  176. {
  177. egdeImages.resize(egdeAnimation->size(0));
  178. for(size_t i = 0; i < egdeImages.size(); i++)
  179. egdeImages[i] = egdeAnimation->getImage(i);
  180. edgeFrames.resize(sizes.x, frameW, frameW);
  181. for (int i=0-frameW;i<edgeFrames.size()-frameW;i++)
  182. {
  183. edgeFrames[i].resize(sizes.y, frameH, frameH);
  184. }
  185. for (int i=0-frameW;i<edgeFrames.size()-frameW;i++)
  186. {
  187. for (int j=0-frameH;j<(int)sizes.y+frameH;j++)
  188. edgeFrames[i][j].resize(sizes.z, 0, 0);
  189. }
  190. auto & rand = CRandomGenerator::getDefault();
  191. for (int i=0-frameW; i<sizes.x+frameW; i++) //by width
  192. {
  193. for (int j=0-frameH; j<sizes.y+frameH;j++) //by height
  194. {
  195. for(int k=0; k<sizes.z; ++k) //by levels
  196. {
  197. ui8 terBitmapNum = 0;
  198. if(i < 0 || i > (sizes.x-1) || j < 0 || j > (sizes.y-1))
  199. {
  200. if(i==-1 && j==-1)
  201. terBitmapNum = 16;
  202. else if(i==-1 && j==(sizes.y))
  203. terBitmapNum = 19;
  204. else if(i==(sizes.x) && j==-1)
  205. terBitmapNum = 17;
  206. else if(i==(sizes.x) && j==(sizes.y))
  207. terBitmapNum = 18;
  208. else if(j == -1 && i > -1 && i < sizes.x)
  209. terBitmapNum = rand.nextInt(22, 23);
  210. else if(i == -1 && j > -1 && j < sizes.y)
  211. terBitmapNum = rand.nextInt(33, 34);
  212. else if(j == sizes.y && i >-1 && i < sizes.x)
  213. terBitmapNum = rand.nextInt(29, 30);
  214. else if(i == sizes.x && j > -1 && j < sizes.y)
  215. terBitmapNum = rand.nextInt(25, 26);
  216. else
  217. terBitmapNum = rand.nextInt(15);
  218. }
  219. edgeFrames[i][j][k] = terBitmapNum;
  220. }
  221. }
  222. }
  223. }
  224. void CMapHandler::initObjectRects()
  225. {
  226. //initializing objects / rects
  227. for(auto & elem : map->objects)
  228. {
  229. const CGObjectInstance *obj = elem;
  230. if( !obj
  231. || (obj->ID==Obj::HERO && static_cast<const CGHeroInstance*>(obj)->inTownGarrison) //garrisoned hero
  232. || (obj->ID==Obj::BOAT && static_cast<const CGBoat*>(obj)->hero)) //boat with hero (hero graphics is used)
  233. {
  234. continue;
  235. }
  236. std::shared_ptr<CAnimation> animation = graphics->getAnimation(obj);
  237. //no animation at all
  238. if(!animation)
  239. continue;
  240. //empty animation
  241. if(animation->size(0) == 0)
  242. continue;
  243. auto image = animation->getImage(0,0);
  244. for(int fx=0; fx < obj->getWidth(); ++fx)
  245. {
  246. for(int fy=0; fy < obj->getHeight(); ++fy)
  247. {
  248. int3 currTile(obj->pos.x - fx, obj->pos.y - fy, obj->pos.z);
  249. Rect cr;
  250. cr.w = 32;
  251. cr.h = 32;
  252. cr.x = image->width() - fx * 32 - 32;
  253. cr.y = image->height() - fy * 32 - 32;
  254. TerrainTileObject toAdd(obj, cr, obj->visitableAt(currTile.x, currTile.y));
  255. if( map->isInTheMap(currTile) && // within map
  256. cr.x + cr.w > 0 && // image has data on this tile
  257. cr.y + cr.h > 0 &&
  258. obj->coveringAt(currTile.x, currTile.y) // object is visible here
  259. )
  260. {
  261. ttiles[currTile.z][currTile.x][currTile.y].objects.push_back(toAdd);
  262. }
  263. }
  264. }
  265. }
  266. auto shape = ttiles.shape();
  267. for(size_t z = 0; z < shape[0]; z++)
  268. {
  269. for(size_t x = 0; x < shape[1] - frameW; x++)
  270. {
  271. for(size_t y = 0; y < shape[2] - frameH; y++)
  272. {
  273. auto & objects = ttiles[z][x][y].objects;
  274. stable_sort(objects.begin(), objects.end(), objectBlitOrderSorter);
  275. }
  276. }
  277. }
  278. }
  279. void CMapHandler::init()
  280. {
  281. CStopWatch th;
  282. th.getDiff();
  283. // Size of visible terrain.
  284. int mapW = conf.go()->ac.advmapW;
  285. int mapH = conf.go()->ac.advmapH;
  286. //sizes of terrain
  287. sizes.x = map->width;
  288. sizes.y = map->height;
  289. sizes.z = map->levels();
  290. // Total number of visible tiles. Subtract the center tile, then
  291. // compute the number of tiles on each side, and reassemble.
  292. int t1, t2;
  293. t1 = (mapW-32)/2;
  294. t2 = mapW - 32 - t1;
  295. tilesW = 1 + (t1+31)/32 + (t2+31)/32;
  296. t1 = (mapH-32)/2;
  297. t2 = mapH - 32 - t1;
  298. tilesH = 1 + (t1+31)/32 + (t2+31)/32;
  299. // Size of the frame around the map. In extremes positions, the
  300. // frame must not be on the center of the map, but right on the
  301. // edge of the center tile.
  302. frameW = (mapW+31) /32 / 2;
  303. frameH = (mapH+31) /32 / 2;
  304. offsetX = (mapW - (2*frameW+1)*32)/2;
  305. offsetY = (mapH - (2*frameH+1)*32)/2;
  306. prepareFOWDefs();
  307. initTerrainGraphics();
  308. initBorderGraphics();
  309. logGlobal->info("\tPreparing FoW, terrain, roads, rivers, borders: %d ms", th.getDiff());
  310. initObjectRects();
  311. logGlobal->info("\tMaking object rects: %d ms", th.getDiff());
  312. }
  313. CMapHandler::CMapBlitter *CMapHandler::resolveBlitter(const MapDrawingInfo * info) const
  314. {
  315. if (info->scaled)
  316. return worldViewBlitter;
  317. if (info->puzzleMode)
  318. return puzzleViewBlitter;
  319. return normalBlitter;
  320. }
  321. void CMapHandler::CMapNormalBlitter::drawElement(EMapCacheType cacheType, std::shared_ptr<IImage> source, Rect * sourceRect, SDL_Surface * targetSurf, Rect * destRect) const
  322. {
  323. source->draw(targetSurf, destRect, sourceRect);
  324. }
  325. void CMapHandler::CMapNormalBlitter::init(const MapDrawingInfo * drawingInfo)
  326. {
  327. info = drawingInfo;
  328. // Width and height of the portion of the map to process. Units in tiles.
  329. tileCount.x = parent->tilesW;
  330. tileCount.y = parent->tilesH;
  331. topTile = info->topTile;
  332. initPos.x = parent->offsetX + info->drawBounds.x;
  333. initPos.y = parent->offsetY + info->drawBounds.y;
  334. realTileRect = Rect(initPos.x, initPos.y, tileSize, tileSize);
  335. // If moving, we need to add an extra column/line
  336. if (info->movement.x != 0)
  337. {
  338. tileCount.x++;
  339. initPos.x += info->movement.x;
  340. if (info->movement.x > 0)
  341. {
  342. // Moving right. We still need to draw the old tile on the
  343. // left, so adjust our referential
  344. topTile.x--;
  345. initPos.x -= tileSize;
  346. }
  347. }
  348. if (info->movement.y != 0)
  349. {
  350. tileCount.y++;
  351. initPos.y += info->movement.y;
  352. if (info->movement.y > 0)
  353. {
  354. // Moving down. We still need to draw the tile on the top,
  355. // so adjust our referential.
  356. topTile.y--;
  357. initPos.y -= tileSize;
  358. }
  359. }
  360. // Reduce sizes if we go out of the full map.
  361. if (topTile.x < -parent->frameW)
  362. topTile.x = -parent->frameW;
  363. if (topTile.y < -parent->frameH)
  364. topTile.y = -parent->frameH;
  365. if (topTile.x + tileCount.x > parent->sizes.x + parent->frameW)
  366. tileCount.x = parent->sizes.x + parent->frameW - topTile.x;
  367. if (topTile.y + tileCount.y > parent->sizes.y + parent->frameH)
  368. tileCount.y = parent->sizes.y + parent->frameH - topTile.y;
  369. }
  370. Rect CMapHandler::CMapNormalBlitter::clip(SDL_Surface * targetSurf) const
  371. {
  372. Rect prevClip;
  373. CSDL_Ext::getClipRect(targetSurf, prevClip);
  374. CSDL_Ext::setClipRect(targetSurf, info->drawBounds);
  375. return prevClip;
  376. }
  377. CMapHandler::CMapNormalBlitter::CMapNormalBlitter(CMapHandler * parent)
  378. : CMapBlitter(parent)
  379. {
  380. tileSize = 32;
  381. halfTileSizeCeil = 16;
  382. defaultTileRect = Rect(0, 0, tileSize, tileSize);
  383. }
  384. std::shared_ptr<IImage> CMapHandler::CMapWorldViewBlitter::objectToIcon(Obj id, si32 subId, PlayerColor owner) const
  385. {
  386. int ownerIndex = 0;
  387. if(owner < PlayerColor::PLAYER_LIMIT)
  388. {
  389. ownerIndex = owner.getNum() * 19;
  390. }
  391. else if (owner == PlayerColor::NEUTRAL)
  392. {
  393. ownerIndex = PlayerColor::PLAYER_LIMIT.getNum() * 19;
  394. }
  395. switch(id)
  396. {
  397. case Obj::MONOLITH_ONE_WAY_ENTRANCE:
  398. case Obj::MONOLITH_ONE_WAY_EXIT:
  399. case Obj::MONOLITH_TWO_WAY:
  400. return info->icons->getImage((int)EWorldViewIcon::TELEPORT);
  401. case Obj::SUBTERRANEAN_GATE:
  402. return info->icons->getImage((int)EWorldViewIcon::GATE);
  403. case Obj::ARTIFACT:
  404. return info->icons->getImage((int)EWorldViewIcon::ARTIFACT);
  405. case Obj::TOWN:
  406. return info->icons->getImage((int)EWorldViewIcon::TOWN + ownerIndex);
  407. case Obj::HERO:
  408. return info->icons->getImage((int)EWorldViewIcon::HERO + ownerIndex);
  409. case Obj::MINE:
  410. return info->icons->getImage((int)EWorldViewIcon::MINE_WOOD + subId + ownerIndex);
  411. case Obj::RESOURCE:
  412. return info->icons->getImage((int)EWorldViewIcon::RES_WOOD + subId + ownerIndex);
  413. }
  414. return std::shared_ptr<IImage>();
  415. }
  416. void CMapHandler::CMapWorldViewBlitter::calculateWorldViewCameraPos()
  417. {
  418. bool outsideLeft = topTile.x < 0;
  419. bool outsideTop = topTile.y < 0;
  420. bool outsideRight = std::max(0, topTile.x) + tileCount.x > parent->sizes.x;
  421. bool outsideBottom = std::max(0, topTile.y) + tileCount.y > parent->sizes.y;
  422. if (tileCount.x > parent->sizes.x)
  423. topTile.x = parent->sizes.x / 2 - tileCount.x / 2; // center viewport if the whole map can fit into the screen at once
  424. else if (outsideLeft)
  425. {
  426. if (outsideRight)
  427. topTile.x = parent->sizes.x / 2 - tileCount.x / 2;
  428. else
  429. topTile.x = 0;
  430. }
  431. else if (outsideRight)
  432. topTile.x = parent->sizes.x - tileCount.x;
  433. if (tileCount.y > parent->sizes.y)
  434. topTile.y = parent->sizes.y / 2 - tileCount.y / 2;
  435. else if (outsideTop)
  436. {
  437. if (outsideBottom)
  438. topTile.y = parent->sizes.y / 2 - tileCount.y / 2;
  439. else
  440. topTile.y = 0;
  441. }
  442. else if (outsideBottom)
  443. topTile.y = parent->sizes.y - tileCount.y;
  444. }
  445. void CMapHandler::CMapWorldViewBlitter::drawElement(EMapCacheType cacheType, std::shared_ptr<IImage> source, Rect * sourceRect, SDL_Surface * targetSurf, Rect * destRect) const
  446. {
  447. auto scaled = parent->cache.requestWorldViewCacheOrCreate(cacheType, source);
  448. if(scaled)
  449. scaled->draw(targetSurf, destRect, sourceRect);
  450. }
  451. void CMapHandler::CMapWorldViewBlitter::drawTileOverlay(SDL_Surface * targetSurf, const TerrainTile2 & tile) const
  452. {
  453. auto drawIcon = [this,targetSurf](Obj id, si32 subId, PlayerColor owner)
  454. {
  455. auto wvIcon = this->objectToIcon(id, subId, owner);
  456. if(nullptr != wvIcon)
  457. {
  458. // centering icon on the object
  459. Point dest(realPos.x + tileSize / 2 - wvIcon->width() / 2, realPos.y + tileSize / 2 - wvIcon->height() / 2);
  460. wvIcon->draw(targetSurf, dest.x, dest.y);
  461. }
  462. };
  463. auto & objects = tile.objects;
  464. for(auto & object : objects)
  465. {
  466. const CGObjectInstance * obj = object.obj;
  467. if(!obj)
  468. continue;
  469. const bool sameLevel = obj->pos.z == pos.z;
  470. //FIXME: Don't read options in a loop :v
  471. const bool isVisible = settings["session"]["spectate"].Bool() ? true : (*info->visibilityMap)[pos.z][pos.x][pos.y];
  472. const bool isVisitable = obj->visitableAt(pos.x, pos.y);
  473. if(sameLevel && isVisible && isVisitable)
  474. drawIcon(obj->ID, obj->subID, obj->tempOwner);
  475. }
  476. }
  477. void CMapHandler::CMapWorldViewBlitter::drawOverlayEx(SDL_Surface * targetSurf)
  478. {
  479. if(nullptr == info->additionalIcons)
  480. return;
  481. const int3 bottomRight = pos + tileCount;
  482. for(const ObjectPosInfo & iconInfo : *(info->additionalIcons))
  483. {
  484. if( iconInfo.pos.z != pos.z)
  485. continue;
  486. if((iconInfo.pos.x < topTile.x) || (iconInfo.pos.y < topTile.y))
  487. continue;
  488. if((iconInfo.pos.x > bottomRight.x) || (iconInfo.pos.y > bottomRight.y))
  489. continue;
  490. realPos.x = initPos.x + (iconInfo.pos.x - topTile.x) * tileSize;
  491. realPos.y = initPos.y + (iconInfo.pos.y - topTile.y) * tileSize;
  492. auto wvIcon = this->objectToIcon(iconInfo.id, iconInfo.subId, iconInfo.owner);
  493. if(nullptr != wvIcon)
  494. {
  495. // centering icon on the object
  496. Point dest(realPos.x + tileSize / 2 - wvIcon->width() / 2, realPos.y + tileSize / 2 - wvIcon->height() / 2);
  497. wvIcon->draw(targetSurf, dest.x, dest.y);
  498. }
  499. }
  500. }
  501. void CMapHandler::CMapWorldViewBlitter::drawHeroFlag(SDL_Surface * targetSurf, std::shared_ptr<IImage> source, Rect * sourceRect, Rect * destRect, bool moving) const
  502. {
  503. if (moving)
  504. return;
  505. CMapBlitter::drawHeroFlag(targetSurf, source, sourceRect, destRect, false);
  506. }
  507. void CMapHandler::CMapWorldViewBlitter::drawObject(SDL_Surface * targetSurf, std::shared_ptr<IImage> source, Rect * sourceRect, bool moving) const
  508. {
  509. if (moving)
  510. return;
  511. Rect scaledSourceRect((int)(sourceRect->x * info->scale), (int)(sourceRect->y * info->scale), sourceRect->w, sourceRect->h);
  512. CMapBlitter::drawObject(targetSurf, source, &scaledSourceRect, false);
  513. }
  514. void CMapHandler::CMapBlitter::drawTileTerrain(SDL_Surface * targetSurf, const TerrainTile & tinfo, const TerrainTile2 & tile) const
  515. {
  516. Rect destRect(realTileRect);
  517. ui8 rotation = tinfo.extTileFlags % 4;
  518. //TODO: use ui8 instead of string key
  519. auto terrainName = tinfo.terType->getJsonKey();
  520. if(parent->terrainImages[terrainName].size()<=tinfo.terView)
  521. return;
  522. drawElement(EMapCacheType::TERRAIN, parent->terrainImages[terrainName][tinfo.terView][rotation], nullptr, targetSurf, &destRect);
  523. }
  524. void CMapHandler::CMapWorldViewBlitter::init(const MapDrawingInfo * drawingInfo)
  525. {
  526. info = drawingInfo;
  527. parent->cache.updateWorldViewScale(info->scale);
  528. topTile = info->topTile;
  529. tileSize = (int) floorf(32.0f * info->scale);
  530. halfTileSizeCeil = (int)ceilf(tileSize / 2.0f);
  531. tileCount.x = (int) ceilf((float)info->drawBounds.w / tileSize);
  532. tileCount.y = (int) ceilf((float)info->drawBounds.h / tileSize);
  533. initPos.x = info->drawBounds.x;
  534. initPos.y = info->drawBounds.y;
  535. realTileRect = Rect(initPos.x, initPos.y, tileSize, tileSize);
  536. defaultTileRect = Rect(0, 0, tileSize, tileSize);
  537. calculateWorldViewCameraPos();
  538. }
  539. Rect CMapHandler::CMapWorldViewBlitter::clip(SDL_Surface * targetSurf) const
  540. {
  541. Rect prevClip;
  542. CSDL_Ext::fillRect(targetSurf, info->drawBounds, Colors::BLACK);
  543. // makes the clip area smaller if the map is smaller than the screen frame
  544. // (actually, it could be made 1 tile bigger so that overlay icons on edge tiles could be drawn partly outside)
  545. Rect clipRect(std::max<int>(info->drawBounds.x, info->drawBounds.x - topTile.x * tileSize),
  546. std::max<int>(info->drawBounds.y, info->drawBounds.y - topTile.y * tileSize),
  547. std::min<int>(info->drawBounds.w, parent->sizes.x * tileSize),
  548. std::min<int>(info->drawBounds.h, parent->sizes.y * tileSize));
  549. CSDL_Ext::getClipRect(targetSurf, prevClip);
  550. CSDL_Ext::setClipRect(targetSurf, clipRect); //preventing blitting outside of that rect
  551. return prevClip;
  552. }
  553. CMapHandler::CMapWorldViewBlitter::CMapWorldViewBlitter(CMapHandler * parent)
  554. : CMapBlitter(parent)
  555. {
  556. }
  557. void CMapHandler::CMapPuzzleViewBlitter::drawObjects(SDL_Surface * targetSurf, const TerrainTile2 & tile) const
  558. {
  559. CMapBlitter::drawObjects(targetSurf, tile);
  560. // grail X mark
  561. if(pos.x == info->grailPos.x && pos.y == info->grailPos.y)
  562. {
  563. const auto mark = graphics->heroMoveArrows->getImage(0);
  564. mark->draw(targetSurf,realTileRect.x,realTileRect.y);
  565. }
  566. }
  567. void CMapHandler::CMapPuzzleViewBlitter::postProcessing(SDL_Surface * targetSurf) const
  568. {
  569. CSDL_Ext::applyEffect(targetSurf, info->drawBounds, static_cast<int>(!ADVOPT.puzzleSepia));
  570. }
  571. bool CMapHandler::CMapPuzzleViewBlitter::canDrawObject(const CGObjectInstance * obj) const
  572. {
  573. if (!CMapBlitter::canDrawObject(obj))
  574. return false;
  575. //don't print flaggable objects in puzzle mode
  576. if (obj->isVisitable())
  577. return false;
  578. if(std::find(unblittableObjects.begin(), unblittableObjects.end(), obj->ID) != unblittableObjects.end())
  579. return false;
  580. return true;
  581. }
  582. CMapHandler::CMapPuzzleViewBlitter::CMapPuzzleViewBlitter(CMapHandler * parent)
  583. : CMapNormalBlitter(parent)
  584. {
  585. unblittableObjects.push_back(Obj::HOLE);
  586. }
  587. CMapHandler::CMapBlitter::CMapBlitter(CMapHandler * p)
  588. :parent(p), tileSize(0), halfTileSizeCeil(0), info(nullptr)
  589. {
  590. }
  591. CMapHandler::CMapBlitter::~CMapBlitter() = default;
  592. void CMapHandler::CMapBlitter::drawFrame(SDL_Surface * targetSurf) const
  593. {
  594. Rect destRect(realTileRect);
  595. drawElement(EMapCacheType::FRAME, parent->egdeImages[parent->edgeFrames[pos.x][pos.y][topTile.z]], nullptr, targetSurf, &destRect);
  596. }
  597. void CMapHandler::CMapBlitter::drawOverlayEx(SDL_Surface * targetSurf)
  598. {
  599. //nothing to do here
  600. }
  601. void CMapHandler::CMapBlitter::drawHeroFlag(SDL_Surface * targetSurf, std::shared_ptr<IImage> source, Rect * sourceRect, Rect * destRect, bool moving) const
  602. {
  603. drawElement(EMapCacheType::HERO_FLAGS, source, sourceRect, targetSurf, destRect);
  604. }
  605. void CMapHandler::CMapBlitter::drawObject(SDL_Surface * targetSurf, std::shared_ptr<IImage> source, Rect * sourceRect, bool moving) const
  606. {
  607. Rect dstRect(realTileRect);
  608. drawElement(EMapCacheType::OBJECTS, source, sourceRect, targetSurf, &dstRect);
  609. }
  610. void CMapHandler::CMapBlitter::drawObjects(SDL_Surface * targetSurf, const TerrainTile2 & tile) const
  611. {
  612. auto & objects = tile.objects;
  613. for(auto & object : objects)
  614. {
  615. if (object.fadeAnimKey >= 0)
  616. {
  617. auto fadeIter = parent->fadeAnims.find(object.fadeAnimKey);
  618. if (fadeIter != parent->fadeAnims.end())
  619. {
  620. // this object is currently fading, so skip normal drawing
  621. Rect r2(realTileRect);
  622. CFadeAnimation * fade = (*fadeIter).second.second;
  623. fade->draw(targetSurf, r2.topLeft());
  624. continue;
  625. }
  626. logGlobal->error("Fading map object with missing fade anim : %d", object.fadeAnimKey);
  627. continue;
  628. }
  629. const CGObjectInstance * obj = object.obj;
  630. if (!obj)
  631. {
  632. logGlobal->error("Stray map object that isn't fading");
  633. continue;
  634. }
  635. if (!canDrawObject(obj))
  636. continue;
  637. uint8_t animationFrame;
  638. if(obj->ID == Obj::HERO) //non-generic animation frame pick for hero and boat
  639. animationFrame = info->heroAnim;
  640. else
  641. animationFrame = info->anim;
  642. auto objData = findObjectBitmap(obj, animationFrame);
  643. if (objData.objBitmap)
  644. {
  645. Rect srcRect(object.rect.x, object.rect.y, tileSize, tileSize);
  646. drawObject(targetSurf, objData.objBitmap, &srcRect, objData.isMoving);
  647. if (objData.flagBitmap)
  648. {
  649. if (objData.isMoving)
  650. {
  651. srcRect.y += FRAMES_PER_MOVE_ANIM_GROUP * 2 - tileSize;
  652. Rect dstRect(realPos.x, realPos.y - tileSize / 2, tileSize, tileSize);
  653. drawHeroFlag(targetSurf, objData.flagBitmap, &srcRect, &dstRect, true);
  654. }
  655. else if (obj->pos.x == pos.x && obj->pos.y == pos.y)
  656. {
  657. Rect dstRect(realPos.x - 2 * tileSize, realPos.y - tileSize, 3 * tileSize, 2 * tileSize);
  658. drawHeroFlag(targetSurf, objData.flagBitmap, nullptr, &dstRect, false);
  659. }
  660. }
  661. }
  662. }
  663. }
  664. void CMapHandler::CMapBlitter::drawRoad(SDL_Surface * targetSurf, const TerrainTile & tinfo, const TerrainTile * tinfoUpper) const
  665. {
  666. if (tinfoUpper && tinfoUpper->roadType->getId() != Road::NO_ROAD)
  667. {
  668. ui8 rotation = (tinfoUpper->extTileFlags >> 4) % 4;
  669. Rect source(0, tileSize / 2, tileSize, tileSize / 2);
  670. Rect dest(realPos.x, realPos.y, tileSize, tileSize / 2);
  671. drawElement(EMapCacheType::ROADS, parent->roadImages[tinfoUpper->roadType->getJsonKey()][tinfoUpper->roadDir][rotation],
  672. &source, targetSurf, &dest);
  673. }
  674. if(tinfo.roadType->getId() != Road::NO_ROAD) //print road from this tile
  675. {
  676. ui8 rotation = (tinfo.extTileFlags >> 4) % 4;
  677. Rect source(0, 0, tileSize, halfTileSizeCeil);
  678. Rect dest(realPos.x, realPos.y + tileSize / 2, tileSize, tileSize / 2);
  679. drawElement(EMapCacheType::ROADS, parent->roadImages[tinfo.roadType->getJsonKey()][tinfo.roadDir][rotation],
  680. &source, targetSurf, &dest);
  681. }
  682. }
  683. void CMapHandler::CMapBlitter::drawRiver(SDL_Surface * targetSurf, const TerrainTile & tinfo) const
  684. {
  685. Rect destRect(realTileRect);
  686. ui8 rotation = (tinfo.extTileFlags >> 2) % 4;
  687. drawElement(EMapCacheType::RIVERS, parent->riverImages[tinfo.riverType->getJsonKey()][tinfo.riverDir][rotation], nullptr, targetSurf, &destRect);
  688. }
  689. void CMapHandler::CMapBlitter::drawFow(SDL_Surface * targetSurf) const
  690. {
  691. const NeighborTilesInfo neighborInfo(pos, parent->sizes, info->visibilityMap);
  692. int retBitmapID = neighborInfo.getBitmapID();// >=0 -> partial hide, <0 - full hide
  693. if (retBitmapID < 0)
  694. retBitmapID = - parent->hideBitmap[pos.z][pos.x][pos.y] - 1; //fully hidden
  695. std::shared_ptr<IImage> image;
  696. if (retBitmapID >= 0)
  697. image = parent->FoWpartialHide.at(retBitmapID);
  698. else
  699. image = parent->FoWfullHide.at(-retBitmapID - 1);
  700. Rect destRect(realTileRect);
  701. drawElement(EMapCacheType::FOW, image, nullptr, targetSurf, &destRect);
  702. }
  703. void CMapHandler::CMapBlitter::blit(SDL_Surface * targetSurf, const MapDrawingInfo * info)
  704. {
  705. init(info);
  706. auto prevClip = clip(targetSurf);
  707. pos = int3(0, 0, topTile.z);
  708. for (realPos.x = initPos.x, pos.x = topTile.x; pos.x < topTile.x + tileCount.x; pos.x++, realPos.x += tileSize)
  709. {
  710. if (pos.x < 0 || pos.x >= parent->sizes.x)
  711. continue;
  712. for (realPos.y = initPos.y, pos.y = topTile.y; pos.y < topTile.y + tileCount.y; pos.y++, realPos.y += tileSize)
  713. {
  714. if (pos.y < 0 || pos.y >= parent->sizes.y)
  715. continue;
  716. const bool isVisible = canDrawCurrentTile();
  717. realTileRect.x = realPos.x;
  718. realTileRect.y = realPos.y;
  719. const TerrainTile2 & tile = parent->ttiles[pos.z][pos.x][pos.y];
  720. const TerrainTile & tinfo = parent->map->getTile(pos);
  721. const TerrainTile * tinfoUpper = pos.y > 0 ? &parent->map->getTile(int3(pos.x, pos.y - 1, pos.z)) : nullptr;
  722. if(isVisible || info->showAllTerrain)
  723. {
  724. drawTileTerrain(targetSurf, tinfo, tile);
  725. if(tinfo.riverType->getId() != River::NO_RIVER)
  726. drawRiver(targetSurf, tinfo);
  727. drawRoad(targetSurf, tinfo, tinfoUpper);
  728. }
  729. if(isVisible)
  730. drawObjects(targetSurf, tile);
  731. }
  732. }
  733. for (realPos.x = initPos.x, pos.x = topTile.x; pos.x < topTile.x + tileCount.x; pos.x++, realPos.x += tileSize)
  734. {
  735. for (realPos.y = initPos.y, pos.y = topTile.y; pos.y < topTile.y + tileCount.y; pos.y++, realPos.y += tileSize)
  736. {
  737. realTileRect.x = realPos.x;
  738. realTileRect.y = realPos.y;
  739. if (pos.x < 0 || pos.x >= parent->sizes.x ||
  740. pos.y < 0 || pos.y >= parent->sizes.y)
  741. {
  742. drawFrame(targetSurf);
  743. }
  744. else
  745. {
  746. const TerrainTile2 & tile = parent->ttiles[pos.z][pos.x][pos.y];
  747. if(!settings["session"]["spectate"].Bool() && !(*info->visibilityMap)[topTile.z][pos.x][pos.y] && !info->showAllTerrain)
  748. drawFow(targetSurf);
  749. // overlay needs to be drawn over fow, because of artifacts-aura-like spells
  750. drawTileOverlay(targetSurf, tile);
  751. // drawDebugVisitables()
  752. if (settings["session"]["showBlock"].Bool())
  753. {
  754. if(parent->map->getTile(int3(pos.x, pos.y, pos.z)).blocked) //temporary hiding blocked positions
  755. {
  756. static std::shared_ptr<IImage> block;
  757. if (!block)
  758. block = IImage::createFromFile("blocked");
  759. block->draw(targetSurf, realTileRect.x, realTileRect.y);
  760. }
  761. }
  762. if (settings["session"]["showVisit"].Bool())
  763. {
  764. if(parent->map->getTile(int3(pos.x, pos.y, pos.z)).visitable) //temporary hiding visitable positions
  765. {
  766. static std::shared_ptr<IImage> visit;
  767. if (!visit)
  768. visit = IImage::createFromFile("visitable");
  769. visit->draw(targetSurf, realTileRect.x, realTileRect.y);
  770. }
  771. }
  772. }
  773. }
  774. }
  775. drawOverlayEx(targetSurf);
  776. // drawDebugGrid()
  777. if (settings["gameTweaks"]["showGrid"].Bool())
  778. {
  779. for (realPos.x = initPos.x, pos.x = topTile.x; pos.x < topTile.x + tileCount.x; pos.x++, realPos.x += tileSize)
  780. {
  781. for (realPos.y = initPos.y, pos.y = topTile.y; pos.y < topTile.y + tileCount.y; pos.y++, realPos.y += tileSize)
  782. {
  783. const int3 color(0x555555, 0x555555, 0x555555);
  784. if (realPos.y >= info->drawBounds.y &&
  785. realPos.y < info->drawBounds.y + info->drawBounds.h)
  786. for(int i = 0; i < tileSize; i++)
  787. if (realPos.x + i >= info->drawBounds.x &&
  788. realPos.x + i < info->drawBounds.x + info->drawBounds.w)
  789. CSDL_Ext::putPixelWithoutRefresh(targetSurf, realPos.x + i, realPos.y, color.x, color.y, color.z);
  790. if (realPos.x >= info->drawBounds.x &&
  791. realPos.x < info->drawBounds.x + info->drawBounds.w)
  792. for(int i = 0; i < tileSize; i++)
  793. if (realPos.y + i >= info->drawBounds.y &&
  794. realPos.y + i < info->drawBounds.y + info->drawBounds.h)
  795. CSDL_Ext::putPixelWithoutRefresh(targetSurf, realPos.x, realPos.y + i, color.x, color.y, color.z);
  796. }
  797. }
  798. }
  799. postProcessing(targetSurf);
  800. CSDL_Ext::setClipRect(targetSurf, prevClip);
  801. }
  802. CMapHandler::AnimBitmapHolder CMapHandler::CMapBlitter::findHeroBitmap(const CGHeroInstance * hero, int anim) const
  803. {
  804. if(hero && hero->moveDir && hero->type) //it's hero or boat
  805. {
  806. if(hero->tempOwner >= PlayerColor::PLAYER_LIMIT) //Neutral hero?
  807. {
  808. logGlobal->error("A neutral hero (%s) at %s. Should not happen!", hero->getNameTranslated(), hero->pos.toString());
  809. return CMapHandler::AnimBitmapHolder();
  810. }
  811. //pick graphics of hero (or boat if hero is sailing)
  812. std::shared_ptr<CAnimation> animation;
  813. if (hero->boat)
  814. animation = graphics->boatAnimations[hero->boat->subID];
  815. else
  816. animation = graphics->heroAnimations[hero->appearance->animationFile];
  817. bool moving = !hero->isStanding;
  818. int group = getHeroFrameGroup(hero->moveDir, moving);
  819. if(animation->size(group) > 0)
  820. {
  821. int frame = anim % animation->size(group);
  822. auto heroImage = animation->getImage(frame, group);
  823. //get flag overlay only if we have main image
  824. auto flagImage = findFlagBitmap(hero, anim, &hero->tempOwner, group);
  825. return CMapHandler::AnimBitmapHolder(heroImage, flagImage, moving);
  826. }
  827. }
  828. return CMapHandler::AnimBitmapHolder();
  829. }
  830. CMapHandler::AnimBitmapHolder CMapHandler::CMapBlitter::findBoatBitmap(const CGBoat * boat, int anim) const
  831. {
  832. auto animation = graphics->boatAnimations.at(boat->subID);
  833. int group = getHeroFrameGroup(boat->direction, false);
  834. if(animation->size(group) > 0)
  835. return CMapHandler::AnimBitmapHolder(animation->getImage(anim % animation->size(group), group));
  836. else
  837. return CMapHandler::AnimBitmapHolder();
  838. }
  839. std::shared_ptr<IImage> CMapHandler::CMapBlitter::findFlagBitmap(const CGHeroInstance * hero, int anim, const PlayerColor * color, int group) const
  840. {
  841. if(!hero)
  842. return std::shared_ptr<IImage>();
  843. if(hero->boat)
  844. return findBoatFlagBitmap(hero->boat, anim, color, group, hero->moveDir);
  845. return findHeroFlagBitmap(hero, anim, color, group);
  846. }
  847. std::shared_ptr<IImage> CMapHandler::CMapBlitter::findHeroFlagBitmap(const CGHeroInstance * hero, int anim, const PlayerColor * color, int group) const
  848. {
  849. return findFlagBitmapInternal(graphics->heroFlagAnimations.at(color->getNum()), anim, group, hero->moveDir, !hero->isStanding);
  850. }
  851. std::shared_ptr<IImage> CMapHandler::CMapBlitter::findBoatFlagBitmap(const CGBoat * boat, int anim, const PlayerColor * color, int group, ui8 dir) const
  852. {
  853. int boatType = boat->subID;
  854. if(boatType < 0 || boatType >= graphics->boatFlagAnimations.size())
  855. {
  856. logGlobal->error("Not supported boat subtype: %d", boat->subID);
  857. return nullptr;
  858. }
  859. const auto & subtypeFlags = graphics->boatFlagAnimations.at(boatType);
  860. int colorIndex = color->getNum();
  861. if(colorIndex < 0 || colorIndex >= subtypeFlags.size())
  862. {
  863. logGlobal->error("Invalid player color %d", colorIndex);
  864. return nullptr;
  865. }
  866. return findFlagBitmapInternal(subtypeFlags.at(colorIndex), anim, group, dir, false);
  867. }
  868. std::shared_ptr<IImage> CMapHandler::CMapBlitter::findFlagBitmapInternal(std::shared_ptr<CAnimation> animation, int anim, int group, ui8 dir, bool moving) const
  869. {
  870. size_t groupSize = animation->size(group);
  871. if(groupSize == 0)
  872. return nullptr;
  873. if(moving)
  874. return animation->getImage(anim % groupSize, group);
  875. else
  876. return animation->getImage((anim / 4) % groupSize, group);
  877. }
  878. CMapHandler::AnimBitmapHolder CMapHandler::CMapBlitter::findObjectBitmap(const CGObjectInstance * obj, int anim) const
  879. {
  880. if (!obj)
  881. return CMapHandler::AnimBitmapHolder();
  882. if (obj->ID == Obj::HERO)
  883. return findHeroBitmap(static_cast<const CGHeroInstance*>(obj), anim);
  884. if (obj->ID == Obj::BOAT)
  885. return findBoatBitmap(static_cast<const CGBoat*>(obj), anim);
  886. // normal object
  887. std::shared_ptr<CAnimation> animation = graphics->getAnimation(obj);
  888. size_t groupSize = animation->size();
  889. if(groupSize == 0)
  890. return CMapHandler::AnimBitmapHolder();
  891. auto bitmap = animation->getImage((anim + getPhaseShift(obj)) % groupSize);
  892. if(!bitmap)
  893. return CMapHandler::AnimBitmapHolder();
  894. bitmap->setFlagColor(obj->tempOwner);
  895. return CMapHandler::AnimBitmapHolder(bitmap);
  896. }
  897. ui8 CMapHandler::CMapBlitter::getPhaseShift(const CGObjectInstance *object) const
  898. {
  899. auto i = parent->animationPhase.find(object);
  900. if(i == parent->animationPhase.end())
  901. {
  902. ui8 ret = CRandomGenerator::getDefault().nextInt(254);
  903. parent->animationPhase[object] = ret;
  904. return ret;
  905. }
  906. return i->second;
  907. }
  908. bool CMapHandler::CMapBlitter::canDrawObject(const CGObjectInstance * obj) const
  909. {
  910. //checking if object has non-empty graphic on this tile
  911. return obj->ID == Obj::HERO || obj->coveringAt(pos.x, pos.y);
  912. }
  913. bool CMapHandler::CMapBlitter::canDrawCurrentTile() const
  914. {
  915. if(settings["session"]["spectate"].Bool())
  916. return true;
  917. const NeighborTilesInfo neighbors(pos, parent->sizes, info->visibilityMap);
  918. return !neighbors.areAllHidden();
  919. }
  920. ui8 CMapHandler::CMapBlitter::getHeroFrameGroup(ui8 dir, bool isMoving) const
  921. {
  922. if(isMoving)
  923. {
  924. static const ui8 frame [] = {0xff, 10, 5, 6, 7, 8, 9, 12, 11};
  925. return frame[dir];
  926. }
  927. else //if(isMoving)
  928. {
  929. static const ui8 frame [] = {0xff, 13, 0, 1, 2, 3, 4, 15, 14};
  930. return frame[dir];
  931. }
  932. }
  933. bool CMapHandler::updateObjectsFade()
  934. {
  935. for (auto iter = fadeAnims.begin(); iter != fadeAnims.end(); )
  936. {
  937. int3 pos = (*iter).second.first;
  938. CFadeAnimation * anim = (*iter).second.second;
  939. anim->update();
  940. if (anim->isFading())
  941. ++iter;
  942. else // fade finished
  943. {
  944. auto &objs = ttiles[pos.z][pos.x][pos.y].objects;
  945. for (auto objIter = objs.begin(); objIter != objs.end(); ++objIter)
  946. {
  947. if ((*objIter).fadeAnimKey == (*iter).first)
  948. {
  949. logAnim->trace("Fade anim finished for obj at %s; remaining: %d", pos.toString(), fadeAnims.size() - 1);
  950. if (anim->fadingMode == CFadeAnimation::EMode::OUT)
  951. objs.erase(objIter); // if this was fadeout, remove the object from the map
  952. else
  953. (*objIter).fadeAnimKey = -1; // for fadein, just remove its connection to the finished fade
  954. break;
  955. }
  956. }
  957. delete (*iter).second.second;
  958. iter = fadeAnims.erase(iter);
  959. }
  960. }
  961. return !fadeAnims.empty();
  962. }
  963. bool CMapHandler::startObjectFade(TerrainTileObject & obj, bool in, int3 pos)
  964. {
  965. SDL_Surface * fadeBitmap;
  966. assert(obj.obj);
  967. auto objData = normalBlitter->findObjectBitmap(obj.obj, 0);
  968. if (objData.objBitmap)
  969. {
  970. if (objData.isMoving) // ignore fading of moving objects (for now?)
  971. {
  972. logAnim->debug("Ignoring fade of moving object");
  973. return false;
  974. }
  975. fadeBitmap = CSDL_Ext::newSurface(32, 32); // TODO cache these bitmaps instead of creating new ones?
  976. Rect objSrcRect(obj.rect.x, obj.rect.y, 32, 32);
  977. objData.objBitmap->draw(fadeBitmap,0,0,&objSrcRect);
  978. if (objData.flagBitmap)
  979. {
  980. if (obj.obj->pos.x - 1 == pos.x && obj.obj->pos.y - 1 == pos.y) // -1 to draw flag in top-center instead of right-bottom; kind of a hack
  981. {
  982. Rect flagSrcRect(32, 0, 32, 32);
  983. objData.flagBitmap->draw(fadeBitmap,0,0, &flagSrcRect);
  984. }
  985. }
  986. auto anim = new CFadeAnimation();
  987. anim->init(in ? CFadeAnimation::EMode::IN : CFadeAnimation::EMode::OUT, fadeBitmap, true);
  988. fadeAnims[++fadeAnimCounter] = std::pair<int3, CFadeAnimation*>(pos, anim);
  989. obj.fadeAnimKey = fadeAnimCounter;
  990. logAnim->trace("Fade anim started for obj %d at %s; anim count: %d", obj.obj->ID, pos.toString(), fadeAnims.size());
  991. return true;
  992. }
  993. return false;
  994. }
  995. bool CMapHandler::printObject(const CGObjectInstance * obj, bool fadein)
  996. {
  997. auto animation = graphics->getAnimation(obj);
  998. if(!animation)
  999. return false;
  1000. auto bitmap = animation->getImage(0);
  1001. if(!bitmap)
  1002. return false;
  1003. const int tilesW = bitmap->width()/32;
  1004. const int tilesH = bitmap->height()/32;
  1005. auto ttilesWidth = ttiles.shape()[1];
  1006. auto ttilesHeight = ttiles.shape()[2];
  1007. for(int fx=0; fx<tilesW; ++fx)
  1008. {
  1009. for(int fy=0; fy<tilesH; ++fy)
  1010. {
  1011. Rect cr;
  1012. cr.w = 32;
  1013. cr.h = 32;
  1014. cr.x = fx*32;
  1015. cr.y = fy*32;
  1016. if((obj->pos.x + fx - tilesW + 1) >= 0 &&
  1017. (obj->pos.x + fx - tilesW + 1) < ttilesWidth - frameW &&
  1018. (obj->pos.y + fy - tilesH + 1) >= 0 &&
  1019. (obj->pos.y + fy - tilesH + 1) < ttilesHeight - frameH)
  1020. {
  1021. int3 pos(obj->pos.x + fx - tilesW + 1, obj->pos.y + fy - tilesH + 1, obj->pos.z);
  1022. TerrainTile2 & curt = ttiles[pos.z][pos.x][pos.y];
  1023. TerrainTileObject toAdd(obj, cr, obj->visitableAt(pos.x, pos.y));
  1024. if (fadein && ADVOPT.objectFading)
  1025. {
  1026. startObjectFade(toAdd, true, pos);
  1027. }
  1028. auto i = curt.objects.begin();
  1029. for(; i != curt.objects.end(); i++)
  1030. {
  1031. if(objectBlitOrderSorter(toAdd, *i))
  1032. {
  1033. curt.objects.insert(i, toAdd);
  1034. i = curt.objects.begin(); //to validate and avoid adding it second time
  1035. break;
  1036. }
  1037. }
  1038. if(i == curt.objects.end())
  1039. curt.objects.insert(i, toAdd);
  1040. }
  1041. }
  1042. }
  1043. return true;
  1044. }
  1045. bool CMapHandler::hideObject(const CGObjectInstance * obj, bool fadeout)
  1046. {
  1047. for(size_t z = 0; z < map->levels(); z++)
  1048. {
  1049. for(size_t x = 0; x < map->width; x++)
  1050. {
  1051. for(size_t y = 0; y < map->height; y++)
  1052. {
  1053. auto &objs = ttiles[(int)z][(int)x][(int)y].objects;
  1054. for(size_t i = 0; i < objs.size(); i++)
  1055. {
  1056. if (objs[i].obj && objs[i].obj->id == obj->id)
  1057. {
  1058. if (fadeout && ADVOPT.objectFading) // object should be faded == erase is delayed until the end of fadeout
  1059. {
  1060. if (startObjectFade(objs[i], false, int3((si32)x, (si32)y, (si32)z)))
  1061. objs[i].obj = nullptr;
  1062. else
  1063. objs.erase(objs.begin() + i);
  1064. }
  1065. else
  1066. objs.erase(objs.begin() + i);
  1067. break;
  1068. }
  1069. }
  1070. }
  1071. }
  1072. }
  1073. return true;
  1074. }
  1075. bool CMapHandler::canStartHeroMovement()
  1076. {
  1077. return fadeAnims.empty(); // don't allow movement during fade animation
  1078. }
  1079. void CMapHandler::updateWater() //shift colors in palettes of water tiles
  1080. {
  1081. for(auto & elem : terrainImages["lava"])
  1082. {
  1083. for(auto img : elem)
  1084. img->shiftPalette(246, 9);
  1085. }
  1086. for(auto & elem : terrainImages["water"])
  1087. {
  1088. for(auto img : elem)
  1089. {
  1090. img->shiftPalette(229, 12);
  1091. img->shiftPalette(242, 14);
  1092. }
  1093. }
  1094. for(auto & elem : riverImages["clrrvr"])
  1095. {
  1096. for(auto img : elem)
  1097. {
  1098. img->shiftPalette(183, 12);
  1099. img->shiftPalette(195, 6);
  1100. }
  1101. }
  1102. for(auto & elem : riverImages["mudrvr"])
  1103. {
  1104. for(auto img : elem)
  1105. {
  1106. img->shiftPalette(228, 12);
  1107. img->shiftPalette(183, 6);
  1108. img->shiftPalette(240, 6);
  1109. }
  1110. }
  1111. for(auto & elem : riverImages["lavrvr"])
  1112. {
  1113. for(auto img : elem)
  1114. img->shiftPalette(240, 9);
  1115. }
  1116. }
  1117. CMapHandler::~CMapHandler()
  1118. {
  1119. delete normalBlitter;
  1120. delete worldViewBlitter;
  1121. delete puzzleViewBlitter;
  1122. for (auto & elem : fadeAnims)
  1123. {
  1124. delete elem.second.second;
  1125. }
  1126. }
  1127. CMapHandler::CMapHandler()
  1128. {
  1129. frameW = frameH = 0;
  1130. normalBlitter = new CMapNormalBlitter(this);
  1131. worldViewBlitter = new CMapWorldViewBlitter(this);
  1132. puzzleViewBlitter = new CMapPuzzleViewBlitter(this);
  1133. fadeAnimCounter = 0;
  1134. map = nullptr;
  1135. tilesW = tilesH = 0;
  1136. offsetX = offsetY = 0;
  1137. egdeAnimation = std::make_unique<CAnimation>("EDG");
  1138. egdeAnimation->preload();
  1139. }
  1140. bool CMapHandler::hasObjectHole(const int3 & pos) const
  1141. {
  1142. const TerrainTile2 & tt = ttiles[pos.z][pos.x][pos.y];
  1143. for(auto & elem : tt.objects)
  1144. {
  1145. if(elem.obj && elem.obj->ID == Obj::HOLE)
  1146. return true;
  1147. }
  1148. return false;
  1149. }
  1150. void CMapHandler::getTerrainDescr(const int3 & pos, std::string & out, bool isRMB) const
  1151. {
  1152. const TerrainTile & t = map->getTile(pos);
  1153. if(t.hasFavorableWinds())
  1154. {
  1155. out = CGI->objtypeh->getObjectName(Obj::FAVORABLE_WINDS, 0);
  1156. return;
  1157. }
  1158. const TerrainTile2 & tt = ttiles[pos.z][pos.x][pos.y];
  1159. bool isTile2Terrain = false;
  1160. out.clear();
  1161. for(auto & elem : tt.objects)
  1162. {
  1163. if(elem.obj)
  1164. {
  1165. out = elem.obj->getObjectName();
  1166. if(elem.obj->ID == Obj::HOLE)
  1167. return;
  1168. isTile2Terrain = elem.obj->isTile2Terrain();
  1169. break;
  1170. }
  1171. }
  1172. if(!isTile2Terrain || out.empty())
  1173. out = t.terType->getNameTranslated();
  1174. if(t.getDiggingStatus(false) == EDiggingStatus::CAN_DIG)
  1175. {
  1176. out = boost::str(boost::format(isRMB ? "%s\r\n%s" : "%s %s") // New line for the Message Box, space for the Status Bar
  1177. % out
  1178. % CGI->generaltexth->allTexts[330]); // 'digging ok'
  1179. }
  1180. }
  1181. void CMapHandler::discardWorldViewCache()
  1182. {
  1183. cache.discardWorldViewCache();
  1184. }
  1185. CMapHandler::CMapCache::CMapCache()
  1186. {
  1187. worldViewCachedScale = 0;
  1188. }
  1189. void CMapHandler::CMapCache::discardWorldViewCache()
  1190. {
  1191. for(auto & cache : data)
  1192. cache.clear();
  1193. logAnim->debug("Discarded world view cache");
  1194. }
  1195. void CMapHandler::CMapCache::updateWorldViewScale(float scale)
  1196. {
  1197. if (fabs(scale - worldViewCachedScale) > 0.001f)
  1198. discardWorldViewCache();
  1199. worldViewCachedScale = scale;
  1200. }
  1201. std::shared_ptr<IImage> CMapHandler::CMapCache::requestWorldViewCacheOrCreate(CMapHandler::EMapCacheType type, std::shared_ptr<IImage> fullSurface)
  1202. {
  1203. intptr_t key = (intptr_t) (fullSurface.get());
  1204. auto & cache = data[(ui8)type];
  1205. auto iter = cache.find(key);
  1206. if(iter == cache.end())
  1207. {
  1208. auto scaled = fullSurface->scaleFast(fullSurface->dimensions() * worldViewCachedScale);
  1209. cache[key] = scaled;
  1210. return scaled;
  1211. }
  1212. else
  1213. {
  1214. return (*iter).second;
  1215. }
  1216. }
  1217. bool CMapHandler::compareObjectBlitOrder(const CGObjectInstance * a, const CGObjectInstance * b)
  1218. {
  1219. if (!a)
  1220. return true;
  1221. if (!b)
  1222. return false;
  1223. if (a->appearance->printPriority != b->appearance->printPriority)
  1224. return a->appearance->printPriority > b->appearance->printPriority;
  1225. if(a->pos.y != b->pos.y)
  1226. return a->pos.y < b->pos.y;
  1227. if(b->ID==Obj::HERO && a->ID!=Obj::HERO)
  1228. return true;
  1229. if(b->ID!=Obj::HERO && a->ID==Obj::HERO)
  1230. return false;
  1231. if(!a->isVisitable() && b->isVisitable())
  1232. return true;
  1233. if(!b->isVisitable() && a->isVisitable())
  1234. return false;
  1235. if(a->pos.x < b->pos.x)
  1236. return true;
  1237. return false;
  1238. }
  1239. TerrainTileObject::TerrainTileObject(const CGObjectInstance * obj_, Rect rect_, bool visitablePos)
  1240. : obj(obj_),
  1241. rect(rect_),
  1242. fadeAnimKey(-1)
  1243. {
  1244. // We store information about ambient sound is here because object might disappear while sound is updating
  1245. if(obj->getAmbientSound())
  1246. {
  1247. // All tiles of static objects are sound sources. E.g Volcanos and special terrains
  1248. // For visitable object only their visitable tile is sound source
  1249. if(!CCS->soundh->ambientCheckVisitable() || !obj->isVisitable() || visitablePos)
  1250. ambientSound = obj->getAmbientSound();
  1251. }
  1252. }
  1253. TerrainTileObject::~TerrainTileObject()
  1254. {
  1255. }