Image.cpp 75 KB

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