mapHandler.cpp 49 KB

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