CAnimation.cpp 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275
  1. #include "StdInc.h"
  2. #include "CAnimation.h"
  3. #include <SDL_image.h>
  4. #include "../CBitmapHandler.h"
  5. #include "../Graphics.h"
  6. #include "../gui/SDL_Extensions.h"
  7. #include "../gui/SDL_Pixels.h"
  8. #include "../lib/filesystem/Filesystem.h"
  9. #include "../lib/filesystem/ISimpleResourceLoader.h"
  10. #include "../lib/JsonNode.h"
  11. #include "../lib/CRandomGenerator.h"
  12. /*
  13. * CAnimation.cpp, part of VCMI engine
  14. *
  15. * Authors: listed in file AUTHORS in main folder
  16. *
  17. * License: GNU General Public License v2.0 or later
  18. * Full text of license available in license.txt file, in main folder
  19. *
  20. */
  21. typedef std::map <size_t, std::vector <JsonNode> > source_map;
  22. typedef std::map<size_t, IImage* > image_map;
  23. typedef std::map<size_t, image_map > group_map;
  24. class SDLImageLoader
  25. {
  26. SDLImage * image;
  27. ui8 * lineStart;
  28. ui8 * position;
  29. public:
  30. //load size raw pixels from data
  31. inline void Load(size_t size, const ui8 * data);
  32. //set size pixels to color
  33. inline void Load(size_t size, ui8 color=0);
  34. inline void EndLine();
  35. //init image with these sizes and palette
  36. inline void init(Point SpriteSize, Point Margins, Point FullSize, SDL_Color *pal);
  37. SDLImageLoader(SDLImage * Img);
  38. ~SDLImageLoader();
  39. };
  40. class CompImageLoader
  41. {
  42. CompImage * image;
  43. ui8 *position;
  44. ui8 *entry;
  45. ui32 currentLine;
  46. inline ui8 typeOf(ui8 color);
  47. inline void NewEntry(ui8 color, size_t size);
  48. inline void NewEntry(const ui8 * &data, size_t size);
  49. public:
  50. //load size raw pixels from data
  51. inline void Load(size_t size, const ui8 * data);
  52. //set size pixels to color
  53. inline void Load(size_t size, ui8 color=0);
  54. inline void EndLine();
  55. //init image with these sizes and palette
  56. inline void init(Point SpriteSize, Point Margins, Point FullSize, SDL_Color *pal);
  57. CompImageLoader(CompImage * Img);
  58. ~CompImageLoader();
  59. };
  60. // Extremely simple file cache. TODO: smarter, more general solution
  61. class CFileCache
  62. {
  63. static const int cacheSize = 50; //Max number of cached files
  64. struct FileData
  65. {
  66. ResourceID name;
  67. size_t size;
  68. ui8 * data;
  69. ui8 * getCopy()
  70. {
  71. auto ret = new ui8[size];
  72. std::copy(data, data + size, ret);
  73. return ret;
  74. }
  75. FileData():
  76. size(0),
  77. data(nullptr)
  78. {}
  79. ~FileData()
  80. {
  81. delete [] data;
  82. }
  83. };
  84. std::list<FileData> cache;
  85. public:
  86. ui8 * getCachedFile(ResourceID && rid)
  87. {
  88. for(auto & file : cache)
  89. {
  90. if (file.name == rid)
  91. return file.getCopy();
  92. }
  93. // Still here? Cache miss
  94. if (cache.size() > cacheSize)
  95. cache.pop_front();
  96. cache.push_back(FileData());
  97. auto data = CResourceHandler::get()->load(rid)->readAll();
  98. cache.back().name = ResourceID(rid);
  99. cache.back().size = data.second;
  100. cache.back().data = data.first.release();
  101. return cache.back().getCopy();
  102. }
  103. };
  104. static CFileCache animationCache;
  105. /*************************************************************************
  106. * DefFile, class used for def loading *
  107. *************************************************************************/
  108. CDefFile::CDefFile(std::string Name):
  109. data(nullptr),
  110. palette(nullptr)
  111. {
  112. //First 8 colors in def palette used for transparency
  113. static SDL_Color H3Palette[8] =
  114. {
  115. { 0, 0, 0, 0},// 100% - transparency
  116. { 0, 0, 0, 64},// 75% - shadow border,
  117. { 0, 0, 0, 128},// TODO: find exact value
  118. { 0, 0, 0, 128},// TODO: for transparency
  119. { 0, 0, 0, 128},// 50% - shadow body
  120. { 0, 0, 0, 0},// 100% - selection highlight
  121. { 0, 0, 0, 128},// 50% - shadow body below selection
  122. { 0, 0, 0, 64} // 75% - shadow border below selection
  123. };
  124. data = animationCache.getCachedFile(ResourceID(std::string("SPRITES/") + Name, EResType::ANIMATION));
  125. palette = new SDL_Color[256];
  126. int it = 0;
  127. ui32 type = read_le_u32(data + it);
  128. it+=4;
  129. //int width = read_le_u32(data + it); it+=4;//not used
  130. //int height = read_le_u32(data + it); it+=4;
  131. it+=8;
  132. ui32 totalBlocks = read_le_u32(data + it);
  133. it+=4;
  134. for (ui32 i= 0; i<256; i++)
  135. {
  136. palette[i].r = data[it++];
  137. palette[i].g = data[it++];
  138. palette[i].b = data[it++];
  139. CSDL_Ext::colorSetAlpha(palette[i],255);
  140. }
  141. if (type == 71 || type == 64)//Buttons/buildings don't have shadows\semi-transparency
  142. memset(palette, 0, sizeof(SDL_Color)*2);
  143. else
  144. memcpy(palette, H3Palette, sizeof(SDL_Color)*8);//initialize shadow\selection colors
  145. for (ui32 i=0; i<totalBlocks; i++)
  146. {
  147. size_t blockID = read_le_u32(data + it);
  148. it+=4;
  149. size_t totalEntries = read_le_u32(data + it);
  150. it+=12;
  151. //8 unknown bytes - skipping
  152. //13 bytes for name of every frame in this block - not used, skipping
  153. it+= 13 * totalEntries;
  154. for (ui32 j=0; j<totalEntries; j++)
  155. {
  156. size_t currOffset = read_le_u32(data + it);
  157. offset[blockID].push_back(currOffset);
  158. it += 4;
  159. }
  160. }
  161. }
  162. template<class ImageLoader>
  163. void CDefFile::loadFrame(size_t frame, size_t group, ImageLoader &loader) const
  164. {
  165. std::map<size_t, std::vector <size_t> >::const_iterator it;
  166. it = offset.find(group);
  167. assert (it != offset.end());
  168. const ui8 * FDef = data+it->second[frame];
  169. const SSpriteDef sd = * reinterpret_cast<const SSpriteDef *>(FDef);
  170. SSpriteDef sprite;
  171. sprite.format = read_le_u32(&sd.format);
  172. sprite.fullWidth = read_le_u32(&sd.fullWidth);
  173. sprite.fullHeight = read_le_u32(&sd.fullHeight);
  174. sprite.width = read_le_u32(&sd.width);
  175. sprite.height = read_le_u32(&sd.height);
  176. sprite.leftMargin = read_le_u32(&sd.leftMargin);
  177. sprite.topMargin = read_le_u32(&sd.topMargin);
  178. ui32 currentOffset = sizeof(SSpriteDef);
  179. ui32 BaseOffset = sizeof(SSpriteDef);
  180. loader.init(Point(sprite.width, sprite.height),
  181. Point(sprite.leftMargin, sprite.topMargin),
  182. Point(sprite.fullWidth, sprite.fullHeight), palette);
  183. switch (sprite.format)
  184. {
  185. case 0:
  186. {
  187. //pixel data is not compressed, copy data to surface
  188. for (ui32 i=0; i<sprite.height; i++)
  189. {
  190. loader.Load(sprite.width, FDef[currentOffset]);
  191. currentOffset += sprite.width;
  192. loader.EndLine();
  193. }
  194. break;
  195. }
  196. case 1:
  197. {
  198. //for each line we have offset of pixel data
  199. const ui32 * RWEntriesLoc = reinterpret_cast<const ui32 *>(FDef+currentOffset);
  200. currentOffset += sizeof(ui32) * sprite.height;
  201. for (ui32 i=0; i<sprite.height; i++)
  202. {
  203. //get position of the line
  204. currentOffset=BaseOffset + read_le_u32(RWEntriesLoc + i);
  205. ui32 TotalRowLength = 0;
  206. while (TotalRowLength<sprite.width)
  207. {
  208. ui8 type=FDef[currentOffset++];
  209. ui32 length=FDef[currentOffset++] + 1;
  210. if (type==0xFF)//Raw data
  211. {
  212. loader.Load(length, FDef + currentOffset);
  213. currentOffset+=length;
  214. }
  215. else// RLE
  216. {
  217. loader.Load(length, type);
  218. }
  219. TotalRowLength += length;
  220. }
  221. loader.EndLine();
  222. }
  223. break;
  224. }
  225. case 2:
  226. {
  227. currentOffset = BaseOffset + read_le_u16(FDef + BaseOffset);
  228. for (ui32 i=0; i<sprite.height; i++)
  229. {
  230. ui32 TotalRowLength=0;
  231. while (TotalRowLength<sprite.width)
  232. {
  233. ui8 SegmentType=FDef[currentOffset++];
  234. ui8 code = SegmentType / 32;
  235. ui8 length = (SegmentType & 31) + 1;
  236. if (code==7)//Raw data
  237. {
  238. loader.Load(length, FDef[currentOffset]);
  239. currentOffset += length;
  240. }
  241. else//RLE
  242. {
  243. loader.Load(length, code);
  244. }
  245. TotalRowLength+=length;
  246. }
  247. loader.EndLine();
  248. }
  249. break;
  250. }
  251. case 3:
  252. {
  253. for (ui32 i=0; i<sprite.height; i++)
  254. {
  255. currentOffset = BaseOffset + read_le_u16(FDef + BaseOffset+i*2*(sprite.width/32));
  256. ui32 TotalRowLength=0;
  257. while (TotalRowLength<sprite.width)
  258. {
  259. ui8 segment = FDef[currentOffset++];
  260. ui8 code = segment / 32;
  261. ui8 length = (segment & 31) + 1;
  262. if (code==7)//Raw data
  263. {
  264. loader.Load(length, FDef + currentOffset);
  265. currentOffset += length;
  266. }
  267. else//RLE
  268. {
  269. loader.Load(length, code);
  270. }
  271. TotalRowLength += length;
  272. }
  273. loader.EndLine();
  274. }
  275. break;
  276. }
  277. default:
  278. logGlobal->errorStream()<<"Error: unsupported format of def file: "<<sprite.format;
  279. break;
  280. }
  281. };
  282. CDefFile::~CDefFile()
  283. {
  284. delete[] data;
  285. delete[] palette;
  286. }
  287. const std::map<size_t, size_t > CDefFile::getEntries() const
  288. {
  289. std::map<size_t, size_t > ret;
  290. for (auto & elem : offset)
  291. ret[elem.first] = elem.second.size();
  292. return ret;
  293. }
  294. /*************************************************************************
  295. * Classes for image loaders - helpers for loading from def files *
  296. *************************************************************************/
  297. SDLImageLoader::SDLImageLoader(SDLImage * Img):
  298. image(Img),
  299. lineStart(nullptr),
  300. position(nullptr)
  301. {
  302. }
  303. void SDLImageLoader::init(Point SpriteSize, Point Margins, Point FullSize, SDL_Color *pal)
  304. {
  305. //Init image
  306. image->surf = SDL_CreateRGBSurface(SDL_SWSURFACE, SpriteSize.x, SpriteSize.y, 8, 0, 0, 0, 0);
  307. image->margins = Margins;
  308. image->fullSize = FullSize;
  309. //Prepare surface
  310. SDL_SetColors(image->surf, pal, 0, 256);
  311. SDL_LockSurface(image->surf);
  312. lineStart = position = (ui8*)image->surf->pixels;
  313. }
  314. inline void SDLImageLoader::Load(size_t size, const ui8 * data)
  315. {
  316. if (size)
  317. {
  318. memcpy((void *)position, data, size);
  319. position += size;
  320. }
  321. }
  322. inline void SDLImageLoader::Load(size_t size, ui8 color)
  323. {
  324. if (size)
  325. {
  326. memset((void *)position, color, size);
  327. position += size;
  328. }
  329. }
  330. inline void SDLImageLoader::EndLine()
  331. {
  332. lineStart += image->surf->pitch;
  333. position = lineStart;
  334. }
  335. SDLImageLoader::~SDLImageLoader()
  336. {
  337. SDL_UnlockSurface(image->surf);
  338. SDL_SetColorKey(image->surf, SDL_TRUE, 0);
  339. //TODO: RLE if compressed and bpp>1
  340. }
  341. ////////////////////////////////////////////////////////////////////////////////
  342. CompImageLoader::CompImageLoader(CompImage * Img):
  343. image(Img),
  344. position(nullptr),
  345. entry(nullptr),
  346. currentLine(0)
  347. {
  348. }
  349. void CompImageLoader::init(Point SpriteSize, Point Margins, Point FullSize, SDL_Color *pal)
  350. {
  351. image->sprite = Rect(Margins, SpriteSize);
  352. image->fullSize = FullSize;
  353. if (SpriteSize.x && SpriteSize.y)
  354. {
  355. image->palette = new SDL_Color[256];
  356. memcpy((void*)image->palette, (void*)pal, 256*sizeof(SDL_Color));
  357. //Allocate enought space for worst possible case, c-style malloc used due to resizing after load
  358. image->surf = (ui8*)malloc(SpriteSize.x*SpriteSize.y*3);
  359. image->line = new ui32[SpriteSize.y+1];
  360. image->line[0] = 0;
  361. position = image->surf;
  362. }
  363. }
  364. inline void CompImageLoader::NewEntry(ui8 color, size_t size)
  365. {
  366. assert(color != 0xff);
  367. assert(size && size<256);
  368. entry = position;
  369. entry[0] = color;
  370. entry[1] = size;
  371. position +=2;
  372. }
  373. inline void CompImageLoader::NewEntry(const ui8 * &data, size_t size)
  374. {
  375. assert(size && size<256);
  376. entry = position;
  377. entry[0] = 0xff;
  378. entry[1] = size;
  379. position +=2;
  380. memcpy(position, data, size);
  381. position+=size;
  382. data+=size;
  383. }
  384. inline ui8 CompImageLoader::typeOf(ui8 color)
  385. {
  386. if (color == 0)
  387. return 0;
  388. if (image->palette[color].a != 255)
  389. return 1;
  390. return 2;
  391. }
  392. inline void CompImageLoader::Load(size_t size, const ui8 * data)
  393. {
  394. while (size)
  395. {
  396. //Try to compress data
  397. while(true)
  398. {
  399. ui8 color = data[0];
  400. if (color != 0xff)
  401. {
  402. size_t runLength = 1;
  403. while (runLength < size && color == data[runLength])
  404. runLength++;
  405. if (runLength > 1 && runLength < 255)//Row of one color found - use RLE
  406. {
  407. Load(runLength, color);
  408. data += runLength;
  409. size -= runLength;
  410. if (!size)
  411. return;
  412. }
  413. else
  414. break;
  415. }
  416. else
  417. break;
  418. }
  419. //Select length for new raw entry
  420. size_t runLength = 1;
  421. ui8 color = data[0];
  422. ui8 type = typeOf(color);
  423. ui8 color2;
  424. ui8 type2;
  425. if (size > 1)
  426. {
  427. do
  428. {
  429. color2 = data[runLength];
  430. type2 = typeOf(color2);
  431. runLength++;
  432. }
  433. //While we have data of this type and different colors
  434. while ((runLength < size) && (type == type2) && ( (color2 != 0xff) || (color2 != color)));
  435. }
  436. size -= runLength;
  437. //add data to last entry
  438. if (entry && entry[0] == 0xff && type == typeOf(entry[2]))
  439. {
  440. size_t toCopy = std::min<size_t>(runLength, 255 - entry[1]);
  441. runLength -= toCopy;
  442. entry[1] += toCopy;
  443. memcpy(position, data, toCopy);
  444. data+=toCopy;
  445. position+=toCopy;
  446. }
  447. //Create new entries
  448. while (runLength > 255)
  449. {
  450. NewEntry(data, 255);
  451. runLength -= 255;
  452. }
  453. if (runLength)
  454. NewEntry(data, runLength);
  455. }
  456. }
  457. inline void CompImageLoader::Load(size_t size, ui8 color)
  458. {
  459. if (!size)
  460. return;
  461. if (color==0xff)
  462. {
  463. auto tmpbuf = new ui8[size];
  464. memset((void*)tmpbuf, color, size);
  465. Load(size, tmpbuf);
  466. delete [] tmpbuf;
  467. return;
  468. }
  469. //Current entry is RLE with same color as new block
  470. if (entry && entry[0] == color)
  471. {
  472. size_t toCopy = std::min<size_t>(size, 255 - entry[1]);
  473. size -= toCopy;
  474. entry[1] += toCopy;
  475. }
  476. //Create new entries
  477. while (size > 255)
  478. {
  479. NewEntry(color, 255);
  480. size -= 255;
  481. }
  482. if (size)
  483. NewEntry(color, size);
  484. }
  485. void CompImageLoader::EndLine()
  486. {
  487. currentLine++;
  488. image->line[currentLine] = position - image->surf;
  489. entry = nullptr;
  490. }
  491. CompImageLoader::~CompImageLoader()
  492. {
  493. if (!image->surf)
  494. return;
  495. ui8* newPtr = (ui8*)realloc((void*)image->surf, position - image->surf);
  496. if (newPtr)
  497. image->surf = newPtr;
  498. }
  499. /*************************************************************************
  500. * Classes for images, support loading from file and drawing on surface *
  501. *************************************************************************/
  502. IImage::IImage():
  503. refCount(1)
  504. {
  505. }
  506. bool IImage::decreaseRef()
  507. {
  508. refCount--;
  509. return refCount <= 0;
  510. }
  511. void IImage::increaseRef()
  512. {
  513. refCount++;
  514. }
  515. SDLImage::SDLImage(CDefFile *data, size_t frame, size_t group, bool compressed):
  516. surf(nullptr)
  517. {
  518. SDLImageLoader loader(this);
  519. data->loadFrame(frame, group, loader);
  520. }
  521. SDLImage::SDLImage(SDL_Surface * from, bool extraRef):
  522. margins(0,0)
  523. {
  524. surf = from;
  525. if (extraRef)
  526. surf->refcount++;
  527. fullSize.x = surf->w;
  528. fullSize.y = surf->h;
  529. }
  530. SDLImage::SDLImage(std::string filename, bool compressed):
  531. margins(0,0)
  532. {
  533. surf = BitmapHandler::loadBitmap(filename);
  534. if (surf == nullptr)
  535. {
  536. logGlobal->errorStream() << "Error: failed to load image "<<filename;
  537. return;
  538. }
  539. else
  540. {
  541. fullSize.x = surf->w;
  542. fullSize.y = surf->h;
  543. }
  544. if (compressed)
  545. {
  546. SDL_Surface *temp = surf;
  547. // add RLE flag
  548. if (surf->format->palette)
  549. {
  550. CSDL_Ext::setColorKey(temp,temp->format->palette->colors[0]);
  551. }
  552. SDL_SetSurfaceRLE(temp, SDL_RLEACCEL);
  553. // convert surface to enable RLE
  554. surf = SDL_ConvertSurface(temp, temp->format, temp->flags);
  555. SDL_FreeSurface(temp);
  556. }
  557. }
  558. void SDLImage::draw(SDL_Surface *where, int posX, int posY, Rect *src, ui8 rotation) const
  559. {
  560. if (!surf)
  561. return;
  562. Rect sourceRect(margins.x, margins.y, surf->w, surf->h);
  563. //TODO: rotation and scaling
  564. if (src)
  565. {
  566. sourceRect = sourceRect & *src;
  567. }
  568. Rect destRect(posX, posY, surf->w, surf->h);
  569. destRect += sourceRect.topLeft();
  570. sourceRect -= margins;
  571. CSDL_Ext::blitSurface(surf, &sourceRect, where, &destRect);
  572. }
  573. void SDLImage::playerColored(PlayerColor player)
  574. {
  575. graphics->blueToPlayersAdv(surf, player);
  576. }
  577. int SDLImage::width() const
  578. {
  579. return fullSize.x;
  580. }
  581. int SDLImage::height() const
  582. {
  583. return fullSize.y;
  584. }
  585. SDLImage::~SDLImage()
  586. {
  587. SDL_FreeSurface(surf);
  588. }
  589. CompImage::CompImage(const CDefFile *data, size_t frame, size_t group):
  590. surf(nullptr),
  591. line(nullptr),
  592. palette(nullptr)
  593. {
  594. CompImageLoader loader(this);
  595. data->loadFrame(frame, group, loader);
  596. }
  597. CompImage::CompImage(SDL_Surface * surf)
  598. {
  599. //TODO
  600. assert(0);
  601. }
  602. void CompImage::draw(SDL_Surface *where, int posX, int posY, Rect *src, ui8 alpha) const
  603. {
  604. int rotation = 0; //TODO
  605. //rotation & 2 = horizontal rotation
  606. //rotation & 4 = vertical rotation
  607. if (!surf)
  608. return;
  609. Rect sourceRect(sprite);
  610. //TODO: rotation and scaling
  611. if (src)
  612. sourceRect = sourceRect & *src;
  613. //Limit source rect to sizes of surface
  614. sourceRect = sourceRect & Rect(0, 0, where->w, where->h);
  615. //Starting point on SDL surface
  616. Point dest(posX+sourceRect.x, posY+sourceRect.y);
  617. if (rotation & 2)
  618. dest.y += sourceRect.h;
  619. if (rotation & 4)
  620. dest.x += sourceRect.w;
  621. sourceRect -= sprite.topLeft();
  622. for (int currY = 0; currY <sourceRect.h; currY++)
  623. {
  624. ui8* data = surf + line[currY+sourceRect.y];
  625. ui8 type = *(data++);
  626. ui8 size = *(data++);
  627. int currX = sourceRect.x;
  628. //Skip blocks until starting position reached
  629. while ( currX > size )
  630. {
  631. currX -= size;
  632. if (type == 0xff)
  633. data += size;
  634. type = *(data++);
  635. size = *(data++);
  636. }
  637. //This block will be shown partially - calculate size\position
  638. size -= currX;
  639. if (type == 0xff)
  640. data += currX;
  641. currX = 0;
  642. ui8 bpp = where->format->BytesPerPixel;
  643. //Calculate position for blitting: pixels + Y + X
  644. ui8* blitPos = (ui8*) where->pixels;
  645. if (rotation & 4)
  646. blitPos += (dest.y - currY) * where->pitch;
  647. else
  648. blitPos += (dest.y + currY) * where->pitch;
  649. blitPos += dest.x * bpp;
  650. //Blit blocks that must be fully visible
  651. while (currX + size < sourceRect.w)
  652. {
  653. //blit block, pointers will be modified if needed
  654. BlitBlockWithBpp(bpp, type, size, data, blitPos, alpha, rotation & 2);
  655. currX += size;
  656. type = *(data++);
  657. size = *(data++);
  658. }
  659. //Blit last, semi-visible block
  660. size = sourceRect.w - currX;
  661. BlitBlockWithBpp(bpp, type, size, data, blitPos, alpha, rotation & 2);
  662. }
  663. }
  664. #define CASEBPP(x,y) case x: BlitBlock<x,y>(type, size, data, dest, alpha); break
  665. //FIXME: better way to get blitter
  666. void CompImage::BlitBlockWithBpp(ui8 bpp, ui8 type, ui8 size, ui8 *&data, ui8 *&dest, ui8 alpha, bool rotated) const
  667. {
  668. assert(bpp>1 && bpp<5);
  669. if (rotated)
  670. switch (bpp)
  671. {
  672. CASEBPP(2,1);
  673. CASEBPP(3,1);
  674. CASEBPP(4,1);
  675. }
  676. else
  677. switch (bpp)
  678. {
  679. CASEBPP(2,1);
  680. CASEBPP(3,1);
  681. CASEBPP(4,1);
  682. }
  683. }
  684. #undef CASEBPP
  685. //Blit one block from RLE-d surface
  686. template<int bpp, int dir>
  687. void CompImage::BlitBlock(ui8 type, ui8 size, ui8 *&data, ui8 *&dest, ui8 alpha) const
  688. {
  689. //Raw data
  690. if (type == 0xff)
  691. {
  692. ui8 color = *data;
  693. if (alpha != 255)//Per-surface alpha is set
  694. {
  695. for (size_t i=0; i<size; i++)
  696. {
  697. SDL_Color col = palette[*(data++)];
  698. col.a = (ui32)col.a*alpha/255;
  699. ColorPutter<bpp, 1>::PutColorAlpha(dest, col);
  700. }
  701. return;
  702. }
  703. if (palette[color].a == 255)
  704. {
  705. //Put row of RGB data
  706. for (size_t i=0; i<size; i++)
  707. ColorPutter<bpp, 1>::PutColor(dest, palette[*(data++)]);
  708. }
  709. else
  710. {
  711. //Put row of RGBA data
  712. for (size_t i=0; i<size; i++)
  713. ColorPutter<bpp, 1>::PutColorAlpha(dest, palette[*(data++)]);
  714. }
  715. }
  716. //RLE-d sequence
  717. else
  718. {
  719. if (alpha != 255 && palette[type].a !=0)//Per-surface alpha is set
  720. {
  721. SDL_Color col = palette[type];
  722. col.a = (int)col.a*(255-alpha)/255;
  723. for (size_t i=0; i<size; i++)
  724. ColorPutter<bpp, 1>::PutColorAlpha(dest, col);
  725. return;
  726. }
  727. switch (palette[type].a)
  728. {
  729. case 0:
  730. {
  731. //Skip row
  732. dest += size*bpp;
  733. break;
  734. }
  735. case 255:
  736. {
  737. //Put RGB row
  738. ColorPutter<bpp, 1>::PutColorRow(dest, palette[type], size);
  739. break;
  740. }
  741. default:
  742. {
  743. //Put RGBA row
  744. for (size_t i=0; i<size; i++)
  745. ColorPutter<bpp, 1>::PutColorAlpha(dest, palette[type]);
  746. break;
  747. }
  748. }
  749. }
  750. }
  751. void CompImage::playerColored(PlayerColor player)
  752. {
  753. SDL_Color *pal = nullptr;
  754. if(player < PlayerColor::PLAYER_LIMIT)
  755. {
  756. pal = graphics->playerColorPalette + 32*player.getNum();
  757. }
  758. else if(player == PlayerColor::NEUTRAL)
  759. {
  760. pal = graphics->neutralColorPalette;
  761. }
  762. else
  763. assert(0);
  764. for(int i=0; i<32; ++i)
  765. {
  766. CSDL_Ext::colorAssign(palette[224+i],pal[i]);
  767. }
  768. }
  769. int CompImage::width() const
  770. {
  771. return fullSize.x;
  772. }
  773. int CompImage::height() const
  774. {
  775. return fullSize.y;
  776. }
  777. CompImage::~CompImage()
  778. {
  779. free(surf);
  780. delete [] line;
  781. delete [] palette;
  782. }
  783. /*************************************************************************
  784. * CAnimation for animations handling, can load part of file if needed *
  785. *************************************************************************/
  786. IImage * CAnimation::getFromExtraDef(std::string filename)
  787. {
  788. size_t pos = filename.find(':');
  789. if (pos == -1)
  790. return nullptr;
  791. CAnimation anim(filename.substr(0, pos));
  792. pos++;
  793. size_t frame = atoi(filename.c_str()+pos);
  794. size_t group = 0;
  795. pos = filename.find(':', pos);
  796. if (pos != -1)
  797. {
  798. group = frame;
  799. frame = atoi(filename.c_str()+pos);
  800. }
  801. anim.load(frame ,group);
  802. IImage * ret = anim.images[group][frame];
  803. anim.images.clear();
  804. return ret;
  805. }
  806. bool CAnimation::loadFrame(CDefFile * file, size_t frame, size_t group)
  807. {
  808. if (size(group) <= frame)
  809. {
  810. printError(frame, group, "LoadFrame");
  811. return false;
  812. }
  813. IImage *image = getImage(frame, group, false);
  814. if (image)
  815. {
  816. image->increaseRef();
  817. return true;
  818. }
  819. //try to get image from def
  820. if (source[group][frame].getType() == JsonNode::DATA_NULL)
  821. {
  822. if (file)
  823. {
  824. auto frameList = file->getEntries();
  825. if (vstd::contains(frameList, group) && frameList.at(group) > frame) // frame is present
  826. {
  827. if (compressed)
  828. images[group][frame] = new CompImage(file, frame, group);
  829. else
  830. images[group][frame] = new SDLImage(file, frame, group);
  831. return true;
  832. }
  833. }
  834. // still here? image is missing
  835. printError(frame, group, "LoadFrame");
  836. images[group][frame] = new SDLImage("DEFAULT", compressed);
  837. }
  838. else //load from separate file
  839. {
  840. std::string filename = source[group][frame].Struct().find("file")->second.String();
  841. IImage * img = getFromExtraDef(filename);
  842. if (!img)
  843. img = new SDLImage(filename, compressed);
  844. images[group][frame] = img;
  845. return true;
  846. }
  847. return false;
  848. }
  849. bool CAnimation::unloadFrame(size_t frame, size_t group)
  850. {
  851. IImage *image = getImage(frame, group, false);
  852. if (image)
  853. {
  854. //decrease ref count for image and delete if needed
  855. if (image->decreaseRef())
  856. {
  857. delete image;
  858. images[group].erase(frame);
  859. }
  860. if (images[group].empty())
  861. images.erase(group);
  862. return true;
  863. }
  864. return false;
  865. }
  866. void CAnimation::initFromJson(const JsonNode & config)
  867. {
  868. std::string basepath;
  869. basepath = config["basepath"].String();
  870. for(const JsonNode &group : config["sequences"].Vector())
  871. {
  872. size_t groupID = group["group"].Float();//TODO: string-to-value conversion("moving" -> MOVING)
  873. source[groupID].clear();
  874. for(const JsonNode &frame : group["frames"].Vector())
  875. {
  876. source[groupID].push_back(JsonNode());
  877. std::string filename = frame.String();
  878. source[groupID].back()["file"].String() = basepath + filename;
  879. }
  880. }
  881. for(const JsonNode &node : config["images"].Vector())
  882. {
  883. size_t group = node["group"].Float();
  884. size_t frame = node["frame"].Float();
  885. if (source[group].size() <= frame)
  886. source[group].resize(frame+1);
  887. source[group][frame] = node;
  888. std::string filename = node["file"].String();
  889. source[group][frame]["file"].String() = basepath + filename;
  890. }
  891. }
  892. void CAnimation::init(CDefFile * file)
  893. {
  894. if (file)
  895. {
  896. const std::map<size_t, size_t> defEntries = file->getEntries();
  897. for (auto & defEntry : defEntries)
  898. source[defEntry.first].resize(defEntry.second);
  899. }
  900. ResourceID resID(std::string("SPRITES/") + name, EResType::TEXT);
  901. if (vstd::contains(graphics->imageLists, resID.getName()))
  902. initFromJson(graphics->imageLists[resID.getName()]);
  903. auto configList = CResourceHandler::get()->getResourcesWithName(resID);
  904. for(auto & loader : configList)
  905. {
  906. auto stream = loader->load(resID);
  907. std::unique_ptr<ui8[]> textData(new ui8[stream->getSize()]);
  908. stream->read(textData.get(), stream->getSize());
  909. const JsonNode config((char*)textData.get(), stream->getSize());
  910. initFromJson(config);
  911. }
  912. }
  913. CDefFile * CAnimation::getFile() const
  914. {
  915. ResourceID identifier(std::string("SPRITES/") + name, EResType::ANIMATION);
  916. if (CResourceHandler::get()->existsResource(identifier))
  917. return new CDefFile(name);
  918. return nullptr;
  919. }
  920. void CAnimation::printError(size_t frame, size_t group, std::string type) const
  921. {
  922. logGlobal->errorStream() << type <<" error: Request for frame not present in CAnimation! "
  923. <<"\tFile name: "<<name<<" Group: "<<group<<" Frame: "<<frame;
  924. }
  925. CAnimation::CAnimation(std::string Name, bool Compressed):
  926. name(Name),
  927. compressed(Compressed)
  928. {
  929. size_t dotPos = name.find_last_of('.');
  930. if ( dotPos!=-1 )
  931. name.erase(dotPos);
  932. std::transform(name.begin(), name.end(), name.begin(), toupper);
  933. CDefFile * file = getFile();
  934. init(file);
  935. delete file;
  936. loadedAnims.insert(this);
  937. }
  938. CAnimation::CAnimation():
  939. name(""),
  940. compressed(false)
  941. {
  942. init(nullptr);
  943. loadedAnims.insert(this);
  944. }
  945. CAnimation::~CAnimation()
  946. {
  947. if (!images.empty())
  948. {
  949. logGlobal->warnStream()<<"Warning: not all frames were unloaded from "<<name;
  950. for (auto & elem : images)
  951. for (auto & _image : elem.second)
  952. delete _image.second;
  953. }
  954. loadedAnims.erase(this);
  955. }
  956. void CAnimation::setCustom(std::string filename, size_t frame, size_t group)
  957. {
  958. if (source[group].size() <= frame)
  959. source[group].resize(frame+1);
  960. source[group][frame]["file"].String() = filename;
  961. //FIXME: update image if already loaded
  962. }
  963. IImage * CAnimation::getImage(size_t frame, size_t group, bool verbose) const
  964. {
  965. auto groupIter = images.find(group);
  966. if (groupIter != images.end())
  967. {
  968. auto imageIter = groupIter->second.find(frame);
  969. if (imageIter != groupIter->second.end())
  970. return imageIter->second;
  971. }
  972. if (verbose)
  973. printError(frame, group, "GetImage");
  974. return nullptr;
  975. }
  976. void CAnimation::load()
  977. {
  978. CDefFile * file = getFile();
  979. for (auto & elem : source)
  980. for (size_t image=0; image < elem.second.size(); image++)
  981. loadFrame(file, image, elem.first);
  982. delete file;
  983. }
  984. void CAnimation::unload()
  985. {
  986. for (auto & elem : source)
  987. for (size_t image=0; image < elem.second.size(); image++)
  988. unloadFrame(image, elem.first);
  989. }
  990. void CAnimation::loadGroup(size_t group)
  991. {
  992. CDefFile * file = getFile();
  993. if (vstd::contains(source, group))
  994. for (size_t image=0; image < source[group].size(); image++)
  995. loadFrame(file, image, group);
  996. delete file;
  997. }
  998. void CAnimation::unloadGroup(size_t group)
  999. {
  1000. if (vstd::contains(source, group))
  1001. for (size_t image=0; image < source[group].size(); image++)
  1002. unloadFrame(image, group);
  1003. }
  1004. void CAnimation::load(size_t frame, size_t group)
  1005. {
  1006. CDefFile * file = getFile();
  1007. loadFrame(file, frame, group);
  1008. delete file;
  1009. }
  1010. void CAnimation::unload(size_t frame, size_t group)
  1011. {
  1012. unloadFrame(frame, group);
  1013. }
  1014. size_t CAnimation::size(size_t group) const
  1015. {
  1016. auto iter = source.find(group);
  1017. if (iter != source.end())
  1018. return iter->second.size();
  1019. return 0;
  1020. }
  1021. std::set<CAnimation*> CAnimation::loadedAnims;
  1022. void CAnimation::getAnimInfo()
  1023. {
  1024. logGlobal->errorStream()<<"Animation stats: Loaded "<<loadedAnims.size()<<" total";
  1025. for (auto anim : loadedAnims)
  1026. {
  1027. logGlobal->errorStream()<<"Name: "<<anim->name<<" Groups: "<<anim->images.size();
  1028. if (!anim->images.empty())
  1029. logGlobal->errorStream()<<", "<<anim->images.begin()->second.size()<<" image loaded in group "<< anim->images.begin()->first;
  1030. }
  1031. }
  1032. float CFadeAnimation::initialCounter() const
  1033. {
  1034. if (fadingMode == EMode::OUT)
  1035. return 1.0f;
  1036. return 0.0f;
  1037. }
  1038. void CFadeAnimation::update()
  1039. {
  1040. if (!fading)
  1041. return;
  1042. if (fadingMode == EMode::OUT)
  1043. fadingCounter -= delta;
  1044. else
  1045. fadingCounter += delta;
  1046. if (isFinished())
  1047. {
  1048. fading = false;
  1049. if (shouldFreeSurface)
  1050. {
  1051. SDL_FreeSurface(fadingSurface);
  1052. fadingSurface = nullptr;
  1053. }
  1054. }
  1055. }
  1056. bool CFadeAnimation::isFinished() const
  1057. {
  1058. if (fadingMode == EMode::OUT)
  1059. return fadingCounter <= 0.0f;
  1060. return fadingCounter >= 1.0f;
  1061. }
  1062. CFadeAnimation::CFadeAnimation()
  1063. : fadingSurface(nullptr),
  1064. fading(false),
  1065. fadingMode(EMode::NONE)
  1066. {
  1067. }
  1068. CFadeAnimation::~CFadeAnimation()
  1069. {
  1070. if (fadingSurface && shouldFreeSurface)
  1071. SDL_FreeSurface(fadingSurface);
  1072. }
  1073. void CFadeAnimation::init(EMode mode, SDL_Surface * sourceSurface, bool freeSurfaceAtEnd /* = false */, float animDelta /* = DEFAULT_DELTA */)
  1074. {
  1075. if (fading)
  1076. {
  1077. // in that case, immediately finish the previous fade
  1078. // (alternatively, we could just return here to ignore the new fade request until this one finished (but we'd need to free the passed bitmap to avoid leaks))
  1079. logGlobal->warnStream() << "Tried to init fading animation that is already running.";
  1080. if (fadingSurface && shouldFreeSurface)
  1081. SDL_FreeSurface(fadingSurface);
  1082. }
  1083. if (animDelta <= 0.0f)
  1084. {
  1085. logGlobal->warnStream() << "Fade anim: delta should be positive; " << animDelta << " given.";
  1086. animDelta = DEFAULT_DELTA;
  1087. }
  1088. if (sourceSurface)
  1089. fadingSurface = sourceSurface;
  1090. delta = animDelta;
  1091. fadingMode = mode;
  1092. fadingCounter = initialCounter();
  1093. fading = true;
  1094. shouldFreeSurface = freeSurfaceAtEnd;
  1095. }
  1096. void CFadeAnimation::draw(SDL_Surface * targetSurface, const SDL_Rect * sourceRect, SDL_Rect * destRect)
  1097. {
  1098. if (!fading || !fadingSurface || fadingMode == EMode::NONE)
  1099. {
  1100. fading = false;
  1101. return;
  1102. }
  1103. CSDL_Ext::setAlpha(fadingSurface, fadingCounter * 255);
  1104. SDL_BlitSurface(fadingSurface, const_cast<SDL_Rect *>(sourceRect), targetSurface, destRect); //FIXME
  1105. CSDL_Ext::setAlpha(fadingSurface, 255);
  1106. }