CAnimation.cpp 35 KB

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