Image.cpp 70 KB

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