Image.cpp 78 KB

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