Image.cpp 77 KB

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