Image.cpp 70 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163
  1. //
  2. // Copyright (c) 2008-2015 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 "../Core/Context.h"
  24. #include "../Core/Profiler.h"
  25. #include "../IO/File.h"
  26. #include "../IO/FileSystem.h"
  27. #include "../IO/Log.h"
  28. #include "../Resource/Decompress.h"
  29. #include <JO/jo_jpeg.h>
  30. #include <SDL/include/SDL_surface.h>
  31. #include <STB/stb_image.h>
  32. #include <STB/stb_image_write.h>
  33. #include "../DebugNew.h"
  34. #ifdef ATOMIC_PLATFORM_DESKTOP
  35. #include <libsquish/squish.h>
  36. #endif
  37. extern "C" unsigned char* stbi_write_png_to_mem(unsigned char* pixels, int stride_bytes, int x, int y, int n, int* out_len);
  38. #ifndef MAKEFOURCC
  39. #define MAKEFOURCC(ch0, ch1, ch2, ch3) ((unsigned)(ch0) | ((unsigned)(ch1) << 8) | ((unsigned)(ch2) << 16) | ((unsigned)(ch3) << 24))
  40. #endif
  41. #define FOURCC_DXT1 (MAKEFOURCC('D','X','T','1'))
  42. #define FOURCC_DXT2 (MAKEFOURCC('D','X','T','2'))
  43. #define FOURCC_DXT3 (MAKEFOURCC('D','X','T','3'))
  44. #define FOURCC_DXT4 (MAKEFOURCC('D','X','T','4'))
  45. #define FOURCC_DXT5 (MAKEFOURCC('D','X','T','5'))
  46. #define FOURCC_DX10 (MAKEFOURCC('D','X','1','0'))
  47. static const unsigned DDSCAPS_COMPLEX = 0x00000008U;
  48. static const unsigned DDSCAPS_TEXTURE = 0x00001000U;
  49. static const unsigned DDSCAPS_MIPMAP = 0x00400000U;
  50. static const unsigned DDSCAPS2_VOLUME = 0x00200000U;
  51. static const unsigned DDSCAPS2_CUBEMAP = 0x00000200U;
  52. static const unsigned DDSCAPS2_CUBEMAP_POSITIVEX = 0x00000400U;
  53. static const unsigned DDSCAPS2_CUBEMAP_NEGATIVEX = 0x00000800U;
  54. static const unsigned DDSCAPS2_CUBEMAP_POSITIVEY = 0x00001000U;
  55. static const unsigned DDSCAPS2_CUBEMAP_NEGATIVEY = 0x00002000U;
  56. static const unsigned DDSCAPS2_CUBEMAP_POSITIVEZ = 0x00004000U;
  57. static const unsigned DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x00008000U;
  58. static const unsigned DDSCAPS2_CUBEMAP_ALL_FACES = 0x0000FC00U;
  59. // DX10 flags
  60. static const unsigned DDS_DIMENSION_TEXTURE1D = 2;
  61. static const unsigned DDS_DIMENSION_TEXTURE2D = 3;
  62. static const unsigned DDS_DIMENSION_TEXTURE3D = 4;
  63. static const unsigned DDS_RESOURCE_MISC_TEXTURECUBE = 0x4;
  64. static const unsigned DDS_DXGI_FORMAT_R8G8B8A8_UNORM = 28;
  65. static const unsigned DDS_DXGI_FORMAT_R8G8B8A8_UNORM_SRGB = 26;
  66. static const unsigned DDS_DXGI_FORMAT_BC1_UNORM = 71;
  67. static const unsigned DDS_DXGI_FORMAT_BC1_UNORM_SRGB = 72;
  68. static const unsigned DDS_DXGI_FORMAT_BC2_UNORM = 74;
  69. static const unsigned DDS_DXGI_FORMAT_BC2_UNORM_SRGB = 75;
  70. static const unsigned DDS_DXGI_FORMAT_BC3_UNORM = 77;
  71. static const unsigned DDS_DXGI_FORMAT_BC3_UNORM_SRGB = 78;
  72. namespace Atomic
  73. {
  74. /// DirectDraw color key definition.
  75. struct DDColorKey
  76. {
  77. unsigned dwColorSpaceLowValue_;
  78. unsigned dwColorSpaceHighValue_;
  79. };
  80. /// DirectDraw pixel format definition.
  81. struct DDPixelFormat
  82. {
  83. unsigned dwSize_;
  84. unsigned dwFlags_;
  85. unsigned dwFourCC_;
  86. union
  87. {
  88. unsigned dwRGBBitCount_;
  89. unsigned dwYUVBitCount_;
  90. unsigned dwZBufferBitDepth_;
  91. unsigned dwAlphaBitDepth_;
  92. unsigned dwLuminanceBitCount_;
  93. unsigned dwBumpBitCount_;
  94. unsigned dwPrivateFormatBitCount_;
  95. };
  96. union
  97. {
  98. unsigned dwRBitMask_;
  99. unsigned dwYBitMask_;
  100. unsigned dwStencilBitDepth_;
  101. unsigned dwLuminanceBitMask_;
  102. unsigned dwBumpDuBitMask_;
  103. unsigned dwOperations_;
  104. };
  105. union
  106. {
  107. unsigned dwGBitMask_;
  108. unsigned dwUBitMask_;
  109. unsigned dwZBitMask_;
  110. unsigned dwBumpDvBitMask_;
  111. struct
  112. {
  113. unsigned short wFlipMSTypes_;
  114. unsigned short wBltMSTypes_;
  115. } multiSampleCaps_;
  116. };
  117. union
  118. {
  119. unsigned dwBBitMask_;
  120. unsigned dwVBitMask_;
  121. unsigned dwStencilBitMask_;
  122. unsigned dwBumpLuminanceBitMask_;
  123. };
  124. union
  125. {
  126. unsigned dwRGBAlphaBitMask_;
  127. unsigned dwYUVAlphaBitMask_;
  128. unsigned dwLuminanceAlphaBitMask_;
  129. unsigned dwRGBZBitMask_;
  130. unsigned dwYUVZBitMask_;
  131. };
  132. };
  133. /// DirectDraw surface capabilities.
  134. struct DDSCaps2
  135. {
  136. unsigned dwCaps_;
  137. unsigned dwCaps2_;
  138. unsigned dwCaps3_;
  139. union
  140. {
  141. unsigned dwCaps4_;
  142. unsigned dwVolumeDepth_;
  143. };
  144. };
  145. struct DDSHeader10
  146. {
  147. unsigned dxgiFormat;
  148. unsigned resourceDimension;
  149. unsigned miscFlag;
  150. unsigned arraySize;
  151. unsigned reserved;
  152. };
  153. /// DirectDraw surface description.
  154. struct DDSurfaceDesc2
  155. {
  156. unsigned dwSize_;
  157. unsigned dwFlags_;
  158. unsigned dwHeight_;
  159. unsigned dwWidth_;
  160. union
  161. {
  162. unsigned lPitch_;
  163. unsigned dwLinearSize_;
  164. };
  165. union
  166. {
  167. unsigned dwBackBufferCount_;
  168. unsigned dwDepth_;
  169. };
  170. union
  171. {
  172. unsigned dwMipMapCount_;
  173. unsigned dwRefreshRate_;
  174. unsigned dwSrcVBHandle_;
  175. };
  176. unsigned dwAlphaBitDepth_;
  177. unsigned dwReserved_;
  178. unsigned lpSurface_; // Do not define as a void pointer, as it is 8 bytes in a 64bit build
  179. union
  180. {
  181. DDColorKey ddckCKDestOverlay_;
  182. unsigned dwEmptyFaceColor_;
  183. };
  184. DDColorKey ddckCKDestBlt_;
  185. DDColorKey ddckCKSrcOverlay_;
  186. DDColorKey ddckCKSrcBlt_;
  187. union
  188. {
  189. DDPixelFormat ddpfPixelFormat_;
  190. unsigned dwFVF_;
  191. };
  192. DDSCaps2 ddsCaps_;
  193. unsigned dwTextureStage_;
  194. };
  195. bool CompressedLevel::Decompress(unsigned char* dest)
  196. {
  197. if (!data_)
  198. return false;
  199. switch (format_)
  200. {
  201. case CF_DXT1:
  202. case CF_DXT3:
  203. case CF_DXT5:
  204. DecompressImageDXT(dest, data_, width_, height_, depth_, format_);
  205. return true;
  206. case CF_ETC1:
  207. DecompressImageETC(dest, data_, width_, height_);
  208. return true;
  209. case CF_PVRTC_RGB_2BPP:
  210. case CF_PVRTC_RGBA_2BPP:
  211. case CF_PVRTC_RGB_4BPP:
  212. case CF_PVRTC_RGBA_4BPP:
  213. DecompressImagePVRTC(dest, data_, width_, height_, format_);
  214. return true;
  215. default:
  216. // Unknown format
  217. return false;
  218. }
  219. }
  220. Image::Image(Context* context) :
  221. Resource(context),
  222. width_(0),
  223. height_(0),
  224. depth_(0),
  225. components_(0),
  226. cubemap_(false),
  227. array_(false),
  228. sRGB_(false)
  229. {
  230. }
  231. Image::~Image()
  232. {
  233. }
  234. void Image::RegisterObject(Context* context)
  235. {
  236. context->RegisterFactory<Image>();
  237. }
  238. bool Image::BeginLoad(Deserializer& source)
  239. {
  240. // Check for DDS, KTX or PVR compressed format
  241. String fileID = source.ReadFileID();
  242. if (fileID == "DDS ")
  243. {
  244. // DDS compressed format
  245. DDSurfaceDesc2 ddsd;
  246. source.Read(&ddsd, sizeof(ddsd));
  247. // DDS DX10+
  248. const bool hasDXGI = ddsd.ddpfPixelFormat_.dwFourCC_ == FOURCC_DX10;
  249. DDSHeader10 dxgiHeader;
  250. if (hasDXGI)
  251. source.Read(&dxgiHeader, sizeof(dxgiHeader));
  252. unsigned fourCC = ddsd.ddpfPixelFormat_.dwFourCC_;
  253. // If the DXGI header is available then remap formats and check sRGB
  254. if (hasDXGI)
  255. {
  256. switch (dxgiHeader.dxgiFormat)
  257. {
  258. case DDS_DXGI_FORMAT_BC1_UNORM:
  259. case DDS_DXGI_FORMAT_BC1_UNORM_SRGB:
  260. fourCC = FOURCC_DXT1;
  261. break;
  262. case DDS_DXGI_FORMAT_BC2_UNORM:
  263. case DDS_DXGI_FORMAT_BC2_UNORM_SRGB:
  264. fourCC = FOURCC_DXT3;
  265. break;
  266. case DDS_DXGI_FORMAT_BC3_UNORM:
  267. case DDS_DXGI_FORMAT_BC3_UNORM_SRGB:
  268. fourCC = FOURCC_DXT5;
  269. break;
  270. case DDS_DXGI_FORMAT_R8G8B8A8_UNORM:
  271. case DDS_DXGI_FORMAT_R8G8B8A8_UNORM_SRGB:
  272. fourCC = 0;
  273. break;
  274. default:
  275. LOGERROR("Unrecognized DDS DXGI image format");
  276. return false;
  277. }
  278. // Check the internal sRGB formats
  279. if (dxgiHeader.dxgiFormat == DDS_DXGI_FORMAT_BC1_UNORM_SRGB ||
  280. dxgiHeader.dxgiFormat == DDS_DXGI_FORMAT_BC2_UNORM_SRGB ||
  281. dxgiHeader.dxgiFormat == DDS_DXGI_FORMAT_BC3_UNORM_SRGB ||
  282. dxgiHeader.dxgiFormat == DDS_DXGI_FORMAT_R8G8B8A8_UNORM_SRGB)
  283. {
  284. sRGB_ = true;
  285. }
  286. }
  287. switch (fourCC)
  288. {
  289. case FOURCC_DXT1:
  290. compressedFormat_ = CF_DXT1;
  291. components_ = 3;
  292. break;
  293. case FOURCC_DXT3:
  294. compressedFormat_ = CF_DXT3;
  295. components_ = 4;
  296. break;
  297. case FOURCC_DXT5:
  298. compressedFormat_ = CF_DXT5;
  299. components_ = 4;
  300. break;
  301. case 0:
  302. if (ddsd.ddpfPixelFormat_.dwRGBBitCount_ != 32 && ddsd.ddpfPixelFormat_.dwRGBBitCount_ != 24 &&
  303. ddsd.ddpfPixelFormat_.dwRGBBitCount_ != 16)
  304. {
  305. LOGERROR("Unsupported DDS pixel byte size");
  306. return false;
  307. }
  308. compressedFormat_ = CF_RGBA;
  309. components_ = 4;
  310. break;
  311. default:
  312. LOGERROR("Unrecognized DDS image format");
  313. return false;
  314. }
  315. // Is it a cube map or texture array? If so determine the size of the image chain.
  316. cubemap_ = (ddsd.ddsCaps_.dwCaps2_ & DDSCAPS2_CUBEMAP_ALL_FACES) != 0 || (hasDXGI && (dxgiHeader.miscFlag & DDS_RESOURCE_MISC_TEXTURECUBE) != 0);
  317. unsigned imageChainCount = 1;
  318. if (cubemap_)
  319. imageChainCount = 6;
  320. else if (hasDXGI && dxgiHeader.arraySize > 1)
  321. {
  322. imageChainCount = dxgiHeader.arraySize;
  323. array_ = true;
  324. }
  325. // Calculate the size of the data
  326. unsigned dataSize = 0;
  327. if (compressedFormat_ != CF_RGBA)
  328. {
  329. const unsigned blockSize = compressedFormat_ == CF_DXT1 ? 8 : 16; //DXT1/BC1 is 8 bytes, DXT3/BC2 and DXT5/BC3 are 16 bytes
  330. // Add 3 to ensure valid block: ie 2x2 fits uses a whole 4x4 block
  331. unsigned blocksWide = (ddsd.dwWidth_ + 3) / 4;
  332. unsigned blocksHeight = (ddsd.dwHeight_ + 3) / 4;
  333. dataSize = blocksWide * blocksHeight * blockSize;
  334. // Calculate mip data size
  335. unsigned x = ddsd.dwWidth_ / 2;
  336. unsigned y = ddsd.dwHeight_ / 2;
  337. unsigned z = ddsd.dwDepth_ / 2;
  338. for (unsigned level = ddsd.dwMipMapCount_; level > 0; x /= 2, y /= 2, z /= 2, level -= 1)
  339. {
  340. blocksWide = (Max(x, 1) + 3) / 4;
  341. blocksHeight = (Max(y, 1) + 3) / 4;
  342. dataSize += blockSize * blocksWide * blocksHeight * Max(z, 1);
  343. }
  344. }
  345. else
  346. {
  347. dataSize = (ddsd.ddpfPixelFormat_.dwRGBBitCount_ / 8) * ddsd.dwWidth_ * ddsd.dwHeight_ * Max(ddsd.dwDepth_, 1);
  348. // Calculate mip data size
  349. unsigned x = ddsd.dwWidth_ / 2;
  350. unsigned y = ddsd.dwHeight_ / 2;
  351. unsigned z = ddsd.dwDepth_ / 2;
  352. for (unsigned level = ddsd.dwMipMapCount_; level > 0; x /= 2, y /= 2, z /= 2, level -= 1)
  353. dataSize += (ddsd.ddpfPixelFormat_.dwRGBBitCount_ / 8) * Max(x, 1) * Max(y, 1) * Max(z, 1);
  354. }
  355. // Do not use a shared ptr here, in case nothing is refcounting the image outside this function.
  356. // A raw pointer is fine as the image chain (if needed) uses shared ptr's properly
  357. Image* currentImage = this;
  358. for (unsigned faceIndex = 0; faceIndex < imageChainCount; ++faceIndex)
  359. {
  360. currentImage->data_ = new unsigned char[dataSize];
  361. currentImage->cubemap_ = cubemap_;
  362. currentImage->array_ = array_;
  363. currentImage->components_ = components_;
  364. currentImage->compressedFormat_ = compressedFormat_;
  365. currentImage->width_ = ddsd.dwWidth_;
  366. currentImage->height_ = ddsd.dwHeight_;
  367. currentImage->depth_ = ddsd.dwDepth_;
  368. currentImage->numCompressedLevels_ = ddsd.dwMipMapCount_;
  369. if (!currentImage->numCompressedLevels_)
  370. currentImage->numCompressedLevels_ = 1;
  371. // Memory use needs to be exact per image as it's used for verifying the data size in GetCompressedLevel()
  372. // even though it would be more proper for the first image to report the size of all siblings combined
  373. currentImage->SetMemoryUse(dataSize);
  374. source.Read(currentImage->data_.Get(), dataSize);
  375. if (faceIndex < imageChainCount - 1)
  376. {
  377. // Build the image chain
  378. SharedPtr<Image> nextImage(new Image(context_));
  379. currentImage->nextSibling_ = nextImage;
  380. currentImage = nextImage;
  381. }
  382. }
  383. // If uncompressed DDS, convert the data to 8bit RGBA as the texture classes can not currently use eg. RGB565 format
  384. if (compressedFormat_ == CF_RGBA)
  385. {
  386. PROFILE(ConvertDDSToRGBA);
  387. SharedPtr<Image> currentImage(this);
  388. while (currentImage.NotNull())
  389. {
  390. unsigned sourcePixelByteSize = ddsd.ddpfPixelFormat_.dwRGBBitCount_ >> 3;
  391. unsigned numPixels = dataSize / sourcePixelByteSize;
  392. #define ADJUSTSHIFT(mask, l, r) \
  393. if (mask && mask >= 0x100) \
  394. { \
  395. while ((mask >> r) >= 0x100) \
  396. ++r; \
  397. } \
  398. else if (mask && mask < 0x80) \
  399. { \
  400. while ((mask << l) < 0x80) \
  401. ++l; \
  402. }
  403. unsigned rShiftL = 0, gShiftL = 0, bShiftL = 0, aShiftL = 0;
  404. unsigned rShiftR = 0, gShiftR = 0, bShiftR = 0, aShiftR = 0;
  405. unsigned rMask = ddsd.ddpfPixelFormat_.dwRBitMask_;
  406. unsigned gMask = ddsd.ddpfPixelFormat_.dwGBitMask_;
  407. unsigned bMask = ddsd.ddpfPixelFormat_.dwBBitMask_;
  408. unsigned aMask = ddsd.ddpfPixelFormat_.dwRGBAlphaBitMask_;
  409. ADJUSTSHIFT(rMask, rShiftL, rShiftR)
  410. ADJUSTSHIFT(gMask, gShiftL, gShiftR)
  411. ADJUSTSHIFT(bMask, bShiftL, bShiftR)
  412. ADJUSTSHIFT(aMask, aShiftL, aShiftR)
  413. SharedArrayPtr<unsigned char> rgbaData(new unsigned char[numPixels * 4]);
  414. SetMemoryUse(numPixels * 4);
  415. switch (sourcePixelByteSize)
  416. {
  417. case 4:
  418. {
  419. unsigned* src = (unsigned*)currentImage->data_.Get();
  420. unsigned char* dest = rgbaData.Get();
  421. while (numPixels--)
  422. {
  423. unsigned pixels = *src++;
  424. *dest++ = ((pixels & rMask) << rShiftL) >> rShiftR;
  425. *dest++ = ((pixels & gMask) << gShiftL) >> gShiftR;
  426. *dest++ = ((pixels & bMask) << bShiftL) >> bShiftR;
  427. *dest++ = ((pixels & aMask) << aShiftL) >> aShiftR;
  428. }
  429. }
  430. break;
  431. case 3:
  432. {
  433. unsigned char* src = currentImage->data_.Get();
  434. unsigned char* dest = rgbaData.Get();
  435. while (numPixels--)
  436. {
  437. unsigned pixels = src[0] | (src[1] << 8) | (src[2] << 16);
  438. src += 3;
  439. *dest++ = ((pixels & rMask) << rShiftL) >> rShiftR;
  440. *dest++ = ((pixels & gMask) << gShiftL) >> gShiftR;
  441. *dest++ = ((pixels & bMask) << bShiftL) >> bShiftR;
  442. *dest++ = ((pixels & aMask) << aShiftL) >> aShiftR;
  443. }
  444. }
  445. break;
  446. default:
  447. {
  448. unsigned short* src = (unsigned short*)currentImage->data_.Get();
  449. unsigned char* dest = rgbaData.Get();
  450. while (numPixels--)
  451. {
  452. unsigned short pixels = *src++;
  453. *dest++ = ((pixels & rMask) << rShiftL) >> rShiftR;
  454. *dest++ = ((pixels & gMask) << gShiftL) >> gShiftR;
  455. *dest++ = ((pixels & bMask) << bShiftL) >> bShiftR;
  456. *dest++ = ((pixels & aMask) << aShiftL) >> aShiftR;
  457. }
  458. }
  459. break;
  460. }
  461. // Replace with converted data
  462. currentImage->data_ = rgbaData;
  463. currentImage = currentImage->GetNextSibling();
  464. }
  465. }
  466. }
  467. else if (fileID == "\253KTX")
  468. {
  469. source.Seek(12);
  470. unsigned endianness = source.ReadUInt();
  471. unsigned type = source.ReadUInt();
  472. /* unsigned typeSize = */ source.ReadUInt();
  473. unsigned format = source.ReadUInt();
  474. unsigned internalFormat = source.ReadUInt();
  475. /* unsigned baseInternalFormat = */ source.ReadUInt();
  476. unsigned width = source.ReadUInt();
  477. unsigned height = source.ReadUInt();
  478. unsigned depth = source.ReadUInt();
  479. /* unsigned arrayElements = */ source.ReadUInt();
  480. unsigned faces = source.ReadUInt();
  481. unsigned mipmaps = source.ReadUInt();
  482. unsigned keyValueBytes = source.ReadUInt();
  483. if (endianness != 0x04030201)
  484. {
  485. LOGERROR("Big-endian KTX files not supported");
  486. return false;
  487. }
  488. if (type != 0 || format != 0)
  489. {
  490. LOGERROR("Uncompressed KTX files not supported");
  491. return false;
  492. }
  493. if (faces > 1 || depth > 1)
  494. {
  495. LOGERROR("3D or cube KTX files not supported");
  496. return false;
  497. }
  498. if (mipmaps == 0)
  499. {
  500. LOGERROR("KTX files without explicitly specified mipmap count not supported");
  501. return false;
  502. }
  503. switch (internalFormat)
  504. {
  505. case 0x83f1:
  506. compressedFormat_ = CF_DXT1;
  507. components_ = 4;
  508. break;
  509. case 0x83f2:
  510. compressedFormat_ = CF_DXT3;
  511. components_ = 4;
  512. break;
  513. case 0x83f3:
  514. compressedFormat_ = CF_DXT5;
  515. components_ = 4;
  516. break;
  517. case 0x8d64:
  518. compressedFormat_ = CF_ETC1;
  519. components_ = 3;
  520. break;
  521. case 0x8c00:
  522. compressedFormat_ = CF_PVRTC_RGB_4BPP;
  523. components_ = 3;
  524. break;
  525. case 0x8c01:
  526. compressedFormat_ = CF_PVRTC_RGB_2BPP;
  527. components_ = 3;
  528. break;
  529. case 0x8c02:
  530. compressedFormat_ = CF_PVRTC_RGBA_4BPP;
  531. components_ = 4;
  532. break;
  533. case 0x8c03:
  534. compressedFormat_ = CF_PVRTC_RGBA_2BPP;
  535. components_ = 4;
  536. break;
  537. default:
  538. compressedFormat_ = CF_NONE;
  539. break;
  540. }
  541. if (compressedFormat_ == CF_NONE)
  542. {
  543. LOGERROR("Unsupported texture format in KTX file");
  544. return false;
  545. }
  546. source.Seek(source.GetPosition() + keyValueBytes);
  547. unsigned dataSize = (unsigned)(source.GetSize() - source.GetPosition() - mipmaps * sizeof(unsigned));
  548. data_ = new unsigned char[dataSize];
  549. width_ = width;
  550. height_ = height;
  551. numCompressedLevels_ = mipmaps;
  552. unsigned dataOffset = 0;
  553. for (unsigned i = 0; i < mipmaps; ++i)
  554. {
  555. unsigned levelSize = source.ReadUInt();
  556. if (levelSize + dataOffset > dataSize)
  557. {
  558. LOGERROR("KTX mipmap level data size exceeds file size");
  559. return false;
  560. }
  561. source.Read(&data_[dataOffset], levelSize);
  562. dataOffset += levelSize;
  563. if (source.GetPosition() & 3)
  564. source.Seek((source.GetPosition() + 3) & 0xfffffffc);
  565. }
  566. SetMemoryUse(dataSize);
  567. }
  568. else if (fileID == "PVR\3")
  569. {
  570. /* unsigned flags = */ source.ReadUInt();
  571. unsigned pixelFormatLo = source.ReadUInt();
  572. /* unsigned pixelFormatHi = */ source.ReadUInt();
  573. /* unsigned colourSpace = */ source.ReadUInt();
  574. /* unsigned channelType = */ source.ReadUInt();
  575. unsigned height = source.ReadUInt();
  576. unsigned width = source.ReadUInt();
  577. unsigned depth = source.ReadUInt();
  578. /* unsigned numSurfaces = */ source.ReadUInt();
  579. unsigned numFaces = source.ReadUInt();
  580. unsigned mipmapCount = source.ReadUInt();
  581. unsigned metaDataSize = source.ReadUInt();
  582. if (depth > 1 || numFaces > 1)
  583. {
  584. LOGERROR("3D or cube PVR files not supported");
  585. return false;
  586. }
  587. if (mipmapCount == 0)
  588. {
  589. LOGERROR("PVR files without explicitly specified mipmap count not supported");
  590. return false;
  591. }
  592. switch (pixelFormatLo)
  593. {
  594. case 0:
  595. compressedFormat_ = CF_PVRTC_RGB_2BPP;
  596. components_ = 3;
  597. break;
  598. case 1:
  599. compressedFormat_ = CF_PVRTC_RGBA_2BPP;
  600. components_ = 4;
  601. break;
  602. case 2:
  603. compressedFormat_ = CF_PVRTC_RGB_4BPP;
  604. components_ = 3;
  605. break;
  606. case 3:
  607. compressedFormat_ = CF_PVRTC_RGBA_4BPP;
  608. components_ = 4;
  609. break;
  610. case 6:
  611. compressedFormat_ = CF_ETC1;
  612. components_ = 3;
  613. break;
  614. case 7:
  615. compressedFormat_ = CF_DXT1;
  616. components_ = 4;
  617. break;
  618. case 9:
  619. compressedFormat_ = CF_DXT3;
  620. components_ = 4;
  621. break;
  622. case 11:
  623. compressedFormat_ = CF_DXT5;
  624. components_ = 4;
  625. break;
  626. default:
  627. compressedFormat_ = CF_NONE;
  628. break;
  629. }
  630. if (compressedFormat_ == CF_NONE)
  631. {
  632. LOGERROR("Unsupported texture format in PVR file");
  633. return false;
  634. }
  635. source.Seek(source.GetPosition() + metaDataSize);
  636. unsigned dataSize = source.GetSize() - source.GetPosition();
  637. data_ = new unsigned char[dataSize];
  638. width_ = width;
  639. height_ = height;
  640. numCompressedLevels_ = mipmapCount;
  641. source.Read(data_.Get(), dataSize);
  642. SetMemoryUse(dataSize);
  643. }
  644. else
  645. {
  646. // Not DDS, KTX or PVR, use STBImage to load other image formats as uncompressed
  647. source.Seek(0);
  648. int width, height;
  649. unsigned components;
  650. unsigned char* pixelData = GetImageData(source, width, height, components);
  651. if (!pixelData)
  652. {
  653. LOGERROR("Could not load image " + source.GetName() + ": " + String(stbi_failure_reason()));
  654. return false;
  655. }
  656. SetSize(width, height, components);
  657. SetData(pixelData);
  658. FreeImageData(pixelData);
  659. }
  660. return true;
  661. }
  662. bool Image::Save(Serializer& dest) const
  663. {
  664. PROFILE(SaveImage);
  665. if (IsCompressed())
  666. {
  667. LOGERROR("Can not save compressed image " + GetName());
  668. return false;
  669. }
  670. if (!data_)
  671. {
  672. LOGERROR("Can not save zero-sized image " + GetName());
  673. return false;
  674. }
  675. int len;
  676. unsigned char* png = stbi_write_png_to_mem(data_.Get(), 0, width_, height_, components_, &len);
  677. bool success = dest.Write(png, (unsigned)len) == (unsigned)len;
  678. free(png);
  679. return success;
  680. }
  681. bool Image::SetSize(int width, int height, unsigned components)
  682. {
  683. return SetSize(width, height, 1, components);
  684. }
  685. bool Image::SetSize(int width, int height, int depth, unsigned components)
  686. {
  687. if (width == width_ && height == height_ && depth == depth_ && components == components_)
  688. return true;
  689. if (width <= 0 || height <= 0 || depth <= 0)
  690. return false;
  691. if (components > 4)
  692. {
  693. LOGERROR("More than 4 color components are not supported");
  694. return false;
  695. }
  696. data_ = new unsigned char[width * height * depth * components];
  697. width_ = width;
  698. height_ = height;
  699. depth_ = depth;
  700. components_ = components;
  701. compressedFormat_ = CF_NONE;
  702. numCompressedLevels_ = 0;
  703. nextLevel_.Reset();
  704. SetMemoryUse(width * height * depth * components);
  705. return true;
  706. }
  707. void Image::SetPixel(int x, int y, const Color& color)
  708. {
  709. SetPixelInt(x, y, 0, color.ToUInt());
  710. }
  711. void Image::SetPixel(int x, int y, int z, const Color& color)
  712. {
  713. SetPixelInt(x, y, z, color.ToUInt());
  714. }
  715. void Image::SetPixelInt(int x, int y, unsigned uintColor)
  716. {
  717. SetPixelInt(x, y, 0, uintColor);
  718. }
  719. void Image::SetPixelInt(int x, int y, int z, unsigned uintColor)
  720. {
  721. if (!data_ || x < 0 || x >= width_ || y < 0 || y >= height_ || z < 0 || z >= depth_ || IsCompressed())
  722. return;
  723. unsigned char* dest = data_ + (z * width_ * height_ + y * width_ + x) * components_;
  724. unsigned char* src = (unsigned char*)&uintColor;
  725. switch (components_)
  726. {
  727. case 4:
  728. dest[3] = src[3];
  729. // Fall through
  730. case 3:
  731. dest[2] = src[2];
  732. // Fall through
  733. case 2:
  734. dest[1] = src[1];
  735. // Fall through
  736. default:
  737. dest[0] = src[0];
  738. break;
  739. }
  740. }
  741. void Image::SetData(const unsigned char* pixelData)
  742. {
  743. if (!data_)
  744. return;
  745. if (IsCompressed())
  746. {
  747. LOGERROR("Can not set new pixel data for a compressed image");
  748. return;
  749. }
  750. memcpy(data_.Get(), pixelData, width_ * height_ * depth_ * components_);
  751. nextLevel_.Reset();
  752. }
  753. bool Image::LoadColorLUT(Deserializer& source)
  754. {
  755. String fileID = source.ReadFileID();
  756. if (fileID == "DDS " || fileID == "\253KTX" || fileID == "PVR\3")
  757. {
  758. LOGERROR("Invalid image format, can not load image");
  759. return false;
  760. }
  761. source.Seek(0);
  762. int width, height;
  763. unsigned components;
  764. unsigned char* pixelDataIn = GetImageData(source, width, height, components);
  765. if (!pixelDataIn)
  766. {
  767. LOGERROR("Could not load image " + source.GetName() + ": " + String(stbi_failure_reason()));
  768. return false;
  769. }
  770. if (components != 3)
  771. {
  772. LOGERROR("Invalid image format, can not load image");
  773. return false;
  774. }
  775. SetSize(COLOR_LUT_SIZE, COLOR_LUT_SIZE, COLOR_LUT_SIZE, components);
  776. SetMemoryUse(width_ * height_ * depth_ * components);
  777. unsigned char* pixelDataOut = GetData();
  778. for (int z = 0; z < depth_; ++z)
  779. {
  780. for (int y = 0; y < height_; ++y)
  781. {
  782. unsigned char* in = &pixelDataIn[z * width_ * 3 + y * width * 3];
  783. unsigned char* out = &pixelDataOut[z * width_ * height_ * 3 + y * width_ * 3];
  784. for (int x = 0; x < width_ * 3; x += 3)
  785. {
  786. out[x] = in[x];
  787. out[x + 1] = in[x + 1];
  788. out[x + 2] = in[x + 2];
  789. }
  790. }
  791. }
  792. FreeImageData(pixelDataIn);
  793. return true;
  794. }
  795. bool Image::FlipHorizontal()
  796. {
  797. if (!data_)
  798. return false;
  799. if (depth_ > 1)
  800. {
  801. LOGERROR("FlipHorizontal not supported for 3D images");
  802. return false;
  803. }
  804. if (!IsCompressed())
  805. {
  806. SharedArrayPtr<unsigned char> newData(new unsigned char[width_ * height_ * components_]);
  807. unsigned rowSize = width_ * components_;
  808. for (int y = 0; y < height_; ++y)
  809. {
  810. for (int x = 0; x < width_; ++x)
  811. {
  812. for (unsigned c = 0; c < components_; ++c)
  813. newData[y * rowSize + x * components_ + c] = data_[y * rowSize + (width_ - x - 1) * components_ + c];
  814. }
  815. }
  816. data_ = newData;
  817. }
  818. else
  819. {
  820. if (compressedFormat_ > CF_DXT5)
  821. {
  822. LOGERROR("FlipHorizontal not yet implemented for other compressed formats than RGBA & DXT1,3,5");
  823. return false;
  824. }
  825. // Memory use = combined size of the compressed mip levels
  826. SharedArrayPtr<unsigned char> newData(new unsigned char[GetMemoryUse()]);
  827. unsigned dataOffset = 0;
  828. for (unsigned i = 0; i < numCompressedLevels_; ++i)
  829. {
  830. CompressedLevel level = GetCompressedLevel(i);
  831. if (!level.data_)
  832. {
  833. LOGERROR("Got compressed level with no data, aborting horizontal flip");
  834. return false;
  835. }
  836. for (unsigned y = 0; y < level.rows_; ++y)
  837. {
  838. for (unsigned x = 0; x < level.rowSize_; x += level.blockSize_)
  839. {
  840. unsigned char* src = level.data_ + y * level.rowSize_ + (level.rowSize_ - level.blockSize_ - x);
  841. unsigned char* dest = newData.Get() + y * level.rowSize_ + x;
  842. FlipBlockHorizontal(dest, src, compressedFormat_);
  843. }
  844. }
  845. dataOffset += level.dataSize_;
  846. }
  847. data_ = newData;
  848. }
  849. return true;
  850. }
  851. bool Image::FlipVertical()
  852. {
  853. if (!data_)
  854. return false;
  855. if (depth_ > 1)
  856. {
  857. LOGERROR("FlipVertical not supported for 3D images");
  858. return false;
  859. }
  860. if (!IsCompressed())
  861. {
  862. SharedArrayPtr<unsigned char> newData(new unsigned char[width_ * height_ * components_]);
  863. unsigned rowSize = width_ * components_;
  864. for (int y = 0; y < height_; ++y)
  865. memcpy(&newData[(height_ - y - 1) * rowSize], &data_[y * rowSize], rowSize);
  866. data_ = newData;
  867. }
  868. else
  869. {
  870. if (compressedFormat_ > CF_DXT5)
  871. {
  872. LOGERROR("FlipVertical not yet implemented for other compressed formats than DXT1,3,5");
  873. return false;
  874. }
  875. // Memory use = combined size of the compressed mip levels
  876. SharedArrayPtr<unsigned char> newData(new unsigned char[GetMemoryUse()]);
  877. unsigned dataOffset = 0;
  878. for (unsigned i = 0; i < numCompressedLevels_; ++i)
  879. {
  880. CompressedLevel level = GetCompressedLevel(i);
  881. if (!level.data_)
  882. {
  883. LOGERROR("Got compressed level with no data, aborting vertical flip");
  884. return false;
  885. }
  886. for (unsigned y = 0; y < level.rows_; ++y)
  887. {
  888. unsigned char* src = level.data_ + y * level.rowSize_;
  889. unsigned char* dest = newData.Get() + dataOffset + (level.rows_ - y - 1) * level.rowSize_;
  890. for (unsigned x = 0; x < level.rowSize_; x += level.blockSize_)
  891. FlipBlockVertical(dest + x, src + x, compressedFormat_);
  892. }
  893. dataOffset += level.dataSize_;
  894. }
  895. data_ = newData;
  896. }
  897. return true;
  898. }
  899. bool Image::Resize(int width, int height)
  900. {
  901. PROFILE(ResizeImage);
  902. if (IsCompressed())
  903. {
  904. LOGERROR("Resize not supported for compressed images");
  905. return false;
  906. }
  907. if (depth_ > 1)
  908. {
  909. LOGERROR("Resize not supported for 3D images");
  910. return false;
  911. }
  912. if (!data_ || width <= 0 || height <= 0)
  913. return false;
  914. /// \todo Reducing image size does not sample all needed pixels
  915. SharedArrayPtr<unsigned char> newData(new unsigned char[width * height * components_]);
  916. for (int y = 0; y < height; ++y)
  917. {
  918. for (int x = 0; x < width; ++x)
  919. {
  920. // Calculate float coordinates between 0 - 1 for resampling
  921. float xF = (width_ > 1) ? (float)x / (float)(width - 1) : 0.0f;
  922. float yF = (height_ > 1) ? (float)y / (float)(height - 1) : 0.0f;
  923. unsigned uintColor = GetPixelBilinear(xF, yF).ToUInt();
  924. unsigned char* dest = newData + (y * width + x) * components_;
  925. unsigned char* src = (unsigned char*)&uintColor;
  926. switch (components_)
  927. {
  928. case 4:
  929. dest[3] = src[3];
  930. // Fall through
  931. case 3:
  932. dest[2] = src[2];
  933. // Fall through
  934. case 2:
  935. dest[1] = src[1];
  936. // Fall through
  937. default:
  938. dest[0] = src[0];
  939. break;
  940. }
  941. }
  942. }
  943. width_ = width;
  944. height_ = height;
  945. data_ = newData;
  946. SetMemoryUse(width * height * depth_ * components_);
  947. return true;
  948. }
  949. void Image::Clear(const Color& color)
  950. {
  951. ClearInt(color.ToUInt());
  952. }
  953. void Image::ClearInt(unsigned uintColor)
  954. {
  955. PROFILE(ClearImage);
  956. if (!data_)
  957. return;
  958. if (IsCompressed())
  959. {
  960. LOGERROR("Clear not supported for compressed images");
  961. return;
  962. }
  963. unsigned char* src = (unsigned char*)&uintColor;
  964. for (unsigned i = 0; i < width_ * height_ * depth_ * components_; ++i)
  965. data_[i] = src[i % components_];
  966. }
  967. bool Image::SaveBMP(const String& fileName) const
  968. {
  969. PROFILE(SaveImageBMP);
  970. FileSystem* fileSystem = GetSubsystem<FileSystem>();
  971. if (fileSystem && !fileSystem->CheckAccess(GetPath(fileName)))
  972. {
  973. LOGERROR("Access denied to " + fileName);
  974. return false;
  975. }
  976. if (IsCompressed())
  977. {
  978. LOGERROR("Can not save compressed image to BMP");
  979. return false;
  980. }
  981. if (data_)
  982. return stbi_write_bmp(fileName.CString(), width_, height_, components_, data_.Get()) != 0;
  983. else
  984. return false;
  985. }
  986. bool Image::SavePNG(const String& fileName) const
  987. {
  988. PROFILE(SaveImagePNG);
  989. FileSystem* fileSystem = GetSubsystem<FileSystem>();
  990. if (fileSystem && !fileSystem->CheckAccess(GetPath(fileName)))
  991. {
  992. LOGERROR("Access denied to " + fileName);
  993. return false;
  994. }
  995. if (IsCompressed())
  996. {
  997. LOGERROR("Can not save compressed image to PNG");
  998. return false;
  999. }
  1000. if (data_)
  1001. return stbi_write_png(GetNativePath(fileName).CString(), width_, height_, components_, data_.Get(), 0) != 0;
  1002. else
  1003. return false;
  1004. }
  1005. bool Image::SaveTGA(const String& fileName) const
  1006. {
  1007. PROFILE(SaveImageTGA);
  1008. FileSystem* fileSystem = GetSubsystem<FileSystem>();
  1009. if (fileSystem && !fileSystem->CheckAccess(GetPath(fileName)))
  1010. {
  1011. LOGERROR("Access denied to " + fileName);
  1012. return false;
  1013. }
  1014. if (IsCompressed())
  1015. {
  1016. LOGERROR("Can not save compressed image to TGA");
  1017. return false;
  1018. }
  1019. if (data_)
  1020. return stbi_write_tga(GetNativePath(fileName).CString(), width_, height_, components_, data_.Get()) != 0;
  1021. else
  1022. return false;
  1023. }
  1024. bool Image::SaveJPG(const String& fileName, int quality) const
  1025. {
  1026. PROFILE(SaveImageJPG);
  1027. FileSystem* fileSystem = GetSubsystem<FileSystem>();
  1028. if (fileSystem && !fileSystem->CheckAccess(GetPath(fileName)))
  1029. {
  1030. LOGERROR("Access denied to " + fileName);
  1031. return false;
  1032. }
  1033. if (IsCompressed())
  1034. {
  1035. LOGERROR("Can not save compressed image to JPG");
  1036. return false;
  1037. }
  1038. if (data_)
  1039. return jo_write_jpg(GetNativePath(fileName).CString(), data_.Get(), width_, height_, components_, quality) != 0;
  1040. else
  1041. return false;
  1042. }
  1043. bool Image::SaveDDS(const String& fileName) const
  1044. {
  1045. #if !defined(ATOMIC_PLATFORM_DESKTOP)
  1046. LOGERRORF("Image::SaveDDS - Unsupported on current platform: %s", fileName.CString());
  1047. return false;
  1048. #else
  1049. PROFILE(SaveImageDDS);
  1050. FileSystem* fileSystem = GetSubsystem<FileSystem>();
  1051. if (fileSystem && !fileSystem->CheckAccess(GetPath(fileName)))
  1052. {
  1053. LOGERROR("Access denied to " + fileName);
  1054. return false;
  1055. }
  1056. if (IsCompressed())
  1057. {
  1058. LOGERROR("Can not save compressed image to DDS");
  1059. return false;
  1060. }
  1061. if (data_)
  1062. {
  1063. // #623 BEGIN TODO: Should have an abstract ImageReader and ImageWriter classes
  1064. // with subclasses for particular image output types. Also should have image settings in the image meta.
  1065. // ImageReader/Writers should also support a progress callback so UI can be updated.
  1066. if (!width_ || !height_)
  1067. {
  1068. LOGERRORF("Attempting to save zero width/height DDS to %s", fileName.CString());
  1069. return false;
  1070. }
  1071. squish::u8 *inputData = (squish::u8 *) data_.Get();
  1072. SharedPtr<Image> tempImage;
  1073. // libsquish expects 4 channel RGBA, so create a temporary image if necessary
  1074. if (components_ != 4)
  1075. {
  1076. if (components_ != 3)
  1077. {
  1078. LOGERROR("Can only save images with 3 or 4 components to DDS");
  1079. return false;
  1080. }
  1081. tempImage = new Image(context_);
  1082. tempImage->SetSize(width_, height_, 4);
  1083. squish::u8* srcBits = (squish::u8*) data_;
  1084. squish::u8* dstBits = (squish::u8*) tempImage->data_;
  1085. for (unsigned i = 0; i < width_ * height_ * 4; i++)
  1086. {
  1087. *dstBits++ = *srcBits++;
  1088. *dstBits++ = *srcBits++;
  1089. *dstBits++ = *srcBits++;
  1090. *dstBits++ = 255;
  1091. }
  1092. inputData = (squish::u8 *) tempImage->data_.Get();
  1093. }
  1094. unsigned storageRequirements = (unsigned) squish::GetStorageRequirements( width_, height_, HasAlphaChannel() ? squish::kDxt5 : squish::kDxt1 );
  1095. SharedArrayPtr<unsigned char> compressedData(new unsigned char[storageRequirements]);
  1096. squish::CompressImage(inputData, width_, height_, compressedData.Get(), HasAlphaChannel() ? squish::kDxt5 : squish::kDxt1);
  1097. if (compressedData)
  1098. {
  1099. LOGERROR("Failed to compress image to DXT");
  1100. return false;
  1101. }
  1102. SharedPtr<File> dest(new File(context_, fileName, FILE_WRITE));
  1103. if (!dest->IsOpen())
  1104. {
  1105. LOGERRORF("Failed to open DXT image file for writing %s", fileName.CString());
  1106. return false;
  1107. }
  1108. else
  1109. {
  1110. bool success = dest->Write(compressedData.Get(), storageRequirements) == storageRequirements;
  1111. if (!success)
  1112. LOGERRORF("Failed to write image to DXT, file size mismatch %s", fileName.CString());
  1113. return success;
  1114. }
  1115. // #623 END TODO
  1116. }
  1117. #endif
  1118. return false;
  1119. }
  1120. bool Image::IsPOT() const
  1121. {
  1122. return IsPowerOfTwo(width_) && IsPowerOfTwo(height_);
  1123. }
  1124. bool Image::HasAlphaChannel() const
  1125. {
  1126. return components_ > 3;
  1127. }
  1128. Color Image::GetPixel(int x, int y) const
  1129. {
  1130. return GetPixel(x, y, 0);
  1131. }
  1132. Color Image::GetPixel(int x, int y, int z) const
  1133. {
  1134. if (!data_ || z < 0 || z >= depth_ || IsCompressed())
  1135. return Color::BLACK;
  1136. x = Clamp(x, 0, width_ - 1);
  1137. y = Clamp(y, 0, height_ - 1);
  1138. unsigned char* src = data_ + (z * width_ * height_ + y * width_ + x) * components_;
  1139. Color ret;
  1140. switch (components_)
  1141. {
  1142. case 4:
  1143. ret.a_ = (float)src[3] / 255.0f;
  1144. // Fall through
  1145. case 3:
  1146. ret.b_ = (float)src[2] / 255.0f;
  1147. // Fall through
  1148. case 2:
  1149. ret.g_ = (float)src[1] / 255.0f;
  1150. ret.r_ = (float)src[0] / 255.0f;
  1151. break;
  1152. default:
  1153. ret.r_ = ret.g_ = ret.b_ = (float)src[0] / 255.0f;
  1154. break;
  1155. }
  1156. return ret;
  1157. }
  1158. unsigned Image::GetPixelInt(int x, int y) const
  1159. {
  1160. return GetPixelInt(x, y, 0);
  1161. }
  1162. unsigned Image::GetPixelInt(int x, int y, int z) const
  1163. {
  1164. if (!data_ || z < 0 || z >= depth_ || IsCompressed())
  1165. return 0xff000000;
  1166. x = Clamp(x, 0, width_ - 1);
  1167. y = Clamp(y, 0, height_ - 1);
  1168. unsigned char* src = data_ + (z * width_ * height_ + y * width_ + x) * components_;
  1169. unsigned ret = 0;
  1170. if (components_ < 4)
  1171. ret |= 0xff000000;
  1172. switch (components_)
  1173. {
  1174. case 4:
  1175. ret |= (unsigned)src[3] << 24;
  1176. // Fall through
  1177. case 3:
  1178. ret |= (unsigned)src[2] << 16;
  1179. // Fall through
  1180. case 2:
  1181. ret |= (unsigned)src[1] << 8;
  1182. ret |= (unsigned)src[0];
  1183. break;
  1184. default:
  1185. ret |= (unsigned)src[0] << 16;
  1186. ret |= (unsigned)src[0] << 8;
  1187. ret |= (unsigned)src[0];
  1188. break;
  1189. }
  1190. return ret;
  1191. }
  1192. Color Image::GetPixelBilinear(float x, float y) const
  1193. {
  1194. x = Clamp(x * width_ - 0.5f, 0.0f, (float)(width_ - 1));
  1195. y = Clamp(y * height_ - 0.5f, 0.0f, (float)(height_ - 1));
  1196. int xI = (int)x;
  1197. int yI = (int)y;
  1198. float xF = x - floorf(x);
  1199. float yF = y - floorf(y);
  1200. Color topColor = GetPixel(xI, yI).Lerp(GetPixel(xI + 1, yI), xF);
  1201. Color bottomColor = GetPixel(xI, yI + 1).Lerp(GetPixel(xI + 1, yI + 1), xF);
  1202. return topColor.Lerp(bottomColor, yF);
  1203. }
  1204. Color Image::GetPixelTrilinear(float x, float y, float z) const
  1205. {
  1206. if (depth_ < 2)
  1207. return GetPixelBilinear(x, y);
  1208. x = Clamp(x * width_ - 0.5f, 0.0f, (float)(width_ - 1));
  1209. y = Clamp(y * height_ - 0.5f, 0.0f, (float)(height_ - 1));
  1210. z = Clamp(z * depth_ - 0.5f, 0.0f, (float)(depth_ - 1));
  1211. int xI = (int)x;
  1212. int yI = (int)y;
  1213. int zI = (int)z;
  1214. if (zI == depth_ - 1)
  1215. return GetPixelBilinear(x, y);
  1216. float xF = x - floorf(x);
  1217. float yF = y - floorf(y);
  1218. float zF = z - floorf(z);
  1219. Color topColorNear = GetPixel(xI, yI, zI).Lerp(GetPixel(xI + 1, yI, zI), xF);
  1220. Color bottomColorNear = GetPixel(xI, yI + 1, zI).Lerp(GetPixel(xI + 1, yI + 1, zI), xF);
  1221. Color colorNear = topColorNear.Lerp(bottomColorNear, yF);
  1222. Color topColorFar = GetPixel(xI, yI, zI + 1).Lerp(GetPixel(xI + 1, yI, zI + 1), xF);
  1223. Color bottomColorFar = GetPixel(xI, yI + 1, zI + 1).Lerp(GetPixel(xI + 1, yI + 1, zI + 1), xF);
  1224. Color colorFar = topColorFar.Lerp(bottomColorFar, yF);
  1225. return colorNear.Lerp(colorFar, zF);
  1226. }
  1227. SharedPtr<Image> Image::GetNextLevel() const
  1228. {
  1229. if (IsCompressed())
  1230. {
  1231. LOGERROR("Can not generate mip level from compressed data");
  1232. return SharedPtr<Image>();
  1233. }
  1234. if (components_ < 1 || components_ > 4)
  1235. {
  1236. LOGERROR("Illegal number of image components for mip level generation");
  1237. return SharedPtr<Image>();
  1238. }
  1239. if (nextLevel_)
  1240. return nextLevel_;
  1241. PROFILE(CalculateImageMipLevel);
  1242. int widthOut = width_ / 2;
  1243. int heightOut = height_ / 2;
  1244. int depthOut = depth_ / 2;
  1245. if (widthOut < 1)
  1246. widthOut = 1;
  1247. if (heightOut < 1)
  1248. heightOut = 1;
  1249. if (depthOut < 1)
  1250. depthOut = 1;
  1251. SharedPtr<Image> mipImage(new Image(context_));
  1252. if (depth_ > 1)
  1253. mipImage->SetSize(widthOut, heightOut, depthOut, components_);
  1254. else
  1255. mipImage->SetSize(widthOut, heightOut, components_);
  1256. const unsigned char* pixelDataIn = data_.Get();
  1257. unsigned char* pixelDataOut = mipImage->data_.Get();
  1258. // 1D case
  1259. if (depth_ == 1 && (height_ == 1 || width_ == 1))
  1260. {
  1261. // Loop using the larger dimension
  1262. if (widthOut < heightOut)
  1263. widthOut = heightOut;
  1264. switch (components_)
  1265. {
  1266. case 1:
  1267. for (int x = 0; x < widthOut; ++x)
  1268. pixelDataOut[x] = (unsigned char)(((unsigned)pixelDataIn[x * 2] + pixelDataIn[x * 2 + 1]) >> 1);
  1269. break;
  1270. case 2:
  1271. for (int x = 0; x < widthOut * 2; x += 2)
  1272. {
  1273. pixelDataOut[x] = (unsigned char)(((unsigned)pixelDataIn[x * 2] + pixelDataIn[x * 2 + 2]) >> 1);
  1274. pixelDataOut[x + 1] = (unsigned char)(((unsigned)pixelDataIn[x * 2 + 1] + pixelDataIn[x * 2 + 3]) >> 1);
  1275. }
  1276. break;
  1277. case 3:
  1278. for (int x = 0; x < widthOut * 3; x += 3)
  1279. {
  1280. pixelDataOut[x] = (unsigned char)(((unsigned)pixelDataIn[x * 2] + pixelDataIn[x * 2 + 3]) >> 1);
  1281. pixelDataOut[x + 1] = (unsigned char)(((unsigned)pixelDataIn[x * 2 + 1] + pixelDataIn[x * 2 + 4]) >> 1);
  1282. pixelDataOut[x + 2] = (unsigned char)(((unsigned)pixelDataIn[x * 2 + 2] + pixelDataIn[x * 2 + 5]) >> 1);
  1283. }
  1284. break;
  1285. case 4:
  1286. for (int x = 0; x < widthOut * 4; x += 4)
  1287. {
  1288. pixelDataOut[x] = (unsigned char)(((unsigned)pixelDataIn[x * 2] + pixelDataIn[x * 2 + 4]) >> 1);
  1289. pixelDataOut[x + 1] = (unsigned char)(((unsigned)pixelDataIn[x * 2 + 1] + pixelDataIn[x * 2 + 5]) >> 1);
  1290. pixelDataOut[x + 2] = (unsigned char)(((unsigned)pixelDataIn[x * 2 + 2] + pixelDataIn[x * 2 + 6]) >> 1);
  1291. pixelDataOut[x + 3] = (unsigned char)(((unsigned)pixelDataIn[x * 2 + 3] + pixelDataIn[x * 2 + 7]) >> 1);
  1292. }
  1293. break;
  1294. default:
  1295. assert(false); // Should never reach here
  1296. break;
  1297. }
  1298. }
  1299. // 2D case
  1300. else if (depth_ == 1)
  1301. {
  1302. switch (components_)
  1303. {
  1304. case 1:
  1305. for (int y = 0; y < heightOut; ++y)
  1306. {
  1307. const unsigned char* inUpper = &pixelDataIn[(y * 2) * width_];
  1308. const unsigned char* inLower = &pixelDataIn[(y * 2 + 1) * width_];
  1309. unsigned char* out = &pixelDataOut[y * widthOut];
  1310. for (int x = 0; x < widthOut; ++x)
  1311. {
  1312. out[x] = (unsigned char)(((unsigned)inUpper[x * 2] + inUpper[x * 2 + 1] +
  1313. inLower[x * 2] + inLower[x * 2 + 1]) >> 2);
  1314. }
  1315. }
  1316. break;
  1317. case 2:
  1318. for (int y = 0; y < heightOut; ++y)
  1319. {
  1320. const unsigned char* inUpper = &pixelDataIn[(y * 2) * width_ * 2];
  1321. const unsigned char* inLower = &pixelDataIn[(y * 2 + 1) * width_ * 2];
  1322. unsigned char* out = &pixelDataOut[y * widthOut * 2];
  1323. for (int x = 0; x < widthOut * 2; x += 2)
  1324. {
  1325. out[x] = (unsigned char)(((unsigned)inUpper[x * 2] + inUpper[x * 2 + 2] +
  1326. inLower[x * 2] + inLower[x * 2 + 2]) >> 2);
  1327. out[x + 1] = (unsigned char)(((unsigned)inUpper[x * 2 + 1] + inUpper[x * 2 + 3] +
  1328. inLower[x * 2 + 1] + inLower[x * 2 + 3]) >> 2);
  1329. }
  1330. }
  1331. break;
  1332. case 3:
  1333. for (int y = 0; y < heightOut; ++y)
  1334. {
  1335. const unsigned char* inUpper = &pixelDataIn[(y * 2) * width_ * 3];
  1336. const unsigned char* inLower = &pixelDataIn[(y * 2 + 1) * width_ * 3];
  1337. unsigned char* out = &pixelDataOut[y * widthOut * 3];
  1338. for (int x = 0; x < widthOut * 3; x += 3)
  1339. {
  1340. out[x] = (unsigned char)(((unsigned)inUpper[x * 2] + inUpper[x * 2 + 3] +
  1341. inLower[x * 2] + inLower[x * 2 + 3]) >> 2);
  1342. out[x + 1] = (unsigned char)(((unsigned)inUpper[x * 2 + 1] + inUpper[x * 2 + 4] +
  1343. inLower[x * 2 + 1] + inLower[x * 2 + 4]) >> 2);
  1344. out[x + 2] = (unsigned char)(((unsigned)inUpper[x * 2 + 2] + inUpper[x * 2 + 5] +
  1345. inLower[x * 2 + 2] + inLower[x * 2 + 5]) >> 2);
  1346. }
  1347. }
  1348. break;
  1349. case 4:
  1350. for (int y = 0; y < heightOut; ++y)
  1351. {
  1352. const unsigned char* inUpper = &pixelDataIn[(y * 2) * width_ * 4];
  1353. const unsigned char* inLower = &pixelDataIn[(y * 2 + 1) * width_ * 4];
  1354. unsigned char* out = &pixelDataOut[y * widthOut * 4];
  1355. for (int x = 0; x < widthOut * 4; x += 4)
  1356. {
  1357. out[x] = (unsigned char)(((unsigned)inUpper[x * 2] + inUpper[x * 2 + 4] +
  1358. inLower[x * 2] + inLower[x * 2 + 4]) >> 2);
  1359. out[x + 1] = (unsigned char)(((unsigned)inUpper[x * 2 + 1] + inUpper[x * 2 + 5] +
  1360. inLower[x * 2 + 1] + inLower[x * 2 + 5]) >> 2);
  1361. out[x + 2] = (unsigned char)(((unsigned)inUpper[x * 2 + 2] + inUpper[x * 2 + 6] +
  1362. inLower[x * 2 + 2] + inLower[x * 2 + 6]) >> 2);
  1363. out[x + 3] = (unsigned char)(((unsigned)inUpper[x * 2 + 3] + inUpper[x * 2 + 7] +
  1364. inLower[x * 2 + 3] + inLower[x * 2 + 7]) >> 2);
  1365. }
  1366. }
  1367. break;
  1368. default:
  1369. assert(false); // Should never reach here
  1370. break;
  1371. }
  1372. }
  1373. // 3D case
  1374. else
  1375. {
  1376. switch (components_)
  1377. {
  1378. case 1:
  1379. for (int z = 0; z < depthOut; ++z)
  1380. {
  1381. const unsigned char* inOuter = &pixelDataIn[(z * 2) * width_ * height_];
  1382. const unsigned char* inInner = &pixelDataIn[(z * 2 + 1) * width_ * height_];
  1383. for (int y = 0; y < heightOut; ++y)
  1384. {
  1385. const unsigned char* inOuterUpper = &inOuter[(y * 2) * width_];
  1386. const unsigned char* inOuterLower = &inOuter[(y * 2 + 1) * width_];
  1387. const unsigned char* inInnerUpper = &inInner[(y * 2) * width_];
  1388. const unsigned char* inInnerLower = &inInner[(y * 2 + 1) * width_];
  1389. unsigned char* out = &pixelDataOut[z * widthOut * heightOut + y * widthOut];
  1390. for (int x = 0; x < widthOut; ++x)
  1391. {
  1392. out[x] = (unsigned char)(((unsigned)inOuterUpper[x * 2] + inOuterUpper[x * 2 + 1] +
  1393. inOuterLower[x * 2] + inOuterLower[x * 2 + 1] +
  1394. inInnerUpper[x * 2] + inInnerUpper[x * 2 + 1] +
  1395. inInnerLower[x * 2] + inInnerLower[x * 2 + 1]) >> 3);
  1396. }
  1397. }
  1398. }
  1399. break;
  1400. case 2:
  1401. for (int z = 0; z < depthOut; ++z)
  1402. {
  1403. const unsigned char* inOuter = &pixelDataIn[(z * 2) * width_ * height_ * 2];
  1404. const unsigned char* inInner = &pixelDataIn[(z * 2 + 1) * width_ * height_ * 2];
  1405. for (int y = 0; y < heightOut; ++y)
  1406. {
  1407. const unsigned char* inOuterUpper = &inOuter[(y * 2) * width_ * 2];
  1408. const unsigned char* inOuterLower = &inOuter[(y * 2 + 1) * width_ * 2];
  1409. const unsigned char* inInnerUpper = &inInner[(y * 2) * width_ * 2];
  1410. const unsigned char* inInnerLower = &inInner[(y * 2 + 1) * width_ * 2];
  1411. unsigned char* out = &pixelDataOut[z * widthOut * heightOut * 2 + y * widthOut * 2];
  1412. for (int x = 0; x < widthOut * 2; x += 2)
  1413. {
  1414. out[x] = (unsigned char)(((unsigned)inOuterUpper[x * 2] + inOuterUpper[x * 2 + 2] +
  1415. inOuterLower[x * 2] + inOuterLower[x * 2 + 2] +
  1416. inInnerUpper[x * 2] + inInnerUpper[x * 2 + 2] +
  1417. inInnerLower[x * 2] + inInnerLower[x * 2 + 2]) >> 3);
  1418. out[x + 1] = (unsigned char)(((unsigned)inOuterUpper[x * 2 + 1] + inOuterUpper[x * 2 + 3] +
  1419. inOuterLower[x * 2 + 1] + inOuterLower[x * 2 + 3] +
  1420. inInnerUpper[x * 2 + 1] + inInnerUpper[x * 2 + 3] +
  1421. inInnerLower[x * 2 + 1] + inInnerLower[x * 2 + 3]) >> 3);
  1422. }
  1423. }
  1424. }
  1425. break;
  1426. case 3:
  1427. for (int z = 0; z < depthOut; ++z)
  1428. {
  1429. const unsigned char* inOuter = &pixelDataIn[(z * 2) * width_ * height_ * 3];
  1430. const unsigned char* inInner = &pixelDataIn[(z * 2 + 1) * width_ * height_ * 3];
  1431. for (int y = 0; y < heightOut; ++y)
  1432. {
  1433. const unsigned char* inOuterUpper = &inOuter[(y * 2) * width_ * 3];
  1434. const unsigned char* inOuterLower = &inOuter[(y * 2 + 1) * width_ * 3];
  1435. const unsigned char* inInnerUpper = &inInner[(y * 2) * width_ * 3];
  1436. const unsigned char* inInnerLower = &inInner[(y * 2 + 1) * width_ * 3];
  1437. unsigned char* out = &pixelDataOut[z * widthOut * heightOut * 3 + y * widthOut * 3];
  1438. for (int x = 0; x < widthOut * 3; x += 3)
  1439. {
  1440. out[x] = (unsigned char)(((unsigned)inOuterUpper[x * 2] + inOuterUpper[x * 2 + 3] +
  1441. inOuterLower[x * 2] + inOuterLower[x * 2 + 3] +
  1442. inInnerUpper[x * 2] + inInnerUpper[x * 2 + 3] +
  1443. inInnerLower[x * 2] + inInnerLower[x * 2 + 3]) >> 3);
  1444. out[x + 1] = (unsigned char)(((unsigned)inOuterUpper[x * 2 + 1] + inOuterUpper[x * 2 + 4] +
  1445. inOuterLower[x * 2 + 1] + inOuterLower[x * 2 + 4] +
  1446. inInnerUpper[x * 2 + 1] + inInnerUpper[x * 2 + 4] +
  1447. inInnerLower[x * 2 + 1] + inInnerLower[x * 2 + 4]) >> 3);
  1448. out[x + 2] = (unsigned char)(((unsigned)inOuterUpper[x * 2 + 2] + inOuterUpper[x * 2 + 5] +
  1449. inOuterLower[x * 2 + 2] + inOuterLower[x * 2 + 5] +
  1450. inInnerUpper[x * 2 + 2] + inInnerUpper[x * 2 + 5] +
  1451. inInnerLower[x * 2 + 2] + inInnerLower[x * 2 + 5]) >> 3);
  1452. }
  1453. }
  1454. }
  1455. break;
  1456. case 4:
  1457. for (int z = 0; z < depthOut; ++z)
  1458. {
  1459. const unsigned char* inOuter = &pixelDataIn[(z * 2) * width_ * height_ * 4];
  1460. const unsigned char* inInner = &pixelDataIn[(z * 2 + 1) * width_ * height_ * 4];
  1461. for (int y = 0; y < heightOut; ++y)
  1462. {
  1463. const unsigned char* inOuterUpper = &inOuter[(y * 2) * width_ * 4];
  1464. const unsigned char* inOuterLower = &inOuter[(y * 2 + 1) * width_ * 4];
  1465. const unsigned char* inInnerUpper = &inInner[(y * 2) * width_ * 4];
  1466. const unsigned char* inInnerLower = &inInner[(y * 2 + 1) * width_ * 4];
  1467. unsigned char* out = &pixelDataOut[z * widthOut * heightOut * 4 + y * widthOut * 4];
  1468. for (int x = 0; x < widthOut * 4; x += 4)
  1469. {
  1470. out[x] = (unsigned char)(((unsigned)inOuterUpper[x * 2] + inOuterUpper[x * 2 + 4] +
  1471. inOuterLower[x * 2] + inOuterLower[x * 2 + 4] +
  1472. inInnerUpper[x * 2] + inInnerUpper[x * 2 + 4] +
  1473. inInnerLower[x * 2] + inInnerLower[x * 2 + 4]) >> 3);
  1474. out[x + 1] = (unsigned char)(((unsigned)inOuterUpper[x * 2 + 1] + inOuterUpper[x * 2 + 5] +
  1475. inOuterLower[x * 2 + 1] + inOuterLower[x * 2 + 5] +
  1476. inInnerUpper[x * 2 + 1] + inInnerUpper[x * 2 + 5] +
  1477. inInnerLower[x * 2 + 1] + inInnerLower[x * 2 + 5]) >> 3);
  1478. out[x + 2] = (unsigned char)(((unsigned)inOuterUpper[x * 2 + 2] + inOuterUpper[x * 2 + 6] +
  1479. inOuterLower[x * 2 + 2] + inOuterLower[x * 2 + 6] +
  1480. inInnerUpper[x * 2 + 2] + inInnerUpper[x * 2 + 6] +
  1481. inInnerLower[x * 2 + 2] + inInnerLower[x * 2 + 6]) >> 3);
  1482. }
  1483. }
  1484. }
  1485. break;
  1486. default:
  1487. assert(false); // Should never reach here
  1488. break;
  1489. }
  1490. }
  1491. return mipImage;
  1492. }
  1493. SharedPtr<Image> Image::ConvertToRGBA() const
  1494. {
  1495. if (IsCompressed())
  1496. {
  1497. LOGERROR("Can not convert compressed image to RGBA");
  1498. return SharedPtr<Image>();
  1499. }
  1500. if (components_ < 1 || components_ > 4)
  1501. {
  1502. LOGERROR("Illegal number of image components for conversion to RGBA");
  1503. return SharedPtr<Image>();
  1504. }
  1505. if (!data_)
  1506. {
  1507. LOGERROR("Can not convert image without data to RGBA");
  1508. return SharedPtr<Image>();
  1509. }
  1510. // Already RGBA?
  1511. if (components_ == 4)
  1512. return SharedPtr<Image>(const_cast<Image*>(this));
  1513. SharedPtr<Image> ret(new Image(context_));
  1514. ret->SetSize(width_, height_, depth_, 4);
  1515. const unsigned char* src = data_;
  1516. unsigned char* dest = ret->GetData();
  1517. switch (components_)
  1518. {
  1519. case 1:
  1520. for (unsigned i = 0; i < static_cast<unsigned>(width_ * height_ * depth_); ++i)
  1521. {
  1522. unsigned char pixel = *src++;
  1523. *dest++ = pixel;
  1524. *dest++ = pixel;
  1525. *dest++ = pixel;
  1526. *dest++ = 255;
  1527. }
  1528. break;
  1529. case 2:
  1530. for (unsigned i = 0; i < static_cast<unsigned>(width_ * height_ * depth_); ++i)
  1531. {
  1532. unsigned char pixel = *src++;
  1533. *dest++ = pixel;
  1534. *dest++ = pixel;
  1535. *dest++ = pixel;
  1536. *dest++ = *src++;
  1537. }
  1538. break;
  1539. case 3:
  1540. for (unsigned i = 0; i < static_cast<unsigned>(width_ * height_ * depth_); ++i)
  1541. {
  1542. *dest++ = *src++;
  1543. *dest++ = *src++;
  1544. *dest++ = *src++;
  1545. *dest++ = 255;
  1546. }
  1547. break;
  1548. default:
  1549. assert(false); // Should never reach nere
  1550. break;
  1551. }
  1552. return ret;
  1553. }
  1554. CompressedLevel Image::GetCompressedLevel(unsigned index) const
  1555. {
  1556. CompressedLevel level;
  1557. if (compressedFormat_ == CF_NONE)
  1558. {
  1559. LOGERROR("Image is not compressed");
  1560. return level;
  1561. }
  1562. if (index >= numCompressedLevels_)
  1563. {
  1564. LOGERROR("Compressed image mip level out of bounds");
  1565. return level;
  1566. }
  1567. level.format_ = compressedFormat_;
  1568. level.width_ = width_;
  1569. level.height_ = height_;
  1570. level.depth_ = depth_;
  1571. if (compressedFormat_ == CF_RGBA)
  1572. {
  1573. level.blockSize_ = 4;
  1574. unsigned i = 0;
  1575. unsigned offset = 0;
  1576. for (;;)
  1577. {
  1578. if (!level.width_)
  1579. level.width_ = 1;
  1580. if (!level.height_)
  1581. level.height_ = 1;
  1582. if (!level.depth_)
  1583. level.depth_ = 1;
  1584. level.rowSize_ = level.width_ * level.blockSize_;
  1585. level.rows_ = (unsigned)level.height_;
  1586. level.data_ = data_.Get() + offset;
  1587. level.dataSize_ = level.depth_ * level.rows_ * level.rowSize_;
  1588. if (offset + level.dataSize_ > GetMemoryUse())
  1589. {
  1590. LOGERROR("Compressed level is outside image data. Offset: " + String(offset) + " Size: " + String(level.dataSize_) +
  1591. " Datasize: " + String(GetMemoryUse()));
  1592. level.data_ = 0;
  1593. return level;
  1594. }
  1595. if (i == index)
  1596. return level;
  1597. offset += level.dataSize_;
  1598. level.width_ /= 2;
  1599. level.height_ /= 2;
  1600. level.depth_ /= 2;
  1601. ++i;
  1602. }
  1603. }
  1604. else if (compressedFormat_ < CF_PVRTC_RGB_2BPP)
  1605. {
  1606. level.blockSize_ = (compressedFormat_ == CF_DXT1 || compressedFormat_ == CF_ETC1) ? 8 : 16;
  1607. unsigned i = 0;
  1608. unsigned offset = 0;
  1609. for (;;)
  1610. {
  1611. if (!level.width_)
  1612. level.width_ = 1;
  1613. if (!level.height_)
  1614. level.height_ = 1;
  1615. if (!level.depth_)
  1616. level.depth_ = 1;
  1617. level.rowSize_ = ((level.width_ + 3) / 4) * level.blockSize_;
  1618. level.rows_ = (unsigned)((level.height_ + 3) / 4);
  1619. level.data_ = data_.Get() + offset;
  1620. level.dataSize_ = level.depth_ * level.rows_ * level.rowSize_;
  1621. if (offset + level.dataSize_ > GetMemoryUse())
  1622. {
  1623. LOGERROR("Compressed level is outside image data. Offset: " + String(offset) + " Size: " + String(level.dataSize_) +
  1624. " Datasize: " + String(GetMemoryUse()));
  1625. level.data_ = 0;
  1626. return level;
  1627. }
  1628. if (i == index)
  1629. return level;
  1630. offset += level.dataSize_;
  1631. level.width_ /= 2;
  1632. level.height_ /= 2;
  1633. level.depth_ /= 2;
  1634. ++i;
  1635. }
  1636. }
  1637. else
  1638. {
  1639. level.blockSize_ = compressedFormat_ < CF_PVRTC_RGB_4BPP ? 2 : 4;
  1640. unsigned i = 0;
  1641. unsigned offset = 0;
  1642. for (;;)
  1643. {
  1644. if (!level.width_)
  1645. level.width_ = 1;
  1646. if (!level.height_)
  1647. level.height_ = 1;
  1648. int dataWidth = Max(level.width_, level.blockSize_ == 2 ? 16 : 8);
  1649. int dataHeight = Max(level.height_, 8);
  1650. level.data_ = data_.Get() + offset;
  1651. level.dataSize_ = (dataWidth * dataHeight * level.blockSize_ + 7) >> 3;
  1652. level.rows_ = (unsigned)dataHeight;
  1653. level.rowSize_ = level.dataSize_ / level.rows_;
  1654. if (offset + level.dataSize_ > GetMemoryUse())
  1655. {
  1656. LOGERROR("Compressed level is outside image data. Offset: " + String(offset) + " Size: " + String(level.dataSize_) +
  1657. " Datasize: " + String(GetMemoryUse()));
  1658. level.data_ = 0;
  1659. return level;
  1660. }
  1661. if (i == index)
  1662. return level;
  1663. offset += level.dataSize_;
  1664. level.width_ /= 2;
  1665. level.height_ /= 2;
  1666. ++i;
  1667. }
  1668. }
  1669. }
  1670. Image* Image::GetSubimage(const IntRect& rect) const
  1671. {
  1672. if (!data_)
  1673. return 0;
  1674. if (depth_ > 1)
  1675. {
  1676. LOGERROR("Subimage not supported for 3D images");
  1677. return 0;
  1678. }
  1679. if (rect.left_ < 0 || rect.top_ < 0 || rect.right_ > width_ || rect.bottom_ > height_ || !rect.Width() || !rect.Height())
  1680. {
  1681. LOGERROR("Can not get subimage from image " + GetName() + " with invalid region");
  1682. return 0;
  1683. }
  1684. if (!IsCompressed())
  1685. {
  1686. int x = rect.left_;
  1687. int y = rect.top_;
  1688. int width = rect.Width();
  1689. int height = rect.Height();
  1690. Image* image = new Image(context_);
  1691. image->SetSize(width, height, components_);
  1692. unsigned char* dest = image->GetData();
  1693. unsigned char* src = data_.Get() + (y * width_ + x) * components_;
  1694. for (int i = 0; i < height; ++i)
  1695. {
  1696. memcpy(dest, src, width * components_);
  1697. dest += width * components_;
  1698. src += width_ * components_;
  1699. }
  1700. return image;
  1701. }
  1702. else
  1703. {
  1704. // Pad the region to be a multiple of block size
  1705. IntRect paddedRect = rect;
  1706. paddedRect.left_ = (rect.left_ / 4) * 4;
  1707. paddedRect.top_ = (rect.top_ / 4) * 4;
  1708. paddedRect.right_ = (rect.right_ / 4) * 4;
  1709. paddedRect.bottom_ = (rect.bottom_ / 4) * 4;
  1710. IntRect currentRect = paddedRect;
  1711. PODVector<unsigned char> subimageData;
  1712. unsigned subimageLevels = 0;
  1713. // Save as many mips as possible until the next mip would cross a block boundary
  1714. for (unsigned i = 0; i < numCompressedLevels_; ++i)
  1715. {
  1716. CompressedLevel level = GetCompressedLevel(i);
  1717. if (!level.data_)
  1718. break;
  1719. // Mips are stored continuously
  1720. unsigned destStartOffset = subimageData.Size();
  1721. unsigned destRowSize = currentRect.Width() / 4 * level.blockSize_;
  1722. unsigned destSize = currentRect.Height() / 4 * destRowSize;
  1723. if (!destSize)
  1724. break;
  1725. subimageData.Resize(destStartOffset + destSize);
  1726. unsigned char* dest = &subimageData[destStartOffset];
  1727. for (int y = currentRect.top_; y < currentRect.bottom_; y += 4)
  1728. {
  1729. unsigned char* src = level.data_ + level.rowSize_ * (y / 4) + currentRect.left_ / 4 * level.blockSize_;
  1730. memcpy(dest, src, destRowSize);
  1731. dest += destRowSize;
  1732. }
  1733. ++subimageLevels;
  1734. if ((currentRect.left_ & 4) || (currentRect.right_ & 4) || (currentRect.top_ & 4) || (currentRect.bottom_ & 4))
  1735. break;
  1736. else
  1737. {
  1738. currentRect.left_ /= 2;
  1739. currentRect.right_ /= 2;
  1740. currentRect.top_ /= 2;
  1741. currentRect.bottom_ /= 2;
  1742. }
  1743. }
  1744. if (!subimageLevels)
  1745. {
  1746. LOGERROR("Subimage region from compressed image " + GetName() + " did not produce any data");
  1747. return 0;
  1748. }
  1749. Image* image = new Image(context_);
  1750. image->width_ = paddedRect.Width();
  1751. image->height_ = paddedRect.Height();
  1752. image->depth_ = 1;
  1753. image->compressedFormat_ = compressedFormat_;
  1754. image->numCompressedLevels_ = subimageLevels;
  1755. image->components_ = components_;
  1756. image->data_ = new unsigned char[subimageData.Size()];
  1757. memcpy(image->data_.Get(), &subimageData[0], subimageData.Size());
  1758. image->SetMemoryUse(subimageData.Size());
  1759. return image;
  1760. }
  1761. }
  1762. SDL_Surface* Image::GetSDLSurface(const IntRect& rect) const
  1763. {
  1764. if (!data_)
  1765. return 0;
  1766. if (depth_ > 1)
  1767. {
  1768. LOGERROR("Can not get SDL surface from 3D image");
  1769. return 0;
  1770. }
  1771. if (IsCompressed())
  1772. {
  1773. LOGERROR("Can not get SDL surface from compressed image " + GetName());
  1774. return 0;
  1775. }
  1776. if (components_ < 3)
  1777. {
  1778. LOGERROR("Can not get SDL surface from image " + GetName() + " with less than 3 components");
  1779. return 0;
  1780. }
  1781. IntRect imageRect = rect;
  1782. // Use full image if illegal rect
  1783. if (imageRect.left_ < 0 || imageRect.top_ < 0 || imageRect.right_ > width_ || imageRect.bottom_ > height_ ||
  1784. imageRect.left_ >= imageRect.right_ || imageRect.top_ >= imageRect.bottom_)
  1785. {
  1786. imageRect.left_ = 0;
  1787. imageRect.top_ = 0;
  1788. imageRect.right_ = width_;
  1789. imageRect.bottom_ = height_;
  1790. }
  1791. int imageWidth = width_;
  1792. int width = imageRect.Width();
  1793. int height = imageRect.Height();
  1794. // Assume little-endian for all the supported platforms
  1795. unsigned rMask = 0x000000ff;
  1796. unsigned gMask = 0x0000ff00;
  1797. unsigned bMask = 0x00ff0000;
  1798. unsigned aMask = 0xff000000;
  1799. SDL_Surface* surface = SDL_CreateRGBSurface(0, width, height, components_ * 8, rMask, gMask, bMask, aMask);
  1800. if (surface)
  1801. {
  1802. SDL_LockSurface(surface);
  1803. unsigned char* destination = reinterpret_cast<unsigned char*>(surface->pixels);
  1804. unsigned char* source = data_ + components_ * (imageWidth * imageRect.top_ + imageRect.left_);
  1805. for (int i = 0; i < height; ++i)
  1806. {
  1807. memcpy(destination, source, components_ * width);
  1808. destination += surface->pitch;
  1809. source += components_ * imageWidth;
  1810. }
  1811. SDL_UnlockSurface(surface);
  1812. }
  1813. else
  1814. LOGERROR("Failed to create SDL surface from image " + GetName());
  1815. return surface;
  1816. }
  1817. void Image::PrecalculateLevels()
  1818. {
  1819. if (!data_ || IsCompressed())
  1820. return;
  1821. PROFILE(PrecalculateImageMipLevels);
  1822. nextLevel_.Reset();
  1823. if (width_ > 1 || height_ > 1)
  1824. {
  1825. SharedPtr<Image> current = GetNextLevel();
  1826. nextLevel_ = current;
  1827. while (current && (current->width_ > 1 || current->height_ > 1))
  1828. {
  1829. current->nextLevel_ = current->GetNextLevel();
  1830. current = current->nextLevel_;
  1831. }
  1832. }
  1833. }
  1834. unsigned char* Image::GetImageData(Deserializer& source, int& width, int& height, unsigned& components)
  1835. {
  1836. unsigned dataSize = source.GetSize();
  1837. SharedArrayPtr<unsigned char> buffer(new unsigned char[dataSize]);
  1838. source.Read(buffer.Get(), dataSize);
  1839. return stbi_load_from_memory(buffer.Get(), dataSize, &width, &height, (int*)&components, 0);
  1840. }
  1841. void Image::FreeImageData(unsigned char* pixelData)
  1842. {
  1843. if (!pixelData)
  1844. return;
  1845. stbi_image_free(pixelData);
  1846. }
  1847. }