Image.cpp 47 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536
  1. //
  2. // Copyright (c) 2008-2014 the Urho3D project.
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to deal
  6. // in the Software without restriction, including without limitation the rights
  7. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. // copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. // THE SOFTWARE.
  21. //
  22. #include "Precompiled.h"
  23. #include "Context.h"
  24. #include "Decompress.h"
  25. #include "File.h"
  26. #include "FileSystem.h"
  27. #include "Log.h"
  28. #include "Profiler.h"
  29. #include <cstdlib>
  30. #include <cstring>
  31. #include <stb_image.h>
  32. #include <stb_image_write.h>
  33. #include <jo_jpeg.h>
  34. #include <SDL_surface.h>
  35. #include "DebugNew.h"
  36. extern "C" unsigned char *stbi_write_png_to_mem(unsigned char *pixels, int stride_bytes, int x, int y, int n, int *out_len);
  37. #ifndef MAKEFOURCC
  38. #define MAKEFOURCC(ch0, ch1, ch2, ch3) ((unsigned)(ch0) | ((unsigned)(ch1) << 8) | ((unsigned)(ch2) << 16) | ((unsigned)(ch3) << 24))
  39. #endif
  40. #define FOURCC_DXT1 (MAKEFOURCC('D','X','T','1'))
  41. #define FOURCC_DXT2 (MAKEFOURCC('D','X','T','2'))
  42. #define FOURCC_DXT3 (MAKEFOURCC('D','X','T','3'))
  43. #define FOURCC_DXT4 (MAKEFOURCC('D','X','T','4'))
  44. #define FOURCC_DXT5 (MAKEFOURCC('D','X','T','5'))
  45. namespace Urho3D
  46. {
  47. /// DirectDraw color key definition.
  48. struct DDColorKey
  49. {
  50. unsigned dwColorSpaceLowValue_;
  51. unsigned dwColorSpaceHighValue_;
  52. };
  53. /// DirectDraw pixel format definition.
  54. struct DDPixelFormat
  55. {
  56. unsigned dwSize_;
  57. unsigned dwFlags_;
  58. unsigned dwFourCC_;
  59. union
  60. {
  61. unsigned dwRGBBitCount_;
  62. unsigned dwYUVBitCount_;
  63. unsigned dwZBufferBitDepth_;
  64. unsigned dwAlphaBitDepth_;
  65. unsigned dwLuminanceBitCount_;
  66. unsigned dwBumpBitCount_;
  67. unsigned dwPrivateFormatBitCount_;
  68. };
  69. union
  70. {
  71. unsigned dwRBitMask_;
  72. unsigned dwYBitMask_;
  73. unsigned dwStencilBitDepth_;
  74. unsigned dwLuminanceBitMask_;
  75. unsigned dwBumpDuBitMask_;
  76. unsigned dwOperations_;
  77. };
  78. union
  79. {
  80. unsigned dwGBitMask_;
  81. unsigned dwUBitMask_;
  82. unsigned dwZBitMask_;
  83. unsigned dwBumpDvBitMask_;
  84. struct
  85. {
  86. unsigned short wFlipMSTypes_;
  87. unsigned short wBltMSTypes_;
  88. } multiSampleCaps_;
  89. };
  90. union
  91. {
  92. unsigned dwBBitMask_;
  93. unsigned dwVBitMask_;
  94. unsigned dwStencilBitMask_;
  95. unsigned dwBumpLuminanceBitMask_;
  96. };
  97. union
  98. {
  99. unsigned dwRGBAlphaBitMask_;
  100. unsigned dwYUVAlphaBitMask_;
  101. unsigned dwLuminanceAlphaBitMask_;
  102. unsigned dwRGBZBitMask_;
  103. unsigned dwYUVZBitMask_;
  104. };
  105. };
  106. /// DirectDraw surface capabilities.
  107. struct DDSCaps2
  108. {
  109. unsigned dwCaps_;
  110. unsigned dwCaps2_;
  111. unsigned dwCaps3_;
  112. union
  113. {
  114. unsigned dwCaps4_;
  115. unsigned dwVolumeDepth_;
  116. };
  117. };
  118. /// DirectDraw surface description.
  119. struct DDSurfaceDesc2
  120. {
  121. unsigned dwSize_;
  122. unsigned dwFlags_;
  123. unsigned dwHeight_;
  124. unsigned dwWidth_;
  125. union
  126. {
  127. unsigned lPitch_;
  128. unsigned dwLinearSize_;
  129. };
  130. union
  131. {
  132. unsigned dwBackBufferCount_;
  133. unsigned dwDepth_;
  134. };
  135. union
  136. {
  137. unsigned dwMipMapCount_;
  138. unsigned dwRefreshRate_;
  139. unsigned dwSrcVBHandle_;
  140. };
  141. unsigned dwAlphaBitDepth_;
  142. unsigned dwReserved_;
  143. unsigned lpSurface_; // Do not define as a void pointer, as it is 8 bytes in a 64bit build
  144. union
  145. {
  146. DDColorKey ddckCKDestOverlay_;
  147. unsigned dwEmptyFaceColor_;
  148. };
  149. DDColorKey ddckCKDestBlt_;
  150. DDColorKey ddckCKSrcOverlay_;
  151. DDColorKey ddckCKSrcBlt_;
  152. union
  153. {
  154. DDPixelFormat ddpfPixelFormat_;
  155. unsigned dwFVF_;
  156. };
  157. DDSCaps2 ddsCaps_;
  158. unsigned dwTextureStage_;
  159. };
  160. bool CompressedLevel::Decompress(unsigned char* dest)
  161. {
  162. if (!data_)
  163. return false;
  164. switch (format_)
  165. {
  166. case CF_DXT1:
  167. case CF_DXT3:
  168. case CF_DXT5:
  169. DecompressImageDXT(dest, data_, width_, height_, depth_, format_);
  170. return true;
  171. case CF_ETC1:
  172. DecompressImageETC(dest, data_, width_, height_);
  173. return true;
  174. case CF_PVRTC_RGB_2BPP:
  175. case CF_PVRTC_RGBA_2BPP:
  176. case CF_PVRTC_RGB_4BPP:
  177. case CF_PVRTC_RGBA_4BPP:
  178. DecompressImagePVRTC(dest, data_, width_, height_, format_);
  179. return true;
  180. default:
  181. // Unknown format
  182. return false;
  183. }
  184. }
  185. Image::Image(Context* context) :
  186. Resource(context),
  187. width_(0),
  188. height_(0),
  189. depth_(0),
  190. components_(0)
  191. {
  192. }
  193. Image::~Image()
  194. {
  195. }
  196. void Image::RegisterObject(Context* context)
  197. {
  198. context->RegisterFactory<Image>();
  199. }
  200. bool Image::BeginLoad(Deserializer& source)
  201. {
  202. // Check for DDS, KTX or PVR compressed format
  203. String fileID = source.ReadFileID();
  204. if (fileID == "DDS ")
  205. {
  206. // DDS compressed format
  207. DDSurfaceDesc2 ddsd;
  208. source.Read(&ddsd, sizeof(ddsd));
  209. switch (ddsd.ddpfPixelFormat_.dwFourCC_)
  210. {
  211. case FOURCC_DXT1:
  212. compressedFormat_ = CF_DXT1;
  213. components_ = 3;
  214. break;
  215. case FOURCC_DXT3:
  216. compressedFormat_ = CF_DXT3;
  217. components_ = 4;
  218. break;
  219. case FOURCC_DXT5:
  220. compressedFormat_ = CF_DXT5;
  221. components_ = 4;
  222. break;
  223. default:
  224. LOGERROR("Unsupported DDS format");
  225. return false;
  226. }
  227. unsigned dataSize = source.GetSize() - source.GetPosition();
  228. data_ = new unsigned char[dataSize];
  229. width_ = ddsd.dwWidth_;
  230. height_ = ddsd.dwHeight_;
  231. depth_ = ddsd.dwDepth_;
  232. numCompressedLevels_ = ddsd.dwMipMapCount_;
  233. if (!numCompressedLevels_)
  234. numCompressedLevels_ = 1;
  235. SetMemoryUse(dataSize);
  236. source.Read(data_.Get(), dataSize);
  237. }
  238. else if (fileID == "\253KTX")
  239. {
  240. source.Seek(12);
  241. unsigned endianness = source.ReadUInt();
  242. unsigned type = source.ReadUInt();
  243. /* unsigned typeSize = */ source.ReadUInt();
  244. unsigned format = source.ReadUInt();
  245. unsigned internalFormat = source.ReadUInt();
  246. /* unsigned baseInternalFormat = */ source.ReadUInt();
  247. unsigned width = source.ReadUInt();
  248. unsigned height = source.ReadUInt();
  249. unsigned depth = source.ReadUInt();
  250. /* unsigned arrayElements = */ source.ReadUInt();
  251. unsigned faces = source.ReadUInt();
  252. unsigned mipmaps = source.ReadUInt();
  253. unsigned keyValueBytes = source.ReadUInt();
  254. if (endianness != 0x04030201)
  255. {
  256. LOGERROR("Big-endian KTX files not supported");
  257. return false;
  258. }
  259. if (type != 0 || format != 0)
  260. {
  261. LOGERROR("Uncompressed KTX files not supported");
  262. return false;
  263. }
  264. if (faces > 1 || depth > 1)
  265. {
  266. LOGERROR("3D or cube KTX files not supported");
  267. return false;
  268. }
  269. if (mipmaps == 0)
  270. {
  271. LOGERROR("KTX files without explicitly specified mipmap count not supported");
  272. return false;
  273. }
  274. compressedFormat_ = CF_NONE;
  275. switch (internalFormat)
  276. {
  277. case 0x83f1:
  278. compressedFormat_ = CF_DXT1;
  279. components_ = 4;
  280. break;
  281. case 0x83f2:
  282. compressedFormat_ = CF_DXT3;
  283. components_ = 4;
  284. break;
  285. case 0x83f3:
  286. compressedFormat_ = CF_DXT5;
  287. components_ = 4;
  288. break;
  289. case 0x8d64:
  290. compressedFormat_ = CF_ETC1;
  291. components_ = 3;
  292. break;
  293. case 0x8c00:
  294. compressedFormat_ = CF_PVRTC_RGB_4BPP;
  295. components_ = 3;
  296. break;
  297. case 0x8c01:
  298. compressedFormat_ = CF_PVRTC_RGB_2BPP;
  299. components_ = 3;
  300. break;
  301. case 0x8c02:
  302. compressedFormat_ = CF_PVRTC_RGBA_4BPP;
  303. components_ = 4;
  304. break;
  305. case 0x8c03:
  306. compressedFormat_ = CF_PVRTC_RGBA_2BPP;
  307. components_ = 4;
  308. break;
  309. }
  310. if (compressedFormat_ == CF_NONE)
  311. {
  312. LOGERROR("Unsupported texture format in KTX file");
  313. return false;
  314. }
  315. source.Seek(source.GetPosition() + keyValueBytes);
  316. unsigned dataSize = source.GetSize() - source.GetPosition() - mipmaps * sizeof(unsigned);
  317. data_ = new unsigned char[dataSize];
  318. width_ = width;
  319. height_ = height;
  320. numCompressedLevels_ = mipmaps;
  321. unsigned dataOffset = 0;
  322. for (unsigned i = 0; i < mipmaps; ++i)
  323. {
  324. unsigned levelSize = source.ReadUInt();
  325. if (levelSize + dataOffset > dataSize)
  326. {
  327. LOGERROR("KTX mipmap level data size exceeds file size");
  328. return false;
  329. }
  330. source.Read(&data_[dataOffset], levelSize);
  331. dataOffset += levelSize;
  332. if (source.GetPosition() & 3)
  333. source.Seek((source.GetPosition() + 3) & 0xfffffffc);
  334. }
  335. SetMemoryUse(dataSize);
  336. }
  337. else if (fileID == "PVR\3")
  338. {
  339. /* unsigned flags = */ source.ReadUInt();
  340. unsigned pixelFormatLo = source.ReadUInt();
  341. /* unsigned pixelFormatHi = */ source.ReadUInt();
  342. /* unsigned colourSpace = */ source.ReadUInt();
  343. /* unsigned channelType = */ source.ReadUInt();
  344. unsigned height = source.ReadUInt();
  345. unsigned width = source.ReadUInt();
  346. unsigned depth = source.ReadUInt();
  347. /* unsigned numSurfaces = */ source.ReadUInt();
  348. unsigned numFaces = source.ReadUInt();
  349. unsigned mipmapCount = source.ReadUInt();
  350. unsigned metaDataSize = source.ReadUInt();
  351. if (depth > 1 || numFaces > 1)
  352. {
  353. LOGERROR("3D or cube PVR files not supported");
  354. return false;
  355. }
  356. if (mipmapCount == 0)
  357. {
  358. LOGERROR("PVR files without explicitly specified mipmap count not supported");
  359. return false;
  360. }
  361. compressedFormat_ = CF_NONE;
  362. switch (pixelFormatLo)
  363. {
  364. case 0:
  365. compressedFormat_ = CF_PVRTC_RGB_2BPP;
  366. components_ = 3;
  367. break;
  368. case 1:
  369. compressedFormat_ = CF_PVRTC_RGBA_2BPP;
  370. components_ = 4;
  371. break;
  372. case 2:
  373. compressedFormat_ = CF_PVRTC_RGB_4BPP;
  374. components_ = 3;
  375. break;
  376. case 3:
  377. compressedFormat_ = CF_PVRTC_RGBA_4BPP;
  378. components_ = 4;
  379. break;
  380. case 6:
  381. compressedFormat_ = CF_ETC1;
  382. components_ = 3;
  383. break;
  384. case 7:
  385. compressedFormat_ = CF_DXT1;
  386. components_ = 4;
  387. break;
  388. case 9:
  389. compressedFormat_ = CF_DXT3;
  390. components_ = 4;
  391. break;
  392. case 11:
  393. compressedFormat_ = CF_DXT5;
  394. components_ = 4;
  395. break;
  396. }
  397. if (compressedFormat_ == CF_NONE)
  398. {
  399. LOGERROR("Unsupported texture format in PVR file");
  400. return false;
  401. }
  402. source.Seek(source.GetPosition() + metaDataSize);
  403. unsigned dataSize = source.GetSize() - source.GetPosition();
  404. data_ = new unsigned char[dataSize];
  405. width_ = width;
  406. height_ = height;
  407. numCompressedLevels_ = mipmapCount;
  408. source.Read(data_.Get(), dataSize);
  409. SetMemoryUse(dataSize);
  410. }
  411. else
  412. {
  413. // Not DDS, KTX or PVR, use STBImage to load other image formats as uncompressed
  414. source.Seek(0);
  415. int width, height;
  416. unsigned components;
  417. unsigned char* pixelData = GetImageData(source, width, height, components);
  418. if (!pixelData)
  419. {
  420. LOGERROR("Could not load image " + source.GetName() + ": " + String(stbi_failure_reason()));
  421. return false;
  422. }
  423. SetSize(width, height, components);
  424. SetData(pixelData);
  425. FreeImageData(pixelData);
  426. }
  427. return true;
  428. }
  429. bool Image::Save(Serializer& dest) const
  430. {
  431. PROFILE(SaveImage);
  432. if (IsCompressed())
  433. {
  434. LOGERROR("Can not save compressed image " + GetName());
  435. return false;
  436. }
  437. if (!data_)
  438. {
  439. LOGERROR("Can not save zero-sized image " + GetName());
  440. return false;
  441. }
  442. int len;
  443. unsigned char *png = stbi_write_png_to_mem(data_.Get(), 0, width_, height_, components_, &len);
  444. bool success = dest.Write(png, len) == (unsigned)len;
  445. free(png);
  446. return success;
  447. }
  448. bool Image::SetSize(int width, int height, unsigned components)
  449. {
  450. return SetSize(width, height, 1, components);
  451. }
  452. bool Image::SetSize(int width, int height, int depth, unsigned components)
  453. {
  454. if (width == width_ && height == height_ && depth == depth_ && components == components_)
  455. return true;
  456. if (width <= 0 || height <= 0 || depth <= 0)
  457. return false;
  458. if (components > 4)
  459. {
  460. LOGERROR("More than 4 color components are not supported");
  461. return false;
  462. }
  463. data_ = new unsigned char[width * height * depth * components];
  464. width_ = width;
  465. height_ = height;
  466. depth_ = depth;
  467. components_ = components;
  468. compressedFormat_ = CF_NONE;
  469. numCompressedLevels_ = 0;
  470. nextLevel_.Reset();
  471. SetMemoryUse(width * height * depth * components);
  472. return true;
  473. }
  474. void Image::SetPixel(int x, int y, const Color& color)
  475. {
  476. SetPixelInt(x, y, 0, color.ToUInt());
  477. }
  478. void Image::SetPixel(int x, int y, int z, const Color& color)
  479. {
  480. SetPixelInt(x, y, z, color.ToUInt());
  481. }
  482. void Image::SetPixelInt(int x, int y, unsigned uintColor)
  483. {
  484. SetPixelInt(x, y, 0, uintColor);
  485. }
  486. void Image::SetPixelInt(int x, int y, int z, unsigned uintColor)
  487. {
  488. if (!data_ || x < 0 || x >= width_ || y < 0 || y >= height_ || z < 0 || z >= depth_ || IsCompressed())
  489. return;
  490. unsigned char* dest = data_ + (z * width_ * height_ + y * width_ + x) * components_;
  491. unsigned char* src = (unsigned char*)&uintColor;
  492. switch (components_)
  493. {
  494. case 4:
  495. dest[3] = src[3];
  496. // Fall through
  497. case 3:
  498. dest[2] = src[2];
  499. // Fall through
  500. case 2:
  501. dest[1]= src[1];
  502. // Fall through
  503. default:
  504. dest[0] = src[0];
  505. break;
  506. }
  507. }
  508. void Image::SetData(const unsigned char* pixelData)
  509. {
  510. if (!data_)
  511. return;
  512. if (IsCompressed())
  513. {
  514. LOGERROR("Can not set new pixel data for a compressed image");
  515. return;
  516. }
  517. memcpy(data_.Get(), pixelData, width_ * height_ * depth_ * components_);
  518. nextLevel_.Reset();
  519. }
  520. bool Image::LoadColorLUT(Deserializer& source)
  521. {
  522. String fileID = source.ReadFileID();
  523. if (fileID == "DDS " || fileID == "\253KTX" || fileID == "PVR\3")
  524. {
  525. LOGERROR("Invalid image format, can not load image");
  526. return false;
  527. }
  528. source.Seek(0);
  529. int width, height;
  530. unsigned components;
  531. unsigned char* pixelDataIn = GetImageData(source, width, height, components);
  532. if (!pixelDataIn)
  533. {
  534. LOGERROR("Could not load image " + source.GetName() + ": " + String(stbi_failure_reason()));
  535. return false;
  536. }
  537. if (components != 3)
  538. {
  539. LOGERROR("Invalid image format, can not load image");
  540. return false;
  541. }
  542. SetSize(COLOR_LUT_SIZE, COLOR_LUT_SIZE, COLOR_LUT_SIZE, components);
  543. SetMemoryUse(width_ * height_ * depth_ * components);
  544. unsigned char* pixelDataOut = GetData();
  545. for (int z = 0; z < depth_; ++z)
  546. {
  547. for (int y = 0; y < height_; ++y)
  548. {
  549. unsigned char* in = &pixelDataIn[z * width_ * 3 + y * width * 3];
  550. unsigned char* out = &pixelDataOut[z * width_ * height_ * 3 + y * width_ * 3];
  551. for (int x = 0; x < width_ * 3; x += 3)
  552. {
  553. out[x] = in[x];
  554. out[x+1] = in[x + 1];
  555. out[x+2] = in[x + 2];
  556. }
  557. }
  558. }
  559. FreeImageData(pixelDataIn);
  560. return true;
  561. }
  562. void Image::FlipVertical()
  563. {
  564. if (!data_)
  565. return;
  566. if (IsCompressed())
  567. {
  568. LOGERROR("FlipVertical not supported for compressed images");
  569. return;
  570. }
  571. if (depth_ > 1)
  572. {
  573. LOGERROR("FlipVertical not supported for 3D images");
  574. return;
  575. }
  576. SharedArrayPtr<unsigned char> newData(new unsigned char[width_ * height_ * components_]);
  577. unsigned rowSize = width_ * components_;
  578. for (int y = 0; y < height_; ++y)
  579. memcpy(&newData[(height_ - y - 1) * rowSize], &data_[y * rowSize], rowSize);
  580. data_ = newData;
  581. }
  582. bool Image::Resize(int width, int height)
  583. {
  584. PROFILE(ResizeImage);
  585. if (IsCompressed())
  586. {
  587. LOGERROR("Resize not supported for compressed images");
  588. return false;
  589. }
  590. if (depth_ > 1)
  591. {
  592. LOGERROR("Resize not supported for 3D images");
  593. return false;
  594. }
  595. if (!data_ || width <= 0 || height <= 0)
  596. return false;
  597. /// \todo Reducing image size does not sample all needed pixels
  598. SharedArrayPtr<unsigned char> newData(new unsigned char[width * height * components_]);
  599. for (int y = 0; y < height; ++y)
  600. {
  601. for (int x = 0; x < width; ++x)
  602. {
  603. // Calculate float coordinates between 0 - 1 for resampling
  604. float xF = (width_ > 1) ? (float)x / (float)(width - 1) : 0.0f;
  605. float yF = (height_ > 1) ? (float)y / (float)(height - 1) : 0.0f;
  606. unsigned uintColor = GetPixelBilinear(xF, yF).ToUInt();
  607. unsigned char* dest = newData + (y * width + x) * components_;
  608. unsigned char* src = (unsigned char*)&uintColor;
  609. switch (components_)
  610. {
  611. case 4:
  612. dest[3] = src[3];
  613. // Fall through
  614. case 3:
  615. dest[2] = src[2];
  616. // Fall through
  617. case 2:
  618. dest[1] = src[1];
  619. // Fall through
  620. default:
  621. dest[0] = src[0];
  622. break;
  623. }
  624. }
  625. }
  626. width_ = width;
  627. height_ = height;
  628. data_ = newData;
  629. SetMemoryUse(width * height * depth_ * components_);
  630. return true;
  631. }
  632. void Image::Clear(const Color& color)
  633. {
  634. ClearInt(color.ToUInt());
  635. }
  636. void Image::ClearInt(unsigned uintColor)
  637. {
  638. PROFILE(ClearImage);
  639. if (!data_)
  640. return;
  641. if (IsCompressed())
  642. {
  643. LOGERROR("Clear not supported for compressed images");
  644. return;
  645. }
  646. unsigned char* src = (unsigned char*)&uintColor;
  647. for (unsigned i = 0; i < width_ * height_ * depth_ * components_; ++i)
  648. data_[i] = src[i % components_];
  649. }
  650. bool Image::SaveBMP(const String& fileName) const
  651. {
  652. PROFILE(SaveImageBMP);
  653. FileSystem* fileSystem = GetSubsystem<FileSystem>();
  654. if (fileSystem && !fileSystem->CheckAccess(GetPath(fileName)))
  655. {
  656. LOGERROR("Access denied to " + fileName);
  657. return false;
  658. }
  659. if (IsCompressed())
  660. {
  661. LOGERROR("Can not save compressed image to BMP");
  662. return false;
  663. }
  664. if (data_)
  665. return stbi_write_bmp(fileName.CString(), width_, height_, components_, data_.Get()) != 0;
  666. else
  667. return false;
  668. }
  669. bool Image::SavePNG(const String& fileName) const
  670. {
  671. PROFILE(SaveImagePNG);
  672. FileSystem* fileSystem = GetSubsystem<FileSystem>();
  673. if (fileSystem && !fileSystem->CheckAccess(GetPath(fileName)))
  674. {
  675. LOGERROR("Access denied to " + fileName);
  676. return false;
  677. }
  678. if (IsCompressed())
  679. {
  680. LOGERROR("Can not save compressed image to PNG");
  681. return false;
  682. }
  683. if (data_)
  684. return stbi_write_png(GetNativePath(fileName).CString(), width_, height_, components_, data_.Get(), 0) != 0;
  685. else
  686. return false;
  687. }
  688. bool Image::SaveTGA(const String& fileName) const
  689. {
  690. PROFILE(SaveImageTGA);
  691. FileSystem* fileSystem = GetSubsystem<FileSystem>();
  692. if (fileSystem && !fileSystem->CheckAccess(GetPath(fileName)))
  693. {
  694. LOGERROR("Access denied to " + fileName);
  695. return false;
  696. }
  697. if (IsCompressed())
  698. {
  699. LOGERROR("Can not save compressed image to TGA");
  700. return false;
  701. }
  702. if (data_)
  703. return stbi_write_tga(GetNativePath(fileName).CString(), width_, height_, components_, data_.Get()) != 0;
  704. else
  705. return false;
  706. }
  707. bool Image::SaveJPG(const String & fileName, int quality) const
  708. {
  709. PROFILE(SaveImageJPG);
  710. FileSystem* fileSystem = GetSubsystem<FileSystem>();
  711. if (fileSystem && !fileSystem->CheckAccess(GetPath(fileName)))
  712. {
  713. LOGERROR("Access denied to " + fileName);
  714. return false;
  715. }
  716. if (IsCompressed())
  717. {
  718. LOGERROR("Can not save compressed image to JPG");
  719. return false;
  720. }
  721. if (data_)
  722. return jo_write_jpg(GetNativePath(fileName).CString(), data_.Get(), width_, height_, components_, quality) != 0;
  723. else
  724. return false;
  725. }
  726. Color Image::GetPixel(int x, int y) const
  727. {
  728. return GetPixel(x, y, 0);
  729. }
  730. Color Image::GetPixel(int x, int y, int z) const
  731. {
  732. if (!data_ || z < 0 || z >= depth_ || IsCompressed())
  733. return Color::BLACK;
  734. x = Clamp(x, 0, width_ - 1);
  735. y = Clamp(y, 0, height_ - 1);
  736. unsigned char* src = data_ + (z * width_ * height_ + y * width_ + x) * components_;
  737. Color ret;
  738. switch (components_)
  739. {
  740. case 4:
  741. ret.a_ = (float)src[3] / 255.0f;
  742. // Fall through
  743. case 3:
  744. ret.b_ = (float)src[2] / 255.0f;
  745. // Fall through
  746. case 2:
  747. ret.g_ = (float)src[1] / 255.0f;
  748. ret.r_ = (float)src[0] / 255.0f;
  749. break;
  750. default:
  751. ret.r_ = ret.g_ = ret.b_ = (float)src[0] / 255.0f;
  752. break;
  753. }
  754. return ret;
  755. }
  756. unsigned Image::GetPixelInt(int x, int y) const
  757. {
  758. return GetPixelInt(x, y, 0);
  759. }
  760. unsigned Image::GetPixelInt(int x, int y, int z) const
  761. {
  762. if (!data_ || z < 0 || z >= depth_ || IsCompressed())
  763. return 0xff000000;
  764. x = Clamp(x, 0, width_ - 1);
  765. y = Clamp(y, 0, height_ - 1);
  766. unsigned char* src = data_ + (z * width_ * height_ + y * width_ + x) * components_;
  767. unsigned ret = 0;
  768. if (components_ < 4)
  769. ret |= 0xff000000;
  770. switch (components_)
  771. {
  772. case 4:
  773. ret |= (unsigned)src[3] << 24;
  774. // Fall through
  775. case 3:
  776. ret |= (unsigned)src[2] << 16;
  777. // Fall through
  778. case 2:
  779. ret |= (unsigned)src[1] << 8;
  780. ret |= (unsigned)src[0];
  781. break;
  782. default:
  783. ret |= (unsigned)src[0] << 16;
  784. ret |= (unsigned)src[0] << 8;
  785. ret |= (unsigned)src[0];
  786. break;
  787. }
  788. return ret;
  789. }
  790. Color Image::GetPixelBilinear(float x, float y) const
  791. {
  792. x = Clamp(x * width_ - 0.5f, 0.0f, (float)(width_ - 1));
  793. y = Clamp(y * height_ - 0.5f, 0.0f, (float)(height_ - 1));
  794. int xI = (int)x;
  795. int yI = (int)y;
  796. float xF = x - floorf(x);
  797. float yF = y - floorf(y);
  798. Color topColor = GetPixel(xI, yI).Lerp(GetPixel(xI + 1, yI), xF);
  799. Color bottomColor = GetPixel(xI, yI + 1).Lerp(GetPixel(xI + 1, yI + 1), xF);
  800. return topColor.Lerp(bottomColor, yF);
  801. }
  802. Color Image::GetPixelTrilinear(float x, float y, float z) const
  803. {
  804. if (depth_ < 2)
  805. return GetPixelBilinear(x, y);
  806. x = Clamp(x * width_ - 0.5f, 0.0f, (float)(width_ - 1));
  807. y = Clamp(y * height_ - 0.5f, 0.0f, (float)(height_ - 1));
  808. z = Clamp(z * depth_ - 0.5f, 0.0f, (float)(depth_ - 1));
  809. int xI = (int)x;
  810. int yI = (int)y;
  811. int zI = (int)z;
  812. if (zI == depth_ - 1)
  813. return GetPixelBilinear(x, y);
  814. float xF = x - floorf(x);
  815. float yF = y - floorf(y);
  816. float zF = z - floorf(z);
  817. Color topColorNear = GetPixel(xI, yI, zI).Lerp(GetPixel(xI + 1, yI, zI), xF);
  818. Color bottomColorNear = GetPixel(xI, yI + 1, zI).Lerp(GetPixel(xI + 1, yI + 1, zI), xF);
  819. Color colorNear = topColorNear.Lerp(bottomColorNear, yF);
  820. Color topColorFar = GetPixel(xI, yI, zI + 1).Lerp(GetPixel(xI + 1, yI, zI + 1), xF);
  821. Color bottomColorFar = GetPixel(xI, yI + 1, zI + 1).Lerp(GetPixel(xI + 1, yI + 1, zI + 1), xF);
  822. Color colorFar = topColorNear.Lerp(bottomColorNear, yF);
  823. return colorNear.Lerp(colorFar, zF);
  824. }
  825. SharedPtr<Image> Image::GetNextLevel() const
  826. {
  827. if (IsCompressed())
  828. {
  829. LOGERROR("Can not generate mip level from compressed data");
  830. return SharedPtr<Image>();
  831. }
  832. if (components_ < 1 || components_ > 4)
  833. {
  834. LOGERROR("Illegal number of image components for mip level generation");
  835. return SharedPtr<Image>();
  836. }
  837. if (nextLevel_)
  838. return nextLevel_;
  839. PROFILE(CalculateImageMipLevel);
  840. int widthOut = width_ / 2;
  841. int heightOut = height_ / 2;
  842. int depthOut = depth_ / 2;
  843. if (widthOut < 1)
  844. widthOut = 1;
  845. if (heightOut < 1)
  846. heightOut = 1;
  847. if (depthOut < 1)
  848. depthOut = 1;
  849. SharedPtr<Image> mipImage(new Image(context_));
  850. if (depth_ > 1)
  851. mipImage->SetSize(widthOut, heightOut, depthOut, components_);
  852. else
  853. mipImage->SetSize(widthOut, heightOut, components_);
  854. const unsigned char* pixelDataIn = data_.Get();
  855. unsigned char* pixelDataOut = mipImage->data_.Get();
  856. // 1D case
  857. if (depth_ == 1 && (height_ == 1 || width_ == 1))
  858. {
  859. // Loop using the larger dimension
  860. if (widthOut < heightOut)
  861. widthOut = heightOut;
  862. switch (components_)
  863. {
  864. case 1:
  865. for (int x = 0; x < widthOut; ++x)
  866. pixelDataOut[x] = ((unsigned)pixelDataIn[x*2] + pixelDataIn[x*2+1]) >> 1;
  867. break;
  868. case 2:
  869. for (int x = 0; x < widthOut*2; x += 2)
  870. {
  871. pixelDataOut[x] = ((unsigned)pixelDataIn[x*2] + pixelDataIn[x*2+2]) >> 1;
  872. pixelDataOut[x+1] = ((unsigned)pixelDataIn[x*2+1] + pixelDataIn[x*2+3]) >> 1;
  873. }
  874. break;
  875. case 3:
  876. for (int x = 0; x < widthOut*3; x += 3)
  877. {
  878. pixelDataOut[x] = ((unsigned)pixelDataIn[x*2] + pixelDataIn[x*2+3]) >> 1;
  879. pixelDataOut[x+1] = ((unsigned)pixelDataIn[x*2+1] + pixelDataIn[x*2+4]) >> 1;
  880. pixelDataOut[x+2] = ((unsigned)pixelDataIn[x*2+2] + pixelDataIn[x*2+5]) >> 1;
  881. }
  882. break;
  883. case 4:
  884. for (int x = 0; x < widthOut*4; x += 4)
  885. {
  886. pixelDataOut[x] = ((unsigned)pixelDataIn[x*2] + pixelDataIn[x*2+4]) >> 1;
  887. pixelDataOut[x+1] = ((unsigned)pixelDataIn[x*2+1] + pixelDataIn[x*2+5]) >> 1;
  888. pixelDataOut[x+2] = ((unsigned)pixelDataIn[x*2+2] + pixelDataIn[x*2+6]) >> 1;
  889. pixelDataOut[x+3] = ((unsigned)pixelDataIn[x*2+3] + pixelDataIn[x*2+7]) >> 1;
  890. }
  891. break;
  892. }
  893. }
  894. // 2D case
  895. else if (depth_ == 1)
  896. {
  897. switch (components_)
  898. {
  899. case 1:
  900. for (int y = 0; y < heightOut; ++y)
  901. {
  902. const unsigned char* inUpper = &pixelDataIn[(y*2)*width_];
  903. const unsigned char* inLower = &pixelDataIn[(y*2+1)*width_];
  904. unsigned char* out = &pixelDataOut[y*widthOut];
  905. for (int x = 0; x < widthOut; ++x)
  906. {
  907. out[x] = ((unsigned)inUpper[x*2] + inUpper[x*2+1] + inLower[x*2] + inLower[x*2+1]) >> 2;
  908. }
  909. }
  910. break;
  911. case 2:
  912. for (int y = 0; y < heightOut; ++y)
  913. {
  914. const unsigned char* inUpper = &pixelDataIn[(y*2)*width_*2];
  915. const unsigned char* inLower = &pixelDataIn[(y*2+1)*width_*2];
  916. unsigned char* out = &pixelDataOut[y*widthOut*2];
  917. for (int x = 0; x < widthOut*2; x += 2)
  918. {
  919. out[x] = ((unsigned)inUpper[x*2] + inUpper[x*2+2] + inLower[x*2] + inLower[x*2+2]) >> 2;
  920. out[x+1] = ((unsigned)inUpper[x*2+1] + inUpper[x*2+3] + inLower[x*2+1] + inLower[x*2+3]) >> 2;
  921. }
  922. }
  923. break;
  924. case 3:
  925. for (int y = 0; y < heightOut; ++y)
  926. {
  927. const unsigned char* inUpper = &pixelDataIn[(y*2)*width_*3];
  928. const unsigned char* inLower = &pixelDataIn[(y*2+1)*width_*3];
  929. unsigned char* out = &pixelDataOut[y*widthOut*3];
  930. for (int x = 0; x < widthOut*3; x += 3)
  931. {
  932. out[x] = ((unsigned)inUpper[x*2] + inUpper[x*2+3] + inLower[x*2] + inLower[x*2+3]) >> 2;
  933. out[x+1] = ((unsigned)inUpper[x*2+1] + inUpper[x*2+4] + inLower[x*2+1] + inLower[x*2+4]) >> 2;
  934. out[x+2] = ((unsigned)inUpper[x*2+2] + inUpper[x*2+5] + inLower[x*2+2] + inLower[x*2+5]) >> 2;
  935. }
  936. }
  937. break;
  938. case 4:
  939. for (int y = 0; y < heightOut; ++y)
  940. {
  941. const unsigned char* inUpper = &pixelDataIn[(y*2)*width_*4];
  942. const unsigned char* inLower = &pixelDataIn[(y*2+1)*width_*4];
  943. unsigned char* out = &pixelDataOut[y*widthOut*4];
  944. for (int x = 0; x < widthOut*4; x += 4)
  945. {
  946. out[x] = ((unsigned)inUpper[x*2] + inUpper[x*2+4] + inLower[x*2] + inLower[x*2+4]) >> 2;
  947. out[x+1] = ((unsigned)inUpper[x*2+1] + inUpper[x*2+5] + inLower[x*2+1] + inLower[x*2+5]) >> 2;
  948. out[x+2] = ((unsigned)inUpper[x*2+2] + inUpper[x*2+6] + inLower[x*2+2] + inLower[x*2+6]) >> 2;
  949. out[x+3] = ((unsigned)inUpper[x*2+3] + inUpper[x*2+7] + inLower[x*2+3] + inLower[x*2+7]) >> 2;
  950. }
  951. }
  952. break;
  953. }
  954. }
  955. // 3D case
  956. else
  957. {
  958. switch (components_)
  959. {
  960. case 1:
  961. for (int z = 0; z < depthOut; ++z)
  962. {
  963. const unsigned char* inOuter = &pixelDataIn[(z*2)*width_*height_];
  964. const unsigned char* inInner = &pixelDataIn[(z*2+1)*width_*height_];
  965. for (int y = 0; y < heightOut; ++y)
  966. {
  967. const unsigned char* inOuterUpper = &inOuter[(y*2)*width_];
  968. const unsigned char* inOuterLower = &inOuter[(y*2+1)*width_];
  969. const unsigned char* inInnerUpper = &inInner[(y*2)*width_];
  970. const unsigned char* inInnerLower = &inInner[(y*2+1)*width_];
  971. unsigned char* out = &pixelDataOut[z*widthOut*heightOut + y*widthOut];
  972. for (int x = 0; x < widthOut; ++x)
  973. {
  974. out[x] = ((unsigned)inOuterUpper[x*2] + inOuterUpper[x*2+1] + inOuterLower[x*2] + inOuterLower[x*2+1] +
  975. inInnerUpper[x*2] + inInnerUpper[x*2+1] + inInnerLower[x*2] + inInnerLower[x*2+1]) >> 3;
  976. }
  977. }
  978. }
  979. break;
  980. case 2:
  981. for (int z = 0; z < depthOut; ++z)
  982. {
  983. const unsigned char* inOuter = &pixelDataIn[(z*2)*width_*height_*2];
  984. const unsigned char* inInner = &pixelDataIn[(z*2+1)*width_*height_*2];
  985. for (int y = 0; y < heightOut; ++y)
  986. {
  987. const unsigned char* inOuterUpper = &inOuter[(y*2)*width_*2];
  988. const unsigned char* inOuterLower = &inOuter[(y*2+1)*width_*2];
  989. const unsigned char* inInnerUpper = &inInner[(y*2)*width_*2];
  990. const unsigned char* inInnerLower = &inInner[(y*2+1)*width_*2];
  991. unsigned char* out = &pixelDataOut[z*widthOut*heightOut*2 + y*widthOut*2];
  992. for (int x = 0; x < widthOut*2; x += 2)
  993. {
  994. out[x] = ((unsigned)inOuterUpper[x*2] + inOuterUpper[x*2+2] + inOuterLower[x*2] + inOuterLower[x*2+2] +
  995. inInnerUpper[x*2] + inInnerUpper[x*2+2] + inInnerLower[x*2] + inInnerLower[x*2+2]) >> 3;
  996. out[x+1] = ((unsigned)inOuterUpper[x*2+1] + inOuterUpper[x*2+3] + inOuterLower[x*2+1] + inOuterLower[x*2+3] +
  997. inInnerUpper[x*2+1] + inInnerUpper[x*2+3] + inInnerLower[x*2+1] + inInnerLower[x*2+3]) >> 3;
  998. }
  999. }
  1000. }
  1001. break;
  1002. case 3:
  1003. for (int z = 0; z < depthOut; ++z)
  1004. {
  1005. const unsigned char* inOuter = &pixelDataIn[(z*2)*width_*height_*3];
  1006. const unsigned char* inInner = &pixelDataIn[(z*2+1)*width_*height_*3];
  1007. for (int y = 0; y < heightOut; ++y)
  1008. {
  1009. const unsigned char* inOuterUpper = &inOuter[(y*2)*width_*3];
  1010. const unsigned char* inOuterLower = &inOuter[(y*2+1)*width_*3];
  1011. const unsigned char* inInnerUpper = &inInner[(y*2)*width_*3];
  1012. const unsigned char* inInnerLower = &inInner[(y*2+1)*width_*3];
  1013. unsigned char* out = &pixelDataOut[z*widthOut*heightOut*3 + y*widthOut*3];
  1014. for (int x = 0; x < widthOut*3; x += 3)
  1015. {
  1016. out[x] = ((unsigned)inOuterUpper[x*2] + inOuterUpper[x*2+3] + inOuterLower[x*2] + inOuterLower[x*2+3] +
  1017. inInnerUpper[x*2] + inInnerUpper[x*2+3] + inInnerLower[x*2] + inInnerLower[x*2+3]) >> 3;
  1018. out[x+1] = ((unsigned)inOuterUpper[x*2+1] + inOuterUpper[x*2+4] + inOuterLower[x*2+1] + inOuterLower[x*2+4] +
  1019. inInnerUpper[x*2+1] + inInnerUpper[x*2+4] + inInnerLower[x*2+1] + inInnerLower[x*2+4]) >> 3;
  1020. out[x+2] = ((unsigned)inOuterUpper[x*2+2] + inOuterUpper[x*2+5] + inOuterLower[x*2+2] + inOuterLower[x*2+5] +
  1021. inInnerUpper[x*2+2] + inInnerUpper[x*2+5] + inInnerLower[x*2+2] + inInnerLower[x*2+5]) >> 3;
  1022. }
  1023. }
  1024. }
  1025. break;
  1026. case 4:
  1027. for (int z = 0; z < depthOut; ++z)
  1028. {
  1029. const unsigned char* inOuter = &pixelDataIn[(z*2)*width_*height_*4];
  1030. const unsigned char* inInner = &pixelDataIn[(z*2+1)*width_*height_*4];
  1031. for (int y = 0; y < heightOut; ++y)
  1032. {
  1033. const unsigned char* inOuterUpper = &inOuter[(y*2)*width_*4];
  1034. const unsigned char* inOuterLower = &inOuter[(y*2+1)*width_*4];
  1035. const unsigned char* inInnerUpper = &inInner[(y*2)*width_*4];
  1036. const unsigned char* inInnerLower = &inInner[(y*2+1)*width_*4];
  1037. unsigned char* out = &pixelDataOut[z*widthOut*heightOut*4 + y*widthOut*4];
  1038. for (int x = 0; x < widthOut*4; x += 4)
  1039. {
  1040. out[x] = ((unsigned)inOuterUpper[x*2] + inOuterUpper[x*2+4] + inOuterLower[x*2] + inOuterLower[x*2+4] +
  1041. inInnerUpper[x*2] + inInnerUpper[x*2+4] + inInnerLower[x*2] + inInnerLower[x*2+4]) >> 3;
  1042. out[x+1] = ((unsigned)inOuterUpper[x*2+1] + inOuterUpper[x*2+5] + inOuterLower[x*2+1] + inOuterLower[x*2+5] +
  1043. inInnerUpper[x*2+1] + inInnerUpper[x*2+5] + inInnerLower[x*2+1] + inInnerLower[x*2+5]) >> 3;
  1044. out[x+2] = ((unsigned)inOuterUpper[x*2+2] + inOuterUpper[x*2+6] + inOuterLower[x*2+2] + inOuterLower[x*2+6] +
  1045. inInnerUpper[x*2+2] + inInnerUpper[x*2+6] + inInnerLower[x*2+2] + inInnerLower[x*2+6]) >> 3;
  1046. }
  1047. }
  1048. }
  1049. break;
  1050. }
  1051. }
  1052. return mipImage;
  1053. }
  1054. CompressedLevel Image::GetCompressedLevel(unsigned index) const
  1055. {
  1056. CompressedLevel level;
  1057. if (compressedFormat_ == CF_NONE)
  1058. {
  1059. LOGERROR("Image is not compressed");
  1060. return level;
  1061. }
  1062. if (index >= numCompressedLevels_)
  1063. {
  1064. LOGERROR("Compressed image mip level out of bounds");
  1065. return level;
  1066. }
  1067. level.format_ = compressedFormat_;
  1068. level.width_ = width_;
  1069. level.height_ = height_;
  1070. level.depth_ = depth_;
  1071. if (compressedFormat_ < CF_PVRTC_RGB_2BPP)
  1072. {
  1073. level.blockSize_ = (compressedFormat_ == CF_DXT1 || compressedFormat_ == CF_ETC1) ? 8 : 16;
  1074. unsigned i = 0;
  1075. unsigned offset = 0;
  1076. for (;;)
  1077. {
  1078. if (!level.width_)
  1079. level.width_ = 1;
  1080. if (!level.height_)
  1081. level.height_ = 1;
  1082. if (!level.depth_)
  1083. level.depth_ = 1;
  1084. level.rowSize_ = ((level.width_ + 3) / 4) * level.blockSize_;
  1085. level.rows_ = ((level.height_ + 3) / 4);
  1086. level.data_ = data_.Get() + offset;
  1087. level.dataSize_ = level.depth_ * level.rows_ * level.rowSize_;
  1088. if (offset + level.dataSize_ > GetMemoryUse())
  1089. {
  1090. LOGERROR("Compressed level is outside image data. Offset: " + String(offset) + " Size: " + String(level.dataSize_) +
  1091. " Datasize: " + String(GetMemoryUse()));
  1092. level.data_ = 0;
  1093. return level;
  1094. }
  1095. if (i == index)
  1096. return level;
  1097. offset += level.dataSize_;
  1098. level.width_ /= 2;
  1099. level.height_ /= 2;
  1100. level.depth_ /= 2;
  1101. ++i;
  1102. }
  1103. }
  1104. else
  1105. {
  1106. level.blockSize_ = compressedFormat_ < CF_PVRTC_RGB_4BPP ? 2 : 4;
  1107. unsigned i = 0;
  1108. unsigned offset = 0;
  1109. for (;;)
  1110. {
  1111. if (!level.width_)
  1112. level.width_ = 1;
  1113. if (!level.height_)
  1114. level.height_ = 1;
  1115. int dataWidth = Max(level.width_, level.blockSize_ == 2 ? 16 : 8);
  1116. int dataHeight = Max(level.height_, 8);
  1117. level.data_ = data_.Get() + offset;
  1118. level.dataSize_ = (dataWidth * dataHeight * level.blockSize_ + 7) >> 3;
  1119. level.rows_ = dataHeight;
  1120. level.rowSize_ = level.dataSize_ / level.rows_;
  1121. if (offset + level.dataSize_ > GetMemoryUse())
  1122. {
  1123. LOGERROR("Compressed level is outside image data. Offset: " + String(offset) + " Size: " + String(level.dataSize_) +
  1124. " Datasize: " + String(GetMemoryUse()));
  1125. level.data_ = 0;
  1126. return level;
  1127. }
  1128. if (i == index)
  1129. return level;
  1130. offset += level.dataSize_;
  1131. level.width_ /= 2;
  1132. level.height_ /= 2;
  1133. ++i;
  1134. }
  1135. }
  1136. }
  1137. Image* Image::GetSubimage(const IntRect& rect) const
  1138. {
  1139. if (!data_)
  1140. return 0;
  1141. if (depth_ > 1)
  1142. {
  1143. LOGERROR("Subimage not supported for 3D images");
  1144. return 0;
  1145. }
  1146. if (rect.left_ < 0 || rect.top_ < 0 || rect.right_ > width_ || rect.bottom_ > height_ || !rect.Width() || !rect.Height())
  1147. {
  1148. LOGERROR("Can not get subimage from image " + GetName() + " with invalid region");
  1149. return 0;
  1150. }
  1151. if (!IsCompressed())
  1152. {
  1153. int x = rect.left_;
  1154. int y = rect.top_;
  1155. int width = rect.Width();
  1156. int height = rect.Height();
  1157. Image* image = new Image(context_);
  1158. image->SetSize(width, height, components_);
  1159. unsigned char* dest = image->GetData();
  1160. unsigned char* src = data_.Get() + (y * width_ + x) * components_;
  1161. for (int i = 0; i < height; ++i)
  1162. {
  1163. memcpy(dest, src, width * components_);
  1164. dest += width * components_;
  1165. src += width_ * components_;
  1166. }
  1167. return image;
  1168. }
  1169. else
  1170. {
  1171. // Pad the region to be a multiple of block size
  1172. IntRect paddedRect = rect;
  1173. paddedRect.left_ = (rect.left_ / 4) * 4;
  1174. paddedRect.top_ = (rect.top_ / 4) * 4;
  1175. paddedRect.right_ = (rect.right_ / 4) * 4;
  1176. paddedRect.bottom_ = (rect.bottom_ / 4) * 4;
  1177. IntRect currentRect = paddedRect;
  1178. PODVector<unsigned char> subimageData;
  1179. unsigned subimageLevels = 0;
  1180. // Save as many mips as possible until the next mip would cross a block boundary
  1181. for (unsigned i = 0; i < numCompressedLevels_; ++i)
  1182. {
  1183. CompressedLevel level = GetCompressedLevel(i);
  1184. if (!level.data_)
  1185. break;
  1186. // Mips are stored continuously
  1187. unsigned destStartOffset = subimageData.Size();
  1188. unsigned destRowSize = currentRect.Width() / 4 * level.blockSize_;
  1189. unsigned destSize = currentRect.Height() / 4 * destRowSize;
  1190. if (!destSize)
  1191. break;
  1192. subimageData.Resize(destStartOffset + destSize);
  1193. unsigned char* dest = &subimageData[destStartOffset];
  1194. for (int y = currentRect.top_; y < currentRect.bottom_; y += 4)
  1195. {
  1196. unsigned char* src = level.data_ + level.rowSize_ * (y / 4) + currentRect.left_ / 4 * level.blockSize_;
  1197. memcpy(dest, src, destRowSize);
  1198. dest += destRowSize;
  1199. }
  1200. ++subimageLevels;
  1201. if ((currentRect.left_ & 4) || (currentRect.right_ & 4) || (currentRect.top_ & 4) || (currentRect.bottom_ & 4))
  1202. break;
  1203. else
  1204. {
  1205. currentRect.left_ /= 2;
  1206. currentRect.right_ /= 2;
  1207. currentRect.top_ /= 2;
  1208. currentRect.bottom_ /= 2;
  1209. }
  1210. }
  1211. if (!subimageLevels)
  1212. {
  1213. LOGERROR("Subimage region from compressed image " + GetName() + " did not produce any data");
  1214. return 0;
  1215. }
  1216. Image* image = new Image(context_);
  1217. image->width_ = paddedRect.Width();
  1218. image->height_ = paddedRect.Height();
  1219. image->depth_ = 1;
  1220. image->compressedFormat_ = compressedFormat_;
  1221. image->numCompressedLevels_ = subimageLevels;
  1222. image->components_ = components_;
  1223. image->data_ = new unsigned char[subimageData.Size()];
  1224. memcpy(image->data_.Get(), &subimageData[0], subimageData.Size());
  1225. image->SetMemoryUse(subimageData.Size());
  1226. return image;
  1227. }
  1228. }
  1229. SDL_Surface* Image::GetSDLSurface(const IntRect& rect) const
  1230. {
  1231. if (!data_)
  1232. return 0;
  1233. if (depth_ > 1)
  1234. {
  1235. LOGERROR("Can not get SDL surface from 3D image");
  1236. return 0;
  1237. }
  1238. if (IsCompressed())
  1239. {
  1240. LOGERROR("Can not get SDL surface from compressed image " + GetName());
  1241. return 0;
  1242. }
  1243. if (components_ < 3)
  1244. {
  1245. LOGERROR("Can not get SDL surface from image " + GetName() + " with less than 3 components");
  1246. return 0;
  1247. }
  1248. IntRect imageRect = rect;
  1249. // Use full image if illegal rect
  1250. if (imageRect.left_ < 0 || imageRect.top_ < 0 || imageRect.right_ > width_ || imageRect.bottom_ > height_ ||
  1251. imageRect.left_ >= imageRect.right_ || imageRect.top_ >= imageRect.bottom_)
  1252. {
  1253. imageRect.left_ = 0;
  1254. imageRect.top_ = 0;
  1255. imageRect.right_ = width_;
  1256. imageRect.bottom_ = height_;
  1257. }
  1258. int imageWidth = width_;
  1259. int width = imageRect.Width();
  1260. int height = imageRect.Height();
  1261. // Assume little-endian for all the supported platforms
  1262. unsigned rMask = 0x000000ff;
  1263. unsigned gMask = 0x0000ff00;
  1264. unsigned bMask = 0x00ff0000;
  1265. unsigned aMask = 0xff000000;
  1266. SDL_Surface* surface = SDL_CreateRGBSurface(0, width, height, components_ * 8, rMask, gMask, bMask, aMask);
  1267. if (surface)
  1268. {
  1269. SDL_LockSurface(surface);
  1270. unsigned char* destination = reinterpret_cast<unsigned char*>(surface->pixels);
  1271. unsigned char* source = data_ + components_ * (imageWidth * imageRect.top_ + imageRect.left_);
  1272. for (int i = 0; i < height; ++i)
  1273. {
  1274. memcpy(destination, source, components_ * width);
  1275. destination += surface->pitch;
  1276. source += components_ * imageWidth;
  1277. }
  1278. SDL_UnlockSurface(surface);
  1279. }
  1280. else
  1281. LOGERROR("Failed to create SDL surface from image " + GetName());
  1282. return surface;
  1283. }
  1284. void Image::PrecalculateLevels()
  1285. {
  1286. if (!data_ || IsCompressed())
  1287. return;
  1288. PROFILE(PrecalculateImageMipLevels);
  1289. nextLevel_.Reset();
  1290. if (width_ > 1 || height_ > 1)
  1291. {
  1292. SharedPtr<Image> current = GetNextLevel();
  1293. nextLevel_ = current;
  1294. while (current && (current->width_ > 1 || current->height_ > 1))
  1295. {
  1296. current->nextLevel_ = current->GetNextLevel();
  1297. current = current->nextLevel_;
  1298. }
  1299. }
  1300. }
  1301. unsigned char* Image::GetImageData(Deserializer& source, int& width, int& height, unsigned& components)
  1302. {
  1303. unsigned dataSize = source.GetSize();
  1304. SharedArrayPtr<unsigned char> buffer(new unsigned char[dataSize]);
  1305. source.Read(buffer.Get(), dataSize);
  1306. return stbi_load_from_memory(buffer.Get(), dataSize, &width, &height, (int *)&components, 0);
  1307. }
  1308. void Image::FreeImageData(unsigned char* pixelData)
  1309. {
  1310. if (!pixelData)
  1311. return;
  1312. stbi_image_free(pixelData);
  1313. }
  1314. }