Image.cpp 67 KB

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