Graphics.cpp 12 KB

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