CAnimation.cpp 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224
  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_SRCCOLORKEY, 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. #ifdef VCMI_SDL1
  389. if (image->palette[color].unused != 255)
  390. return 1;
  391. #else
  392. if (image->palette[color].a != 255)
  393. return 1;
  394. #endif // 0
  395. return 2;
  396. }
  397. inline void CompImageLoader::Load(size_t size, const ui8 * data)
  398. {
  399. while (size)
  400. {
  401. //Try to compress data
  402. while(true)
  403. {
  404. ui8 color = data[0];
  405. if (color != 0xff)
  406. {
  407. size_t runLength = 1;
  408. while (runLength < size && color == data[runLength])
  409. runLength++;
  410. if (runLength > 1 && runLength < 255)//Row of one color found - use RLE
  411. {
  412. Load(runLength, color);
  413. data += runLength;
  414. size -= runLength;
  415. if (!size)
  416. return;
  417. }
  418. else
  419. break;
  420. }
  421. else
  422. break;
  423. }
  424. //Select length for new raw entry
  425. size_t runLength = 1;
  426. ui8 color = data[0];
  427. ui8 type = typeOf(color);
  428. ui8 color2;
  429. ui8 type2;
  430. if (size > 1)
  431. {
  432. do
  433. {
  434. color2 = data[runLength];
  435. type2 = typeOf(color2);
  436. runLength++;
  437. }
  438. //While we have data of this type and different colors
  439. while ((runLength < size) && (type == type2) && ( (color2 != 0xff) || (color2 != color)));
  440. }
  441. size -= runLength;
  442. //add data to last entry
  443. if (entry && entry[0] == 0xff && type == typeOf(entry[2]))
  444. {
  445. size_t toCopy = std::min<size_t>(runLength, 255 - entry[1]);
  446. runLength -= toCopy;
  447. entry[1] += toCopy;
  448. memcpy(position, data, toCopy);
  449. data+=toCopy;
  450. position+=toCopy;
  451. }
  452. //Create new entries
  453. while (runLength > 255)
  454. {
  455. NewEntry(data, 255);
  456. runLength -= 255;
  457. }
  458. if (runLength)
  459. NewEntry(data, runLength);
  460. }
  461. }
  462. inline void CompImageLoader::Load(size_t size, ui8 color)
  463. {
  464. if (!size)
  465. return;
  466. if (color==0xff)
  467. {
  468. auto tmpbuf = new ui8[size];
  469. memset((void*)tmpbuf, color, size);
  470. Load(size, tmpbuf);
  471. delete [] tmpbuf;
  472. return;
  473. }
  474. //Current entry is RLE with same color as new block
  475. if (entry && entry[0] == color)
  476. {
  477. size_t toCopy = std::min<size_t>(size, 255 - entry[1]);
  478. size -= toCopy;
  479. entry[1] += toCopy;
  480. }
  481. //Create new entries
  482. while (size > 255)
  483. {
  484. NewEntry(color, 255);
  485. size -= 255;
  486. }
  487. if (size)
  488. NewEntry(color, size);
  489. }
  490. void CompImageLoader::EndLine()
  491. {
  492. currentLine++;
  493. image->line[currentLine] = position - image->surf;
  494. entry = nullptr;
  495. }
  496. CompImageLoader::~CompImageLoader()
  497. {
  498. if (!image->surf)
  499. return;
  500. ui8* newPtr = (ui8*)realloc((void*)image->surf, position - image->surf);
  501. if (newPtr)
  502. image->surf = newPtr;
  503. }
  504. /*************************************************************************
  505. * Classes for images, support loading from file and drawing on surface *
  506. *************************************************************************/
  507. IImage::IImage():
  508. refCount(1)
  509. {
  510. }
  511. bool IImage::decreaseRef()
  512. {
  513. refCount--;
  514. return refCount <= 0;
  515. }
  516. void IImage::increaseRef()
  517. {
  518. refCount++;
  519. }
  520. SDLImage::SDLImage(CDefFile *data, size_t frame, size_t group, bool compressed):
  521. surf(nullptr)
  522. {
  523. SDLImageLoader loader(this);
  524. data->loadFrame(frame, group, loader);
  525. }
  526. SDLImage::SDLImage(SDL_Surface * from, bool extraRef):
  527. margins(0,0)
  528. {
  529. surf = from;
  530. if (extraRef)
  531. surf->refcount++;
  532. fullSize.x = surf->w;
  533. fullSize.y = surf->h;
  534. }
  535. SDLImage::SDLImage(std::string filename, bool compressed):
  536. margins(0,0)
  537. {
  538. surf = BitmapHandler::loadBitmap(filename);
  539. if (surf == nullptr)
  540. {
  541. logGlobal->errorStream() << "Error: failed to load image "<<filename;
  542. return;
  543. }
  544. else
  545. {
  546. fullSize.x = surf->w;
  547. fullSize.y = surf->h;
  548. }
  549. if (compressed)
  550. {
  551. SDL_Surface *temp = surf;
  552. // add RLE flag
  553. #ifdef VCMI_SDL1
  554. if (surf->format->palette)
  555. {
  556. const SDL_Color &c = temp->format->palette->colors[0];
  557. SDL_SetColorKey(temp, (SDL_SRCCOLORKEY | SDL_RLEACCEL),
  558. SDL_MapRGB(temp -> format, c.r, c.g, c.b));
  559. }
  560. else
  561. SDL_SetColorKey(temp, SDL_RLEACCEL, 0);
  562. #else
  563. if (surf->format->palette)
  564. {
  565. CSDL_Ext::setColorKey(temp,temp->format->palette->colors[0]);
  566. }
  567. SDL_SetSurfaceRLE(temp, SDL_RLEACCEL);
  568. #endif
  569. // convert surface to enable RLE
  570. surf = SDL_ConvertSurface(temp, temp->format, temp->flags);
  571. SDL_FreeSurface(temp);
  572. }
  573. }
  574. void SDLImage::draw(SDL_Surface *where, int posX, int posY, Rect *src, ui8 rotation) const
  575. {
  576. if (!surf)
  577. return;
  578. Rect sourceRect(margins.x, margins.y, surf->w, surf->h);
  579. //TODO: rotation and scaling
  580. if (src)
  581. {
  582. sourceRect = sourceRect & *src;
  583. }
  584. Rect destRect(posX, posY, surf->w, surf->h);
  585. destRect += sourceRect.topLeft();
  586. sourceRect -= margins;
  587. CSDL_Ext::blitSurface(surf, &sourceRect, where, &destRect);
  588. }
  589. void SDLImage::playerColored(PlayerColor player)
  590. {
  591. graphics->blueToPlayersAdv(surf, player);
  592. }
  593. int SDLImage::width() const
  594. {
  595. return fullSize.x;
  596. }
  597. int SDLImage::height() const
  598. {
  599. return fullSize.y;
  600. }
  601. SDLImage::~SDLImage()
  602. {
  603. SDL_FreeSurface(surf);
  604. }
  605. CompImage::CompImage(const CDefFile *data, size_t frame, size_t group):
  606. surf(nullptr),
  607. line(nullptr),
  608. palette(nullptr)
  609. {
  610. CompImageLoader loader(this);
  611. data->loadFrame(frame, group, loader);
  612. }
  613. CompImage::CompImage(SDL_Surface * surf)
  614. {
  615. //TODO
  616. assert(0);
  617. }
  618. void CompImage::draw(SDL_Surface *where, int posX, int posY, Rect *src, ui8 alpha) const
  619. {
  620. int rotation = 0; //TODO
  621. //rotation & 2 = horizontal rotation
  622. //rotation & 4 = vertical rotation
  623. if (!surf)
  624. return;
  625. Rect sourceRect(sprite);
  626. //TODO: rotation and scaling
  627. if (src)
  628. sourceRect = sourceRect & *src;
  629. //Limit source rect to sizes of surface
  630. sourceRect = sourceRect & Rect(0, 0, where->w, where->h);
  631. //Starting point on SDL surface
  632. Point dest(posX+sourceRect.x, posY+sourceRect.y);
  633. if (rotation & 2)
  634. dest.y += sourceRect.h;
  635. if (rotation & 4)
  636. dest.x += sourceRect.w;
  637. sourceRect -= sprite.topLeft();
  638. for (int currY = 0; currY <sourceRect.h; currY++)
  639. {
  640. ui8* data = surf + line[currY+sourceRect.y];
  641. ui8 type = *(data++);
  642. ui8 size = *(data++);
  643. int currX = sourceRect.x;
  644. //Skip blocks until starting position reached
  645. while ( currX > size )
  646. {
  647. currX -= size;
  648. if (type == 0xff)
  649. data += size;
  650. type = *(data++);
  651. size = *(data++);
  652. }
  653. //This block will be shown partially - calculate size\position
  654. size -= currX;
  655. if (type == 0xff)
  656. data += currX;
  657. currX = 0;
  658. ui8 bpp = where->format->BytesPerPixel;
  659. //Calculate position for blitting: pixels + Y + X
  660. ui8* blitPos = (ui8*) where->pixels;
  661. if (rotation & 4)
  662. blitPos += (dest.y - currY) * where->pitch;
  663. else
  664. blitPos += (dest.y + currY) * where->pitch;
  665. blitPos += dest.x * bpp;
  666. //Blit blocks that must be fully visible
  667. while (currX + size < sourceRect.w)
  668. {
  669. //blit block, pointers will be modified if needed
  670. BlitBlockWithBpp(bpp, type, size, data, blitPos, alpha, rotation & 2);
  671. currX += size;
  672. type = *(data++);
  673. size = *(data++);
  674. }
  675. //Blit last, semi-visible block
  676. size = sourceRect.w - currX;
  677. BlitBlockWithBpp(bpp, type, size, data, blitPos, alpha, rotation & 2);
  678. }
  679. }
  680. #define CASEBPP(x,y) case x: BlitBlock<x,y>(type, size, data, dest, alpha); break
  681. //FIXME: better way to get blitter
  682. void CompImage::BlitBlockWithBpp(ui8 bpp, ui8 type, ui8 size, ui8 *&data, ui8 *&dest, ui8 alpha, bool rotated) const
  683. {
  684. assert(bpp>1 && bpp<5);
  685. if (rotated)
  686. switch (bpp)
  687. {
  688. CASEBPP(2,1);
  689. CASEBPP(3,1);
  690. CASEBPP(4,1);
  691. }
  692. else
  693. switch (bpp)
  694. {
  695. CASEBPP(2,1);
  696. CASEBPP(3,1);
  697. CASEBPP(4,1);
  698. }
  699. }
  700. #undef CASEBPP
  701. //Blit one block from RLE-d surface
  702. template<int bpp, int dir>
  703. void CompImage::BlitBlock(ui8 type, ui8 size, ui8 *&data, ui8 *&dest, ui8 alpha) const
  704. {
  705. //Raw data
  706. if (type == 0xff)
  707. {
  708. ui8 color = *data;
  709. if (alpha != 255)//Per-surface alpha is set
  710. {
  711. for (size_t i=0; i<size; i++)
  712. {
  713. SDL_Color col = palette[*(data++)];
  714. #ifdef VCMI_SDL1
  715. col.unused = (ui32)col.unused*alpha/255;
  716. #else
  717. col.a = (ui32)col.a*alpha/255;
  718. #endif // 0
  719. ColorPutter<bpp, 1>::PutColorAlpha(dest, col);
  720. }
  721. return;
  722. }
  723. #ifdef VCMI_SDL1
  724. if (palette[color].unused == 255)
  725. #else
  726. if (palette[color].a == 255)
  727. #endif // 0
  728. {
  729. //Put row of RGB data
  730. for (size_t i=0; i<size; i++)
  731. ColorPutter<bpp, 1>::PutColor(dest, palette[*(data++)]);
  732. }
  733. else
  734. {
  735. //Put row of RGBA data
  736. for (size_t i=0; i<size; i++)
  737. ColorPutter<bpp, 1>::PutColorAlpha(dest, palette[*(data++)]);
  738. }
  739. }
  740. //RLE-d sequence
  741. else
  742. {
  743. #ifdef VCMI_SDL1
  744. if (alpha != 255 && palette[type].unused !=0)//Per-surface alpha is set
  745. {
  746. SDL_Color col = palette[type];
  747. col.unused = (int)col.unused*(255-alpha)/255;
  748. for (size_t i=0; i<size; i++)
  749. ColorPutter<bpp, 1>::PutColorAlpha(dest, col);
  750. return;
  751. }
  752. switch (palette[type].unused)
  753. #else
  754. if (alpha != 255 && palette[type].a !=0)//Per-surface alpha is set
  755. {
  756. SDL_Color col = palette[type];
  757. col.a = (int)col.a*(255-alpha)/255;
  758. for (size_t i=0; i<size; i++)
  759. ColorPutter<bpp, 1>::PutColorAlpha(dest, col);
  760. return;
  761. }
  762. switch (palette[type].a)
  763. #endif // 0
  764. {
  765. case 0:
  766. {
  767. //Skip row
  768. dest += size*bpp;
  769. break;
  770. }
  771. case 255:
  772. {
  773. //Put RGB row
  774. ColorPutter<bpp, 1>::PutColorRow(dest, palette[type], size);
  775. break;
  776. }
  777. default:
  778. {
  779. //Put RGBA row
  780. for (size_t i=0; i<size; i++)
  781. ColorPutter<bpp, 1>::PutColorAlpha(dest, palette[type]);
  782. break;
  783. }
  784. }
  785. }
  786. }
  787. void CompImage::playerColored(PlayerColor player)
  788. {
  789. SDL_Color *pal = nullptr;
  790. if(player < PlayerColor::PLAYER_LIMIT)
  791. {
  792. pal = graphics->playerColorPalette + 32*player.getNum();
  793. }
  794. else if(player == PlayerColor::NEUTRAL)
  795. {
  796. pal = graphics->neutralColorPalette;
  797. }
  798. else
  799. assert(0);
  800. for(int i=0; i<32; ++i)
  801. {
  802. CSDL_Ext::colorAssign(palette[224+i],pal[i]);
  803. }
  804. }
  805. int CompImage::width() const
  806. {
  807. return fullSize.x;
  808. }
  809. int CompImage::height() const
  810. {
  811. return fullSize.y;
  812. }
  813. CompImage::~CompImage()
  814. {
  815. free(surf);
  816. delete [] line;
  817. delete [] palette;
  818. }
  819. /*************************************************************************
  820. * CAnimation for animations handling, can load part of file if needed *
  821. *************************************************************************/
  822. IImage * CAnimation::getFromExtraDef(std::string filename)
  823. {
  824. size_t pos = filename.find(':');
  825. if (pos == -1)
  826. return nullptr;
  827. CAnimation anim(filename.substr(0, pos));
  828. pos++;
  829. size_t frame = atoi(filename.c_str()+pos);
  830. size_t group = 0;
  831. pos = filename.find(':', pos);
  832. if (pos != -1)
  833. {
  834. group = frame;
  835. frame = atoi(filename.c_str()+pos);
  836. }
  837. anim.load(frame ,group);
  838. IImage * ret = anim.images[group][frame];
  839. anim.images.clear();
  840. return ret;
  841. }
  842. bool CAnimation::loadFrame(CDefFile * file, size_t frame, size_t group)
  843. {
  844. if (size(group) <= frame)
  845. {
  846. printError(frame, group, "LoadFrame");
  847. return false;
  848. }
  849. IImage *image = getImage(frame, group, false);
  850. if (image)
  851. {
  852. image->increaseRef();
  853. return true;
  854. }
  855. //try to get image from def
  856. if (source[group][frame].getType() == JsonNode::DATA_NULL)
  857. {
  858. if (file)
  859. {
  860. auto frameList = file->getEntries();
  861. if (vstd::contains(frameList, group) && frameList.at(group) > frame) // frame is present
  862. {
  863. if (compressed)
  864. images[group][frame] = new CompImage(file, frame, group);
  865. else
  866. images[group][frame] = new SDLImage(file, frame, group);
  867. return true;
  868. }
  869. }
  870. // still here? image is missing
  871. printError(frame, group, "LoadFrame");
  872. images[group][frame] = new SDLImage("DEFAULT", compressed);
  873. }
  874. else //load from separate file
  875. {
  876. std::string filename = source[group][frame].Struct().find("file")->second.String();
  877. IImage * img = getFromExtraDef(filename);
  878. if (!img)
  879. img = new SDLImage(filename, compressed);
  880. images[group][frame] = img;
  881. return true;
  882. }
  883. return false;
  884. }
  885. bool CAnimation::unloadFrame(size_t frame, size_t group)
  886. {
  887. IImage *image = getImage(frame, group, false);
  888. if (image)
  889. {
  890. //decrease ref count for image and delete if needed
  891. if (image->decreaseRef())
  892. {
  893. delete image;
  894. images[group].erase(frame);
  895. }
  896. if (images[group].empty())
  897. images.erase(group);
  898. return true;
  899. }
  900. return false;
  901. }
  902. void CAnimation::initFromJson(const JsonNode & config)
  903. {
  904. std::string basepath;
  905. basepath = config["basepath"].String();
  906. for(const JsonNode &group : config["sequences"].Vector())
  907. {
  908. size_t groupID = group["group"].Float();//TODO: string-to-value conversion("moving" -> MOVING)
  909. source[groupID].clear();
  910. for(const JsonNode &frame : group["frames"].Vector())
  911. {
  912. source[groupID].push_back(JsonNode());
  913. std::string filename = frame.String();
  914. source[groupID].back()["file"].String() = basepath + filename;
  915. }
  916. }
  917. for(const JsonNode &node : config["images"].Vector())
  918. {
  919. size_t group = node["group"].Float();
  920. size_t frame = node["frame"].Float();
  921. if (source[group].size() <= frame)
  922. source[group].resize(frame+1);
  923. source[group][frame] = node;
  924. std::string filename = node["file"].String();
  925. source[group][frame]["file"].String() = basepath + filename;
  926. }
  927. }
  928. void CAnimation::init(CDefFile * file)
  929. {
  930. if (file)
  931. {
  932. const std::map<size_t, size_t> defEntries = file->getEntries();
  933. for (auto & defEntry : defEntries)
  934. source[defEntry.first].resize(defEntry.second);
  935. }
  936. ResourceID resID(std::string("SPRITES/") + name, EResType::TEXT);
  937. if (vstd::contains(graphics->imageLists, resID.getName()))
  938. initFromJson(graphics->imageLists[resID.getName()]);
  939. auto configList = CResourceHandler::get()->getResourcesWithName(resID);
  940. for(auto & loader : configList)
  941. {
  942. auto stream = loader->load(resID);
  943. std::unique_ptr<ui8[]> textData(new ui8[stream->getSize()]);
  944. stream->read(textData.get(), stream->getSize());
  945. const JsonNode config((char*)textData.get(), stream->getSize());
  946. initFromJson(config);
  947. }
  948. }
  949. CDefFile * CAnimation::getFile() const
  950. {
  951. ResourceID identifier(std::string("SPRITES/") + name, EResType::ANIMATION);
  952. if (CResourceHandler::get()->existsResource(identifier))
  953. return new CDefFile(name);
  954. return nullptr;
  955. }
  956. void CAnimation::printError(size_t frame, size_t group, std::string type) const
  957. {
  958. logGlobal->errorStream() << type <<" error: Request for frame not present in CAnimation! "
  959. <<"\tFile name: "<<name<<" Group: "<<group<<" Frame: "<<frame;
  960. }
  961. CAnimation::CAnimation(std::string Name, bool Compressed):
  962. name(Name),
  963. compressed(Compressed)
  964. {
  965. size_t dotPos = name.find_last_of('.');
  966. if ( dotPos!=-1 )
  967. name.erase(dotPos);
  968. std::transform(name.begin(), name.end(), name.begin(), toupper);
  969. CDefFile * file = getFile();
  970. init(file);
  971. delete file;
  972. loadedAnims.insert(this);
  973. }
  974. CAnimation::CAnimation():
  975. name(""),
  976. compressed(false)
  977. {
  978. init(nullptr);
  979. loadedAnims.insert(this);
  980. }
  981. CAnimation::~CAnimation()
  982. {
  983. if (!images.empty())
  984. {
  985. logGlobal->warnStream()<<"Warning: not all frames were unloaded from "<<name;
  986. for (auto & elem : images)
  987. for (auto & _image : elem.second)
  988. delete _image.second;
  989. }
  990. loadedAnims.erase(this);
  991. }
  992. void CAnimation::setCustom(std::string filename, size_t frame, size_t group)
  993. {
  994. if (source[group].size() <= frame)
  995. source[group].resize(frame+1);
  996. source[group][frame]["file"].String() = filename;
  997. //FIXME: update image if already loaded
  998. }
  999. IImage * CAnimation::getImage(size_t frame, size_t group, bool verbose) const
  1000. {
  1001. auto groupIter = images.find(group);
  1002. if (groupIter != images.end())
  1003. {
  1004. auto imageIter = groupIter->second.find(frame);
  1005. if (imageIter != groupIter->second.end())
  1006. return imageIter->second;
  1007. }
  1008. if (verbose)
  1009. printError(frame, group, "GetImage");
  1010. return nullptr;
  1011. }
  1012. void CAnimation::load()
  1013. {
  1014. CDefFile * file = getFile();
  1015. for (auto & elem : source)
  1016. for (size_t image=0; image < elem.second.size(); image++)
  1017. loadFrame(file, image, elem.first);
  1018. delete file;
  1019. }
  1020. void CAnimation::unload()
  1021. {
  1022. for (auto & elem : source)
  1023. for (size_t image=0; image < elem.second.size(); image++)
  1024. unloadFrame(image, elem.first);
  1025. }
  1026. void CAnimation::loadGroup(size_t group)
  1027. {
  1028. CDefFile * file = getFile();
  1029. if (vstd::contains(source, group))
  1030. for (size_t image=0; image < source[group].size(); image++)
  1031. loadFrame(file, image, group);
  1032. delete file;
  1033. }
  1034. void CAnimation::unloadGroup(size_t group)
  1035. {
  1036. if (vstd::contains(source, group))
  1037. for (size_t image=0; image < source[group].size(); image++)
  1038. unloadFrame(image, group);
  1039. }
  1040. void CAnimation::load(size_t frame, size_t group)
  1041. {
  1042. CDefFile * file = getFile();
  1043. loadFrame(file, frame, group);
  1044. delete file;
  1045. }
  1046. void CAnimation::unload(size_t frame, size_t group)
  1047. {
  1048. unloadFrame(frame, group);
  1049. }
  1050. size_t CAnimation::size(size_t group) const
  1051. {
  1052. auto iter = source.find(group);
  1053. if (iter != source.end())
  1054. return iter->second.size();
  1055. return 0;
  1056. }
  1057. std::set<CAnimation*> CAnimation::loadedAnims;
  1058. void CAnimation::getAnimInfo()
  1059. {
  1060. logGlobal->errorStream()<<"Animation stats: Loaded "<<loadedAnims.size()<<" total";
  1061. for (auto anim : loadedAnims)
  1062. {
  1063. logGlobal->errorStream()<<"Name: "<<anim->name<<" Groups: "<<anim->images.size();
  1064. if (!anim->images.empty())
  1065. logGlobal->errorStream()<<", "<<anim->images.begin()->second.size()<<" image loaded in group "<< anim->images.begin()->first;
  1066. }
  1067. }