Image.cpp 48 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570
  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. bool Image::FlipVertical()
  563. {
  564. if (!data_)
  565. return false;
  566. if (depth_ > 1)
  567. {
  568. LOGERROR("FlipVertical not supported for 3D images");
  569. return false;
  570. }
  571. if (!IsCompressed())
  572. {
  573. SharedArrayPtr<unsigned char> newData(new unsigned char[width_ * height_ * components_]);
  574. unsigned rowSize = width_ * components_;
  575. for (int y = 0; y < height_; ++y)
  576. memcpy(&newData[(height_ - y - 1) * rowSize], &data_[y * rowSize], rowSize);
  577. data_ = newData;
  578. }
  579. else
  580. {
  581. if (compressedFormat_ > CF_DXT5)
  582. {
  583. LOGERROR("FlipVertical not yet implemented for other compressed formats than DXT1,3,5");
  584. return false;
  585. }
  586. // Memory use = combined size of the compressed mip levels
  587. SharedArrayPtr<unsigned char> newData(new unsigned char[GetMemoryUse()]);
  588. unsigned dataOffset = 0;
  589. for (unsigned i = 0; i < numCompressedLevels_; ++i)
  590. {
  591. CompressedLevel level = GetCompressedLevel(i);
  592. if (!level.data_)
  593. {
  594. LOGERROR("Got compressed level with no data, aborting vertical flip");
  595. return false;
  596. }
  597. for (unsigned y = 0; y < level.rows_; ++y)
  598. {
  599. unsigned char* src = level.data_ + y * level.rowSize_;
  600. unsigned char* dest = newData.Get() + dataOffset + (level.rows_ - y - 1) * level.rowSize_;
  601. for (unsigned x = 0; x < level.rowSize_; x += level.blockSize_)
  602. FlipBlockVertical(dest + x, src + x, compressedFormat_);
  603. }
  604. dataOffset += level.dataSize_;
  605. }
  606. data_ = newData;
  607. }
  608. return true;
  609. }
  610. bool Image::Resize(int width, int height)
  611. {
  612. PROFILE(ResizeImage);
  613. if (IsCompressed())
  614. {
  615. LOGERROR("Resize not supported for compressed images");
  616. return false;
  617. }
  618. if (depth_ > 1)
  619. {
  620. LOGERROR("Resize not supported for 3D images");
  621. return false;
  622. }
  623. if (!data_ || width <= 0 || height <= 0)
  624. return false;
  625. /// \todo Reducing image size does not sample all needed pixels
  626. SharedArrayPtr<unsigned char> newData(new unsigned char[width * height * components_]);
  627. for (int y = 0; y < height; ++y)
  628. {
  629. for (int x = 0; x < width; ++x)
  630. {
  631. // Calculate float coordinates between 0 - 1 for resampling
  632. float xF = (width_ > 1) ? (float)x / (float)(width - 1) : 0.0f;
  633. float yF = (height_ > 1) ? (float)y / (float)(height - 1) : 0.0f;
  634. unsigned uintColor = GetPixelBilinear(xF, yF).ToUInt();
  635. unsigned char* dest = newData + (y * width + x) * components_;
  636. unsigned char* src = (unsigned char*)&uintColor;
  637. switch (components_)
  638. {
  639. case 4:
  640. dest[3] = src[3];
  641. // Fall through
  642. case 3:
  643. dest[2] = src[2];
  644. // Fall through
  645. case 2:
  646. dest[1] = src[1];
  647. // Fall through
  648. default:
  649. dest[0] = src[0];
  650. break;
  651. }
  652. }
  653. }
  654. width_ = width;
  655. height_ = height;
  656. data_ = newData;
  657. SetMemoryUse(width * height * depth_ * components_);
  658. return true;
  659. }
  660. void Image::Clear(const Color& color)
  661. {
  662. ClearInt(color.ToUInt());
  663. }
  664. void Image::ClearInt(unsigned uintColor)
  665. {
  666. PROFILE(ClearImage);
  667. if (!data_)
  668. return;
  669. if (IsCompressed())
  670. {
  671. LOGERROR("Clear not supported for compressed images");
  672. return;
  673. }
  674. unsigned char* src = (unsigned char*)&uintColor;
  675. for (unsigned i = 0; i < width_ * height_ * depth_ * components_; ++i)
  676. data_[i] = src[i % components_];
  677. }
  678. bool Image::SaveBMP(const String& fileName) const
  679. {
  680. PROFILE(SaveImageBMP);
  681. FileSystem* fileSystem = GetSubsystem<FileSystem>();
  682. if (fileSystem && !fileSystem->CheckAccess(GetPath(fileName)))
  683. {
  684. LOGERROR("Access denied to " + fileName);
  685. return false;
  686. }
  687. if (IsCompressed())
  688. {
  689. LOGERROR("Can not save compressed image to BMP");
  690. return false;
  691. }
  692. if (data_)
  693. return stbi_write_bmp(fileName.CString(), width_, height_, components_, data_.Get()) != 0;
  694. else
  695. return false;
  696. }
  697. bool Image::SavePNG(const String& fileName) const
  698. {
  699. PROFILE(SaveImagePNG);
  700. FileSystem* fileSystem = GetSubsystem<FileSystem>();
  701. if (fileSystem && !fileSystem->CheckAccess(GetPath(fileName)))
  702. {
  703. LOGERROR("Access denied to " + fileName);
  704. return false;
  705. }
  706. if (IsCompressed())
  707. {
  708. LOGERROR("Can not save compressed image to PNG");
  709. return false;
  710. }
  711. if (data_)
  712. return stbi_write_png(GetNativePath(fileName).CString(), width_, height_, components_, data_.Get(), 0) != 0;
  713. else
  714. return false;
  715. }
  716. bool Image::SaveTGA(const String& fileName) const
  717. {
  718. PROFILE(SaveImageTGA);
  719. FileSystem* fileSystem = GetSubsystem<FileSystem>();
  720. if (fileSystem && !fileSystem->CheckAccess(GetPath(fileName)))
  721. {
  722. LOGERROR("Access denied to " + fileName);
  723. return false;
  724. }
  725. if (IsCompressed())
  726. {
  727. LOGERROR("Can not save compressed image to TGA");
  728. return false;
  729. }
  730. if (data_)
  731. return stbi_write_tga(GetNativePath(fileName).CString(), width_, height_, components_, data_.Get()) != 0;
  732. else
  733. return false;
  734. }
  735. bool Image::SaveJPG(const String & fileName, int quality) const
  736. {
  737. PROFILE(SaveImageJPG);
  738. FileSystem* fileSystem = GetSubsystem<FileSystem>();
  739. if (fileSystem && !fileSystem->CheckAccess(GetPath(fileName)))
  740. {
  741. LOGERROR("Access denied to " + fileName);
  742. return false;
  743. }
  744. if (IsCompressed())
  745. {
  746. LOGERROR("Can not save compressed image to JPG");
  747. return false;
  748. }
  749. if (data_)
  750. return jo_write_jpg(GetNativePath(fileName).CString(), data_.Get(), width_, height_, components_, quality) != 0;
  751. else
  752. return false;
  753. }
  754. Color Image::GetPixel(int x, int y) const
  755. {
  756. return GetPixel(x, y, 0);
  757. }
  758. Color Image::GetPixel(int x, int y, int z) const
  759. {
  760. if (!data_ || z < 0 || z >= depth_ || IsCompressed())
  761. return Color::BLACK;
  762. x = Clamp(x, 0, width_ - 1);
  763. y = Clamp(y, 0, height_ - 1);
  764. unsigned char* src = data_ + (z * width_ * height_ + y * width_ + x) * components_;
  765. Color ret;
  766. switch (components_)
  767. {
  768. case 4:
  769. ret.a_ = (float)src[3] / 255.0f;
  770. // Fall through
  771. case 3:
  772. ret.b_ = (float)src[2] / 255.0f;
  773. // Fall through
  774. case 2:
  775. ret.g_ = (float)src[1] / 255.0f;
  776. ret.r_ = (float)src[0] / 255.0f;
  777. break;
  778. default:
  779. ret.r_ = ret.g_ = ret.b_ = (float)src[0] / 255.0f;
  780. break;
  781. }
  782. return ret;
  783. }
  784. unsigned Image::GetPixelInt(int x, int y) const
  785. {
  786. return GetPixelInt(x, y, 0);
  787. }
  788. unsigned Image::GetPixelInt(int x, int y, int z) const
  789. {
  790. if (!data_ || z < 0 || z >= depth_ || IsCompressed())
  791. return 0xff000000;
  792. x = Clamp(x, 0, width_ - 1);
  793. y = Clamp(y, 0, height_ - 1);
  794. unsigned char* src = data_ + (z * width_ * height_ + y * width_ + x) * components_;
  795. unsigned ret = 0;
  796. if (components_ < 4)
  797. ret |= 0xff000000;
  798. switch (components_)
  799. {
  800. case 4:
  801. ret |= (unsigned)src[3] << 24;
  802. // Fall through
  803. case 3:
  804. ret |= (unsigned)src[2] << 16;
  805. // Fall through
  806. case 2:
  807. ret |= (unsigned)src[1] << 8;
  808. ret |= (unsigned)src[0];
  809. break;
  810. default:
  811. ret |= (unsigned)src[0] << 16;
  812. ret |= (unsigned)src[0] << 8;
  813. ret |= (unsigned)src[0];
  814. break;
  815. }
  816. return ret;
  817. }
  818. Color Image::GetPixelBilinear(float x, float y) const
  819. {
  820. x = Clamp(x * width_ - 0.5f, 0.0f, (float)(width_ - 1));
  821. y = Clamp(y * height_ - 0.5f, 0.0f, (float)(height_ - 1));
  822. int xI = (int)x;
  823. int yI = (int)y;
  824. float xF = x - floorf(x);
  825. float yF = y - floorf(y);
  826. Color topColor = GetPixel(xI, yI).Lerp(GetPixel(xI + 1, yI), xF);
  827. Color bottomColor = GetPixel(xI, yI + 1).Lerp(GetPixel(xI + 1, yI + 1), xF);
  828. return topColor.Lerp(bottomColor, yF);
  829. }
  830. Color Image::GetPixelTrilinear(float x, float y, float z) const
  831. {
  832. if (depth_ < 2)
  833. return GetPixelBilinear(x, y);
  834. x = Clamp(x * width_ - 0.5f, 0.0f, (float)(width_ - 1));
  835. y = Clamp(y * height_ - 0.5f, 0.0f, (float)(height_ - 1));
  836. z = Clamp(z * depth_ - 0.5f, 0.0f, (float)(depth_ - 1));
  837. int xI = (int)x;
  838. int yI = (int)y;
  839. int zI = (int)z;
  840. if (zI == depth_ - 1)
  841. return GetPixelBilinear(x, y);
  842. float xF = x - floorf(x);
  843. float yF = y - floorf(y);
  844. float zF = z - floorf(z);
  845. Color topColorNear = GetPixel(xI, yI, zI).Lerp(GetPixel(xI + 1, yI, zI), xF);
  846. Color bottomColorNear = GetPixel(xI, yI + 1, zI).Lerp(GetPixel(xI + 1, yI + 1, zI), xF);
  847. Color colorNear = topColorNear.Lerp(bottomColorNear, yF);
  848. Color topColorFar = GetPixel(xI, yI, zI + 1).Lerp(GetPixel(xI + 1, yI, zI + 1), xF);
  849. Color bottomColorFar = GetPixel(xI, yI + 1, zI + 1).Lerp(GetPixel(xI + 1, yI + 1, zI + 1), xF);
  850. Color colorFar = topColorNear.Lerp(bottomColorNear, yF);
  851. return colorNear.Lerp(colorFar, zF);
  852. }
  853. SharedPtr<Image> Image::GetNextLevel() const
  854. {
  855. if (IsCompressed())
  856. {
  857. LOGERROR("Can not generate mip level from compressed data");
  858. return SharedPtr<Image>();
  859. }
  860. if (components_ < 1 || components_ > 4)
  861. {
  862. LOGERROR("Illegal number of image components for mip level generation");
  863. return SharedPtr<Image>();
  864. }
  865. if (nextLevel_)
  866. return nextLevel_;
  867. PROFILE(CalculateImageMipLevel);
  868. int widthOut = width_ / 2;
  869. int heightOut = height_ / 2;
  870. int depthOut = depth_ / 2;
  871. if (widthOut < 1)
  872. widthOut = 1;
  873. if (heightOut < 1)
  874. heightOut = 1;
  875. if (depthOut < 1)
  876. depthOut = 1;
  877. SharedPtr<Image> mipImage(new Image(context_));
  878. if (depth_ > 1)
  879. mipImage->SetSize(widthOut, heightOut, depthOut, components_);
  880. else
  881. mipImage->SetSize(widthOut, heightOut, components_);
  882. const unsigned char* pixelDataIn = data_.Get();
  883. unsigned char* pixelDataOut = mipImage->data_.Get();
  884. // 1D case
  885. if (depth_ == 1 && (height_ == 1 || width_ == 1))
  886. {
  887. // Loop using the larger dimension
  888. if (widthOut < heightOut)
  889. widthOut = heightOut;
  890. switch (components_)
  891. {
  892. case 1:
  893. for (int x = 0; x < widthOut; ++x)
  894. pixelDataOut[x] = ((unsigned)pixelDataIn[x*2] + pixelDataIn[x*2+1]) >> 1;
  895. break;
  896. case 2:
  897. for (int x = 0; x < widthOut*2; x += 2)
  898. {
  899. pixelDataOut[x] = ((unsigned)pixelDataIn[x*2] + pixelDataIn[x*2+2]) >> 1;
  900. pixelDataOut[x+1] = ((unsigned)pixelDataIn[x*2+1] + pixelDataIn[x*2+3]) >> 1;
  901. }
  902. break;
  903. case 3:
  904. for (int x = 0; x < widthOut*3; x += 3)
  905. {
  906. pixelDataOut[x] = ((unsigned)pixelDataIn[x*2] + pixelDataIn[x*2+3]) >> 1;
  907. pixelDataOut[x+1] = ((unsigned)pixelDataIn[x*2+1] + pixelDataIn[x*2+4]) >> 1;
  908. pixelDataOut[x+2] = ((unsigned)pixelDataIn[x*2+2] + pixelDataIn[x*2+5]) >> 1;
  909. }
  910. break;
  911. case 4:
  912. for (int x = 0; x < widthOut*4; x += 4)
  913. {
  914. pixelDataOut[x] = ((unsigned)pixelDataIn[x*2] + pixelDataIn[x*2+4]) >> 1;
  915. pixelDataOut[x+1] = ((unsigned)pixelDataIn[x*2+1] + pixelDataIn[x*2+5]) >> 1;
  916. pixelDataOut[x+2] = ((unsigned)pixelDataIn[x*2+2] + pixelDataIn[x*2+6]) >> 1;
  917. pixelDataOut[x+3] = ((unsigned)pixelDataIn[x*2+3] + pixelDataIn[x*2+7]) >> 1;
  918. }
  919. break;
  920. }
  921. }
  922. // 2D case
  923. else if (depth_ == 1)
  924. {
  925. switch (components_)
  926. {
  927. case 1:
  928. for (int y = 0; y < heightOut; ++y)
  929. {
  930. const unsigned char* inUpper = &pixelDataIn[(y*2)*width_];
  931. const unsigned char* inLower = &pixelDataIn[(y*2+1)*width_];
  932. unsigned char* out = &pixelDataOut[y*widthOut];
  933. for (int x = 0; x < widthOut; ++x)
  934. {
  935. out[x] = ((unsigned)inUpper[x*2] + inUpper[x*2+1] + inLower[x*2] + inLower[x*2+1]) >> 2;
  936. }
  937. }
  938. break;
  939. case 2:
  940. for (int y = 0; y < heightOut; ++y)
  941. {
  942. const unsigned char* inUpper = &pixelDataIn[(y*2)*width_*2];
  943. const unsigned char* inLower = &pixelDataIn[(y*2+1)*width_*2];
  944. unsigned char* out = &pixelDataOut[y*widthOut*2];
  945. for (int x = 0; x < widthOut*2; x += 2)
  946. {
  947. out[x] = ((unsigned)inUpper[x*2] + inUpper[x*2+2] + inLower[x*2] + inLower[x*2+2]) >> 2;
  948. out[x+1] = ((unsigned)inUpper[x*2+1] + inUpper[x*2+3] + inLower[x*2+1] + inLower[x*2+3]) >> 2;
  949. }
  950. }
  951. break;
  952. case 3:
  953. for (int y = 0; y < heightOut; ++y)
  954. {
  955. const unsigned char* inUpper = &pixelDataIn[(y*2)*width_*3];
  956. const unsigned char* inLower = &pixelDataIn[(y*2+1)*width_*3];
  957. unsigned char* out = &pixelDataOut[y*widthOut*3];
  958. for (int x = 0; x < widthOut*3; x += 3)
  959. {
  960. out[x] = ((unsigned)inUpper[x*2] + inUpper[x*2+3] + inLower[x*2] + inLower[x*2+3]) >> 2;
  961. out[x+1] = ((unsigned)inUpper[x*2+1] + inUpper[x*2+4] + inLower[x*2+1] + inLower[x*2+4]) >> 2;
  962. out[x+2] = ((unsigned)inUpper[x*2+2] + inUpper[x*2+5] + inLower[x*2+2] + inLower[x*2+5]) >> 2;
  963. }
  964. }
  965. break;
  966. case 4:
  967. for (int y = 0; y < heightOut; ++y)
  968. {
  969. const unsigned char* inUpper = &pixelDataIn[(y*2)*width_*4];
  970. const unsigned char* inLower = &pixelDataIn[(y*2+1)*width_*4];
  971. unsigned char* out = &pixelDataOut[y*widthOut*4];
  972. for (int x = 0; x < widthOut*4; x += 4)
  973. {
  974. out[x] = ((unsigned)inUpper[x*2] + inUpper[x*2+4] + inLower[x*2] + inLower[x*2+4]) >> 2;
  975. out[x+1] = ((unsigned)inUpper[x*2+1] + inUpper[x*2+5] + inLower[x*2+1] + inLower[x*2+5]) >> 2;
  976. out[x+2] = ((unsigned)inUpper[x*2+2] + inUpper[x*2+6] + inLower[x*2+2] + inLower[x*2+6]) >> 2;
  977. out[x+3] = ((unsigned)inUpper[x*2+3] + inUpper[x*2+7] + inLower[x*2+3] + inLower[x*2+7]) >> 2;
  978. }
  979. }
  980. break;
  981. }
  982. }
  983. // 3D case
  984. else
  985. {
  986. switch (components_)
  987. {
  988. case 1:
  989. for (int z = 0; z < depthOut; ++z)
  990. {
  991. const unsigned char* inOuter = &pixelDataIn[(z*2)*width_*height_];
  992. const unsigned char* inInner = &pixelDataIn[(z*2+1)*width_*height_];
  993. for (int y = 0; y < heightOut; ++y)
  994. {
  995. const unsigned char* inOuterUpper = &inOuter[(y*2)*width_];
  996. const unsigned char* inOuterLower = &inOuter[(y*2+1)*width_];
  997. const unsigned char* inInnerUpper = &inInner[(y*2)*width_];
  998. const unsigned char* inInnerLower = &inInner[(y*2+1)*width_];
  999. unsigned char* out = &pixelDataOut[z*widthOut*heightOut + y*widthOut];
  1000. for (int x = 0; x < widthOut; ++x)
  1001. {
  1002. out[x] = ((unsigned)inOuterUpper[x*2] + inOuterUpper[x*2+1] + inOuterLower[x*2] + inOuterLower[x*2+1] +
  1003. inInnerUpper[x*2] + inInnerUpper[x*2+1] + inInnerLower[x*2] + inInnerLower[x*2+1]) >> 3;
  1004. }
  1005. }
  1006. }
  1007. break;
  1008. case 2:
  1009. for (int z = 0; z < depthOut; ++z)
  1010. {
  1011. const unsigned char* inOuter = &pixelDataIn[(z*2)*width_*height_*2];
  1012. const unsigned char* inInner = &pixelDataIn[(z*2+1)*width_*height_*2];
  1013. for (int y = 0; y < heightOut; ++y)
  1014. {
  1015. const unsigned char* inOuterUpper = &inOuter[(y*2)*width_*2];
  1016. const unsigned char* inOuterLower = &inOuter[(y*2+1)*width_*2];
  1017. const unsigned char* inInnerUpper = &inInner[(y*2)*width_*2];
  1018. const unsigned char* inInnerLower = &inInner[(y*2+1)*width_*2];
  1019. unsigned char* out = &pixelDataOut[z*widthOut*heightOut*2 + y*widthOut*2];
  1020. for (int x = 0; x < widthOut*2; x += 2)
  1021. {
  1022. out[x] = ((unsigned)inOuterUpper[x*2] + inOuterUpper[x*2+2] + inOuterLower[x*2] + inOuterLower[x*2+2] +
  1023. inInnerUpper[x*2] + inInnerUpper[x*2+2] + inInnerLower[x*2] + inInnerLower[x*2+2]) >> 3;
  1024. out[x+1] = ((unsigned)inOuterUpper[x*2+1] + inOuterUpper[x*2+3] + inOuterLower[x*2+1] + inOuterLower[x*2+3] +
  1025. inInnerUpper[x*2+1] + inInnerUpper[x*2+3] + inInnerLower[x*2+1] + inInnerLower[x*2+3]) >> 3;
  1026. }
  1027. }
  1028. }
  1029. break;
  1030. case 3:
  1031. for (int z = 0; z < depthOut; ++z)
  1032. {
  1033. const unsigned char* inOuter = &pixelDataIn[(z*2)*width_*height_*3];
  1034. const unsigned char* inInner = &pixelDataIn[(z*2+1)*width_*height_*3];
  1035. for (int y = 0; y < heightOut; ++y)
  1036. {
  1037. const unsigned char* inOuterUpper = &inOuter[(y*2)*width_*3];
  1038. const unsigned char* inOuterLower = &inOuter[(y*2+1)*width_*3];
  1039. const unsigned char* inInnerUpper = &inInner[(y*2)*width_*3];
  1040. const unsigned char* inInnerLower = &inInner[(y*2+1)*width_*3];
  1041. unsigned char* out = &pixelDataOut[z*widthOut*heightOut*3 + y*widthOut*3];
  1042. for (int x = 0; x < widthOut*3; x += 3)
  1043. {
  1044. out[x] = ((unsigned)inOuterUpper[x*2] + inOuterUpper[x*2+3] + inOuterLower[x*2] + inOuterLower[x*2+3] +
  1045. inInnerUpper[x*2] + inInnerUpper[x*2+3] + inInnerLower[x*2] + inInnerLower[x*2+3]) >> 3;
  1046. out[x+1] = ((unsigned)inOuterUpper[x*2+1] + inOuterUpper[x*2+4] + inOuterLower[x*2+1] + inOuterLower[x*2+4] +
  1047. inInnerUpper[x*2+1] + inInnerUpper[x*2+4] + inInnerLower[x*2+1] + inInnerLower[x*2+4]) >> 3;
  1048. out[x+2] = ((unsigned)inOuterUpper[x*2+2] + inOuterUpper[x*2+5] + inOuterLower[x*2+2] + inOuterLower[x*2+5] +
  1049. inInnerUpper[x*2+2] + inInnerUpper[x*2+5] + inInnerLower[x*2+2] + inInnerLower[x*2+5]) >> 3;
  1050. }
  1051. }
  1052. }
  1053. break;
  1054. case 4:
  1055. for (int z = 0; z < depthOut; ++z)
  1056. {
  1057. const unsigned char* inOuter = &pixelDataIn[(z*2)*width_*height_*4];
  1058. const unsigned char* inInner = &pixelDataIn[(z*2+1)*width_*height_*4];
  1059. for (int y = 0; y < heightOut; ++y)
  1060. {
  1061. const unsigned char* inOuterUpper = &inOuter[(y*2)*width_*4];
  1062. const unsigned char* inOuterLower = &inOuter[(y*2+1)*width_*4];
  1063. const unsigned char* inInnerUpper = &inInner[(y*2)*width_*4];
  1064. const unsigned char* inInnerLower = &inInner[(y*2+1)*width_*4];
  1065. unsigned char* out = &pixelDataOut[z*widthOut*heightOut*4 + y*widthOut*4];
  1066. for (int x = 0; x < widthOut*4; x += 4)
  1067. {
  1068. out[x] = ((unsigned)inOuterUpper[x*2] + inOuterUpper[x*2+4] + inOuterLower[x*2] + inOuterLower[x*2+4] +
  1069. inInnerUpper[x*2] + inInnerUpper[x*2+4] + inInnerLower[x*2] + inInnerLower[x*2+4]) >> 3;
  1070. out[x+1] = ((unsigned)inOuterUpper[x*2+1] + inOuterUpper[x*2+5] + inOuterLower[x*2+1] + inOuterLower[x*2+5] +
  1071. inInnerUpper[x*2+1] + inInnerUpper[x*2+5] + inInnerLower[x*2+1] + inInnerLower[x*2+5]) >> 3;
  1072. out[x+2] = ((unsigned)inOuterUpper[x*2+2] + inOuterUpper[x*2+6] + inOuterLower[x*2+2] + inOuterLower[x*2+6] +
  1073. inInnerUpper[x*2+2] + inInnerUpper[x*2+6] + inInnerLower[x*2+2] + inInnerLower[x*2+6]) >> 3;
  1074. }
  1075. }
  1076. }
  1077. break;
  1078. }
  1079. }
  1080. return mipImage;
  1081. }
  1082. CompressedLevel Image::GetCompressedLevel(unsigned index) const
  1083. {
  1084. CompressedLevel level;
  1085. if (compressedFormat_ == CF_NONE)
  1086. {
  1087. LOGERROR("Image is not compressed");
  1088. return level;
  1089. }
  1090. if (index >= numCompressedLevels_)
  1091. {
  1092. LOGERROR("Compressed image mip level out of bounds");
  1093. return level;
  1094. }
  1095. level.format_ = compressedFormat_;
  1096. level.width_ = width_;
  1097. level.height_ = height_;
  1098. level.depth_ = depth_;
  1099. if (compressedFormat_ < CF_PVRTC_RGB_2BPP)
  1100. {
  1101. level.blockSize_ = (compressedFormat_ == CF_DXT1 || compressedFormat_ == CF_ETC1) ? 8 : 16;
  1102. unsigned i = 0;
  1103. unsigned offset = 0;
  1104. for (;;)
  1105. {
  1106. if (!level.width_)
  1107. level.width_ = 1;
  1108. if (!level.height_)
  1109. level.height_ = 1;
  1110. if (!level.depth_)
  1111. level.depth_ = 1;
  1112. level.rowSize_ = ((level.width_ + 3) / 4) * level.blockSize_;
  1113. level.rows_ = ((level.height_ + 3) / 4);
  1114. level.data_ = data_.Get() + offset;
  1115. level.dataSize_ = level.depth_ * level.rows_ * level.rowSize_;
  1116. if (offset + level.dataSize_ > GetMemoryUse())
  1117. {
  1118. LOGERROR("Compressed level is outside image data. Offset: " + String(offset) + " Size: " + String(level.dataSize_) +
  1119. " Datasize: " + String(GetMemoryUse()));
  1120. level.data_ = 0;
  1121. return level;
  1122. }
  1123. if (i == index)
  1124. return level;
  1125. offset += level.dataSize_;
  1126. level.width_ /= 2;
  1127. level.height_ /= 2;
  1128. level.depth_ /= 2;
  1129. ++i;
  1130. }
  1131. }
  1132. else
  1133. {
  1134. level.blockSize_ = compressedFormat_ < CF_PVRTC_RGB_4BPP ? 2 : 4;
  1135. unsigned i = 0;
  1136. unsigned offset = 0;
  1137. for (;;)
  1138. {
  1139. if (!level.width_)
  1140. level.width_ = 1;
  1141. if (!level.height_)
  1142. level.height_ = 1;
  1143. int dataWidth = Max(level.width_, level.blockSize_ == 2 ? 16 : 8);
  1144. int dataHeight = Max(level.height_, 8);
  1145. level.data_ = data_.Get() + offset;
  1146. level.dataSize_ = (dataWidth * dataHeight * level.blockSize_ + 7) >> 3;
  1147. level.rows_ = dataHeight;
  1148. level.rowSize_ = level.dataSize_ / level.rows_;
  1149. if (offset + level.dataSize_ > GetMemoryUse())
  1150. {
  1151. LOGERROR("Compressed level is outside image data. Offset: " + String(offset) + " Size: " + String(level.dataSize_) +
  1152. " Datasize: " + String(GetMemoryUse()));
  1153. level.data_ = 0;
  1154. return level;
  1155. }
  1156. if (i == index)
  1157. return level;
  1158. offset += level.dataSize_;
  1159. level.width_ /= 2;
  1160. level.height_ /= 2;
  1161. ++i;
  1162. }
  1163. }
  1164. }
  1165. Image* Image::GetSubimage(const IntRect& rect) const
  1166. {
  1167. if (!data_)
  1168. return 0;
  1169. if (depth_ > 1)
  1170. {
  1171. LOGERROR("Subimage not supported for 3D images");
  1172. return 0;
  1173. }
  1174. if (rect.left_ < 0 || rect.top_ < 0 || rect.right_ > width_ || rect.bottom_ > height_ || !rect.Width() || !rect.Height())
  1175. {
  1176. LOGERROR("Can not get subimage from image " + GetName() + " with invalid region");
  1177. return 0;
  1178. }
  1179. if (!IsCompressed())
  1180. {
  1181. int x = rect.left_;
  1182. int y = rect.top_;
  1183. int width = rect.Width();
  1184. int height = rect.Height();
  1185. Image* image = new Image(context_);
  1186. image->SetSize(width, height, components_);
  1187. unsigned char* dest = image->GetData();
  1188. unsigned char* src = data_.Get() + (y * width_ + x) * components_;
  1189. for (int i = 0; i < height; ++i)
  1190. {
  1191. memcpy(dest, src, width * components_);
  1192. dest += width * components_;
  1193. src += width_ * components_;
  1194. }
  1195. return image;
  1196. }
  1197. else
  1198. {
  1199. // Pad the region to be a multiple of block size
  1200. IntRect paddedRect = rect;
  1201. paddedRect.left_ = (rect.left_ / 4) * 4;
  1202. paddedRect.top_ = (rect.top_ / 4) * 4;
  1203. paddedRect.right_ = (rect.right_ / 4) * 4;
  1204. paddedRect.bottom_ = (rect.bottom_ / 4) * 4;
  1205. IntRect currentRect = paddedRect;
  1206. PODVector<unsigned char> subimageData;
  1207. unsigned subimageLevels = 0;
  1208. // Save as many mips as possible until the next mip would cross a block boundary
  1209. for (unsigned i = 0; i < numCompressedLevels_; ++i)
  1210. {
  1211. CompressedLevel level = GetCompressedLevel(i);
  1212. if (!level.data_)
  1213. break;
  1214. // Mips are stored continuously
  1215. unsigned destStartOffset = subimageData.Size();
  1216. unsigned destRowSize = currentRect.Width() / 4 * level.blockSize_;
  1217. unsigned destSize = currentRect.Height() / 4 * destRowSize;
  1218. if (!destSize)
  1219. break;
  1220. subimageData.Resize(destStartOffset + destSize);
  1221. unsigned char* dest = &subimageData[destStartOffset];
  1222. for (int y = currentRect.top_; y < currentRect.bottom_; y += 4)
  1223. {
  1224. unsigned char* src = level.data_ + level.rowSize_ * (y / 4) + currentRect.left_ / 4 * level.blockSize_;
  1225. memcpy(dest, src, destRowSize);
  1226. dest += destRowSize;
  1227. }
  1228. ++subimageLevels;
  1229. if ((currentRect.left_ & 4) || (currentRect.right_ & 4) || (currentRect.top_ & 4) || (currentRect.bottom_ & 4))
  1230. break;
  1231. else
  1232. {
  1233. currentRect.left_ /= 2;
  1234. currentRect.right_ /= 2;
  1235. currentRect.top_ /= 2;
  1236. currentRect.bottom_ /= 2;
  1237. }
  1238. }
  1239. if (!subimageLevels)
  1240. {
  1241. LOGERROR("Subimage region from compressed image " + GetName() + " did not produce any data");
  1242. return 0;
  1243. }
  1244. Image* image = new Image(context_);
  1245. image->width_ = paddedRect.Width();
  1246. image->height_ = paddedRect.Height();
  1247. image->depth_ = 1;
  1248. image->compressedFormat_ = compressedFormat_;
  1249. image->numCompressedLevels_ = subimageLevels;
  1250. image->components_ = components_;
  1251. image->data_ = new unsigned char[subimageData.Size()];
  1252. memcpy(image->data_.Get(), &subimageData[0], subimageData.Size());
  1253. image->SetMemoryUse(subimageData.Size());
  1254. return image;
  1255. }
  1256. }
  1257. SDL_Surface* Image::GetSDLSurface(const IntRect& rect) const
  1258. {
  1259. if (!data_)
  1260. return 0;
  1261. if (depth_ > 1)
  1262. {
  1263. LOGERROR("Can not get SDL surface from 3D image");
  1264. return 0;
  1265. }
  1266. if (IsCompressed())
  1267. {
  1268. LOGERROR("Can not get SDL surface from compressed image " + GetName());
  1269. return 0;
  1270. }
  1271. if (components_ < 3)
  1272. {
  1273. LOGERROR("Can not get SDL surface from image " + GetName() + " with less than 3 components");
  1274. return 0;
  1275. }
  1276. IntRect imageRect = rect;
  1277. // Use full image if illegal rect
  1278. if (imageRect.left_ < 0 || imageRect.top_ < 0 || imageRect.right_ > width_ || imageRect.bottom_ > height_ ||
  1279. imageRect.left_ >= imageRect.right_ || imageRect.top_ >= imageRect.bottom_)
  1280. {
  1281. imageRect.left_ = 0;
  1282. imageRect.top_ = 0;
  1283. imageRect.right_ = width_;
  1284. imageRect.bottom_ = height_;
  1285. }
  1286. int imageWidth = width_;
  1287. int width = imageRect.Width();
  1288. int height = imageRect.Height();
  1289. // Assume little-endian for all the supported platforms
  1290. unsigned rMask = 0x000000ff;
  1291. unsigned gMask = 0x0000ff00;
  1292. unsigned bMask = 0x00ff0000;
  1293. unsigned aMask = 0xff000000;
  1294. SDL_Surface* surface = SDL_CreateRGBSurface(0, width, height, components_ * 8, rMask, gMask, bMask, aMask);
  1295. if (surface)
  1296. {
  1297. SDL_LockSurface(surface);
  1298. unsigned char* destination = reinterpret_cast<unsigned char*>(surface->pixels);
  1299. unsigned char* source = data_ + components_ * (imageWidth * imageRect.top_ + imageRect.left_);
  1300. for (int i = 0; i < height; ++i)
  1301. {
  1302. memcpy(destination, source, components_ * width);
  1303. destination += surface->pitch;
  1304. source += components_ * imageWidth;
  1305. }
  1306. SDL_UnlockSurface(surface);
  1307. }
  1308. else
  1309. LOGERROR("Failed to create SDL surface from image " + GetName());
  1310. return surface;
  1311. }
  1312. void Image::PrecalculateLevels()
  1313. {
  1314. if (!data_ || IsCompressed())
  1315. return;
  1316. PROFILE(PrecalculateImageMipLevels);
  1317. nextLevel_.Reset();
  1318. if (width_ > 1 || height_ > 1)
  1319. {
  1320. SharedPtr<Image> current = GetNextLevel();
  1321. nextLevel_ = current;
  1322. while (current && (current->width_ > 1 || current->height_ > 1))
  1323. {
  1324. current->nextLevel_ = current->GetNextLevel();
  1325. current = current->nextLevel_;
  1326. }
  1327. }
  1328. }
  1329. unsigned char* Image::GetImageData(Deserializer& source, int& width, int& height, unsigned& components)
  1330. {
  1331. unsigned dataSize = source.GetSize();
  1332. SharedArrayPtr<unsigned char> buffer(new unsigned char[dataSize]);
  1333. source.Read(buffer.Get(), dataSize);
  1334. return stbi_load_from_memory(buffer.Get(), dataSize, &width, &height, (int *)&components, 0);
  1335. }
  1336. void Image::FreeImageData(unsigned char* pixelData)
  1337. {
  1338. if (!pixelData)
  1339. return;
  1340. stbi_image_free(pixelData);
  1341. }
  1342. }