mapHandler.cpp 44 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504
  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 = [this](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, const 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. 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 nullptr;
  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, const 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, const 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, const 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, const 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, const 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. const IImage * image = nullptr;
  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. IImage * CMapHandler::CMapBlitter::findFlagBitmap(const CGHeroInstance * hero, int anim, const PlayerColor * color, int group) const
  857. {
  858. if (!hero)
  859. return nullptr;
  860. if (hero->boat)
  861. return findBoatFlagBitmap(hero->boat, anim, color, group, hero->moveDir);
  862. return findHeroFlagBitmap(hero, anim, color, group);
  863. }
  864. 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. 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. 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. IImage * CMapHandler::CMapCache::requestWorldViewCacheOrCreate(CMapHandler::EMapCacheType type, const IImage * fullSurface)
  1226. {
  1227. intptr_t key = (intptr_t) fullSurface;
  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. IImage * ret = scaled.get();
  1234. cache[key] = std::move(scaled);
  1235. return ret;
  1236. }
  1237. else
  1238. {
  1239. return (*iter).second.get();
  1240. }
  1241. }
  1242. bool CMapHandler::compareObjectBlitOrder(const CGObjectInstance * a, const CGObjectInstance * b)
  1243. {
  1244. if (!a)
  1245. return true;
  1246. if (!b)
  1247. return false;
  1248. if (a->appearance.printPriority != b->appearance.printPriority)
  1249. return a->appearance.printPriority > b->appearance.printPriority;
  1250. if(a->pos.y != b->pos.y)
  1251. return a->pos.y < b->pos.y;
  1252. if(b->ID==Obj::HERO && a->ID!=Obj::HERO)
  1253. return true;
  1254. if(b->ID!=Obj::HERO && a->ID==Obj::HERO)
  1255. return false;
  1256. if(!a->isVisitable() && b->isVisitable())
  1257. return true;
  1258. if(!b->isVisitable() && a->isVisitable())
  1259. return false;
  1260. if(a->pos.x < b->pos.x)
  1261. return true;
  1262. return false;
  1263. }
  1264. TerrainTileObject::TerrainTileObject(const CGObjectInstance * obj_, SDL_Rect rect_, bool visitablePos)
  1265. : obj(obj_),
  1266. rect(rect_),
  1267. fadeAnimKey(-1)
  1268. {
  1269. // We store information about ambient sound is here because object might disappear while sound is updating
  1270. if(obj->getAmbientSound())
  1271. {
  1272. // All tiles of static objects are sound sources. E.g Volcanos and special terrains
  1273. // For visitable object only their visitable tile is sound source
  1274. if(!CCS->soundh->ambientCheckVisitable() || !obj->isVisitable() || visitablePos)
  1275. ambientSound = obj->getAmbientSound();
  1276. }
  1277. }
  1278. TerrainTileObject::~TerrainTileObject()
  1279. {
  1280. }