CAnimation.cpp 33 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429
  1. #include <boost/bind.hpp>
  2. #include <boost/algorithm/string/trim.hpp>
  3. #include <SDL_image.h>
  4. #include "../lib/CLodHandler.h"
  5. #include "../lib/JsonNode.h"
  6. #include "CBitmapHandler.h"
  7. #include "Graphics.h"
  8. #include "CAnimation.h"
  9. #include "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_EXPORT CLodHandler *spriteh;
  20. extern DLL_EXPORT 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. unsigned int 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. unsigned int type = readNormalNr(data, it);
  83. it+=4;
  84. //int width = readNormalNr(data, it); it+=4;//not used
  85. //int height = readNormalNr(data, it); it+=4;
  86. it+=8;
  87. unsigned int totalBlocks = readNormalNr(data, it);
  88. it+=4;
  89. for (unsigned int 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 (unsigned int i=0; i<totalBlocks; i++)
  101. {
  102. size_t blockID = readNormalNr(data, it);
  103. it+=4;
  104. size_t totalEntries = readNormalNr(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 (unsigned int j=0; j<totalEntries; j++)
  110. {
  111. size_t currOffset = readNormalNr(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. unsigned int currentOffset = sizeof(SSpriteDef);
  135. unsigned int 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 (unsigned int 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 (unsigned int i=0; i<sprite.height; i++)
  158. {
  159. //get position of the line
  160. currentOffset=BaseOffset + SDL_SwapLE32(read_unaligned_u32(RWEntriesLoc + i));
  161. unsigned int TotalRowLength = 0;
  162. while (TotalRowLength<sprite.width)
  163. {
  164. unsigned char type=FDef[currentOffset++];
  165. unsigned int 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 + SDL_SwapLE16(read_unaligned_u16(FDef + BaseOffset));
  184. for (unsigned int i=0; i<sprite.height; i++)
  185. {
  186. unsigned int TotalRowLength=0;
  187. while (TotalRowLength<sprite.width)
  188. {
  189. unsigned char SegmentType=FDef[currentOffset++];
  190. unsigned char code = SegmentType / 32;
  191. unsigned char 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 (unsigned int i=0; i<sprite.height; i++)
  210. {
  211. currentOffset = BaseOffset + SDL_SwapLE16(read_unaligned_u16(FDef + BaseOffset+i*2*(sprite.width/32)));
  212. unsigned int TotalRowLength=0;
  213. while (TotalRowLength<sprite.width)
  214. {
  215. unsigned char segment = FDef[currentOffset++];
  216. unsigned char code = segment / 32;
  217. unsigned char 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 unsigned int[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, unsigned char 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 = (unsigned int)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 < 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. std::string configFile = spriteh->getTextFile(name);
  828. const JsonNode config(configFile);
  829. std::string basepath;
  830. if (!config["basepath"].isNull())
  831. basepath = config["basepath"].String();
  832. if (!config["sequences"].isNull())
  833. {
  834. const JsonVector &groups = config["sequences"].Vector();
  835. for (JsonVector::const_iterator groupsIter = groups.begin(); groupsIter!=groups.end(); ++groupsIter)
  836. {
  837. JsonNode group = *groupsIter;
  838. size_t groupID = group["group"].Float();//TODO: string-to-value conversion
  839. source[groupID].clear();
  840. const JsonVector &frames = group["frames"].Vector();
  841. for (JsonVector::const_iterator framesIter = frames.begin(); framesIter!=frames.end(); ++framesIter)
  842. {
  843. const JsonNode &frame = *framesIter;
  844. source[groupID].push_back(frame);
  845. std::string filename = frame["file"].String();
  846. source[groupID].back()["file"].String() = basepath + filename;
  847. }
  848. }
  849. }
  850. if (!config["images"].isNull())
  851. {
  852. const JsonVector &vector = config["images"].Vector();
  853. for (JsonVector::const_iterator it = vector.begin(); it!=vector.end(); ++it)
  854. {
  855. const JsonNode &node = *it;
  856. size_t group=0;
  857. if (!node["group"].isNull())
  858. group = node["group"].Float();
  859. size_t frame = node["frame"].Float();
  860. if (source[group].size() <= frame)
  861. source[group].resize(frame+1);
  862. source[group][frame] = node;
  863. std::string filename = node["file"].String();
  864. source[group][frame]["file"].String() = basepath + filename;
  865. }
  866. }
  867. }
  868. }
  869. CDefFile * CAnimation::getFile() const
  870. {
  871. if (spriteh->haveFile(name, FILE_ANIMATION))
  872. return new CDefFile(name);
  873. return NULL;
  874. }
  875. void CAnimation::printError(size_t frame, size_t group, std::string type) const
  876. {
  877. tlog0 << type <<" error: Request for frame not present in CAnimation!\n"
  878. <<"\tFile name: "<<name<<" Group: "<<group<<" Frame: "<<frame<<"\n";
  879. }
  880. CAnimation::CAnimation(std::string Name, bool Compressed):
  881. name(Name),
  882. compressed(Compressed)
  883. {
  884. size_t dotPos = name.find_last_of('.');
  885. if ( dotPos!=-1 )
  886. name.erase(dotPos);
  887. std::transform(name.begin(), name.end(), name.begin(), toupper);
  888. CDefFile * file = getFile();
  889. init(file);
  890. delete file;
  891. loadedAnims.insert(this);
  892. }
  893. CAnimation::CAnimation():
  894. name(""),
  895. compressed(false)
  896. {
  897. init(NULL);
  898. loadedAnims.insert(this);
  899. }
  900. CAnimation::~CAnimation()
  901. {
  902. if (!images.empty())
  903. {
  904. tlog2<<"Warning: not all frames were unloaded from "<<name<<"\n";
  905. for (group_map::iterator group = images.begin(); group != images.end(); ++group )
  906. for (image_map::iterator image = group->second.begin(); image != group->second.end(); ++image )
  907. delete image->second;
  908. }
  909. loadedAnims.erase(this);
  910. }
  911. void CAnimation::setCustom(std::string filename, size_t frame, size_t group)
  912. {
  913. if (source[group].size() <= frame)
  914. source[group].resize(frame+1);
  915. source[group][frame]["file"].String() = filename;
  916. //FIXME: update image if already loaded
  917. }
  918. IImage * CAnimation::getImage(size_t frame, size_t group, bool verbose) const
  919. {
  920. group_map::const_iterator groupIter = images.find(group);
  921. if (groupIter != images.end())
  922. {
  923. image_map::const_iterator imageIter = groupIter->second.find(frame);
  924. if (imageIter != groupIter->second.end())
  925. return imageIter->second;
  926. }
  927. if (verbose)
  928. printError(frame, group, "GetImage");
  929. return NULL;
  930. }
  931. void CAnimation::load()
  932. {
  933. CDefFile * file = getFile();
  934. for (source_map::iterator group = source.begin(); group != source.end(); ++group )
  935. for (size_t image=0; image < group->second.size(); image++)
  936. loadFrame(file, image, group->first);
  937. delete file;
  938. }
  939. void CAnimation::unload()
  940. {
  941. for (source_map::iterator group = source.begin(); group != source.end(); ++group )
  942. for (size_t image=0; image < group->second.size(); image++)
  943. unloadFrame(image, group->first);
  944. }
  945. void CAnimation::loadGroup(size_t group)
  946. {
  947. CDefFile * file = getFile();
  948. if (vstd::contains(source, group))
  949. for (size_t image=0; image < source[group].size(); image++)
  950. loadFrame(file, image, group);
  951. delete file;
  952. }
  953. void CAnimation::unloadGroup(size_t group)
  954. {
  955. if (vstd::contains(source, group))
  956. for (size_t image=0; image < source[group].size(); image++)
  957. unloadFrame(image, group);
  958. }
  959. void CAnimation::load(size_t frame, size_t group)
  960. {
  961. CDefFile * file = getFile();
  962. loadFrame(file, frame, group);
  963. delete file;
  964. }
  965. void CAnimation::unload(size_t frame, size_t group)
  966. {
  967. unloadFrame(frame, group);
  968. }
  969. size_t CAnimation::size(size_t group) const
  970. {
  971. source_map::const_iterator iter = source.find(group);
  972. if (iter != source.end())
  973. return iter->second.size();
  974. return 0;
  975. }
  976. std::set<CAnimation*> CAnimation::loadedAnims;
  977. void CAnimation::getAnimInfo()
  978. {
  979. tlog1<<"Animation stats: Loaded "<<loadedAnims.size()<<" total\n";
  980. for (std::set<CAnimation*>::iterator it = loadedAnims.begin(); it != loadedAnims.end(); it++)
  981. {
  982. CAnimation * anim = *it;
  983. tlog1<<"Name: "<<anim->name<<" Groups: "<<anim->images.size();
  984. if (!anim->images.empty())
  985. tlog1<<", "<<anim->images.begin()->second.size()<<" image loaded in group "<< anim->images.begin()->first;
  986. tlog1<<"\n";
  987. }
  988. }
  989. CAnimImage::CAnimImage(std::string name, size_t Frame, size_t Group, int x, int y, unsigned char Flags):
  990. frame(Frame),
  991. group(Group),
  992. player(-1),
  993. flags(Flags)
  994. {
  995. pos.x += x;
  996. pos.y += y;
  997. anim = new CAnimation(name);
  998. init();
  999. }
  1000. CAnimImage::CAnimImage(CAnimation *Anim, size_t Frame, size_t Group, int x, int y, unsigned char Flags):
  1001. anim(Anim),
  1002. frame(Frame),
  1003. group(Group),
  1004. player(-1),
  1005. flags(Flags)
  1006. {
  1007. pos.x += x;
  1008. pos.y += y;
  1009. init();
  1010. }
  1011. size_t CAnimImage::size()
  1012. {
  1013. return anim->size(group);
  1014. }
  1015. void CAnimImage::init()
  1016. {
  1017. anim->load(frame, group);
  1018. if (flags & CShowableAnim::BASE)
  1019. anim->load(0,group);
  1020. IImage *img = anim->getImage(frame, group);
  1021. if (img)
  1022. {
  1023. pos.w = img->width();
  1024. pos.h = img->height();
  1025. }
  1026. }
  1027. CAnimImage::~CAnimImage()
  1028. {
  1029. anim->unload(frame, group);
  1030. if (flags & CShowableAnim::BASE)
  1031. anim->unload(0,group);
  1032. delete anim;
  1033. }
  1034. void CAnimImage::showAll(SDL_Surface *to)
  1035. {
  1036. IImage *img = anim->getImage(frame, group);
  1037. if (img)
  1038. img->draw(to, pos.x, pos.y);
  1039. }
  1040. void CAnimImage::setFrame(size_t Frame, size_t Group)
  1041. {
  1042. if (frame == Frame && group==Group)
  1043. return;
  1044. if (anim->size(Group) > Frame)
  1045. {
  1046. anim->load(Frame, Group);
  1047. anim->unload(frame, group);
  1048. frame = Frame;
  1049. group = Group;
  1050. IImage *img = anim->getImage(frame, group);
  1051. if (img)
  1052. {
  1053. if (flags & CShowableAnim::PLAYER_COLORED)
  1054. img->playerColored(player);
  1055. pos.w = img->width();
  1056. pos.h = img->height();
  1057. }
  1058. }
  1059. }
  1060. void CAnimImage::playerColored(int currPlayer)
  1061. {
  1062. player = currPlayer;
  1063. flags |= CShowableAnim::PLAYER_COLORED;
  1064. anim->getImage(frame, group)->playerColored(player);
  1065. if (flags & CShowableAnim::BASE)
  1066. anim->getImage(0, group)->playerColored(player);
  1067. }
  1068. CShowableAnim::CShowableAnim(int x, int y, std::string name, unsigned char Flags, unsigned int Delay, size_t Group):
  1069. anim(name, Flags & USE_RLE),
  1070. group(Group),
  1071. frame(0),
  1072. first(0),
  1073. frameDelay(Delay),
  1074. value(0),
  1075. flags(Flags),
  1076. xOffset(0),
  1077. yOffset(0),
  1078. alpha(255)
  1079. {
  1080. anim.loadGroup(group);
  1081. last = anim.size(group);
  1082. pos.w = anim.getImage(0, group)->width();
  1083. pos.h = anim.getImage(0, group)->height();
  1084. pos.x+= x;
  1085. pos.y+= y;
  1086. }
  1087. CShowableAnim::~CShowableAnim()
  1088. {
  1089. anim.unloadGroup(group);
  1090. }
  1091. void CShowableAnim::setAlpha(unsigned int alphaValue)
  1092. {
  1093. alpha = std::min<unsigned int>(alphaValue, 255);
  1094. }
  1095. bool CShowableAnim::set(size_t Group, size_t from, size_t to)
  1096. {
  1097. size_t max = anim.size(Group);
  1098. if (max>to)
  1099. max = to;
  1100. if (max < from || max == 0)
  1101. return false;
  1102. anim.load(Group);
  1103. anim.unload(group);
  1104. group = Group;
  1105. frame = first = from;
  1106. last = max;
  1107. value = 0;
  1108. return true;
  1109. }
  1110. bool CShowableAnim::set(size_t Group)
  1111. {
  1112. if (anim.size(Group)== 0)
  1113. return false;
  1114. if (group != Group)
  1115. {
  1116. anim.loadGroup(Group);
  1117. anim.unloadGroup(group);
  1118. first = 0;
  1119. group = Group;
  1120. last = anim.size(Group);
  1121. }
  1122. frame = value = 0;
  1123. return true;
  1124. }
  1125. void CShowableAnim::reset()
  1126. {
  1127. value = 0;
  1128. frame = first;
  1129. if (callback)
  1130. callback();
  1131. }
  1132. void CShowableAnim::clipRect(int posX, int posY, int width, int height)
  1133. {
  1134. xOffset = posX;
  1135. yOffset = posY;
  1136. pos.w = width;
  1137. pos.h = height;
  1138. }
  1139. void CShowableAnim::show(SDL_Surface *to)
  1140. {
  1141. if ( flags & BASE && frame != first)
  1142. blitImage(first, group, to);
  1143. blitImage(frame, group, to);
  1144. if ( ++value == frameDelay )
  1145. {
  1146. value = 0;
  1147. if ( ++frame == last)
  1148. reset();
  1149. }
  1150. }
  1151. void CShowableAnim::showAll(SDL_Surface *to)
  1152. {
  1153. if ( flags & BASE && frame != first)
  1154. blitImage(first, group, to);
  1155. blitImage(frame, group, to);
  1156. }
  1157. void CShowableAnim::blitImage(size_t frame, size_t group, SDL_Surface *to)
  1158. {
  1159. assert(to);
  1160. Rect src( xOffset, yOffset, pos.w, pos.h);
  1161. IImage * img = anim.getImage(frame, group);
  1162. if (img)
  1163. img->draw(to, pos.x-xOffset, pos.y-yOffset, &src, alpha);
  1164. }
  1165. void CShowableAnim::rotate(bool on, bool vertical)
  1166. {
  1167. unsigned char flag = vertical? VERTICAL_FLIP:HORIZONTAL_FLIP;
  1168. if (on)
  1169. flags |= flag;
  1170. else
  1171. flags &= ~flag;
  1172. }
  1173. CCreatureAnim::CCreatureAnim(int x, int y, std::string name, Rect picPos, unsigned char flags, EAnimType type):
  1174. CShowableAnim(x,y,name,flags,3,type)
  1175. {
  1176. xOffset = picPos.x;
  1177. yOffset = picPos.y;
  1178. if (picPos.w)
  1179. pos.w = picPos.w;
  1180. if (picPos.h)
  1181. pos.h = picPos.h;
  1182. };
  1183. void CCreatureAnim::loopPreview()
  1184. {
  1185. std::vector<EAnimType> available;
  1186. static const EAnimType previewList[] = {HOLDING, HITTED, DEFENCE, ATTACK_FRONT, CAST_FRONT};
  1187. for (size_t i=0; i<5; i++)
  1188. if (anim.size(previewList[i]))
  1189. available.push_back(previewList[i]);
  1190. size_t rnd = rand()%(available.size()*2);
  1191. if (rnd >= available.size())
  1192. {
  1193. if ( anim.size(MOVING) == 0 )//no moving animation present
  1194. addLast( HOLDING );
  1195. else
  1196. addLast( MOVING ) ;
  1197. }
  1198. else
  1199. addLast(available[rnd]);
  1200. }
  1201. void CCreatureAnim::addLast(EAnimType newType)
  1202. {
  1203. if (type != MOVING && newType == MOVING)//starting moving - play init sequence
  1204. {
  1205. queue.push( MOVE_START );
  1206. }
  1207. else if (type == MOVING && newType != MOVING )//previous anim was moving - finish it
  1208. {
  1209. queue.push( MOVE_END );
  1210. }
  1211. if (newType == TURN_L || newType == TURN_R)
  1212. queue.push(newType);
  1213. queue.push(newType);
  1214. }
  1215. void CCreatureAnim::reset()
  1216. {
  1217. //if we are in the middle of rotation - set flag
  1218. if (type == TURN_L && !queue.empty() && queue.front() == TURN_L)
  1219. rotate(true);
  1220. if (type == TURN_R && !queue.empty() && queue.front() == TURN_R)
  1221. rotate(false);
  1222. while (!queue.empty())
  1223. {
  1224. EAnimType at = queue.front();
  1225. queue.pop();
  1226. if (set(at))
  1227. return;
  1228. }
  1229. if (callback)
  1230. callback();
  1231. while (!queue.empty())
  1232. {
  1233. EAnimType at = queue.front();
  1234. queue.pop();
  1235. if (set(at))
  1236. return;
  1237. }
  1238. set(HOLDING);
  1239. }
  1240. void CCreatureAnim::startPreview()
  1241. {
  1242. callback = boost::bind(&CCreatureAnim::loopPreview,this);
  1243. }
  1244. void CCreatureAnim::clearAndSet(EAnimType type)
  1245. {
  1246. while (!queue.empty())
  1247. queue.pop();
  1248. set(type);
  1249. }