Image.cpp 68 KB

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