Image.cpp 68 KB

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