Graphics.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466
  1. /*
  2. * Graphics.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 "Graphics.h"
  12. #include <vcmi/Entity.h>
  13. #include <vcmi/ArtifactService.h>
  14. #include <vcmi/CreatureService.h>
  15. #include <vcmi/FactionService.h>
  16. #include <vcmi/HeroTypeService.h>
  17. #include <vcmi/SkillService.h>
  18. #include <vcmi/spells/Service.h>
  19. #include "../lib/filesystem/Filesystem.h"
  20. #include "../lib/filesystem/CBinaryReader.h"
  21. #include "gui/SDL_Extensions.h"
  22. #include "gui/CAnimation.h"
  23. #include <SDL_ttf.h>
  24. #include "../lib/CThreadHelper.h"
  25. #include "../lib/CModHandler.h"
  26. #include "CGameInfo.h"
  27. #include "../lib/VCMI_Lib.h"
  28. #include "../CCallback.h"
  29. #include "../lib/CGeneralTextHandler.h"
  30. #include "CBitmapHandler.h"
  31. #include "../lib/CGameState.h"
  32. #include "../lib/JsonNode.h"
  33. #include "../lib/vcmi_endian.h"
  34. #include "../lib/CStopWatch.h"
  35. #include "../lib/mapObjects/CObjectClassesHandler.h"
  36. #include "../lib/mapObjects/CObjectHandler.h"
  37. #include "../lib/CHeroHandler.h"
  38. using namespace CSDL_Ext;
  39. Graphics * graphics = nullptr;
  40. void Graphics::loadPaletteAndColors()
  41. {
  42. auto textFile = CResourceHandler::get()->load(ResourceID("DATA/PLAYERS.PAL"))->readAll();
  43. std::string pals((char*)textFile.first.get(), textFile.second);
  44. playerColorPalette = new SDL_Color[256];
  45. neutralColor = new SDL_Color;
  46. playerColors = new SDL_Color[PlayerColor::PLAYER_LIMIT_I];
  47. int startPoint = 24; //beginning byte; used to read
  48. for(int i=0; i<256; ++i)
  49. {
  50. SDL_Color col;
  51. col.r = pals[startPoint++];
  52. col.g = pals[startPoint++];
  53. col.b = pals[startPoint++];
  54. col.a = SDL_ALPHA_OPAQUE;
  55. startPoint++;
  56. playerColorPalette[i] = col;
  57. }
  58. neutralColorPalette = new SDL_Color[32];
  59. auto stream = CResourceHandler::get()->load(ResourceID("config/NEUTRAL.PAL"));
  60. CBinaryReader reader(stream.get());
  61. for(int i=0; i<32; ++i)
  62. {
  63. neutralColorPalette[i].r = reader.readUInt8();
  64. neutralColorPalette[i].g = reader.readUInt8();
  65. neutralColorPalette[i].b = reader.readUInt8();
  66. reader.readUInt8(); // this is "flags" entry, not alpha
  67. neutralColorPalette[i].a = SDL_ALPHA_OPAQUE;
  68. }
  69. //colors initialization
  70. SDL_Color colors[] = {
  71. {0xff,0, 0, SDL_ALPHA_OPAQUE},
  72. {0x31,0x52,0xff,SDL_ALPHA_OPAQUE},
  73. {0x9c,0x73,0x52,SDL_ALPHA_OPAQUE},
  74. {0x42,0x94,0x29,SDL_ALPHA_OPAQUE},
  75. {0xff,0x84,0, SDL_ALPHA_OPAQUE},
  76. {0x8c,0x29,0xa5,SDL_ALPHA_OPAQUE},
  77. {0x09,0x9c,0xa5,SDL_ALPHA_OPAQUE},
  78. {0xc6,0x7b,0x8c,SDL_ALPHA_OPAQUE}};
  79. for(int i=0;i<8;i++)
  80. {
  81. playerColors[i] = colors[i];
  82. }
  83. //gray
  84. neutralColor->r = 0x84;
  85. neutralColor->g = 0x84;
  86. neutralColor->b = 0x84;
  87. neutralColor->a = SDL_ALPHA_OPAQUE;
  88. }
  89. void Graphics::initializeBattleGraphics()
  90. {
  91. auto allConfigs = VLC->modh->getActiveMods();
  92. allConfigs.insert(allConfigs.begin(), CModHandler::scopeBuiltin());
  93. for(auto & mod : allConfigs)
  94. {
  95. if(!CResourceHandler::get(mod)->existsResource(ResourceID("config/battles_graphics.json")))
  96. continue;
  97. const JsonNode config(mod, ResourceID("config/battles_graphics.json"));
  98. //initialization of AC->def name mapping
  99. if(!config["ac_mapping"].isNull())
  100. for(const JsonNode &ac : config["ac_mapping"].Vector())
  101. {
  102. int ACid = static_cast<int>(ac["id"].Float());
  103. std::vector< std::string > toAdd;
  104. for(const JsonNode &defname : ac["defnames"].Vector())
  105. {
  106. toAdd.push_back(defname.String());
  107. }
  108. battleACToDef[ACid] = toAdd;
  109. }
  110. }
  111. }
  112. Graphics::Graphics()
  113. {
  114. #if 0
  115. std::vector<Task> tasks; //preparing list of graphics to load
  116. tasks += std::bind(&Graphics::loadFonts,this);
  117. tasks += std::bind(&Graphics::loadPaletteAndColors,this);
  118. tasks += std::bind(&Graphics::initializeBattleGraphics,this);
  119. tasks += std::bind(&Graphics::loadErmuToPicture,this);
  120. tasks += std::bind(&Graphics::initializeImageLists,this);
  121. CThreadHelper th(&tasks,std::max((ui32)1,boost::thread::hardware_concurrency()));
  122. th.run();
  123. #else
  124. loadFonts();
  125. loadPaletteAndColors();
  126. initializeBattleGraphics();
  127. loadErmuToPicture();
  128. initializeImageLists();
  129. #endif
  130. //(!) do not load any CAnimation here
  131. }
  132. Graphics::~Graphics()
  133. {
  134. delete[] playerColors;
  135. delete neutralColor;
  136. delete[] playerColorPalette;
  137. delete[] neutralColorPalette;
  138. }
  139. void Graphics::load()
  140. {
  141. heroMoveArrows = std::make_shared<CAnimation>("ADAG");
  142. heroMoveArrows->preload();
  143. loadHeroAnimations();
  144. loadHeroFlagAnimations();
  145. loadFogOfWar();
  146. }
  147. void Graphics::loadHeroAnimations()
  148. {
  149. for(auto & elem : CGI->heroh->classes.objects)
  150. {
  151. for (auto & templ : VLC->objtypeh->getHandlerFor(Obj::HERO, elem->getIndex())->getTemplates())
  152. {
  153. if (!heroAnimations.count(templ->animationFile))
  154. heroAnimations[templ->animationFile] = loadHeroAnimation(templ->animationFile);
  155. }
  156. }
  157. boatAnimations[0] = loadHeroAnimation("AB01_.DEF");
  158. boatAnimations[1] = loadHeroAnimation("AB02_.DEF");
  159. boatAnimations[2] = loadHeroAnimation("AB03_.DEF");
  160. mapObjectAnimations["AB01_.DEF"] = boatAnimations[0];
  161. mapObjectAnimations["AB02_.DEF"] = boatAnimations[1];
  162. mapObjectAnimations["AB03_.DEF"] = boatAnimations[2];
  163. }
  164. void Graphics::loadHeroFlagAnimations()
  165. {
  166. static const std::vector<std::string> HERO_FLAG_ANIMATIONS =
  167. {
  168. "AF00", "AF01","AF02","AF03",
  169. "AF04", "AF05","AF06","AF07"
  170. };
  171. static const std::vector< std::vector<std::string> > BOAT_FLAG_ANIMATIONS =
  172. {
  173. {
  174. "ABF01L", "ABF01G", "ABF01R", "ABF01D",
  175. "ABF01B", "ABF01P", "ABF01W", "ABF01K"
  176. },
  177. {
  178. "ABF02L", "ABF02G", "ABF02R", "ABF02D",
  179. "ABF02B", "ABF02P", "ABF02W", "ABF02K"
  180. },
  181. {
  182. "ABF03L", "ABF03G", "ABF03R", "ABF03D",
  183. "ABF03B", "ABF03P", "ABF03W", "ABF03K"
  184. }
  185. };
  186. for(const auto & name : HERO_FLAG_ANIMATIONS)
  187. heroFlagAnimations.push_back(loadHeroFlagAnimation(name));
  188. for(int i = 0; i < BOAT_FLAG_ANIMATIONS.size(); i++)
  189. for(const auto & name : BOAT_FLAG_ANIMATIONS[i])
  190. boatFlagAnimations[i].push_back(loadHeroFlagAnimation(name));
  191. }
  192. std::shared_ptr<CAnimation> Graphics::loadHeroFlagAnimation(const std::string & name)
  193. {
  194. //first - group number to be rotated, second - group number after rotation
  195. static const std::vector<std::pair<int,int> > rotations =
  196. {
  197. {6,10}, {7,11}, {8,12}, {1,13},
  198. {2,14}, {3,15}
  199. };
  200. std::shared_ptr<CAnimation> anim = std::make_shared<CAnimation>(name);
  201. anim->preload();
  202. for(const auto & rotation : rotations)
  203. {
  204. const int sourceGroup = rotation.first;
  205. const int targetGroup = rotation.second;
  206. anim->createFlippedGroup(sourceGroup, targetGroup);
  207. }
  208. return anim;
  209. }
  210. std::shared_ptr<CAnimation> Graphics::loadHeroAnimation(const std::string &name)
  211. {
  212. //first - group number to be rotated, second - group number after rotation
  213. static const std::vector<std::pair<int,int> > rotations =
  214. {
  215. {6,10}, {7,11}, {8,12}, {1,13},
  216. {2,14}, {3,15}
  217. };
  218. std::shared_ptr<CAnimation> anim = std::make_shared<CAnimation>(name);
  219. anim->preload();
  220. for(const auto & rotation : rotations)
  221. {
  222. const int sourceGroup = rotation.first;
  223. const int targetGroup = rotation.second;
  224. anim->createFlippedGroup(sourceGroup, targetGroup);
  225. }
  226. return anim;
  227. }
  228. void Graphics::blueToPlayersAdv(SDL_Surface * sur, PlayerColor player)
  229. {
  230. if(sur->format->palette)
  231. {
  232. SDL_Color * palette = nullptr;
  233. if(player < PlayerColor::PLAYER_LIMIT)
  234. {
  235. palette = playerColorPalette + 32*player.getNum();
  236. }
  237. else if(player == PlayerColor::NEUTRAL)
  238. {
  239. palette = neutralColorPalette;
  240. }
  241. else
  242. {
  243. logGlobal->error("Wrong player id in blueToPlayersAdv (%s)!", player.getStr());
  244. return;
  245. }
  246. //FIXME: not all player colored images have player palette at last 32 indexes
  247. //NOTE: following code is much more correct but still not perfect (bugged with status bar)
  248. SDL_SetColors(sur, palette, 224, 32);
  249. #if 0
  250. SDL_Color * bluePalette = playerColorPalette + 32;
  251. SDL_Palette * oldPalette = sur->format->palette;
  252. SDL_Palette * newPalette = SDL_AllocPalette(256);
  253. for(size_t destIndex = 0; destIndex < 256; destIndex++)
  254. {
  255. SDL_Color old = oldPalette->colors[destIndex];
  256. bool found = false;
  257. for(size_t srcIndex = 0; srcIndex < 32; srcIndex++)
  258. {
  259. if(old.b == bluePalette[srcIndex].b && old.g == bluePalette[srcIndex].g && old.r == bluePalette[srcIndex].r)
  260. {
  261. found = true;
  262. newPalette->colors[destIndex] = palette[srcIndex];
  263. break;
  264. }
  265. }
  266. if(!found)
  267. newPalette->colors[destIndex] = old;
  268. }
  269. SDL_SetSurfacePalette(sur, newPalette);
  270. SDL_FreePalette(newPalette);
  271. #endif // 0
  272. }
  273. else
  274. {
  275. //TODO: implement. H3 method works only for images with palettes.
  276. // Add some kind of player-colored overlay?
  277. // Or keep palette approach here and replace only colors of specific value(s)
  278. // Or just wait for OpenGL support?
  279. logGlobal->warn("Image must have palette to be player-colored!");
  280. }
  281. }
  282. void Graphics::loadFogOfWar()
  283. {
  284. fogOfWarFullHide = std::make_shared<CAnimation>("TSHRC");
  285. fogOfWarFullHide->preload();
  286. fogOfWarPartialHide = std::make_shared<CAnimation>("TSHRE");
  287. fogOfWarPartialHide->preload();
  288. static const int rotations [] = {22, 15, 2, 13, 12, 16, 28, 17, 20, 19, 7, 24, 26, 25, 30, 32, 27};
  289. size_t size = fogOfWarPartialHide->size(0);//group size after next rotation
  290. for(const int rotation : rotations)
  291. {
  292. fogOfWarPartialHide->duplicateImage(0, rotation, 0);
  293. auto image = fogOfWarPartialHide->getImage(size, 0);
  294. image->verticalFlip();
  295. size++;
  296. }
  297. }
  298. void Graphics::loadFonts()
  299. {
  300. const JsonNode config(ResourceID("config/fonts.json"));
  301. const JsonVector & bmpConf = config["bitmap"].Vector();
  302. const JsonNode & ttfConf = config["trueType"];
  303. const JsonNode & hanConf = config["bitmapHan"];
  304. assert(bmpConf.size() == FONTS_NUMBER);
  305. for (size_t i=0; i<FONTS_NUMBER; i++)
  306. {
  307. std::string filename = bmpConf[i].String();
  308. if (!hanConf[filename].isNull())
  309. fonts[i] = std::make_shared<CBitmapHanFont>(hanConf[filename]);
  310. else if (!ttfConf[filename].isNull()) // no ttf override
  311. fonts[i] = std::make_shared<CTrueTypeFont>(ttfConf[filename]);
  312. else
  313. fonts[i] = std::make_shared<CBitmapFont>(filename);
  314. }
  315. }
  316. std::shared_ptr<CAnimation> Graphics::getAnimation(const CGObjectInstance* obj)
  317. {
  318. return getAnimation(obj->appearance);
  319. }
  320. std::shared_ptr<CAnimation> Graphics::getAnimation(std::shared_ptr<const ObjectTemplate> info)
  321. {
  322. //the only(?) invisible object
  323. if(info->id == Obj::EVENT)
  324. {
  325. return std::shared_ptr<CAnimation>();
  326. }
  327. if(info->animationFile.empty())
  328. {
  329. logGlobal->warn("Def name for obj (%d,%d) is empty!", info->id, info->subid);
  330. return std::shared_ptr<CAnimation>();
  331. }
  332. std::shared_ptr<CAnimation> ret = mapObjectAnimations[info->animationFile];
  333. //already loaded
  334. if(ret)
  335. {
  336. ret->preload();
  337. return ret;
  338. }
  339. ret = std::make_shared<CAnimation>(info->animationFile);
  340. mapObjectAnimations[info->animationFile] = ret;
  341. ret->preload();
  342. return ret;
  343. }
  344. void Graphics::loadErmuToPicture()
  345. {
  346. //loading ERMU to picture
  347. const JsonNode config(ResourceID("config/ERMU_to_picture.json"));
  348. int etp_idx = 0;
  349. for(const JsonNode &etp : config["ERMU_to_picture"].Vector()) {
  350. int idx = 0;
  351. for(const JsonNode &n : etp.Vector()) {
  352. ERMUtoPicture[idx][etp_idx] = n.String();
  353. idx ++;
  354. }
  355. assert (idx == ARRAY_COUNT(ERMUtoPicture));
  356. etp_idx ++;
  357. }
  358. assert (etp_idx == 44);
  359. }
  360. void Graphics::addImageListEntry(size_t index, size_t group, const std::string & listName, const std::string & imageName)
  361. {
  362. if (!imageName.empty())
  363. {
  364. JsonNode entry;
  365. if (group != 0)
  366. entry["group"].Integer() = group;
  367. entry["frame"].Integer() = index;
  368. entry["file"].String() = imageName;
  369. imageLists["SPRITES/" + listName]["images"].Vector().push_back(entry);
  370. }
  371. }
  372. void Graphics::addImageListEntries(const EntityService * service)
  373. {
  374. auto cb = std::bind(&Graphics::addImageListEntry, this, _1, _2, _3, _4);
  375. auto loopCb = [&](const Entity * entity, bool & stop)
  376. {
  377. entity->registerIcons(cb);
  378. };
  379. service->forEachBase(loopCb);
  380. }
  381. void Graphics::initializeImageLists()
  382. {
  383. addImageListEntries(CGI->creatures());
  384. addImageListEntries(CGI->heroTypes());
  385. addImageListEntries(CGI->artifacts());
  386. addImageListEntries(CGI->factions());
  387. addImageListEntries(CGI->spells());
  388. addImageListEntries(CGI->skills());
  389. }