CCImage.cpp 78 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487
  1. /****************************************************************************
  2. Copyright (c) 2010-2012 cocos2d-x.org
  3. Copyright (c) 2013-2016 Chukong Technologies Inc.
  4. Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
  5. http://www.cocos2d-x.org
  6. Permission is hereby granted, free of charge, to any person obtaining a copy
  7. of this software and associated documentation files (the "Software"), to deal
  8. in the Software without restriction, including without limitation the rights
  9. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  10. copies of the Software, and to permit persons to whom the Software is
  11. furnished to do so, subject to the following conditions:
  12. The above copyright notice and this permission notice shall be included in
  13. all copies or substantial portions of the Software.
  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 "platform/CCImage.h"
  23. #include <string>
  24. #include <ctype.h>
  25. #include "base/CCData.h"
  26. #include "base/ccConfig.h" // CC_USE_JPEG, CC_USE_TIFF, CC_USE_WEBP
  27. extern "C"
  28. {
  29. // To resolve link error when building 32bits with Xcode 6.
  30. // More information please refer to the discussion in https://github.com/cocos2d/cocos2d-x/pull/6986
  31. #if defined (__unix) || (CC_TARGET_PLATFORM == CC_PLATFORM_IOS)
  32. #ifndef __ENABLE_COMPATIBILITY_WITH_UNIX_2003__
  33. #define __ENABLE_COMPATIBILITY_WITH_UNIX_2003__
  34. #include <stdio.h>
  35. #include <dirent.h>
  36. FILE *fopen$UNIX2003( const char *filename, const char *mode )
  37. {
  38. return fopen(filename, mode);
  39. }
  40. size_t fwrite$UNIX2003( const void *a, size_t b, size_t c, FILE *d )
  41. {
  42. return fwrite(a, b, c, d);
  43. }
  44. int fputs$UNIX2003(const char *res1, FILE *res2){
  45. return fputs(res1,res2);
  46. }
  47. char *strerror$UNIX2003( int errnum )
  48. {
  49. return strerror(errnum);
  50. }
  51. DIR * opendir$INODE64$UNIX2003( char * dirName )
  52. {
  53. return opendir( dirName );
  54. }
  55. DIR * opendir$INODE64( char * dirName )
  56. {
  57. return opendir( dirName );
  58. }
  59. int closedir$UNIX2003(DIR * dir)
  60. {
  61. return closedir(dir);
  62. }
  63. struct dirent * readdir$INODE64( DIR * dir )
  64. {
  65. return readdir( dir );
  66. }
  67. #endif
  68. #endif
  69. #if CC_USE_PNG
  70. #include "png.h"
  71. #endif //CC_USE_PNG
  72. #if CC_USE_TIFF
  73. #include "tiffio.h"
  74. #endif //CC_USE_TIFF
  75. #include "base/etc1.h"
  76. #if CC_USE_JPEG
  77. #include "jpeglib.h"
  78. #include <setjmp.h>
  79. #endif // CC_USE_JPEG
  80. }
  81. #include "base/s3tc.h"
  82. #include "base/atitc.h"
  83. #include "base/pvr.h"
  84. #include "base/TGAlib.h"
  85. #if CC_USE_WEBP
  86. #include "decode.h"
  87. #endif // CC_USE_WEBP
  88. #include "base/ccMacros.h"
  89. #include "platform/CCCommon.h"
  90. #include "platform/CCStdC.h"
  91. #include "platform/CCFileUtils.h"
  92. #include "base/CCConfiguration.h"
  93. #include "base/ccUtils.h"
  94. #include "base/ZipUtils.h"
  95. #if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID)
  96. #include "platform/android/CCFileUtils-android.h"
  97. #endif
  98. #define CC_GL_ATC_RGB_AMD 0x8C92
  99. #define CC_GL_ATC_RGBA_EXPLICIT_ALPHA_AMD 0x8C93
  100. #define CC_GL_ATC_RGBA_INTERPOLATED_ALPHA_AMD 0x87EE
  101. NS_CC_BEGIN
  102. //////////////////////////////////////////////////////////////////////////
  103. //struct and data for pvr structure
  104. namespace
  105. {
  106. static const int PVR_TEXTURE_FLAG_TYPE_MASK = 0xff;
  107. static bool _PVRHaveAlphaPremultiplied = false;
  108. // Values taken from PVRTexture.h from http://www.imgtec.com
  109. enum class PVR2TextureFlag
  110. {
  111. Mipmap = (1<<8), // has mip map levels
  112. Twiddle = (1<<9), // is twiddled
  113. Bumpmap = (1<<10), // has normals encoded for a bump map
  114. Tiling = (1<<11), // is bordered for tiled pvr
  115. Cubemap = (1<<12), // is a cubemap/skybox
  116. FalseMipCol = (1<<13), // are there false colored MIP levels
  117. Volume = (1<<14), // is this a volume texture
  118. Alpha = (1<<15), // v2.1 is there transparency info in the texture
  119. VerticalFlip = (1<<16), // v2.1 is the texture vertically flipped
  120. };
  121. enum class PVR3TextureFlag
  122. {
  123. PremultipliedAlpha = (1<<1) // has premultiplied alpha
  124. };
  125. static const char gPVRTexIdentifier[5] = "PVR!";
  126. // v2
  127. enum class PVR2TexturePixelFormat : unsigned char
  128. {
  129. RGBA4444 = 0x10,
  130. RGBA5551,
  131. RGBA8888,
  132. RGB565,
  133. RGB555, // unsupported
  134. RGB888,
  135. I8,
  136. AI88,
  137. PVRTC2BPP_RGBA,
  138. PVRTC4BPP_RGBA,
  139. BGRA8888,
  140. A8,
  141. };
  142. // v3
  143. enum class PVR3TexturePixelFormat : uint64_t
  144. {
  145. PVRTC2BPP_RGB = 0ULL,
  146. PVRTC2BPP_RGBA = 1ULL,
  147. PVRTC4BPP_RGB = 2ULL,
  148. PVRTC4BPP_RGBA = 3ULL,
  149. PVRTC2_2BPP_RGBA = 4ULL,
  150. PVRTC2_4BPP_RGBA = 5ULL,
  151. ETC1 = 6ULL,
  152. DXT1 = 7ULL,
  153. DXT2 = 8ULL,
  154. DXT3 = 9ULL,
  155. DXT4 = 10ULL,
  156. DXT5 = 11ULL,
  157. BC1 = 7ULL,
  158. BC2 = 9ULL,
  159. BC3 = 11ULL,
  160. BC4 = 12ULL,
  161. BC5 = 13ULL,
  162. BC6 = 14ULL,
  163. BC7 = 15ULL,
  164. UYVY = 16ULL,
  165. YUY2 = 17ULL,
  166. BW1bpp = 18ULL,
  167. R9G9B9E5 = 19ULL,
  168. RGBG8888 = 20ULL,
  169. GRGB8888 = 21ULL,
  170. ETC2_RGB = 22ULL,
  171. ETC2_RGBA = 23ULL,
  172. ETC2_RGBA1 = 24ULL,
  173. EAC_R11_Unsigned = 25ULL,
  174. EAC_R11_Signed = 26ULL,
  175. EAC_RG11_Unsigned = 27ULL,
  176. EAC_RG11_Signed = 28ULL,
  177. BGRA8888 = 0x0808080861726762ULL,
  178. RGBA8888 = 0x0808080861626772ULL,
  179. RGBA4444 = 0x0404040461626772ULL,
  180. RGBA5551 = 0x0105050561626772ULL,
  181. RGB565 = 0x0005060500626772ULL,
  182. RGB888 = 0x0008080800626772ULL,
  183. A8 = 0x0000000800000061ULL,
  184. L8 = 0x000000080000006cULL,
  185. LA88 = 0x000008080000616cULL,
  186. };
  187. // v2
  188. typedef const std::map<PVR2TexturePixelFormat, Texture2D::PixelFormat> _pixel2_formathash;
  189. static const _pixel2_formathash::value_type v2_pixel_formathash_value[] =
  190. {
  191. _pixel2_formathash::value_type(PVR2TexturePixelFormat::BGRA8888, Texture2D::PixelFormat::BGRA8888),
  192. _pixel2_formathash::value_type(PVR2TexturePixelFormat::RGBA8888, Texture2D::PixelFormat::RGBA8888),
  193. _pixel2_formathash::value_type(PVR2TexturePixelFormat::RGBA4444, Texture2D::PixelFormat::RGBA4444),
  194. _pixel2_formathash::value_type(PVR2TexturePixelFormat::RGBA5551, Texture2D::PixelFormat::RGB5A1),
  195. _pixel2_formathash::value_type(PVR2TexturePixelFormat::RGB565, Texture2D::PixelFormat::RGB565),
  196. _pixel2_formathash::value_type(PVR2TexturePixelFormat::RGB888, Texture2D::PixelFormat::RGB888),
  197. _pixel2_formathash::value_type(PVR2TexturePixelFormat::A8, Texture2D::PixelFormat::A8),
  198. _pixel2_formathash::value_type(PVR2TexturePixelFormat::I8, Texture2D::PixelFormat::I8),
  199. _pixel2_formathash::value_type(PVR2TexturePixelFormat::AI88, Texture2D::PixelFormat::AI88),
  200. _pixel2_formathash::value_type(PVR2TexturePixelFormat::PVRTC2BPP_RGBA, Texture2D::PixelFormat::PVRTC2A),
  201. _pixel2_formathash::value_type(PVR2TexturePixelFormat::PVRTC4BPP_RGBA, Texture2D::PixelFormat::PVRTC4A),
  202. };
  203. static const int PVR2_MAX_TABLE_ELEMENTS = sizeof(v2_pixel_formathash_value) / sizeof(v2_pixel_formathash_value[0]);
  204. static const _pixel2_formathash v2_pixel_formathash(v2_pixel_formathash_value, v2_pixel_formathash_value + PVR2_MAX_TABLE_ELEMENTS);
  205. // v3
  206. typedef const std::map<PVR3TexturePixelFormat, Texture2D::PixelFormat> _pixel3_formathash;
  207. static _pixel3_formathash::value_type v3_pixel_formathash_value[] =
  208. {
  209. _pixel3_formathash::value_type(PVR3TexturePixelFormat::BGRA8888, Texture2D::PixelFormat::BGRA8888),
  210. _pixel3_formathash::value_type(PVR3TexturePixelFormat::RGBA8888, Texture2D::PixelFormat::RGBA8888),
  211. _pixel3_formathash::value_type(PVR3TexturePixelFormat::RGBA4444, Texture2D::PixelFormat::RGBA4444),
  212. _pixel3_formathash::value_type(PVR3TexturePixelFormat::RGBA5551, Texture2D::PixelFormat::RGB5A1),
  213. _pixel3_formathash::value_type(PVR3TexturePixelFormat::RGB565, Texture2D::PixelFormat::RGB565),
  214. _pixel3_formathash::value_type(PVR3TexturePixelFormat::RGB888, Texture2D::PixelFormat::RGB888),
  215. _pixel3_formathash::value_type(PVR3TexturePixelFormat::A8, Texture2D::PixelFormat::A8),
  216. _pixel3_formathash::value_type(PVR3TexturePixelFormat::L8, Texture2D::PixelFormat::I8),
  217. _pixel3_formathash::value_type(PVR3TexturePixelFormat::LA88, Texture2D::PixelFormat::AI88),
  218. _pixel3_formathash::value_type(PVR3TexturePixelFormat::PVRTC2BPP_RGB, Texture2D::PixelFormat::PVRTC2),
  219. _pixel3_formathash::value_type(PVR3TexturePixelFormat::PVRTC2BPP_RGBA, Texture2D::PixelFormat::PVRTC2A),
  220. _pixel3_formathash::value_type(PVR3TexturePixelFormat::PVRTC4BPP_RGB, Texture2D::PixelFormat::PVRTC4),
  221. _pixel3_formathash::value_type(PVR3TexturePixelFormat::PVRTC4BPP_RGBA, Texture2D::PixelFormat::PVRTC4A),
  222. _pixel3_formathash::value_type(PVR3TexturePixelFormat::ETC1, Texture2D::PixelFormat::ETC),
  223. };
  224. static const int PVR3_MAX_TABLE_ELEMENTS = sizeof(v3_pixel_formathash_value) / sizeof(v3_pixel_formathash_value[0]);
  225. static const _pixel3_formathash v3_pixel_formathash(v3_pixel_formathash_value, v3_pixel_formathash_value + PVR3_MAX_TABLE_ELEMENTS);
  226. typedef struct _PVRTexHeader
  227. {
  228. unsigned int headerLength;
  229. unsigned int height;
  230. unsigned int width;
  231. unsigned int numMipmaps;
  232. unsigned int flags;
  233. unsigned int dataLength;
  234. unsigned int bpp;
  235. unsigned int bitmaskRed;
  236. unsigned int bitmaskGreen;
  237. unsigned int bitmaskBlue;
  238. unsigned int bitmaskAlpha;
  239. unsigned int pvrTag;
  240. unsigned int numSurfs;
  241. } PVRv2TexHeader;
  242. #ifdef _MSC_VER
  243. #pragma pack(push,1)
  244. #endif
  245. typedef struct
  246. {
  247. uint32_t version;
  248. uint32_t flags;
  249. uint64_t pixelFormat;
  250. uint32_t colorSpace;
  251. uint32_t channelType;
  252. uint32_t height;
  253. uint32_t width;
  254. uint32_t depth;
  255. uint32_t numberOfSurfaces;
  256. uint32_t numberOfFaces;
  257. uint32_t numberOfMipmaps;
  258. uint32_t metadataLength;
  259. #ifdef _MSC_VER
  260. } PVRv3TexHeader;
  261. #pragma pack(pop)
  262. #else
  263. } __attribute__((packed)) PVRv3TexHeader;
  264. #endif
  265. }
  266. //pvr structure end
  267. //////////////////////////////////////////////////////////////////////////
  268. //struct and data for s3tc(dds) struct
  269. namespace
  270. {
  271. struct DDColorKey
  272. {
  273. uint32_t colorSpaceLowValue;
  274. uint32_t colorSpaceHighValue;
  275. };
  276. struct DDSCaps
  277. {
  278. uint32_t caps;
  279. uint32_t caps2;
  280. uint32_t caps3;
  281. uint32_t caps4;
  282. };
  283. struct DDPixelFormat
  284. {
  285. uint32_t size;
  286. uint32_t flags;
  287. uint32_t fourCC;
  288. uint32_t RGBBitCount;
  289. uint32_t RBitMask;
  290. uint32_t GBitMask;
  291. uint32_t BBitMask;
  292. uint32_t ABitMask;
  293. };
  294. struct DDSURFACEDESC2
  295. {
  296. uint32_t size;
  297. uint32_t flags;
  298. uint32_t height;
  299. uint32_t width;
  300. union
  301. {
  302. uint32_t pitch;
  303. uint32_t linearSize;
  304. } DUMMYUNIONNAMEN1;
  305. union
  306. {
  307. uint32_t backBufferCount;
  308. uint32_t depth;
  309. } DUMMYUNIONNAMEN5;
  310. union
  311. {
  312. uint32_t mipMapCount;
  313. uint32_t refreshRate;
  314. uint32_t srcVBHandle;
  315. } DUMMYUNIONNAMEN2;
  316. uint32_t alphaBitDepth;
  317. uint32_t reserved;
  318. uint32_t surface;
  319. union
  320. {
  321. DDColorKey ddckCKDestOverlay;
  322. uint32_t emptyFaceColor;
  323. } DUMMYUNIONNAMEN3;
  324. DDColorKey ddckCKDestBlt;
  325. DDColorKey ddckCKSrcOverlay;
  326. DDColorKey ddckCKSrcBlt;
  327. union
  328. {
  329. DDPixelFormat ddpfPixelFormat;
  330. uint32_t FVF;
  331. } DUMMYUNIONNAMEN4;
  332. DDSCaps ddsCaps;
  333. uint32_t textureStage;
  334. } ;
  335. #pragma pack(push,1)
  336. struct S3TCTexHeader
  337. {
  338. char fileCode[4];
  339. DDSURFACEDESC2 ddsd;
  340. };
  341. #pragma pack(pop)
  342. }
  343. //s3tc struct end
  344. //////////////////////////////////////////////////////////////////////////
  345. //struct and data for atitc(ktx) struct
  346. namespace
  347. {
  348. struct ATITCTexHeader
  349. {
  350. //HEADER
  351. char identifier[12];
  352. uint32_t endianness;
  353. uint32_t glType;
  354. uint32_t glTypeSize;
  355. uint32_t glFormat;
  356. uint32_t glInternalFormat;
  357. uint32_t glBaseInternalFormat;
  358. uint32_t pixelWidth;
  359. uint32_t pixelHeight;
  360. uint32_t pixelDepth;
  361. uint32_t numberOfArrayElements;
  362. uint32_t numberOfFaces;
  363. uint32_t numberOfMipmapLevels;
  364. uint32_t bytesOfKeyValueData;
  365. };
  366. }
  367. //atitc struct end
  368. //////////////////////////////////////////////////////////////////////////
  369. namespace
  370. {
  371. typedef struct
  372. {
  373. const unsigned char * data;
  374. ssize_t size;
  375. int offset;
  376. }tImageSource;
  377. #if CC_USE_PNG
  378. static void pngReadCallback(png_structp png_ptr, png_bytep data, png_size_t length)
  379. {
  380. tImageSource* isource = (tImageSource*)png_get_io_ptr(png_ptr);
  381. if((int)(isource->offset + length) <= isource->size)
  382. {
  383. memcpy(data, isource->data+isource->offset, length);
  384. isource->offset += length;
  385. }
  386. else
  387. {
  388. png_error(png_ptr, "pngReaderCallback failed");
  389. }
  390. }
  391. #endif //CC_USE_PNG
  392. }
  393. Texture2D::PixelFormat getDevicePixelFormat(Texture2D::PixelFormat format)
  394. {
  395. switch (format) {
  396. case Texture2D::PixelFormat::PVRTC4:
  397. case Texture2D::PixelFormat::PVRTC4A:
  398. case Texture2D::PixelFormat::PVRTC2:
  399. case Texture2D::PixelFormat::PVRTC2A:
  400. if(Configuration::getInstance()->supportsPVRTC())
  401. return format;
  402. else
  403. return Texture2D::PixelFormat::RGBA8888;
  404. case Texture2D::PixelFormat::ETC:
  405. if(Configuration::getInstance()->supportsETC())
  406. return format;
  407. else
  408. return Texture2D::PixelFormat::RGB888;
  409. default:
  410. return format;
  411. }
  412. }
  413. //////////////////////////////////////////////////////////////////////////
  414. // Implement Image
  415. //////////////////////////////////////////////////////////////////////////
  416. bool Image::PNG_PREMULTIPLIED_ALPHA_ENABLED = true;
  417. Image::Image()
  418. : _data(nullptr)
  419. , _dataLen(0)
  420. , _width(0)
  421. , _height(0)
  422. , _unpack(false)
  423. , _fileType(Format::UNKNOWN)
  424. , _renderFormat(Texture2D::PixelFormat::NONE)
  425. , _numberOfMipmaps(0)
  426. , _hasPremultipliedAlpha(false)
  427. {
  428. }
  429. Image::~Image()
  430. {
  431. if(_unpack)
  432. {
  433. for (int i = 0; i < _numberOfMipmaps; ++i)
  434. CC_SAFE_FREE(_mipmaps[i].address);
  435. }
  436. else
  437. CC_SAFE_FREE(_data);
  438. }
  439. bool Image::initWithImageFile(const std::string& path)
  440. {
  441. bool ret = false;
  442. _filePath = FileUtils::getInstance()->fullPathForFilename(path);
  443. Data data = FileUtils::getInstance()->getDataFromFile(_filePath);
  444. if (!data.isNull())
  445. {
  446. ret = initWithImageData(data.getBytes(), data.getSize());
  447. }
  448. return ret;
  449. }
  450. bool Image::initWithImageFileThreadSafe(const std::string& fullpath)
  451. {
  452. bool ret = false;
  453. _filePath = fullpath;
  454. Data data = FileUtils::getInstance()->getDataFromFile(fullpath);
  455. if (!data.isNull())
  456. {
  457. ret = initWithImageData(data.getBytes(), data.getSize());
  458. }
  459. return ret;
  460. }
  461. bool Image::initWithImageData(const unsigned char * data, ssize_t dataLen)
  462. {
  463. bool ret = false;
  464. do
  465. {
  466. CC_BREAK_IF(! data || dataLen <= 0);
  467. unsigned char* unpackedData = nullptr;
  468. ssize_t unpackedLen = 0;
  469. if (ZipUtils::isEpngBuffer(data, dataLen))
  470. {
  471. data += 4;
  472. dataLen -= 4;
  473. }
  474. //detect and unzip the compress file
  475. if (ZipUtils::isCCZBuffer(data, dataLen))
  476. {
  477. unpackedLen = ZipUtils::inflateCCZBuffer(data, dataLen, &unpackedData);
  478. }
  479. else if (ZipUtils::isGZipBuffer(data, dataLen))
  480. {
  481. unpackedLen = ZipUtils::inflateMemory(const_cast<unsigned char*>(data), dataLen, &unpackedData);
  482. }
  483. else
  484. {
  485. unpackedData = const_cast<unsigned char*>(data);
  486. unpackedLen = dataLen;
  487. }
  488. _fileType = detectFormat(unpackedData, unpackedLen);
  489. switch (_fileType)
  490. {
  491. case Format::PNG:
  492. ret = initWithPngData(unpackedData, unpackedLen);
  493. break;
  494. case Format::JPG:
  495. ret = initWithJpgData(unpackedData, unpackedLen);
  496. break;
  497. case Format::TIFF:
  498. ret = initWithTiffData(unpackedData, unpackedLen);
  499. break;
  500. case Format::WEBP:
  501. ret = initWithWebpData(unpackedData, unpackedLen);
  502. break;
  503. case Format::PVR:
  504. ret = initWithPVRData(unpackedData, unpackedLen);
  505. break;
  506. case Format::ETC:
  507. ret = initWithETCData(unpackedData, unpackedLen);
  508. break;
  509. case Format::S3TC:
  510. ret = initWithS3TCData(unpackedData, unpackedLen);
  511. break;
  512. case Format::ATITC:
  513. ret = initWithATITCData(unpackedData, unpackedLen);
  514. break;
  515. default:
  516. {
  517. // load and detect image format
  518. tImageTGA* tgaData = tgaLoadBuffer(unpackedData, unpackedLen);
  519. if (tgaData != nullptr && tgaData->status == TGA_OK)
  520. {
  521. ret = initWithTGAData(tgaData);
  522. }
  523. else
  524. {
  525. CCLOG("cocos2d: unsupported image format!");
  526. }
  527. free(tgaData);
  528. break;
  529. }
  530. }
  531. if(unpackedData != data)
  532. {
  533. free(unpackedData);
  534. }
  535. } while (0);
  536. return ret;
  537. }
  538. bool Image::isPng(const unsigned char * data, ssize_t dataLen)
  539. {
  540. if (dataLen <= 8)
  541. {
  542. return false;
  543. }
  544. static const unsigned char PNG_SIGNATURE[] = {0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a};
  545. return memcmp(PNG_SIGNATURE, data, sizeof(PNG_SIGNATURE)) == 0;
  546. }
  547. bool Image::isEtc(const unsigned char * data, ssize_t /*dataLen*/)
  548. {
  549. return etc1_pkm_is_valid((etc1_byte*)data) ? true : false;
  550. }
  551. bool Image::isS3TC(const unsigned char * data, ssize_t /*dataLen*/)
  552. {
  553. S3TCTexHeader *header = (S3TCTexHeader *)data;
  554. if (strncmp(header->fileCode, "DDS", 3) != 0)
  555. {
  556. return false;
  557. }
  558. return true;
  559. }
  560. bool Image::isATITC(const unsigned char *data, ssize_t /*dataLen*/)
  561. {
  562. ATITCTexHeader *header = (ATITCTexHeader *)data;
  563. if (strncmp(&header->identifier[1], "KTX", 3) != 0)
  564. {
  565. return false;
  566. }
  567. return true;
  568. }
  569. bool Image::isJpg(const unsigned char * data, ssize_t dataLen)
  570. {
  571. if (dataLen <= 4)
  572. {
  573. return false;
  574. }
  575. static const unsigned char JPG_SOI[] = {0xFF, 0xD8};
  576. return memcmp(data, JPG_SOI, 2) == 0;
  577. }
  578. bool Image::isTiff(const unsigned char * data, ssize_t dataLen)
  579. {
  580. if (dataLen <= 4)
  581. {
  582. return false;
  583. }
  584. static const char* TIFF_II = "II";
  585. static const char* TIFF_MM = "MM";
  586. return (memcmp(data, TIFF_II, 2) == 0 && *(static_cast<const unsigned char*>(data) + 2) == 42 && *(static_cast<const unsigned char*>(data) + 3) == 0) ||
  587. (memcmp(data, TIFF_MM, 2) == 0 && *(static_cast<const unsigned char*>(data) + 2) == 0 && *(static_cast<const unsigned char*>(data) + 3) == 42);
  588. }
  589. bool Image::isWebp(const unsigned char * data, ssize_t dataLen)
  590. {
  591. if (dataLen <= 12)
  592. {
  593. return false;
  594. }
  595. static const char* WEBP_RIFF = "RIFF";
  596. static const char* WEBP_WEBP = "WEBP";
  597. return memcmp(data, WEBP_RIFF, 4) == 0
  598. && memcmp(static_cast<const unsigned char*>(data) + 8, WEBP_WEBP, 4) == 0;
  599. }
  600. bool Image::isPvr(const unsigned char * data, ssize_t dataLen)
  601. {
  602. if (static_cast<size_t>(dataLen) < sizeof(PVRv2TexHeader) || static_cast<size_t>(dataLen) < sizeof(PVRv3TexHeader))
  603. {
  604. return false;
  605. }
  606. const PVRv2TexHeader* headerv2 = static_cast<const PVRv2TexHeader*>(static_cast<const void*>(data));
  607. const PVRv3TexHeader* headerv3 = static_cast<const PVRv3TexHeader*>(static_cast<const void*>(data));
  608. return memcmp(&headerv2->pvrTag, gPVRTexIdentifier, strlen(gPVRTexIdentifier)) == 0 || CC_SWAP_INT32_BIG_TO_HOST(headerv3->version) == 0x50565203;
  609. }
  610. Image::Format Image::detectFormat(const unsigned char * data, ssize_t dataLen)
  611. {
  612. if (isPng(data, dataLen))
  613. {
  614. return Format::PNG;
  615. }
  616. else if (isJpg(data, dataLen))
  617. {
  618. return Format::JPG;
  619. }
  620. else if (isTiff(data, dataLen))
  621. {
  622. return Format::TIFF;
  623. }
  624. else if (isWebp(data, dataLen))
  625. {
  626. return Format::WEBP;
  627. }
  628. else if (isPvr(data, dataLen))
  629. {
  630. return Format::PVR;
  631. }
  632. else if (isEtc(data, dataLen))
  633. {
  634. return Format::ETC;
  635. }
  636. else if (isS3TC(data, dataLen))
  637. {
  638. return Format::S3TC;
  639. }
  640. else if (isATITC(data, dataLen))
  641. {
  642. return Format::ATITC;
  643. }
  644. else
  645. {
  646. return Format::UNKNOWN;
  647. }
  648. }
  649. int Image::getBitPerPixel()
  650. {
  651. return Texture2D::getPixelFormatInfoMap().at(_renderFormat).bpp;
  652. }
  653. bool Image::hasAlpha()
  654. {
  655. return Texture2D::getPixelFormatInfoMap().at(_renderFormat).alpha;
  656. }
  657. bool Image::isCompressed()
  658. {
  659. return Texture2D::getPixelFormatInfoMap().at(_renderFormat).compressed;
  660. }
  661. namespace
  662. {
  663. /*
  664. * ERROR HANDLING:
  665. *
  666. * The JPEG library's standard error handler (jerror.c) is divided into
  667. * several "methods" which you can override individually. This lets you
  668. * adjust the behavior without duplicating a lot of code, which you might
  669. * have to update with each future release.
  670. *
  671. * We override the "error_exit" method so that control is returned to the
  672. * library's caller when a fatal error occurs, rather than calling exit()
  673. * as the standard error_exit method does.
  674. *
  675. * We use C's setjmp/longjmp facility to return control. This means that the
  676. * routine which calls the JPEG library must first execute a setjmp() call to
  677. * establish the return point. We want the replacement error_exit to do a
  678. * longjmp(). But we need to make the setjmp buffer accessible to the
  679. * error_exit routine. To do this, we make a private extension of the
  680. * standard JPEG error handler object. (If we were using C++, we'd say we
  681. * were making a subclass of the regular error handler.)
  682. *
  683. * Here's the extended error handler struct:
  684. */
  685. #if CC_USE_JPEG
  686. struct MyErrorMgr
  687. {
  688. struct jpeg_error_mgr pub; /* "public" fields */
  689. jmp_buf setjmp_buffer; /* for return to caller */
  690. };
  691. typedef struct MyErrorMgr * MyErrorPtr;
  692. /*
  693. * Here's the routine that will replace the standard error_exit method:
  694. */
  695. METHODDEF(void)
  696. myErrorExit(j_common_ptr cinfo)
  697. {
  698. /* cinfo->err really points to a MyErrorMgr struct, so coerce pointer */
  699. MyErrorPtr myerr = (MyErrorPtr) cinfo->err;
  700. /* Always display the message. */
  701. /* We could postpone this until after returning, if we chose. */
  702. /* internal message function can't show error message in some platforms, so we rewrite it here.
  703. * edit it if has version conflict.
  704. */
  705. //(*cinfo->err->output_message) (cinfo);
  706. char buffer[JMSG_LENGTH_MAX];
  707. (*cinfo->err->format_message) (cinfo, buffer);
  708. CCLOG("jpeg error: %s", buffer);
  709. /* Return control to the setjmp point */
  710. longjmp(myerr->setjmp_buffer, 1);
  711. }
  712. #endif // CC_USE_JPEG
  713. }
  714. #if CC_USE_WIC
  715. bool Image::decodeWithWIC(const unsigned char *data, ssize_t dataLen)
  716. {
  717. bool bRet = false;
  718. WICImageLoader img;
  719. if (img.decodeImageData(data, dataLen))
  720. {
  721. _width = img.getWidth();
  722. _height = img.getHeight();
  723. WICPixelFormatGUID format = img.getPixelFormat();
  724. if (memcmp(&format, &GUID_WICPixelFormat8bppGray, sizeof(WICPixelFormatGUID)) == 0)
  725. {
  726. _renderFormat = Texture2D::PixelFormat::I8;
  727. }
  728. if (memcmp(&format, &GUID_WICPixelFormat8bppAlpha, sizeof(WICPixelFormatGUID)) == 0)
  729. {
  730. _renderFormat = Texture2D::PixelFormat::AI88;
  731. }
  732. if (memcmp(&format, &GUID_WICPixelFormat24bppRGB, sizeof(WICPixelFormatGUID)) == 0)
  733. {
  734. _renderFormat = Texture2D::PixelFormat::RGB888;
  735. }
  736. if (memcmp(&format, &GUID_WICPixelFormat32bppRGBA, sizeof(WICPixelFormatGUID)) == 0)
  737. {
  738. _renderFormat = Texture2D::PixelFormat::RGBA8888;
  739. }
  740. if (memcmp(&format, &GUID_WICPixelFormat32bppBGRA, sizeof(WICPixelFormatGUID)) == 0)
  741. {
  742. _renderFormat = Texture2D::PixelFormat::BGRA8888;
  743. }
  744. _dataLen = img.getImageDataSize();
  745. CCASSERT(_dataLen > 0, "Image: Decompressed data length is invalid");
  746. _data = new (std::nothrow) unsigned char[_dataLen];
  747. bRet = (img.getImageData(_data, _dataLen) > 0);
  748. if (_renderFormat == Texture2D::PixelFormat::RGBA8888) {
  749. premultipliedAlpha();
  750. }
  751. }
  752. return bRet;
  753. }
  754. bool Image::encodeWithWIC(const std::string& filePath, bool isToRGB, GUID containerFormat)
  755. {
  756. // Save formats supported by WIC
  757. WICPixelFormatGUID targetFormat = isToRGB ? GUID_WICPixelFormat24bppBGR : GUID_WICPixelFormat32bppBGRA;
  758. unsigned char *pSaveData = nullptr;
  759. int saveLen = _dataLen;
  760. int bpp = 4;
  761. if (targetFormat == GUID_WICPixelFormat24bppBGR && _renderFormat == Texture2D::PixelFormat::RGBA8888)
  762. {
  763. bpp = 3;
  764. saveLen = _width * _height * bpp;
  765. pSaveData = new (std::nothrow) unsigned char[saveLen];
  766. int indL = 0, indR = 0;
  767. while (indL < saveLen && indR < _dataLen)
  768. {
  769. memcpy(&pSaveData[indL], &_data[indR], 3);
  770. indL += 3;
  771. indR += 4;
  772. }
  773. }
  774. else
  775. {
  776. pSaveData = new (std::nothrow) unsigned char[saveLen];
  777. memcpy(pSaveData, _data, saveLen);
  778. }
  779. for (int ind = 2; ind < saveLen; ind += bpp) {
  780. std::swap(pSaveData[ind - 2], pSaveData[ind]);
  781. }
  782. WICImageLoader img;
  783. bool bRet = img.encodeImageData(filePath, pSaveData, saveLen, targetFormat, _width, _height, containerFormat);
  784. delete[] pSaveData;
  785. return bRet;
  786. }
  787. #endif //CC_USE_WIC
  788. bool Image::initWithJpgData(const unsigned char * data, ssize_t dataLen)
  789. {
  790. #if CC_USE_WIC
  791. return decodeWithWIC(data, dataLen);
  792. #elif CC_USE_JPEG
  793. /* these are standard libjpeg structures for reading(decompression) */
  794. struct jpeg_decompress_struct cinfo;
  795. /* We use our private extension JPEG error handler.
  796. * Note that this struct must live as long as the main JPEG parameter
  797. * struct, to avoid dangling-pointer problems.
  798. */
  799. struct MyErrorMgr jerr;
  800. /* libjpeg data structure for storing one row, that is, scanline of an image */
  801. JSAMPROW row_pointer[1] = {0};
  802. unsigned long location = 0;
  803. bool ret = false;
  804. do
  805. {
  806. /* We set up the normal JPEG error routines, then override error_exit. */
  807. cinfo.err = jpeg_std_error(&jerr.pub);
  808. jerr.pub.error_exit = myErrorExit;
  809. /* Establish the setjmp return context for MyErrorExit to use. */
  810. if (setjmp(jerr.setjmp_buffer))
  811. {
  812. /* If we get here, the JPEG code has signaled an error.
  813. * We need to clean up the JPEG object, close the input file, and return.
  814. */
  815. jpeg_destroy_decompress(&cinfo);
  816. break;
  817. }
  818. /* setup decompression process and source, then read JPEG header */
  819. jpeg_create_decompress( &cinfo );
  820. #ifndef CC_TARGET_QT5
  821. jpeg_mem_src(&cinfo, const_cast<unsigned char*>(data), dataLen);
  822. #endif /* CC_TARGET_QT5 */
  823. /* reading the image header which contains image information */
  824. #if (JPEG_LIB_VERSION >= 90)
  825. // libjpeg 0.9 adds stricter types.
  826. jpeg_read_header(&cinfo, TRUE);
  827. #else
  828. jpeg_read_header(&cinfo, TRUE);
  829. #endif
  830. // we only support RGB or grayscale
  831. if (cinfo.jpeg_color_space == JCS_GRAYSCALE)
  832. {
  833. _renderFormat = Texture2D::PixelFormat::I8;
  834. }else
  835. {
  836. cinfo.out_color_space = JCS_RGB;
  837. _renderFormat = Texture2D::PixelFormat::RGB888;
  838. }
  839. /* Start decompression jpeg here */
  840. jpeg_start_decompress( &cinfo );
  841. /* init image info */
  842. _width = cinfo.output_width;
  843. _height = cinfo.output_height;
  844. _dataLen = cinfo.output_width*cinfo.output_height*cinfo.output_components;
  845. _data = static_cast<unsigned char*>(malloc(_dataLen * sizeof(unsigned char)));
  846. CC_BREAK_IF(! _data);
  847. /* now actually read the jpeg into the raw buffer */
  848. /* read one scan line at a time */
  849. while (cinfo.output_scanline < cinfo.output_height)
  850. {
  851. row_pointer[0] = _data + location;
  852. location += cinfo.output_width*cinfo.output_components;
  853. jpeg_read_scanlines(&cinfo, row_pointer, 1);
  854. }
  855. /* When read image file with broken data, jpeg_finish_decompress() may cause error.
  856. * Besides, jpeg_destroy_decompress() shall deallocate and release all memory associated
  857. * with the decompression object.
  858. * So it doesn't need to call jpeg_finish_decompress().
  859. */
  860. //jpeg_finish_decompress( &cinfo );
  861. jpeg_destroy_decompress( &cinfo );
  862. /* wrap up decompression, destroy objects, free pointers and close open files */
  863. ret = true;
  864. } while (0);
  865. return ret;
  866. #else
  867. CCLOG("jpeg is not enabled, please enable it in ccConfig.h");
  868. return false;
  869. #endif // CC_USE_JPEG
  870. }
  871. bool Image::initWithPngData(const unsigned char * data, ssize_t dataLen)
  872. {
  873. #if CC_USE_WIC
  874. return decodeWithWIC(data, dataLen);
  875. #elif CC_USE_PNG
  876. // length of bytes to check if it is a valid png file
  877. #define PNGSIGSIZE 8
  878. bool ret = false;
  879. png_byte header[PNGSIGSIZE] = {0};
  880. png_structp png_ptr = 0;
  881. png_infop info_ptr = 0;
  882. do
  883. {
  884. // png header len is 8 bytes
  885. CC_BREAK_IF(dataLen < PNGSIGSIZE);
  886. // check the data is png or not
  887. memcpy(header, data, PNGSIGSIZE);
  888. CC_BREAK_IF(png_sig_cmp(header, 0, PNGSIGSIZE));
  889. // init png_struct
  890. png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, 0, 0, 0);
  891. CC_BREAK_IF(! png_ptr);
  892. // init png_info
  893. info_ptr = png_create_info_struct(png_ptr);
  894. CC_BREAK_IF(!info_ptr);
  895. #if (CC_TARGET_PLATFORM != CC_PLATFORM_BADA && CC_TARGET_PLATFORM != CC_PLATFORM_NACL && CC_TARGET_PLATFORM != CC_PLATFORM_TIZEN)
  896. CC_BREAK_IF(setjmp(png_jmpbuf(png_ptr)));
  897. #endif
  898. // set the read call back function
  899. tImageSource imageSource;
  900. imageSource.data = (unsigned char*)data;
  901. imageSource.size = dataLen;
  902. imageSource.offset = 0;
  903. png_set_read_fn(png_ptr, &imageSource, pngReadCallback);
  904. // read png header info
  905. // read png file info
  906. png_read_info(png_ptr, info_ptr);
  907. _width = png_get_image_width(png_ptr, info_ptr);
  908. _height = png_get_image_height(png_ptr, info_ptr);
  909. png_byte bit_depth = png_get_bit_depth(png_ptr, info_ptr);
  910. png_uint_32 color_type = png_get_color_type(png_ptr, info_ptr);
  911. //CCLOG("color type %u", color_type);
  912. // force palette images to be expanded to 24-bit RGB
  913. // it may include alpha channel
  914. if (color_type == PNG_COLOR_TYPE_PALETTE)
  915. {
  916. png_set_palette_to_rgb(png_ptr);
  917. }
  918. // low-bit-depth grayscale images are to be expanded to 8 bits
  919. if (color_type == PNG_COLOR_TYPE_GRAY && bit_depth < 8)
  920. {
  921. bit_depth = 8;
  922. png_set_expand_gray_1_2_4_to_8(png_ptr);
  923. }
  924. // expand any tRNS chunk data into a full alpha channel
  925. if (png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS))
  926. {
  927. png_set_tRNS_to_alpha(png_ptr);
  928. }
  929. // reduce images with 16-bit samples to 8 bits
  930. if (bit_depth == 16)
  931. {
  932. png_set_strip_16(png_ptr);
  933. }
  934. // Expanded earlier for grayscale, now take care of palette and rgb
  935. if (bit_depth < 8)
  936. {
  937. png_set_packing(png_ptr);
  938. }
  939. // update info
  940. png_read_update_info(png_ptr, info_ptr);
  941. color_type = png_get_color_type(png_ptr, info_ptr);
  942. switch (color_type)
  943. {
  944. case PNG_COLOR_TYPE_GRAY:
  945. _renderFormat = Texture2D::PixelFormat::I8;
  946. break;
  947. case PNG_COLOR_TYPE_GRAY_ALPHA:
  948. _renderFormat = Texture2D::PixelFormat::AI88;
  949. break;
  950. case PNG_COLOR_TYPE_RGB:
  951. _renderFormat = Texture2D::PixelFormat::RGB888;
  952. break;
  953. case PNG_COLOR_TYPE_RGB_ALPHA:
  954. _renderFormat = Texture2D::PixelFormat::RGBA8888;
  955. break;
  956. default:
  957. break;
  958. }
  959. // read png data
  960. png_size_t rowbytes;
  961. png_bytep* row_pointers = (png_bytep*)malloc( sizeof(png_bytep) * _height );
  962. rowbytes = png_get_rowbytes(png_ptr, info_ptr);
  963. _dataLen = rowbytes * _height;
  964. _data = static_cast<unsigned char*>(malloc(_dataLen * sizeof(unsigned char)));
  965. if (!_data)
  966. {
  967. if (row_pointers != nullptr)
  968. {
  969. free(row_pointers);
  970. }
  971. break;
  972. }
  973. for (unsigned short i = 0; i < _height; ++i)
  974. {
  975. row_pointers[i] = _data + i*rowbytes;
  976. }
  977. png_read_image(png_ptr, row_pointers);
  978. png_read_end(png_ptr, nullptr);
  979. // premultiplied alpha for RGBA8888
  980. if (PNG_PREMULTIPLIED_ALPHA_ENABLED && color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  981. {
  982. premultipliedAlpha();
  983. }
  984. if (row_pointers != nullptr)
  985. {
  986. free(row_pointers);
  987. }
  988. ret = true;
  989. } while (0);
  990. if (png_ptr)
  991. {
  992. png_destroy_read_struct(&png_ptr, (info_ptr) ? &info_ptr : 0, 0);
  993. }
  994. return ret;
  995. #else
  996. CCLOG("png is not enabled, please enable it in ccConfig.h");
  997. return false;
  998. #endif //CC_USE_PNG
  999. }
  1000. #if CC_USE_TIFF
  1001. namespace
  1002. {
  1003. static tmsize_t tiffReadProc(thandle_t fd, void* buf, tmsize_t size)
  1004. {
  1005. tImageSource* isource = (tImageSource*)fd;
  1006. uint8* ma;
  1007. uint64 mb;
  1008. unsigned long n;
  1009. unsigned long o;
  1010. tmsize_t p;
  1011. ma=(uint8*)buf;
  1012. mb=size;
  1013. p=0;
  1014. while (mb>0)
  1015. {
  1016. n=0x80000000UL;
  1017. if ((uint64)n>mb)
  1018. n=(unsigned long)mb;
  1019. if ((int)(isource->offset + n) <= isource->size)
  1020. {
  1021. memcpy(ma, isource->data+isource->offset, n);
  1022. isource->offset += n;
  1023. o = n;
  1024. }
  1025. else
  1026. {
  1027. return 0;
  1028. }
  1029. ma+=o;
  1030. mb-=o;
  1031. p+=o;
  1032. if (o!=n)
  1033. {
  1034. break;
  1035. }
  1036. }
  1037. return p;
  1038. }
  1039. static tmsize_t tiffWriteProc(thandle_t /*fd*/, void* /*buf*/, tmsize_t /*size*/)
  1040. {
  1041. return 0;
  1042. }
  1043. static uint64 tiffSeekProc(thandle_t fd, uint64 off, int whence)
  1044. {
  1045. tImageSource* isource = (tImageSource*)fd;
  1046. uint64 ret = -1;
  1047. do
  1048. {
  1049. if (whence == SEEK_SET)
  1050. {
  1051. CC_BREAK_IF(off >= (uint64)isource->size);
  1052. ret = isource->offset = (uint32)off;
  1053. }
  1054. else if (whence == SEEK_CUR)
  1055. {
  1056. CC_BREAK_IF(isource->offset + off >= (uint64)isource->size);
  1057. ret = isource->offset += (uint32)off;
  1058. }
  1059. else if (whence == SEEK_END)
  1060. {
  1061. CC_BREAK_IF(off >= (uint64)isource->size);
  1062. ret = isource->offset = (uint32)(isource->size-1 - off);
  1063. }
  1064. else
  1065. {
  1066. CC_BREAK_IF(off >= (uint64)isource->size);
  1067. ret = isource->offset = (uint32)off;
  1068. }
  1069. } while (0);
  1070. return ret;
  1071. }
  1072. static uint64 tiffSizeProc(thandle_t fd)
  1073. {
  1074. tImageSource* imageSrc = (tImageSource*)fd;
  1075. return imageSrc->size;
  1076. }
  1077. static int tiffCloseProc(thandle_t /*fd*/)
  1078. {
  1079. return 0;
  1080. }
  1081. static int tiffMapProc(thandle_t /*fd*/, void** /*base*/, toff_t* /*size*/)
  1082. {
  1083. return 0;
  1084. }
  1085. static void tiffUnmapProc(thandle_t /*fd*/, void* /*base*/, toff_t /*size*/)
  1086. {
  1087. }
  1088. }
  1089. #endif // CC_USE_TIFF
  1090. bool Image::initWithTiffData(const unsigned char * data, ssize_t dataLen)
  1091. {
  1092. #if CC_USE_WIC
  1093. return decodeWithWIC(data, dataLen);
  1094. #elif CC_USE_TIFF
  1095. bool ret = false;
  1096. do
  1097. {
  1098. // set the read call back function
  1099. tImageSource imageSource;
  1100. imageSource.data = data;
  1101. imageSource.size = dataLen;
  1102. imageSource.offset = 0;
  1103. TIFF* tif = TIFFClientOpen("file.tif", "r", (thandle_t)&imageSource,
  1104. tiffReadProc, tiffWriteProc,
  1105. tiffSeekProc, tiffCloseProc, tiffSizeProc,
  1106. tiffMapProc,
  1107. tiffUnmapProc);
  1108. CC_BREAK_IF(nullptr == tif);
  1109. uint32 w = 0, h = 0;
  1110. uint16 bitsPerSample = 0, samplePerPixel = 0, planarConfig = 0;
  1111. size_t npixels = 0;
  1112. TIFFGetField(tif, TIFFTAG_IMAGEWIDTH, &w);
  1113. TIFFGetField(tif, TIFFTAG_IMAGELENGTH, &h);
  1114. TIFFGetField(tif, TIFFTAG_BITSPERSAMPLE, &bitsPerSample);
  1115. TIFFGetField(tif, TIFFTAG_SAMPLESPERPIXEL, &samplePerPixel);
  1116. TIFFGetField(tif, TIFFTAG_PLANARCONFIG, &planarConfig);
  1117. npixels = w * h;
  1118. _renderFormat = Texture2D::PixelFormat::RGBA8888;
  1119. _width = w;
  1120. _height = h;
  1121. _dataLen = npixels * sizeof (uint32);
  1122. _data = static_cast<unsigned char*>(malloc(_dataLen * sizeof(unsigned char)));
  1123. uint32* raster = (uint32*) _TIFFmalloc(npixels * sizeof (uint32));
  1124. if (raster != nullptr)
  1125. {
  1126. if (TIFFReadRGBAImageOriented(tif, w, h, raster, ORIENTATION_TOPLEFT, 0))
  1127. {
  1128. /* the raster data is pre-multiplied by the alpha component
  1129. after invoking TIFFReadRGBAImageOriented*/
  1130. _hasPremultipliedAlpha = true;
  1131. memcpy(_data, raster, npixels*sizeof (uint32));
  1132. }
  1133. _TIFFfree(raster);
  1134. }
  1135. TIFFClose(tif);
  1136. ret = true;
  1137. } while (0);
  1138. return ret;
  1139. #else
  1140. CCLOG("tiff is not enabled, please enable it in ccConfig.h");
  1141. return false;
  1142. #endif //CC_USE_TIFF
  1143. }
  1144. namespace
  1145. {
  1146. bool testFormatForPvr2TCSupport(PVR2TexturePixelFormat /*format*/)
  1147. {
  1148. return true;
  1149. }
  1150. bool testFormatForPvr3TCSupport(PVR3TexturePixelFormat format)
  1151. {
  1152. switch (format) {
  1153. case PVR3TexturePixelFormat::DXT1:
  1154. case PVR3TexturePixelFormat::DXT3:
  1155. case PVR3TexturePixelFormat::DXT5:
  1156. return Configuration::getInstance()->supportsS3TC();
  1157. case PVR3TexturePixelFormat::BGRA8888:
  1158. return Configuration::getInstance()->supportsBGRA8888();
  1159. case PVR3TexturePixelFormat::PVRTC2BPP_RGB:
  1160. case PVR3TexturePixelFormat::PVRTC2BPP_RGBA:
  1161. case PVR3TexturePixelFormat::PVRTC4BPP_RGB:
  1162. case PVR3TexturePixelFormat::PVRTC4BPP_RGBA:
  1163. case PVR3TexturePixelFormat::ETC1:
  1164. case PVR3TexturePixelFormat::RGBA8888:
  1165. case PVR3TexturePixelFormat::RGBA4444:
  1166. case PVR3TexturePixelFormat::RGBA5551:
  1167. case PVR3TexturePixelFormat::RGB565:
  1168. case PVR3TexturePixelFormat::RGB888:
  1169. case PVR3TexturePixelFormat::A8:
  1170. case PVR3TexturePixelFormat::L8:
  1171. case PVR3TexturePixelFormat::LA88:
  1172. return true;
  1173. default:
  1174. return false;
  1175. }
  1176. }
  1177. }
  1178. bool Image::initWithPVRv2Data(const unsigned char * data, ssize_t dataLen)
  1179. {
  1180. int dataLength = 0, dataOffset = 0, dataSize = 0;
  1181. int blockSize = 0, widthBlocks = 0, heightBlocks = 0;
  1182. int width = 0, height = 0;
  1183. //Cast first sizeof(PVRTexHeader) bytes of data stream as PVRTexHeader
  1184. const PVRv2TexHeader *header = static_cast<const PVRv2TexHeader *>(static_cast<const void*>(data));
  1185. //Make sure that tag is in correct formatting
  1186. if (memcmp(&header->pvrTag, gPVRTexIdentifier, strlen(gPVRTexIdentifier)) != 0)
  1187. {
  1188. return false;
  1189. }
  1190. Configuration *configuration = Configuration::getInstance();
  1191. //can not detect the premultiplied alpha from pvr file, use _PVRHaveAlphaPremultiplied instead.
  1192. _hasPremultipliedAlpha = _PVRHaveAlphaPremultiplied;
  1193. unsigned int flags = CC_SWAP_INT32_LITTLE_TO_HOST(header->flags);
  1194. PVR2TexturePixelFormat formatFlags = static_cast<PVR2TexturePixelFormat>(flags & PVR_TEXTURE_FLAG_TYPE_MASK);
  1195. bool flipped = (flags & (unsigned int)PVR2TextureFlag::VerticalFlip) ? true : false;
  1196. if (flipped)
  1197. {
  1198. CCLOG("cocos2d: WARNING: Image is flipped. Regenerate it using PVRTexTool");
  1199. }
  1200. if (! configuration->supportsNPOT() &&
  1201. (static_cast<int>(header->width) != ccNextPOT(header->width)
  1202. || static_cast<int>(header->height) != ccNextPOT(header->height)))
  1203. {
  1204. CCLOG("cocos2d: ERROR: Loading an NPOT texture (%dx%d) but is not supported on this device", header->width, header->height);
  1205. return false;
  1206. }
  1207. if (!testFormatForPvr2TCSupport(formatFlags))
  1208. {
  1209. CCLOG("cocos2d: WARNING: Unsupported PVR Pixel Format: 0x%02X. Re-encode it with a OpenGL pixel format variant", (int)formatFlags);
  1210. return false;
  1211. }
  1212. if (v2_pixel_formathash.find(formatFlags) == v2_pixel_formathash.end())
  1213. {
  1214. CCLOG("cocos2d: WARNING: Unsupported PVR Pixel Format: 0x%02X. Re-encode it with a OpenGL pixel format variant", (int)formatFlags);
  1215. return false;
  1216. }
  1217. auto it = Texture2D::getPixelFormatInfoMap().find(getDevicePixelFormat(v2_pixel_formathash.at(formatFlags)));
  1218. if (it == Texture2D::getPixelFormatInfoMap().end())
  1219. {
  1220. CCLOG("cocos2d: WARNING: Unsupported PVR Pixel Format: 0x%02X. Re-encode it with a OpenGL pixel format variant", (int)formatFlags);
  1221. return false;
  1222. }
  1223. _renderFormat = it->first;
  1224. int bpp = it->second.bpp;
  1225. //Reset num of mipmaps
  1226. _numberOfMipmaps = 0;
  1227. //Get size of mipmap
  1228. _width = width = CC_SWAP_INT32_LITTLE_TO_HOST(header->width);
  1229. _height = height = CC_SWAP_INT32_LITTLE_TO_HOST(header->height);
  1230. //Get ptr to where data starts..
  1231. dataLength = CC_SWAP_INT32_LITTLE_TO_HOST(header->dataLength);
  1232. //Move by size of header
  1233. _dataLen = dataLen - sizeof(PVRv2TexHeader);
  1234. _data = static_cast<unsigned char*>(malloc(_dataLen * sizeof(unsigned char)));
  1235. memcpy(_data, (unsigned char*)data + sizeof(PVRv2TexHeader), _dataLen);
  1236. // Calculate the data size for each texture level and respect the minimum number of blocks
  1237. while (dataOffset < dataLength)
  1238. {
  1239. switch (formatFlags) {
  1240. case PVR2TexturePixelFormat::PVRTC2BPP_RGBA:
  1241. if (!Configuration::getInstance()->supportsPVRTC())
  1242. {
  1243. CCLOG("cocos2d: Hardware PVR decoder not present. Using software decoder");
  1244. _unpack = true;
  1245. _mipmaps[_numberOfMipmaps].len = width*height*4;
  1246. //_mipmaps[_numberOfMipmaps].address = new (std::nothrow) unsigned char[width*height*4];
  1247. _mipmaps[_numberOfMipmaps].address = static_cast<unsigned char*>(malloc(width*height*4));
  1248. PVRTDecompressPVRTC(_data+dataOffset,width,height,_mipmaps[_numberOfMipmaps].address, true);
  1249. bpp = 2;
  1250. }
  1251. blockSize = 8 * 4; // Pixel by pixel block size for 2bpp
  1252. widthBlocks = width / 8;
  1253. heightBlocks = height / 4;
  1254. break;
  1255. case PVR2TexturePixelFormat::PVRTC4BPP_RGBA:
  1256. if (!Configuration::getInstance()->supportsPVRTC())
  1257. {
  1258. CCLOG("cocos2d: Hardware PVR decoder not present. Using software decoder");
  1259. _unpack = true;
  1260. _mipmaps[_numberOfMipmaps].len = width*height*4;
  1261. //_mipmaps[_numberOfMipmaps].address = new (std::nothrow) unsigned char[width*height*4];
  1262. _mipmaps[_numberOfMipmaps].address = static_cast<unsigned char*>(malloc(width*height*4));
  1263. PVRTDecompressPVRTC(_data+dataOffset,width,height,_mipmaps[_numberOfMipmaps].address, false);
  1264. bpp = 4;
  1265. }
  1266. blockSize = 4 * 4; // Pixel by pixel block size for 4bpp
  1267. widthBlocks = width / 4;
  1268. heightBlocks = height / 4;
  1269. break;
  1270. case PVR2TexturePixelFormat::BGRA8888:
  1271. if (Configuration::getInstance()->supportsBGRA8888() == false)
  1272. {
  1273. CCLOG("cocos2d: Image. BGRA8888 not supported on this device");
  1274. return false;
  1275. }
  1276. default:
  1277. blockSize = 1;
  1278. widthBlocks = width;
  1279. heightBlocks = height;
  1280. break;
  1281. }
  1282. // Clamp to minimum number of blocks
  1283. if (widthBlocks < 2)
  1284. {
  1285. widthBlocks = 2;
  1286. }
  1287. if (heightBlocks < 2)
  1288. {
  1289. heightBlocks = 2;
  1290. }
  1291. dataSize = widthBlocks * heightBlocks * ((blockSize * bpp) / 8);
  1292. int packetLength = (dataLength - dataOffset);
  1293. packetLength = packetLength > dataSize ? dataSize : packetLength;
  1294. //Make record to the mipmaps array and increment counter
  1295. if(!_unpack)
  1296. {
  1297. _mipmaps[_numberOfMipmaps].address = _data + dataOffset;
  1298. _mipmaps[_numberOfMipmaps].len = packetLength;
  1299. }
  1300. _numberOfMipmaps++;
  1301. dataOffset += packetLength;
  1302. //Update width and height to the next lower power of two
  1303. width = MAX(width >> 1, 1);
  1304. height = MAX(height >> 1, 1);
  1305. }
  1306. if(_unpack)
  1307. {
  1308. free(_data);
  1309. _data = _mipmaps[0].address;
  1310. _dataLen = _mipmaps[0].len;
  1311. }
  1312. return true;
  1313. }
  1314. bool Image::initWithPVRv3Data(const unsigned char * data, ssize_t dataLen)
  1315. {
  1316. if (static_cast<size_t>(dataLen) < sizeof(PVRv3TexHeader))
  1317. {
  1318. return false;
  1319. }
  1320. const PVRv3TexHeader *header = static_cast<const PVRv3TexHeader *>(static_cast<const void*>(data));
  1321. // validate version
  1322. if (CC_SWAP_INT32_BIG_TO_HOST(header->version) != 0x50565203)
  1323. {
  1324. CCLOG("cocos2d: WARNING: pvr file version mismatch");
  1325. return false;
  1326. }
  1327. // parse pixel format
  1328. PVR3TexturePixelFormat pixelFormat = static_cast<PVR3TexturePixelFormat>(header->pixelFormat);
  1329. if (!testFormatForPvr3TCSupport(pixelFormat))
  1330. {
  1331. CCLOG("cocos2d: WARNING: Unsupported PVR Pixel Format: 0x%016llX. Re-encode it with a OpenGL pixel format variant",
  1332. static_cast<unsigned long long>(pixelFormat));
  1333. return false;
  1334. }
  1335. if (v3_pixel_formathash.find(pixelFormat) == v3_pixel_formathash.end())
  1336. {
  1337. CCLOG("cocos2d: WARNING: Unsupported PVR Pixel Format: 0x%016llX. Re-encode it with a OpenGL pixel format variant",
  1338. static_cast<unsigned long long>(pixelFormat));
  1339. return false;
  1340. }
  1341. auto it = Texture2D::getPixelFormatInfoMap().find(getDevicePixelFormat(v3_pixel_formathash.at(pixelFormat)));
  1342. if (it == Texture2D::getPixelFormatInfoMap().end())
  1343. {
  1344. CCLOG("cocos2d: WARNING: Unsupported PVR Pixel Format: 0x%016llX. Re-encode it with a OpenGL pixel format variant",
  1345. static_cast<unsigned long long>(pixelFormat));
  1346. return false;
  1347. }
  1348. _renderFormat = it->first;
  1349. int bpp = it->second.bpp;
  1350. // flags
  1351. int flags = CC_SWAP_INT32_LITTLE_TO_HOST(header->flags);
  1352. // PVRv3 specifies premultiply alpha in a flag -- should always respect this in PVRv3 files
  1353. if (flags & (unsigned int)PVR3TextureFlag::PremultipliedAlpha)
  1354. {
  1355. _hasPremultipliedAlpha = true;
  1356. }
  1357. // sizing
  1358. int width = CC_SWAP_INT32_LITTLE_TO_HOST(header->width);
  1359. int height = CC_SWAP_INT32_LITTLE_TO_HOST(header->height);
  1360. _width = width;
  1361. _height = height;
  1362. int dataOffset = 0, dataSize = 0;
  1363. int blockSize = 0, widthBlocks = 0, heightBlocks = 0;
  1364. _dataLen = dataLen - (sizeof(PVRv3TexHeader) + header->metadataLength);
  1365. _data = static_cast<unsigned char*>(malloc(_dataLen * sizeof(unsigned char)));
  1366. memcpy(_data, static_cast<const unsigned char*>(data) + sizeof(PVRv3TexHeader) + header->metadataLength, _dataLen);
  1367. _numberOfMipmaps = header->numberOfMipmaps;
  1368. CCASSERT(_numberOfMipmaps < MIPMAP_MAX, "Image: Maximum number of mimpaps reached. Increase the CC_MIPMAP_MAX value");
  1369. for (int i = 0; i < _numberOfMipmaps; i++)
  1370. {
  1371. switch ((PVR3TexturePixelFormat)pixelFormat)
  1372. {
  1373. case PVR3TexturePixelFormat::PVRTC2BPP_RGB :
  1374. case PVR3TexturePixelFormat::PVRTC2BPP_RGBA :
  1375. if (!Configuration::getInstance()->supportsPVRTC())
  1376. {
  1377. CCLOG("cocos2d: Hardware PVR decoder not present. Using software decoder");
  1378. _unpack = true;
  1379. _mipmaps[i].len = width*height*4;
  1380. //_mipmaps[i].address = new (std::nothrow) unsigned char[width*height*4];
  1381. _mipmaps[i].address = static_cast<unsigned char*>(malloc(width*height*4));
  1382. PVRTDecompressPVRTC(_data+dataOffset,width,height,_mipmaps[i].address, true);
  1383. bpp = 2;
  1384. }
  1385. blockSize = 8 * 4; // Pixel by pixel block size for 2bpp
  1386. widthBlocks = width / 8;
  1387. heightBlocks = height / 4;
  1388. break;
  1389. case PVR3TexturePixelFormat::PVRTC4BPP_RGB :
  1390. case PVR3TexturePixelFormat::PVRTC4BPP_RGBA :
  1391. if (!Configuration::getInstance()->supportsPVRTC())
  1392. {
  1393. CCLOG("cocos2d: Hardware PVR decoder not present. Using software decoder");
  1394. _unpack = true;
  1395. _mipmaps[i].len = width*height*4;
  1396. //_mipmaps[i].address = new (std::nothrow) unsigned char[width*height*4];
  1397. _mipmaps[i].address = static_cast<unsigned char*>(malloc(width*height*4));
  1398. PVRTDecompressPVRTC(_data+dataOffset,width,height,_mipmaps[i].address, false);
  1399. bpp = 4;
  1400. }
  1401. blockSize = 4 * 4; // Pixel by pixel block size for 4bpp
  1402. widthBlocks = width / 4;
  1403. heightBlocks = height / 4;
  1404. break;
  1405. case PVR3TexturePixelFormat::ETC1:
  1406. if (!Configuration::getInstance()->supportsETC())
  1407. {
  1408. CCLOG("cocos2d: Hardware ETC1 decoder not present. Using software decoder");
  1409. int bytePerPixel = 3;
  1410. unsigned int stride = width * bytePerPixel;
  1411. _unpack = true;
  1412. _mipmaps[i].len = width*height*bytePerPixel;
  1413. //_mipmaps[i].address = new (std::nothrow) unsigned char[width*height*bytePerPixel];
  1414. _mipmaps[i].address = static_cast<unsigned char*>(malloc(width*height*4));
  1415. if (etc1_decode_image(static_cast<const unsigned char*>(_data+dataOffset), static_cast<etc1_byte*>(_mipmaps[i].address), width, height, bytePerPixel, stride) != 0)
  1416. {
  1417. return false;
  1418. }
  1419. }
  1420. blockSize = 4 * 4; // Pixel by pixel block size for 4bpp
  1421. widthBlocks = width / 4;
  1422. heightBlocks = height / 4;
  1423. break;
  1424. case PVR3TexturePixelFormat::BGRA8888:
  1425. if (! Configuration::getInstance()->supportsBGRA8888())
  1426. {
  1427. CCLOG("cocos2d: Image. BGRA8888 not supported on this device");
  1428. return false;
  1429. }
  1430. default:
  1431. blockSize = 1;
  1432. widthBlocks = width;
  1433. heightBlocks = height;
  1434. break;
  1435. }
  1436. // Clamp to minimum number of blocks
  1437. if (widthBlocks < 2)
  1438. {
  1439. widthBlocks = 2;
  1440. }
  1441. if (heightBlocks < 2)
  1442. {
  1443. heightBlocks = 2;
  1444. }
  1445. dataSize = widthBlocks * heightBlocks * ((blockSize * bpp) / 8);
  1446. auto packetLength = _dataLen - dataOffset;
  1447. packetLength = packetLength > dataSize ? dataSize : packetLength;
  1448. if(!_unpack)
  1449. {
  1450. _mipmaps[i].address = _data + dataOffset;
  1451. _mipmaps[i].len = static_cast<int>(packetLength);
  1452. }
  1453. dataOffset += packetLength;
  1454. CCASSERT(dataOffset <= _dataLen, "Image: Invalid length");
  1455. width = MAX(width >> 1, 1);
  1456. height = MAX(height >> 1, 1);
  1457. }
  1458. if (_unpack)
  1459. {
  1460. free(_data);
  1461. _data = _mipmaps[0].address;
  1462. _dataLen = _mipmaps[0].len;
  1463. }
  1464. return true;
  1465. }
  1466. bool Image::initWithETCData(const unsigned char * data, ssize_t dataLen)
  1467. {
  1468. const etc1_byte* header = static_cast<const etc1_byte*>(data);
  1469. //check the data
  1470. if (! etc1_pkm_is_valid(header))
  1471. {
  1472. return false;
  1473. }
  1474. _width = etc1_pkm_get_width(header);
  1475. _height = etc1_pkm_get_height(header);
  1476. if (0 == _width || 0 == _height)
  1477. {
  1478. return false;
  1479. }
  1480. if (Configuration::getInstance()->supportsETC())
  1481. {
  1482. //old opengl version has no define for GL_ETC1_RGB8_OES, add macro to make compiler happy.
  1483. #ifdef GL_ETC1_RGB8_OES
  1484. _renderFormat = Texture2D::PixelFormat::ETC;
  1485. _dataLen = dataLen - ETC_PKM_HEADER_SIZE;
  1486. _data = static_cast<unsigned char*>(malloc(_dataLen * sizeof(unsigned char)));
  1487. memcpy(_data, static_cast<const unsigned char*>(data) + ETC_PKM_HEADER_SIZE, _dataLen);
  1488. return true;
  1489. #else
  1490. CC_UNUSED_PARAM(dataLen);
  1491. #endif
  1492. }
  1493. else
  1494. {
  1495. CCLOG("cocos2d: Hardware ETC1 decoder not present. Using software decoder");
  1496. //if it is not gles or device do not support ETC, decode texture by software
  1497. int bytePerPixel = 3;
  1498. unsigned int stride = _width * bytePerPixel;
  1499. _renderFormat = Texture2D::PixelFormat::RGB888;
  1500. _dataLen = _width * _height * bytePerPixel;
  1501. _data = static_cast<unsigned char*>(malloc(_dataLen * sizeof(unsigned char)));
  1502. if (etc1_decode_image(static_cast<const unsigned char*>(data) + ETC_PKM_HEADER_SIZE, static_cast<etc1_byte*>(_data), _width, _height, bytePerPixel, stride) != 0)
  1503. {
  1504. _dataLen = 0;
  1505. if (_data != nullptr)
  1506. {
  1507. free(_data);
  1508. }
  1509. return false;
  1510. }
  1511. return true;
  1512. }
  1513. return false;
  1514. }
  1515. bool Image::initWithTGAData(tImageTGA* tgaData)
  1516. {
  1517. bool ret = false;
  1518. do
  1519. {
  1520. CC_BREAK_IF(tgaData == nullptr);
  1521. // tgaLoadBuffer only support type 2, 3, 10
  1522. if (2 == tgaData->type || 10 == tgaData->type)
  1523. {
  1524. // true color
  1525. // unsupported RGB555
  1526. if (tgaData->pixelDepth == 16)
  1527. {
  1528. _renderFormat = Texture2D::PixelFormat::RGB5A1;
  1529. }
  1530. else if(tgaData->pixelDepth == 24)
  1531. {
  1532. _renderFormat = Texture2D::PixelFormat::RGB888;
  1533. }
  1534. else if(tgaData->pixelDepth == 32)
  1535. {
  1536. _renderFormat = Texture2D::PixelFormat::RGBA8888;
  1537. }
  1538. else
  1539. {
  1540. CCLOG("Image WARNING: unsupported true color tga data pixel format. FILE: %s", _filePath.c_str());
  1541. break;
  1542. }
  1543. }
  1544. else if(3 == tgaData->type)
  1545. {
  1546. // gray
  1547. if (8 == tgaData->pixelDepth)
  1548. {
  1549. _renderFormat = Texture2D::PixelFormat::I8;
  1550. }
  1551. else
  1552. {
  1553. // actually this won't happen, if it happens, maybe the image file is not a tga
  1554. CCLOG("Image WARNING: unsupported gray tga data pixel format. FILE: %s", _filePath.c_str());
  1555. break;
  1556. }
  1557. }
  1558. _width = tgaData->width;
  1559. _height = tgaData->height;
  1560. _data = tgaData->imageData;
  1561. _dataLen = _width * _height * tgaData->pixelDepth / 8;
  1562. _fileType = Format::TGA;
  1563. ret = true;
  1564. }while(false);
  1565. if (ret)
  1566. {
  1567. if (FileUtils::getInstance()->getFileExtension(_filePath) != ".tga")
  1568. {
  1569. CCLOG("Image WARNING: the image file suffix is not tga, but parsed as a tga image file. FILE: %s", _filePath.c_str());
  1570. }
  1571. }
  1572. else
  1573. {
  1574. if (tgaData && tgaData->imageData != nullptr)
  1575. {
  1576. free(tgaData->imageData);
  1577. _data = nullptr;
  1578. }
  1579. }
  1580. return ret;
  1581. }
  1582. namespace
  1583. {
  1584. static uint32_t makeFourCC(char ch0, char ch1, char ch2, char ch3)
  1585. {
  1586. const uint32_t fourCC = ((uint32_t)(char)(ch0) | ((uint32_t)(char)(ch1) << 8) | ((uint32_t)(char)(ch2) << 16) | ((uint32_t)(char)(ch3) << 24 ));
  1587. return fourCC;
  1588. }
  1589. }
  1590. bool Image::initWithS3TCData(const unsigned char * data, ssize_t dataLen)
  1591. {
  1592. const uint32_t FOURCC_DXT1 = makeFourCC('D', 'X', 'T', '1');
  1593. const uint32_t FOURCC_DXT3 = makeFourCC('D', 'X', 'T', '3');
  1594. const uint32_t FOURCC_DXT5 = makeFourCC('D', 'X', 'T', '5');
  1595. /* load the .dds file */
  1596. S3TCTexHeader *header = (S3TCTexHeader *)data;
  1597. unsigned char *pixelData = static_cast<unsigned char*>(malloc((dataLen - sizeof(S3TCTexHeader)) * sizeof(unsigned char)));
  1598. memcpy((void *)pixelData, data + sizeof(S3TCTexHeader), dataLen - sizeof(S3TCTexHeader));
  1599. _width = header->ddsd.width;
  1600. _height = header->ddsd.height;
  1601. _numberOfMipmaps = MAX(1, header->ddsd.DUMMYUNIONNAMEN2.mipMapCount); //if dds header reports 0 mipmaps, set to 1 to force correct software decoding (if needed).
  1602. _dataLen = 0;
  1603. int blockSize = (FOURCC_DXT1 == header->ddsd.DUMMYUNIONNAMEN4.ddpfPixelFormat.fourCC) ? 8 : 16;
  1604. /* calculate the dataLen */
  1605. int width = _width;
  1606. int height = _height;
  1607. if (Configuration::getInstance()->supportsS3TC()) //compressed data length
  1608. {
  1609. _dataLen = dataLen - sizeof(S3TCTexHeader);
  1610. _data = static_cast<unsigned char*>(malloc(_dataLen * sizeof(unsigned char)));
  1611. memcpy((void *)_data,(void *)pixelData , _dataLen);
  1612. }
  1613. else //decompressed data length
  1614. {
  1615. for (int i = 0; i < _numberOfMipmaps && (width || height); ++i)
  1616. {
  1617. if (width == 0) width = 1;
  1618. if (height == 0) height = 1;
  1619. _dataLen += (height * width *4);
  1620. width >>= 1;
  1621. height >>= 1;
  1622. }
  1623. _data = static_cast<unsigned char*>(malloc(_dataLen * sizeof(unsigned char)));
  1624. }
  1625. /* if hardware supports s3tc, set pixelformat before loading mipmaps, to support non-mipmapped textures */
  1626. if (Configuration::getInstance()->supportsS3TC())
  1627. { //decode texture through hardware
  1628. if (FOURCC_DXT1 == header->ddsd.DUMMYUNIONNAMEN4.ddpfPixelFormat.fourCC)
  1629. {
  1630. _renderFormat = Texture2D::PixelFormat::S3TC_DXT1;
  1631. }
  1632. else if (FOURCC_DXT3 == header->ddsd.DUMMYUNIONNAMEN4.ddpfPixelFormat.fourCC)
  1633. {
  1634. _renderFormat = Texture2D::PixelFormat::S3TC_DXT3;
  1635. }
  1636. else if (FOURCC_DXT5 == header->ddsd.DUMMYUNIONNAMEN4.ddpfPixelFormat.fourCC)
  1637. {
  1638. _renderFormat = Texture2D::PixelFormat::S3TC_DXT5;
  1639. }
  1640. } else { //will software decode
  1641. _renderFormat = Texture2D::PixelFormat::RGBA8888;
  1642. }
  1643. /* load the mipmaps */
  1644. int encodeOffset = 0;
  1645. int decodeOffset = 0;
  1646. width = _width; height = _height;
  1647. for (int i = 0; i < _numberOfMipmaps && (width || height); ++i)
  1648. {
  1649. if (width == 0) width = 1;
  1650. if (height == 0) height = 1;
  1651. int size = ((width+3)/4)*((height+3)/4)*blockSize;
  1652. if (Configuration::getInstance()->supportsS3TC())
  1653. { //decode texture through hardware
  1654. _mipmaps[i].address = (unsigned char *)_data + encodeOffset;
  1655. _mipmaps[i].len = size;
  1656. }
  1657. else
  1658. { //if it is not gles or device do not support S3TC, decode texture by software
  1659. CCLOG("cocos2d: Hardware S3TC decoder not present. Using software decoder");
  1660. int bytePerPixel = 4;
  1661. unsigned int stride = width * bytePerPixel;
  1662. std::vector<unsigned char> decodeImageData(stride * height);
  1663. if (FOURCC_DXT1 == header->ddsd.DUMMYUNIONNAMEN4.ddpfPixelFormat.fourCC)
  1664. {
  1665. s3tc_decode(pixelData + encodeOffset, &decodeImageData[0], width, height, S3TCDecodeFlag::DXT1);
  1666. }
  1667. else if (FOURCC_DXT3 == header->ddsd.DUMMYUNIONNAMEN4.ddpfPixelFormat.fourCC)
  1668. {
  1669. s3tc_decode(pixelData + encodeOffset, &decodeImageData[0], width, height, S3TCDecodeFlag::DXT3);
  1670. }
  1671. else if (FOURCC_DXT5 == header->ddsd.DUMMYUNIONNAMEN4.ddpfPixelFormat.fourCC)
  1672. {
  1673. s3tc_decode(pixelData + encodeOffset, &decodeImageData[0], width, height, S3TCDecodeFlag::DXT5);
  1674. }
  1675. _mipmaps[i].address = (unsigned char *)_data + decodeOffset;
  1676. _mipmaps[i].len = (stride * height);
  1677. memcpy((void *)_mipmaps[i].address, (void *)&decodeImageData[0], _mipmaps[i].len);
  1678. decodeOffset += stride * height;
  1679. }
  1680. encodeOffset += size;
  1681. width >>= 1;
  1682. height >>= 1;
  1683. }
  1684. /* end load the mipmaps */
  1685. if (pixelData != nullptr)
  1686. {
  1687. free(pixelData);
  1688. };
  1689. return true;
  1690. }
  1691. bool Image::initWithATITCData(const unsigned char *data, ssize_t dataLen)
  1692. {
  1693. /* load the .ktx file */
  1694. ATITCTexHeader *header = (ATITCTexHeader *)data;
  1695. _width = header->pixelWidth;
  1696. _height = header->pixelHeight;
  1697. _numberOfMipmaps = header->numberOfMipmapLevels;
  1698. int blockSize = 0;
  1699. switch (header->glInternalFormat)
  1700. {
  1701. case CC_GL_ATC_RGB_AMD:
  1702. blockSize = 8;
  1703. break;
  1704. case CC_GL_ATC_RGBA_EXPLICIT_ALPHA_AMD:
  1705. blockSize = 16;
  1706. break;
  1707. case CC_GL_ATC_RGBA_INTERPOLATED_ALPHA_AMD:
  1708. blockSize = 16;
  1709. break;
  1710. default:
  1711. break;
  1712. }
  1713. /* pixelData point to the compressed data address */
  1714. unsigned char *pixelData = (unsigned char *)data + sizeof(ATITCTexHeader) + header->bytesOfKeyValueData + 4;
  1715. /* calculate the dataLen */
  1716. int width = _width;
  1717. int height = _height;
  1718. if (Configuration::getInstance()->supportsATITC()) //compressed data length
  1719. {
  1720. _dataLen = dataLen - sizeof(ATITCTexHeader) - header->bytesOfKeyValueData - 4;
  1721. _data = static_cast<unsigned char*>(malloc(_dataLen * sizeof(unsigned char)));
  1722. memcpy((void *)_data,(void *)pixelData , _dataLen);
  1723. }
  1724. else //decompressed data length
  1725. {
  1726. for (int i = 0; i < _numberOfMipmaps && (width || height); ++i)
  1727. {
  1728. if (width == 0) width = 1;
  1729. if (height == 0) height = 1;
  1730. _dataLen += (height * width *4);
  1731. width >>= 1;
  1732. height >>= 1;
  1733. }
  1734. _data = static_cast<unsigned char*>(malloc(_dataLen * sizeof(unsigned char)));
  1735. }
  1736. /* load the mipmaps */
  1737. int encodeOffset = 0;
  1738. int decodeOffset = 0;
  1739. width = _width; height = _height;
  1740. for (int i = 0; i < _numberOfMipmaps && (width || height); ++i)
  1741. {
  1742. if (width == 0) width = 1;
  1743. if (height == 0) height = 1;
  1744. int size = ((width+3)/4)*((height+3)/4)*blockSize;
  1745. if (Configuration::getInstance()->supportsATITC())
  1746. {
  1747. /* decode texture through hardware */
  1748. CCLOG("this is atitc H decode");
  1749. switch (header->glInternalFormat)
  1750. {
  1751. case CC_GL_ATC_RGB_AMD:
  1752. _renderFormat = Texture2D::PixelFormat::ATC_RGB;
  1753. break;
  1754. case CC_GL_ATC_RGBA_EXPLICIT_ALPHA_AMD:
  1755. _renderFormat = Texture2D::PixelFormat::ATC_EXPLICIT_ALPHA;
  1756. break;
  1757. case CC_GL_ATC_RGBA_INTERPOLATED_ALPHA_AMD:
  1758. _renderFormat = Texture2D::PixelFormat::ATC_INTERPOLATED_ALPHA;
  1759. break;
  1760. default:
  1761. break;
  1762. }
  1763. _mipmaps[i].address = (unsigned char *)_data + encodeOffset;
  1764. _mipmaps[i].len = size;
  1765. }
  1766. else
  1767. {
  1768. /* if it is not gles or device do not support ATITC, decode texture by software */
  1769. CCLOG("cocos2d: Hardware ATITC decoder not present. Using software decoder");
  1770. int bytePerPixel = 4;
  1771. unsigned int stride = width * bytePerPixel;
  1772. _renderFormat = Texture2D::PixelFormat::RGBA8888;
  1773. std::vector<unsigned char> decodeImageData(stride * height);
  1774. switch (header->glInternalFormat)
  1775. {
  1776. case CC_GL_ATC_RGB_AMD:
  1777. atitc_decode(pixelData + encodeOffset, &decodeImageData[0], width, height, ATITCDecodeFlag::ATC_RGB);
  1778. break;
  1779. case CC_GL_ATC_RGBA_EXPLICIT_ALPHA_AMD:
  1780. atitc_decode(pixelData + encodeOffset, &decodeImageData[0], width, height, ATITCDecodeFlag::ATC_EXPLICIT_ALPHA);
  1781. break;
  1782. case CC_GL_ATC_RGBA_INTERPOLATED_ALPHA_AMD:
  1783. atitc_decode(pixelData + encodeOffset, &decodeImageData[0], width, height, ATITCDecodeFlag::ATC_INTERPOLATED_ALPHA);
  1784. break;
  1785. default:
  1786. break;
  1787. }
  1788. _mipmaps[i].address = (unsigned char *)_data + decodeOffset;
  1789. _mipmaps[i].len = (stride * height);
  1790. memcpy((void *)_mipmaps[i].address, (void *)&decodeImageData[0], _mipmaps[i].len);
  1791. decodeOffset += stride * height;
  1792. }
  1793. encodeOffset += (size + 4);
  1794. width >>= 1;
  1795. height >>= 1;
  1796. }
  1797. /* end load the mipmaps */
  1798. return true;
  1799. }
  1800. bool Image::initWithPVRData(const unsigned char * data, ssize_t dataLen)
  1801. {
  1802. return initWithPVRv2Data(data, dataLen) || initWithPVRv3Data(data, dataLen);
  1803. }
  1804. bool Image::initWithWebpData(const unsigned char * data, ssize_t dataLen)
  1805. {
  1806. #if CC_USE_WEBP
  1807. bool ret = false;
  1808. #if (CC_TARGET_PLATFORM == CC_PLATFORM_WINRT)
  1809. CCLOG("WEBP image format not supported on WinRT or WP8");
  1810. #else
  1811. do
  1812. {
  1813. WebPDecoderConfig config;
  1814. if (WebPInitDecoderConfig(&config) == 0) break;
  1815. if (WebPGetFeatures(static_cast<const uint8_t*>(data), dataLen, &config.input) != VP8_STATUS_OK) break;
  1816. if (config.input.width == 0 || config.input.height == 0) break;
  1817. config.output.colorspace = config.input.has_alpha?MODE_rgbA:MODE_RGB;
  1818. _renderFormat = config.input.has_alpha?Texture2D::PixelFormat::RGBA8888:Texture2D::PixelFormat::RGB888;
  1819. _width = config.input.width;
  1820. _height = config.input.height;
  1821. //we ask webp to give data with premultiplied alpha
  1822. _hasPremultipliedAlpha = (config.input.has_alpha != 0);
  1823. _dataLen = _width * _height * (config.input.has_alpha?4:3);
  1824. _data = static_cast<unsigned char*>(malloc(_dataLen * sizeof(unsigned char)));
  1825. config.output.u.RGBA.rgba = static_cast<uint8_t*>(_data);
  1826. config.output.u.RGBA.stride = _width * (config.input.has_alpha?4:3);
  1827. config.output.u.RGBA.size = _dataLen;
  1828. config.output.is_external_memory = 1;
  1829. if (WebPDecode(static_cast<const uint8_t*>(data), dataLen, &config) != VP8_STATUS_OK)
  1830. {
  1831. free(_data);
  1832. _data = nullptr;
  1833. break;
  1834. }
  1835. ret = true;
  1836. } while (0);
  1837. #endif // (CC_TARGET_PLATFORM == CC_PLATFORM_WINRT)
  1838. return ret;
  1839. #else
  1840. CCLOG("webp is not enabled, please enable it in ccConfig.h");
  1841. return false;
  1842. #endif // CC_USE_WEBP
  1843. }
  1844. bool Image::initWithRawData(const unsigned char * data, ssize_t /*dataLen*/, int width, int height, int /*bitsPerComponent*/, bool preMulti)
  1845. {
  1846. bool ret = false;
  1847. do
  1848. {
  1849. CC_BREAK_IF(0 == width || 0 == height);
  1850. _height = height;
  1851. _width = width;
  1852. _hasPremultipliedAlpha = preMulti;
  1853. _renderFormat = Texture2D::PixelFormat::RGBA8888;
  1854. // only RGBA8888 supported
  1855. int bytesPerComponent = 4;
  1856. _dataLen = height * width * bytesPerComponent;
  1857. _data = static_cast<unsigned char*>(malloc(_dataLen * sizeof(unsigned char)));
  1858. CC_BREAK_IF(! _data);
  1859. memcpy(_data, data, _dataLen);
  1860. ret = true;
  1861. } while (0);
  1862. return ret;
  1863. }
  1864. #if (CC_TARGET_PLATFORM != CC_PLATFORM_IOS)
  1865. bool Image::saveToFile(const std::string& filename, bool isToRGB)
  1866. {
  1867. //only support for Texture2D::PixelFormat::RGB888 or Texture2D::PixelFormat::RGBA8888 uncompressed data
  1868. if (isCompressed() || (_renderFormat != Texture2D::PixelFormat::RGB888 && _renderFormat != Texture2D::PixelFormat::RGBA8888))
  1869. {
  1870. CCLOG("cocos2d: Image: saveToFile is only support for Texture2D::PixelFormat::RGB888 or Texture2D::PixelFormat::RGBA8888 uncompressed data for now");
  1871. return false;
  1872. }
  1873. std::string fileExtension = FileUtils::getInstance()->getFileExtension(filename);
  1874. if (fileExtension == ".png")
  1875. {
  1876. return saveImageToPNG(filename, isToRGB);
  1877. }
  1878. else if (fileExtension == ".jpg")
  1879. {
  1880. return saveImageToJPG(filename);
  1881. }
  1882. else
  1883. {
  1884. CCLOG("cocos2d: Image: saveToFile no support file extension(only .png or .jpg) for file: %s", filename.c_str());
  1885. return false;
  1886. }
  1887. }
  1888. #endif
  1889. bool Image::saveImageToPNG(const std::string& filePath, bool isToRGB)
  1890. {
  1891. #if CC_USE_WIC
  1892. return encodeWithWIC(filePath, isToRGB, GUID_ContainerFormatPng);
  1893. #elif CC_USE_PNG
  1894. bool ret = false;
  1895. do
  1896. {
  1897. FILE *fp;
  1898. png_structp png_ptr;
  1899. png_infop info_ptr;
  1900. png_bytep *row_pointers;
  1901. fp = fopen(FileUtils::getInstance()->getSuitableFOpen(filePath).c_str(), "wb");
  1902. CC_BREAK_IF(nullptr == fp);
  1903. png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, nullptr, nullptr, nullptr);
  1904. if (nullptr == png_ptr)
  1905. {
  1906. fclose(fp);
  1907. break;
  1908. }
  1909. info_ptr = png_create_info_struct(png_ptr);
  1910. if (nullptr == info_ptr)
  1911. {
  1912. fclose(fp);
  1913. png_destroy_write_struct(&png_ptr, nullptr);
  1914. break;
  1915. }
  1916. #if (CC_TARGET_PLATFORM != CC_PLATFORM_BADA && CC_TARGET_PLATFORM != CC_PLATFORM_NACL && CC_TARGET_PLATFORM != CC_PLATFORM_TIZEN)
  1917. if (setjmp(png_jmpbuf(png_ptr)))
  1918. {
  1919. fclose(fp);
  1920. png_destroy_write_struct(&png_ptr, &info_ptr);
  1921. break;
  1922. }
  1923. #endif
  1924. png_init_io(png_ptr, fp);
  1925. if (!isToRGB && hasAlpha())
  1926. {
  1927. png_set_IHDR(png_ptr, info_ptr, _width, _height, 8, PNG_COLOR_TYPE_RGB_ALPHA,
  1928. PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);
  1929. }
  1930. else
  1931. {
  1932. png_set_IHDR(png_ptr, info_ptr, _width, _height, 8, PNG_COLOR_TYPE_RGB,
  1933. PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);
  1934. }
  1935. png_write_info(png_ptr, info_ptr);
  1936. png_set_packing(png_ptr);
  1937. row_pointers = (png_bytep *)malloc(_height * sizeof(png_bytep));
  1938. if(row_pointers == nullptr)
  1939. {
  1940. fclose(fp);
  1941. png_destroy_write_struct(&png_ptr, &info_ptr);
  1942. break;
  1943. }
  1944. if (!hasAlpha())
  1945. {
  1946. for (int i = 0; i < (int)_height; i++)
  1947. {
  1948. row_pointers[i] = (png_bytep)_data + i * _width * 3;
  1949. }
  1950. png_write_image(png_ptr, row_pointers);
  1951. free(row_pointers);
  1952. row_pointers = nullptr;
  1953. }
  1954. else
  1955. {
  1956. if (isToRGB)
  1957. {
  1958. unsigned char *tempData = static_cast<unsigned char*>(malloc(_width * _height * 3 * sizeof(unsigned char)));
  1959. if (nullptr == tempData)
  1960. {
  1961. fclose(fp);
  1962. png_destroy_write_struct(&png_ptr, &info_ptr);
  1963. free(row_pointers);
  1964. row_pointers = nullptr;
  1965. break;
  1966. }
  1967. for (int i = 0; i < _height; ++i)
  1968. {
  1969. for (int j = 0; j < _width; ++j)
  1970. {
  1971. tempData[(i * _width + j) * 3] = _data[(i * _width + j) * 4];
  1972. tempData[(i * _width + j) * 3 + 1] = _data[(i * _width + j) * 4 + 1];
  1973. tempData[(i * _width + j) * 3 + 2] = _data[(i * _width + j) * 4 + 2];
  1974. }
  1975. }
  1976. for (int i = 0; i < (int)_height; i++)
  1977. {
  1978. row_pointers[i] = (png_bytep)tempData + i * _width * 3;
  1979. }
  1980. png_write_image(png_ptr, row_pointers);
  1981. free(row_pointers);
  1982. row_pointers = nullptr;
  1983. if (tempData != nullptr)
  1984. {
  1985. free(tempData);
  1986. }
  1987. }
  1988. else
  1989. {
  1990. for (int i = 0; i < (int)_height; i++)
  1991. {
  1992. row_pointers[i] = (png_bytep)_data + i * _width * 4;
  1993. }
  1994. png_write_image(png_ptr, row_pointers);
  1995. free(row_pointers);
  1996. row_pointers = nullptr;
  1997. }
  1998. }
  1999. png_write_end(png_ptr, info_ptr);
  2000. png_destroy_write_struct(&png_ptr, &info_ptr);
  2001. fclose(fp);
  2002. ret = true;
  2003. } while (0);
  2004. return ret;
  2005. #else
  2006. CCLOG("png is not enabled, please enable it in ccConfig.h");
  2007. return false;
  2008. #endif // CC_USE_PNG
  2009. }
  2010. bool Image::saveImageToJPG(const std::string& filePath)
  2011. {
  2012. #if CC_USE_WIC
  2013. return encodeWithWIC(filePath, false, GUID_ContainerFormatJpeg);
  2014. #elif CC_USE_JPEG
  2015. bool ret = false;
  2016. do
  2017. {
  2018. struct jpeg_compress_struct cinfo;
  2019. struct jpeg_error_mgr jerr;
  2020. FILE * outfile; /* target file */
  2021. JSAMPROW row_pointer[1]; /* pointer to JSAMPLE row[s] */
  2022. int row_stride; /* physical row width in image buffer */
  2023. cinfo.err = jpeg_std_error(&jerr);
  2024. /* Now we can initialize the JPEG compression object. */
  2025. jpeg_create_compress(&cinfo);
  2026. CC_BREAK_IF((outfile = fopen(FileUtils::getInstance()->getSuitableFOpen(filePath).c_str(), "wb")) == nullptr);
  2027. jpeg_stdio_dest(&cinfo, outfile);
  2028. cinfo.image_width = _width; /* image width and height, in pixels */
  2029. cinfo.image_height = _height;
  2030. cinfo.input_components = 3; /* # of color components per pixel */
  2031. cinfo.in_color_space = JCS_RGB; /* colorspace of input image */
  2032. jpeg_set_defaults(&cinfo);
  2033. jpeg_set_quality(&cinfo, 90, TRUE);
  2034. jpeg_start_compress(&cinfo, TRUE);
  2035. row_stride = _width * 3; /* JSAMPLEs per row in image_buffer */
  2036. if (hasAlpha())
  2037. {
  2038. unsigned char *tempData = static_cast<unsigned char*>(malloc(_width * _height * 3 * sizeof(unsigned char)));
  2039. if (nullptr == tempData)
  2040. {
  2041. jpeg_finish_compress(&cinfo);
  2042. jpeg_destroy_compress(&cinfo);
  2043. fclose(outfile);
  2044. break;
  2045. }
  2046. for (int i = 0; i < _height; ++i)
  2047. {
  2048. for (int j = 0; j < _width; ++j)
  2049. {
  2050. tempData[(i * _width + j) * 3] = _data[(i * _width + j) * 4];
  2051. tempData[(i * _width + j) * 3 + 1] = _data[(i * _width + j) * 4 + 1];
  2052. tempData[(i * _width + j) * 3 + 2] = _data[(i * _width + j) * 4 + 2];
  2053. }
  2054. }
  2055. while (cinfo.next_scanline < cinfo.image_height)
  2056. {
  2057. row_pointer[0] = & tempData[cinfo.next_scanline * row_stride];
  2058. (void) jpeg_write_scanlines(&cinfo, row_pointer, 1);
  2059. }
  2060. if (tempData != nullptr)
  2061. {
  2062. free(tempData);
  2063. }
  2064. }
  2065. else
  2066. {
  2067. while (cinfo.next_scanline < cinfo.image_height) {
  2068. row_pointer[0] = & _data[cinfo.next_scanline * row_stride];
  2069. (void) jpeg_write_scanlines(&cinfo, row_pointer, 1);
  2070. }
  2071. }
  2072. jpeg_finish_compress(&cinfo);
  2073. fclose(outfile);
  2074. jpeg_destroy_compress(&cinfo);
  2075. ret = true;
  2076. } while (0);
  2077. return ret;
  2078. #else
  2079. CCLOG("jpeg is not enabled, please enable it in ccConfig.h");
  2080. return false;
  2081. #endif // CC_USE_JPEG
  2082. }
  2083. void Image::premultipliedAlpha()
  2084. {
  2085. #if CC_ENABLE_PREMULTIPLIED_ALPHA == 0
  2086. _hasPremultipliedAlpha = false;
  2087. return;
  2088. #else
  2089. CCASSERT(_renderFormat == Texture2D::PixelFormat::RGBA8888, "The pixel format should be RGBA8888!");
  2090. unsigned int* fourBytes = (unsigned int*)_data;
  2091. for(int i = 0; i < _width * _height; i++)
  2092. {
  2093. unsigned char* p = _data + i * 4;
  2094. fourBytes[i] = CC_RGB_PREMULTIPLY_ALPHA(p[0], p[1], p[2], p[3]);
  2095. }
  2096. _hasPremultipliedAlpha = true;
  2097. #endif
  2098. }
  2099. void Image::setPVRImagesHavePremultipliedAlpha(bool haveAlphaPremultiplied)
  2100. {
  2101. _PVRHaveAlphaPremultiplied = haveAlphaPremultiplied;
  2102. }
  2103. NS_CC_END