mapHandler.cpp 46 KB

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