mapHandler.cpp 44 KB

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