CAnimation.cpp 32 KB

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