Image.cpp 74 KB

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