2
0

CAnimation.cpp 32 KB

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