mapHandler.cpp 45 KB

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