Image.cpp 72 KB

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