Image.cpp 76 KB

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