Image.cpp 75 KB

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