CAnimation.cpp 32 KB

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