mapHandler.cpp 44 KB

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