CAnimation.cpp 35 KB

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