mapHandler.cpp 45 KB

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