CAnimation.cpp 32 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412
  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. pos.w = img->width();
  1025. pos.h = img->height();
  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. anim->getImage(frame, group)->draw(to, pos.x, pos.y);
  1037. }
  1038. void CAnimImage::setFrame(size_t Frame, size_t Group)
  1039. {
  1040. if (frame == Frame && group==Group)
  1041. return;
  1042. if (anim->size(Group) > Frame)
  1043. {
  1044. anim->load(Frame, Group);
  1045. anim->unload(frame, group);
  1046. frame = Frame;
  1047. group = Group;
  1048. if (flags & CShowableAnim::PLAYER_COLORED)
  1049. anim->getImage(frame, group)->playerColored(player);
  1050. }
  1051. }
  1052. void CAnimImage::playerColored(int currPlayer)
  1053. {
  1054. player = currPlayer;
  1055. flags |= CShowableAnim::PLAYER_COLORED;
  1056. anim->getImage(frame, group)->playerColored(player);
  1057. if (flags & CShowableAnim::BASE)
  1058. anim->getImage(0, group)->playerColored(player);
  1059. }
  1060. CShowableAnim::CShowableAnim(int x, int y, std::string name, unsigned char Flags, unsigned int Delay, size_t Group):
  1061. anim(name, Flags & USE_RLE),
  1062. group(Group),
  1063. frame(0),
  1064. first(0),
  1065. frameDelay(Delay),
  1066. value(0),
  1067. flags(Flags),
  1068. xOffset(0),
  1069. yOffset(0),
  1070. alpha(255)
  1071. {
  1072. anim.loadGroup(group);
  1073. last = anim.size(group);
  1074. pos.w = anim.getImage(0, group)->width();
  1075. pos.h = anim.getImage(0, group)->height();
  1076. pos.x+= x;
  1077. pos.y+= y;
  1078. }
  1079. CShowableAnim::~CShowableAnim()
  1080. {
  1081. anim.unloadGroup(group);
  1082. }
  1083. void CShowableAnim::setAlpha(unsigned int alphaValue)
  1084. {
  1085. alpha = std::min<unsigned int>(alphaValue, 255);
  1086. }
  1087. bool CShowableAnim::set(size_t Group, size_t from, size_t to)
  1088. {
  1089. size_t max = anim.size(Group);
  1090. if (max>to)
  1091. max = to;
  1092. if (max < from || max == 0)
  1093. return false;
  1094. anim.load(Group);
  1095. anim.unload(group);
  1096. group = Group;
  1097. frame = first = from;
  1098. last = max;
  1099. value = 0;
  1100. return true;
  1101. }
  1102. bool CShowableAnim::set(size_t Group)
  1103. {
  1104. if (anim.size(Group)== 0)
  1105. return false;
  1106. if (group != Group)
  1107. {
  1108. anim.loadGroup(Group);
  1109. anim.unloadGroup(group);
  1110. first = 0;
  1111. group = Group;
  1112. last = anim.size(Group);
  1113. }
  1114. frame = value = 0;
  1115. return true;
  1116. }
  1117. void CShowableAnim::reset()
  1118. {
  1119. value = 0;
  1120. frame = first;
  1121. if (callback)
  1122. callback();
  1123. }
  1124. void CShowableAnim::clipRect(int posX, int posY, int width, int height)
  1125. {
  1126. xOffset = posX;
  1127. yOffset = posY;
  1128. pos.w = width;
  1129. pos.h = height;
  1130. }
  1131. void CShowableAnim::show(SDL_Surface *to)
  1132. {
  1133. if ( flags & BASE && frame != first)
  1134. blitImage(first, group, to);
  1135. blitImage(frame, group, to);
  1136. if ( ++value == frameDelay )
  1137. {
  1138. value = 0;
  1139. if ( ++frame == last)
  1140. reset();
  1141. }
  1142. }
  1143. void CShowableAnim::showAll(SDL_Surface *to)
  1144. {
  1145. if ( flags & BASE && frame != first)
  1146. blitImage(first, group, to);
  1147. blitImage(frame, group, to);
  1148. }
  1149. void CShowableAnim::blitImage(size_t frame, size_t group, SDL_Surface *to)
  1150. {
  1151. assert(to);
  1152. Rect src( xOffset, yOffset, pos.w, pos.h);
  1153. IImage * img = anim.getImage(frame, group);
  1154. img->draw(to, pos.x-xOffset, pos.y-yOffset, &src, alpha);
  1155. }
  1156. void CShowableAnim::rotate(bool on, bool vertical)
  1157. {
  1158. unsigned char 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, unsigned char 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. }