Cocos Creator 图片加密


Cocos Creator 图片加密

https://blog.csdn.net/u013654125/article/details/89395940

  • python 3.7.0

  • encode.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
# -*- coding:UTF-8 -*-
#该脚本用于加密png图片 使用python3以上版本解释执行
__author__ = "ChenGuanzhou"

import os
import time
CUR_DIR = os.getcwd();
CUR_DIR += '\\build\\jsb-default\\res\\raw-assets'
print("cur_dir:",CUR_DIR)
_KEY = 'galaxy2020' #指定加密秘钥,英文
_ENCRYSIG = 'galaxy2'
_PNGSIG = bytes([0x89,0x50,0x4e,0x47,0x0d,0x0a,0x1a,0x0a])
_PNGIEND = bytes([0x00, 0x00, 0x00, 0x00, 0x49, 0x45, 0x4E, 0x44, 0xAE, 0x42, 0x60, 0x82])
#获取filesig是否是png
def isPNGSig(bytes_8):
return bytes_8 == _PNGSIG

def isPNG(absPath):#判断是否是PNG图片
"""
:param absPath: 文件的绝对路径
:return: {Bool}
"""
isFile = os.path.isfile(absPath)
hasPNGSig = False
fileExt = os.path.splitext(absPath)[1]
isPngExt = (fileExt == ".png" or fileExt == ".PNG")
if isFile and isPngExt:
with open(absPath,"rb") as file:
hasPNGSig = isPNGSig(file.read(8)[:8])
return isFile and isPngExt and hasPNGSig

def preProcessPng(pngData):#预处理图片数据
"""
剪掉png的signature(8bytes),IEND(12Bytes)
:param pngData:
:return:
"""
assert type(pngData) == bytes
lostHeadData = pngData[8:]
iendData = lostHeadData[-12:]
if iendData == _PNGIEND:#防止Png已经进行过外部软件的压缩,丢掉了IEND
return lostHeadData[:-12]
else:
return lostHeadData

def encryption(fileData,key):#加密操作 ascii占一个字节
"""
加密png数据
:param fileData:{bytes}预处理后的png数据
:param key:{str}秘钥
:return:{bytes}加密后的数据
"""
assert type(key) is str
k = bytes(key,"utf8")
klen= len(k)
kindex = 0
fileData = bytearray(fileData)
for i,v in enumerate(fileData):
if kindex >= klen:
kindex = 0
fileData[i] = v ^ k[kindex]#加密
kindex = kindex + 1
return bytes(_ENCRYSIG,"utf8") + fileData

#处理图片
def processPNG(filePath):
global filenum
fileData = None
with open(filePath,'rb') as file:
fileData = encryption(preProcessPng(file.read()),_KEY)
os.remove(filePath)
with open(filePath,'wb') as file: #覆盖新文件
file.write(fileData)
filenum = filenum + 1



def traverseDir(absDir):#遍历当前目录以及递归的子目录,找到所有的png图片
"""
:param absDir: 要遍历的路径
:return: None
"""
assert (os.path.isdir(absDir) and os.path.isabs(absDir))
dirName = absDir
for fileName in os.listdir(absDir):
absFileName = os.path.join(dirName,fileName)
print("isPNG:",absFileName)
if os.path.isdir(absFileName):#递归查找文件夹
print("absFileName:",absFileName)
traverseDir(absFileName)
elif isPNG(absFileName):
print("isPNG:",absFileName)
processPNG(absFileName)
else:
pass


#------------------- 主函数-------------------------#
start_clock = time.clock()
filenum = 0
#traverseDir(os.path.join(CUR_DIR,"png2"))
traverseDir(CUR_DIR)
end_clock = time.clock()
time = (end_clock - start_clock)*1000
print("encrypt %d Png Pictures"%filenum)
print("use time %fms"%time)
  • CCImage.h

build\jsb-default\frameworks\cocos2d-x\cocos\platform 目录

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
/****************************************************************************
Copyright (c) 2010-2012 cocos2d-x.org
Copyright (c) 2013-2016 Chukong Technologies Inc.

http://www.cocos2d-x.org

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/

#ifndef __CC_IMAGE_H__
#define __CC_IMAGE_H__
/// @cond DO_NOT_SHOW

#include "base/CCRef.h"
#include "platform/CCGL.h"
#include "platform/CCStdC.h"

#include <string>
#include <map>

// premultiply alpha, or the effect will wrong when want to use other pixel format in Texture2D,
// such as RGB888, RGB5A1
#define CC_RGB_PREMULTIPLY_ALPHA(vr, vg, vb, va) \
(unsigned)(((unsigned)((unsigned char)(vr) * ((unsigned char)(va) + 1)) >> 8) | \
((unsigned)((unsigned char)(vg) * ((unsigned char)(va) + 1) >> 8) << 8) | \
((unsigned)((unsigned char)(vb) * ((unsigned char)(va) + 1) >> 8) << 16) | \
((unsigned)(unsigned char)(va) << 24))

NS_CC_BEGIN

/**
* @addtogroup platform
* @{
*/

/**
@brief Structure which can tell where mipmap begins and how long is it
*/
typedef struct _MipmapInfo
{
unsigned char* address = nullptr;
int offset = 0;
int len = 0;
}MipmapInfo;

class Image : public Ref
{
public:
/**
* @js ctor
*/
Image();

/** Supported formats for Image */
enum class Format
{
//! JPEG
JPG,
//! PNG
PNG,
//! ENCRYPTEDPNG,下面这行是新加的
ENCRYPTEDPNG, //加密后的Png图片
//! TIFF
TIFF,
//! WebP
WEBP,
//! PVR
PVR,
//! ETC
ETC,
//! ETC2
ETC2,
//! S3TC
S3TC,
//! ATITC
// ATITC,
//! TGA
TGA,
//! Raw Data
RAW_DATA,
//! Unknown format
UNKNOWN
};

/** @typedef Texture2D::PixelFormat
Possible texture pixel formats
*/
enum class PixelFormat
{
//! auto detect the type
AUTO,
//! 32-bit texture: BGRA8888
BGRA8888,
//! 32-bit texture: RGBA8888
RGBA8888,
//! 24-bit texture: RGBA888
RGB888,
//! 16-bit texture without Alpha channel
RGB565,
//! 8-bit textures used as masks
A8,
//! 8-bit intensity texture
I8,
//! 16-bit textures used as masks
AI88,
//! 16-bit textures: RGBA4444
RGBA4444,
//! 16-bit textures: RGB5A1
RGB5A1,
//! 4-bit PVRTC-compressed texture: PVRTC4
PVRTC4,
//! 4-bit PVRTC-compressed texture: PVRTC4 (has alpha channel)
PVRTC4A,
//! 2-bit PVRTC-compressed texture: PVRTC2
PVRTC2,
//! 2-bit PVRTC-compressed texture: PVRTC2 (has alpha channel)
PVRTC2A,
//! ETC-compressed texture: ETC
ETC,
//! ETC-compressed texture: GL_COMPRESSED_RGB8_ETC2
ETC2_RGB,
//! ETC-compressed texture: GL_COMPRESSED_RGBA8_ETC2
ETC2_RGBA,
//! S3TC-compressed texture: S3TC_Dxt1
S3TC_DXT1,
//! S3TC-compressed texture: S3TC_Dxt3
S3TC_DXT3,
//! S3TC-compressed texture: S3TC_Dxt5
S3TC_DXT5,
//! ATITC-compressed texture: ATC_RGB
ATC_RGB,
//! ATITC-compressed texture: ATC_EXPLICIT_ALPHA
ATC_EXPLICIT_ALPHA,
//! ATITC-compressed texture: ATC_INTERPOLATED_ALPHA
ATC_INTERPOLATED_ALPHA,
//! Default texture format: AUTO
DEFAULT = AUTO,

NONE = -1
};

struct PixelFormatInfo {

PixelFormatInfo(GLenum anInternalFormat, GLenum aFormat, GLenum aType, int aBpp, bool aCompressed, bool anAlpha)
: internalFormat(anInternalFormat)
, format(aFormat)
, type(aType)
, bpp(aBpp)
, compressed(aCompressed)
, alpha(anAlpha)
{}

GLenum internalFormat;
GLenum format;
GLenum type;
int bpp;
bool compressed;
bool alpha;
};

typedef std::map<PixelFormat, const PixelFormatInfo> PixelFormatInfoMap;

/**
* Enables or disables premultiplied alpha for PNG files.
*
* @param enabled (default: true)
*/
static void setPNGPremultipliedAlphaEnabled(bool enabled) { PNG_PREMULTIPLIED_ALPHA_ENABLED = enabled; }

/** treats (or not) PVR files as if they have alpha premultiplied.
Since it is impossible to know at runtime if the PVR images have the alpha channel premultiplied, it is
possible load them as if they have (or not) the alpha channel premultiplied.

By default it is disabled.
*/
static void setPVRImagesHavePremultipliedAlpha(bool haveAlphaPremultiplied);

/**
@brief Load the image from the specified path.
@param path the absolute file path.
@return true if loaded correctly.
*/
bool initWithImageFile(const std::string& path);

/**
@brief Load image from stream buffer.
@param data stream buffer which holds the image data.
@param dataLen data length expressed in (number of) bytes.
@return true if loaded correctly.
* @js NA
* @lua NA
*/
bool initWithImageData(const unsigned char * data, ssize_t dataLen);

// @warning kFmtRawData only support RGBA8888
bool initWithRawData(const unsigned char * data, ssize_t dataLen, int width, int height, int bitsPerComponent, bool preMulti = false);

// Getters
inline unsigned char* getData() const { return _data; }
inline ssize_t getDataLen() const { return _dataLen; }
inline Format getFileType() const { return _fileType; }
inline PixelFormat getRenderFormat() const { return _renderFormat; }
inline int getWidth() const { return _width; }
inline int getHeight() const { return _height; }
inline int getNumberOfMipmaps() const { return _numberOfMipmaps; }
inline const MipmapInfo* getMipmaps() const { return _mipmaps; }
inline bool hasPremultipliedAlpha() const { return _hasPremultipliedAlpha; }
inline std::string getFilePath() const { return _filePath; }

int getBitPerPixel() const;
bool hasAlpha() const;
bool isCompressed() const;

const PixelFormatInfo& getPixelFormatInfo() const;

/**
@brief Save Image data to the specified file, with specified format.
@param filename the file's absolute path, including file suffix.
@param isToRGB whether the image is saved as RGB format.
*/
bool saveToFile(const std::string &filename, bool isToRGB = true);

protected:
bool initWithJpgData(const unsigned char * data, ssize_t dataLen);
bool initWithPngData(const unsigned char * data, ssize_t dataLen);
bool initWithTiffData(const unsigned char * data, ssize_t dataLen);
bool initWithWebpData(const unsigned char * data, ssize_t dataLen);
bool initWithPVRData(const unsigned char * data, ssize_t dataLen);
bool initWithPVRv2Data(const unsigned char * data, ssize_t dataLen);
bool initWithPVRv3Data(const unsigned char * data, ssize_t dataLen);
bool initWithETCData(const unsigned char * data, ssize_t dataLen);
bool initWithETC2Data(const unsigned char * data, ssize_t dataLen);
bool initWithS3TCData(const unsigned char * data, ssize_t dataLen);

typedef struct sImageTGA tImageTGA;
bool initWithTGAData(tImageTGA* tgaData);

bool saveImageToPNG(const std::string& filePath, bool isToRGB = true);
bool saveImageToJPG(const std::string& filePath);

void premultipliedAlpha();

protected:
/**
@brief Determine how many mipmaps can we have.
It's same as define but it respects namespaces
*/
static const int MIPMAP_MAX = 16;
/**
@brief Determine whether we premultiply alpha for png files.
*/
static bool PNG_PREMULTIPLIED_ALPHA_ENABLED;
unsigned char *_data;
ssize_t _dataLen;
int _width;
int _height;
Format _fileType;
PixelFormat _renderFormat;
MipmapInfo _mipmaps[MIPMAP_MAX]; // pointer to mipmap images
int _numberOfMipmaps;
// false if we can't auto detect the image is premultiplied or not.
bool _hasPremultipliedAlpha;
std::string _filePath;

protected:
// noncopyable
Image(const Image&) = delete;
Image& operator=(const Image&) = delete;

// nonmoveable
Image(Image&&) = delete;
Image& operator=(Image&&) = delete;

/**
* @js NA
* @lua NA
*/
virtual ~Image();

Format detectFormat(const unsigned char * data, ssize_t dataLen);
bool isPng(const unsigned char * data, ssize_t dataLen);
bool isJpg(const unsigned char * data, ssize_t dataLen);
bool isTiff(const unsigned char * data, ssize_t dataLen);
bool isWebp(const unsigned char * data, ssize_t dataLen);
bool isPvr(const unsigned char * data, ssize_t dataLen);
bool isEtc(const unsigned char * data, ssize_t dataLen);
bool isEtc2(const unsigned char * data, ssize_t dataLen);
bool isS3TC(const unsigned char * data,ssize_t dataLen);

//! 下面是新加的
bool isEncryptedPng(const unsigned char *data, ssize_t dataLen);
void deEncryptPng(unsigned char **copyData, const char *key, ssize_t dataLen);
};

// end of platform group
/// @}

NS_CC_END

/// @endcond
#endif // __CC_IMAGE_H__
  • CCImage.cpp

build\jsb-default\frameworks\cocos2d-x\cocos\platform 目录

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
/****************************************************************************
Copyright (c) 2010-2012 cocos2d-x.org
Copyright (c) 2013-2016 Chukong Technologies Inc.

http://www.cocos2d-x.org

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/


#include "CCImage.h"

#include <string>
#include <ctype.h>
#include <assert.h>

#include "base/CCData.h"
#include "base/ccConfig.h" // CC_USE_JPEG, CC_USE_TIFF, CC_USE_WEBP
#include "base/ccUtils.h"

#ifndef MIN
#define MIN(x,y) (((x) > (y)) ? (y) : (x))
#endif // MIN

#ifndef MAX
#define MAX(x,y) (((x) < (y)) ? (y) : (x))
#endif // MAX

extern "C"
{
// To resolve link error when building 32bits with Xcode 6.
// More information please refer to the discussion in https://github.com/cocos2d/cocos2d-x/pull/6986
#if defined (__unix) || (CC_TARGET_PLATFORM == CC_PLATFORM_IOS)
#ifndef __ENABLE_COMPATIBILITY_WITH_UNIX_2003__
#define __ENABLE_COMPATIBILITY_WITH_UNIX_2003__
#include <stdio.h>
FILE *fopen$UNIX2003( const char *filename, const char *mode )
{
return fopen(filename, mode);
}
size_t fwrite$UNIX2003( const void *a, size_t b, size_t c, FILE *d )
{
return fwrite(a, b, c, d);
}
char *strerror$UNIX2003( int errnum )
{
return strerror(errnum);
}
#endif
#endif

#if CC_USE_PNG
#include "png/png.h"
#endif //CC_USE_PNG

#if CC_USE_TIFF
#include "tiff/tiffio.h"
#endif //CC_USE_TIFF

#if CC_USE_JPEG
#include "jpeg/jpeglib.h"
#endif // CC_USE_JPEG

#include "base/etc1.h"
#include "base/etc2.h"
}

#if CC_USE_WEBP
#include "webp/decode.h"
#endif // CC_USE_WEBP

#include "base/pvr.h"
#include "base/TGAlib.h"

#include "base/ccMacros.h"
#include "platform/CCStdC.h"
#include "platform/CCFileUtils.h"
#include "base/CCConfiguration.h"
#include "base/ZipUtils.h"
#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID)
#include "platform/android/CCFileUtils-android.h"
#endif

#include <map>

#define CC_GL_ATC_RGB_AMD 0x8C92
#define CC_GL_ATC_RGBA_EXPLICIT_ALPHA_AMD 0x8C93
#define CC_GL_ATC_RGBA_INTERPOLATED_ALPHA_AMD 0x87EE

NS_CC_BEGIN

//////////////////////////////////////////////////////////////////////////
//struct and data for pvr structure

namespace
{
typedef Image::PixelFormatInfoMap::value_type PixelFormatInfoMapValue;
static const PixelFormatInfoMapValue TexturePixelFormatInfoTablesValue[] =
{
PixelFormatInfoMapValue(Image::PixelFormat::BGRA8888, Image::PixelFormatInfo(GL_BGRA, GL_BGRA, GL_UNSIGNED_BYTE, 32, false, true)),
PixelFormatInfoMapValue(Image::PixelFormat::RGBA8888, Image::PixelFormatInfo(GL_RGBA, GL_RGBA, GL_UNSIGNED_BYTE, 32, false, true)),
PixelFormatInfoMapValue(Image::PixelFormat::RGBA4444, Image::PixelFormatInfo(GL_RGBA, GL_RGBA, GL_UNSIGNED_SHORT_4_4_4_4, 16, false, true)),
PixelFormatInfoMapValue(Image::PixelFormat::RGB5A1, Image::PixelFormatInfo(GL_RGBA, GL_RGBA, GL_UNSIGNED_SHORT_5_5_5_1, 16, false, true)),
PixelFormatInfoMapValue(Image::PixelFormat::RGB565, Image::PixelFormatInfo(GL_RGB, GL_RGB, GL_UNSIGNED_SHORT_5_6_5, 16, false, false)),
PixelFormatInfoMapValue(Image::PixelFormat::RGB888, Image::PixelFormatInfo(GL_RGB, GL_RGB, GL_UNSIGNED_BYTE, 24, false, false)),
PixelFormatInfoMapValue(Image::PixelFormat::A8, Image::PixelFormatInfo(GL_ALPHA, GL_ALPHA, GL_UNSIGNED_BYTE, 8, false, false)),
PixelFormatInfoMapValue(Image::PixelFormat::I8, Image::PixelFormatInfo(GL_LUMINANCE, GL_LUMINANCE, GL_UNSIGNED_BYTE, 8, false, false)),
PixelFormatInfoMapValue(Image::PixelFormat::AI88, Image::PixelFormatInfo(GL_LUMINANCE_ALPHA, GL_LUMINANCE_ALPHA, GL_UNSIGNED_BYTE, 16, false, true)),

#ifdef GL_COMPRESSED_RGB_PVRTC_2BPPV1_IMG
PixelFormatInfoMapValue(Image::PixelFormat::PVRTC2, Image::PixelFormatInfo(GL_COMPRESSED_RGB_PVRTC_2BPPV1_IMG, 0xFFFFFFFF, 0xFFFFFFFF, 2, true, false)),
PixelFormatInfoMapValue(Image::PixelFormat::PVRTC2A, Image::PixelFormatInfo(GL_COMPRESSED_RGBA_PVRTC_2BPPV1_IMG, 0xFFFFFFFF, 0xFFFFFFFF, 2, true, true)),
PixelFormatInfoMapValue(Image::PixelFormat::PVRTC4, Image::PixelFormatInfo(GL_COMPRESSED_RGB_PVRTC_4BPPV1_IMG, 0xFFFFFFFF, 0xFFFFFFFF, 4, true, false)),
PixelFormatInfoMapValue(Image::PixelFormat::PVRTC4A, Image::PixelFormatInfo(GL_COMPRESSED_RGBA_PVRTC_4BPPV1_IMG, 0xFFFFFFFF, 0xFFFFFFFF, 4, true, true)),
#endif

#ifdef GL_ETC1_RGB8_OES
PixelFormatInfoMapValue(Image::PixelFormat::ETC, Image::PixelFormatInfo(GL_ETC1_RGB8_OES, 0xFFFFFFFF, 0xFFFFFFFF, 4, true, false)),
#endif

#ifdef GL_COMPRESSED_RGB8_ETC2
PixelFormatInfoMapValue(Image::PixelFormat::ETC2_RGB, Image::PixelFormatInfo(GL_COMPRESSED_RGB8_ETC2, 0xFFFFFFFF, 0xFFFFFFFF, 4, true, false)),
#endif

#ifdef GL_COMPRESSED_RGBA8_ETC2_EAC
PixelFormatInfoMapValue(Image::PixelFormat::ETC2_RGBA, Image::PixelFormatInfo(GL_COMPRESSED_RGBA8_ETC2_EAC, 0xFFFFFFFF, 0xFFFFFFFF, 8, true, true)),
#endif

#ifdef GL_COMPRESSED_RGBA_S3TC_DXT1_EXT
PixelFormatInfoMapValue(Image::PixelFormat::S3TC_DXT1, Image::PixelFormatInfo(GL_COMPRESSED_RGBA_S3TC_DXT1_EXT, 0xFFFFFFFF, 0xFFFFFFFF, 4, true, false)),
#endif

#ifdef GL_COMPRESSED_RGBA_S3TC_DXT3_EXT
PixelFormatInfoMapValue(Image::PixelFormat::S3TC_DXT3, Image::PixelFormatInfo(GL_COMPRESSED_RGBA_S3TC_DXT3_EXT, 0xFFFFFFFF, 0xFFFFFFFF, 8, true, false)),
#endif

#ifdef GL_COMPRESSED_RGBA_S3TC_DXT5_EXT
PixelFormatInfoMapValue(Image::PixelFormat::S3TC_DXT5, Image::PixelFormatInfo(GL_COMPRESSED_RGBA_S3TC_DXT5_EXT, 0xFFFFFFFF, 0xFFFFFFFF, 8, true, false)),
#endif

#ifdef GL_ATC_RGB_AMD
PixelFormatInfoMapValue(Image::PixelFormat::ATC_RGB, Image::PixelFormatInfo(GL_ATC_RGB_AMD,
0xFFFFFFFF, 0xFFFFFFFF, 4, true, false)),
#endif

#ifdef GL_ATC_RGBA_EXPLICIT_ALPHA_AMD
PixelFormatInfoMapValue(Image::PixelFormat::ATC_EXPLICIT_ALPHA, Image::PixelFormatInfo(GL_ATC_RGBA_EXPLICIT_ALPHA_AMD,
0xFFFFFFFF, 0xFFFFFFFF, 8, true, false)),
#endif

#ifdef GL_ATC_RGBA_INTERPOLATED_ALPHA_AMD
PixelFormatInfoMapValue(Image::PixelFormat::ATC_INTERPOLATED_ALPHA, Image::PixelFormatInfo(GL_ATC_RGBA_INTERPOLATED_ALPHA_AMD,
0xFFFFFFFF, 0xFFFFFFFF, 8, true, false)),
#endif
};

//CLASS IMPLEMENTATIONS:

//The PixpelFormat corresponding information
const Image::PixelFormatInfoMap _pixelFormatInfoTables(TexturePixelFormatInfoTablesValue,
TexturePixelFormatInfoTablesValue + sizeof(TexturePixelFormatInfoTablesValue) / sizeof(TexturePixelFormatInfoTablesValue[0]));

const Image::PixelFormatInfoMap& getPixelFormatInfoMap()
{
return _pixelFormatInfoTables;
}

static const int PVR_TEXTURE_FLAG_TYPE_MASK = 0xff;

static bool _PVRHaveAlphaPremultiplied = false;

// Values taken from PVRTexture.h from http://www.imgtec.com
enum class PVR2TextureFlag
{
Mipmap = (1<<8), // has mip map levels
Twiddle = (1<<9), // is twiddled
Bumpmap = (1<<10), // has normals encoded for a bump map
Tiling = (1<<11), // is bordered for tiled pvr
Cubemap = (1<<12), // is a cubemap/skybox
FalseMipCol = (1<<13), // are there false colored MIP levels
Volume = (1<<14), // is this a volume texture
Alpha = (1<<15), // v2.1 is there transparency info in the texture
VerticalFlip = (1<<16), // v2.1 is the texture vertically flipped
};

enum class PVR3TextureFlag
{
PremultipliedAlpha = (1<<1) // has premultiplied alpha
};

static const char gPVRTexIdentifier[5] = "PVR!";

// v2
enum class PVR2TexturePixelFormat : unsigned char
{
RGBA4444 = 0x10,
RGBA5551,
RGBA8888,
RGB565,
RGB555, // unsupported
RGB888,
I8,
AI88,
PVRTC2BPP_RGBA,
PVRTC4BPP_RGBA,
BGRA8888,
A8,
};

// v3
enum class PVR3TexturePixelFormat : uint64_t
{
PVRTC2BPP_RGB = 0ULL,
PVRTC2BPP_RGBA = 1ULL,
PVRTC4BPP_RGB = 2ULL,
PVRTC4BPP_RGBA = 3ULL,
PVRTC2_2BPP_RGBA = 4ULL,
PVRTC2_4BPP_RGBA = 5ULL,
ETC1 = 6ULL,
DXT1 = 7ULL,
DXT2 = 8ULL,
DXT3 = 9ULL,
DXT4 = 10ULL,
DXT5 = 11ULL,
BC1 = 7ULL,
BC2 = 9ULL,
BC3 = 11ULL,
BC4 = 12ULL,
BC5 = 13ULL,
BC6 = 14ULL,
BC7 = 15ULL,
UYVY = 16ULL,
YUY2 = 17ULL,
BW1bpp = 18ULL,
R9G9B9E5 = 19ULL,
RGBG8888 = 20ULL,
GRGB8888 = 21ULL,
ETC2_RGB = 22ULL,
ETC2_RGBA = 23ULL,
ETC2_RGBA1 = 24ULL,
EAC_R11_Unsigned = 25ULL,
EAC_R11_Signed = 26ULL,
EAC_RG11_Unsigned = 27ULL,
EAC_RG11_Signed = 28ULL,

BGRA8888 = 0x0808080861726762ULL,
RGBA8888 = 0x0808080861626772ULL,
RGBA4444 = 0x0404040461626772ULL,
RGBA5551 = 0x0105050561626772ULL,
RGB565 = 0x0005060500626772ULL,
RGB888 = 0x0008080800626772ULL,
A8 = 0x0000000800000061ULL,
L8 = 0x000000080000006cULL,
LA88 = 0x000008080000616cULL,
};


// v2
typedef const std::map<PVR2TexturePixelFormat, Image::PixelFormat> _pixel2_formathash;

static const _pixel2_formathash::value_type v2_pixel_formathash_value[] =
{
_pixel2_formathash::value_type(PVR2TexturePixelFormat::BGRA8888, Image::PixelFormat::BGRA8888),
_pixel2_formathash::value_type(PVR2TexturePixelFormat::RGBA8888, Image::PixelFormat::RGBA8888),
_pixel2_formathash::value_type(PVR2TexturePixelFormat::RGBA4444, Image::PixelFormat::RGBA4444),
_pixel2_formathash::value_type(PVR2TexturePixelFormat::RGBA5551, Image::PixelFormat::RGB5A1),
_pixel2_formathash::value_type(PVR2TexturePixelFormat::RGB565, Image::PixelFormat::RGB565),
_pixel2_formathash::value_type(PVR2TexturePixelFormat::RGB888, Image::PixelFormat::RGB888),
_pixel2_formathash::value_type(PVR2TexturePixelFormat::A8, Image::PixelFormat::A8),
_pixel2_formathash::value_type(PVR2TexturePixelFormat::I8, Image::PixelFormat::I8),
_pixel2_formathash::value_type(PVR2TexturePixelFormat::AI88, Image::PixelFormat::AI88),

_pixel2_formathash::value_type(PVR2TexturePixelFormat::PVRTC2BPP_RGBA, Image::PixelFormat::PVRTC2A),
_pixel2_formathash::value_type(PVR2TexturePixelFormat::PVRTC4BPP_RGBA, Image::PixelFormat::PVRTC4A),
};

static const int PVR2_MAX_TABLE_ELEMENTS = sizeof(v2_pixel_formathash_value) / sizeof(v2_pixel_formathash_value[0]);
static const _pixel2_formathash v2_pixel_formathash(v2_pixel_formathash_value, v2_pixel_formathash_value + PVR2_MAX_TABLE_ELEMENTS);

// v3
typedef const std::map<PVR3TexturePixelFormat, Image::PixelFormat> _pixel3_formathash;
static _pixel3_formathash::value_type v3_pixel_formathash_value[] =
{
_pixel3_formathash::value_type(PVR3TexturePixelFormat::BGRA8888, Image::PixelFormat::BGRA8888),
_pixel3_formathash::value_type(PVR3TexturePixelFormat::RGBA8888, Image::PixelFormat::RGBA8888),
_pixel3_formathash::value_type(PVR3TexturePixelFormat::RGBA4444, Image::PixelFormat::RGBA4444),
_pixel3_formathash::value_type(PVR3TexturePixelFormat::RGBA5551, Image::PixelFormat::RGB5A1),
_pixel3_formathash::value_type(PVR3TexturePixelFormat::RGB565, Image::PixelFormat::RGB565),
_pixel3_formathash::value_type(PVR3TexturePixelFormat::RGB888, Image::PixelFormat::RGB888),
_pixel3_formathash::value_type(PVR3TexturePixelFormat::A8, Image::PixelFormat::A8),
_pixel3_formathash::value_type(PVR3TexturePixelFormat::L8, Image::PixelFormat::I8),
_pixel3_formathash::value_type(PVR3TexturePixelFormat::LA88, Image::PixelFormat::AI88),

_pixel3_formathash::value_type(PVR3TexturePixelFormat::PVRTC2BPP_RGB, Image::PixelFormat::PVRTC2),
_pixel3_formathash::value_type(PVR3TexturePixelFormat::PVRTC2BPP_RGBA, Image::PixelFormat::PVRTC2A),
_pixel3_formathash::value_type(PVR3TexturePixelFormat::PVRTC4BPP_RGB, Image::PixelFormat::PVRTC4),
_pixel3_formathash::value_type(PVR3TexturePixelFormat::PVRTC4BPP_RGBA, Image::PixelFormat::PVRTC4A),

_pixel3_formathash::value_type(PVR3TexturePixelFormat::ETC1, Image::PixelFormat::ETC),
};

static const int PVR3_MAX_TABLE_ELEMENTS = sizeof(v3_pixel_formathash_value) / sizeof(v3_pixel_formathash_value[0]);

static const _pixel3_formathash v3_pixel_formathash(v3_pixel_formathash_value, v3_pixel_formathash_value + PVR3_MAX_TABLE_ELEMENTS);

typedef struct _PVRTexHeader
{
unsigned int headerLength;
unsigned int height;
unsigned int width;
unsigned int numMipmaps;
unsigned int flags;
unsigned int dataLength;
unsigned int bpp;
unsigned int bitmaskRed;
unsigned int bitmaskGreen;
unsigned int bitmaskBlue;
unsigned int bitmaskAlpha;
unsigned int pvrTag;
unsigned int numSurfs;
} PVRv2TexHeader;

#ifdef _MSC_VER
#pragma pack(push,1)
#endif
typedef struct
{
uint32_t version;
uint32_t flags;
uint64_t pixelFormat;
uint32_t colorSpace;
uint32_t channelType;
uint32_t height;
uint32_t width;
uint32_t depth;
uint32_t numberOfSurfaces;
uint32_t numberOfFaces;
uint32_t numberOfMipmaps;
uint32_t metadataLength;
#ifdef _MSC_VER
} PVRv3TexHeader;
#pragma pack(pop)
#else
} __attribute__((packed)) PVRv3TexHeader;
#endif
}
//pvr structure end

//////////////////////////////////////////////////////////////////////////

//struct and data for s3tc(dds) struct
namespace
{
struct DDColorKey
{
uint32_t colorSpaceLowValue;
uint32_t colorSpaceHighValue;
};

struct DDSCaps
{
uint32_t caps;
uint32_t caps2;
uint32_t caps3;
uint32_t caps4;
};

struct DDPixelFormat
{
uint32_t size;
uint32_t flags;
uint32_t fourCC;
uint32_t RGBBitCount;
uint32_t RBitMask;
uint32_t GBitMask;
uint32_t BBitMask;
uint32_t ABitMask;
};


struct DDSURFACEDESC2
{
uint32_t size;
uint32_t flags;
uint32_t height;
uint32_t width;

union
{
uint32_t pitch;
uint32_t linearSize;
} DUMMYUNIONNAMEN1;

union
{
uint32_t backBufferCount;
uint32_t depth;
} DUMMYUNIONNAMEN5;

union
{
uint32_t mipMapCount;
uint32_t refreshRate;
uint32_t srcVBHandle;
} DUMMYUNIONNAMEN2;

uint32_t alphaBitDepth;
uint32_t reserved;
uint32_t surface;

union
{
DDColorKey ddckCKDestOverlay;
uint32_t emptyFaceColor;
} DUMMYUNIONNAMEN3;

DDColorKey ddckCKDestBlt;
DDColorKey ddckCKSrcOverlay;
DDColorKey ddckCKSrcBlt;

union
{
DDPixelFormat ddpfPixelFormat;
uint32_t FVF;
} DUMMYUNIONNAMEN4;

DDSCaps ddsCaps;
uint32_t textureStage;
} ;

#pragma pack(push,1)

struct S3TCTexHeader
{
char fileCode[4];
DDSURFACEDESC2 ddsd;
};

#pragma pack(pop)

}
//s3tc struct end

namespace
{
typedef struct
{
const unsigned char * data;
ssize_t size;
int offset;
}tImageSource;

#ifdef CC_USE_PNG
static void pngReadCallback(png_structp png_ptr, png_bytep data, png_size_t length)
{
tImageSource* isource = (tImageSource*)png_get_io_ptr(png_ptr);

if((int)(isource->offset + length) <= isource->size)
{
memcpy(data, isource->data+isource->offset, length);
isource->offset += length;
}
else
{
png_error(png_ptr, "pngReaderCallback failed");
}
}
#endif //CC_USE_PNG
}

Image::PixelFormat getDevicePixelFormat(Image::PixelFormat format)
{
switch (format) {
case Image::PixelFormat::PVRTC4:
case Image::PixelFormat::PVRTC4A:
case Image::PixelFormat::PVRTC2:
case Image::PixelFormat::PVRTC2A:
if(Configuration::getInstance()->supportsPVRTC())
return format;
else
return Image::PixelFormat::RGBA8888;
case Image::PixelFormat::ETC:
if(Configuration::getInstance()->supportsETC())
return format;
else
return Image::PixelFormat::RGB888;
default:
return format;
}
}

//////////////////////////////////////////////////////////////////////////
// Implement Image
//////////////////////////////////////////////////////////////////////////
bool Image::PNG_PREMULTIPLIED_ALPHA_ENABLED = false;

Image::Image()
: _data(nullptr)
, _dataLen(0)
, _width(0)
, _height(0)
, _fileType(Format::UNKNOWN)
, _renderFormat(Image::PixelFormat::NONE)
, _numberOfMipmaps(0)
, _hasPremultipliedAlpha(false)
{

}

Image::~Image()
{
CC_SAFE_FREE(_data);
}

bool Image::initWithImageFile(const std::string& path)
{
bool ret = false;
//NOTE: fullPathForFilename isn't threadsafe. we should make sure the parameter is a full path.
// _filePath = FileUtils::getInstance()->fullPathForFilename(path);
_filePath = path;

Data data = FileUtils::getInstance()->getDataFromFile(_filePath);

if (!data.isNull())
{
ret = initWithImageData(data.getBytes(), data.getSize());
}

return ret;
}

bool Image::initWithImageData(const unsigned char * data, ssize_t dataLen)
{
bool ret = false;

do
{
CC_BREAK_IF(! data || dataLen <= 0);

unsigned char* unpackedData = nullptr;
ssize_t unpackedLen = 0;

//detect and unzip the compress file
if (ZipUtils::isCCZBuffer(data, dataLen))
{
unpackedLen = ZipUtils::inflateCCZBuffer(data, dataLen, &unpackedData);
}
else if (ZipUtils::isGZipBuffer(data, dataLen))
{
unpackedLen = ZipUtils::inflateMemory(const_cast<unsigned char*>(data), dataLen, &unpackedData);
}
else
{
unpackedData = const_cast<unsigned char*>(data);
unpackedLen = dataLen;
}

_fileType = detectFormat(unpackedData, unpackedLen);

switch (_fileType)
{
case Format::PNG:
ret = initWithPngData(unpackedData, unpackedLen);
break;
//这个case块是增加的内容
//! 下面是新加的
case Format::ENCRYPTEDPNG:
{
unsigned char* copyData = new unsigned char[unpackedLen + 13]; // 8 + 12 - 7
memcpy(copyData + 8, unpackedData + 7, unpackedLen - 7);
deEncryptPng(&copyData, "galaxy2020", unpackedLen + 13);
ret = initWithPngData(copyData, unpackedLen + 13);
delete [] copyData;
}
break;
case Format::JPG:
ret = initWithJpgData(unpackedData, unpackedLen);
break;
case Format::TIFF:
ret = initWithTiffData(unpackedData, unpackedLen);
break;
case Format::WEBP:
ret = initWithWebpData(unpackedData, unpackedLen);
break;
case Format::PVR:
ret = initWithPVRData(unpackedData, unpackedLen);
break;
case Format::ETC:
ret = initWithETCData(unpackedData, unpackedLen);
break;
case Format::ETC2:
ret = initWithETC2Data(unpackedData, unpackedLen);
break;
case Format::S3TC:
ret = initWithS3TCData(unpackedData, unpackedLen);
break;
default:
{
// load and detect image format
tImageTGA* tgaData = tgaLoadBuffer(unpackedData, unpackedLen);

if (tgaData != nullptr && tgaData->status == TGA_OK)
{
ret = initWithTGAData(tgaData);
}
else
{
CCLOG("Image: unsupported image format!");
}

free(tgaData);
break;
}
}

if(unpackedData != data)
{
free(unpackedData);
}
} while (0);

return ret;
}

bool Image::isPng(const unsigned char * data, ssize_t dataLen)
{
if (dataLen <= 8)
{
return false;
}

static const unsigned char PNG_SIGNATURE[] = {0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a};

return memcmp(PNG_SIGNATURE, data, sizeof(PNG_SIGNATURE)) == 0;
}

bool Image::isEtc(const unsigned char * data, ssize_t dataLen)
{
return etc1_pkm_is_valid((etc1_byte*)data) ? true : false;
}

bool Image::isEtc2(const unsigned char * data, ssize_t dataLen)
{
return etc2_pkm_is_valid((etc2_byte*)data) ? true : false;
}


bool Image::isS3TC(const unsigned char * data, ssize_t /*dataLen*/)
{
S3TCTexHeader *header = (S3TCTexHeader *)data;

if (strncmp(header->fileCode, "DDS", 3) != 0)
{
return false;
}
return true;
}

bool Image::isJpg(const unsigned char * data, ssize_t dataLen)
{
if (dataLen <= 4)
{
return false;
}

static const unsigned char JPG_SOI[] = {0xFF, 0xD8};

return memcmp(data, JPG_SOI, 2) == 0;
}

bool Image::isTiff(const unsigned char * data, ssize_t dataLen)
{
if (dataLen <= 4)
{
return false;
}

static const char* TIFF_II = "II";
static const char* TIFF_MM = "MM";

return (memcmp(data, TIFF_II, 2) == 0 && *(static_cast<const unsigned char*>(data) + 2) == 42 && *(static_cast<const unsigned char*>(data) + 3) == 0) ||
(memcmp(data, TIFF_MM, 2) == 0 && *(static_cast<const unsigned char*>(data) + 2) == 0 && *(static_cast<const unsigned char*>(data) + 3) == 42);
}

bool Image::isWebp(const unsigned char * data, ssize_t dataLen)
{
if (dataLen <= 12)
{
return false;
}

static const char* WEBP_RIFF = "RIFF";
static const char* WEBP_WEBP = "WEBP";

return memcmp(data, WEBP_RIFF, 4) == 0
&& memcmp(static_cast<const unsigned char*>(data) + 8, WEBP_WEBP, 4) == 0;
}

bool Image::isPvr(const unsigned char * data, ssize_t dataLen)
{
if (static_cast<size_t>(dataLen) < sizeof(PVRv2TexHeader) || static_cast<size_t>(dataLen) < sizeof(PVRv3TexHeader))
{
return false;
}

const PVRv2TexHeader* headerv2 = static_cast<const PVRv2TexHeader*>(static_cast<const void*>(data));
const PVRv3TexHeader* headerv3 = static_cast<const PVRv3TexHeader*>(static_cast<const void*>(data));

return memcmp(&headerv2->pvrTag, gPVRTexIdentifier, strlen(gPVRTexIdentifier)) == 0 || CC_SWAP_INT32_BIG_TO_HOST(headerv3->version) == 0x50565203;
}

Image::Format Image::detectFormat(const unsigned char * data, ssize_t dataLen)
{
if (isPng(data, dataLen))
{
return Format::PNG;
}
//新增判断
//! 下面是新加的
else if (isEncryptedPng(data, dataLen)) {
return Format::ENCRYPTEDPNG;
}
else if (isJpg(data, dataLen))
{
return Format::JPG;
}
else if (isTiff(data, dataLen))
{
return Format::TIFF;
}
else if (isWebp(data, dataLen))
{
return Format::WEBP;
}
else if (isPvr(data, dataLen))
{
return Format::PVR;
}
else if (isEtc(data, dataLen))
{
return Format::ETC;
}
else if (isEtc2(data, dataLen))
{
return Format::ETC2;
}
else if (isS3TC(data, dataLen))
{
return Format::S3TC;
}
else
{
return Format::UNKNOWN;
}
}

int Image::getBitPerPixel() const
{
return getPixelFormatInfoMap().at(_renderFormat).bpp;
}

bool Image::hasAlpha() const
{
return getPixelFormatInfoMap().at(_renderFormat).alpha;
}

bool Image::isCompressed() const
{
return getPixelFormatInfoMap().at(_renderFormat).compressed;
}

const Image::PixelFormatInfo& Image::getPixelFormatInfo() const
{
return getPixelFormatInfoMap().at(_renderFormat);
}

namespace
{
/*
* ERROR HANDLING:
*
* The JPEG library's standard error handler (jerror.c) is divided into
* several "methods" which you can override individually. This lets you
* adjust the behavior without duplicating a lot of code, which you might
* have to update with each future release.
*
* We override the "error_exit" method so that control is returned to the
* library's caller when a fatal error occurs, rather than calling exit()
* as the standard error_exit method does.
*
* We use C's setjmp/longjmp facility to return control. This means that the
* routine which calls the JPEG library must first execute a setjmp() call to
* establish the return point. We want the replacement error_exit to do a
* longjmp(). But we need to make the setjmp buffer accessible to the
* error_exit routine. To do this, we make a private extension of the
* standard JPEG error handler object. (If we were using C++, we'd say we
* were making a subclass of the regular error handler.)
*
* Here's the extended error handler struct:
*/
#if CC_USE_JPEG
struct MyErrorMgr
{
struct jpeg_error_mgr pub; /* "public" fields */
jmp_buf setjmp_buffer; /* for return to caller */
};

typedef struct MyErrorMgr * MyErrorPtr;

/*
* Here's the routine that will replace the standard error_exit method:
*/

METHODDEF(void)
myErrorExit(j_common_ptr cinfo)
{
/* cinfo->err really points to a MyErrorMgr struct, so coerce pointer */
MyErrorPtr myerr = (MyErrorPtr) cinfo->err;

/* Always display the message. */
/* We could postpone this until after returning, if we chose. */
/* internal message function can't show error message in some platforms, so we rewrite it here.
* edit it if has version conflict.
*/
//(*cinfo->err->output_message) (cinfo);
char buffer[JMSG_LENGTH_MAX];
(*cinfo->err->format_message) (cinfo, buffer);
CCLOG("jpeg error: %s", buffer);

/* Return control to the setjmp point */
longjmp(myerr->setjmp_buffer, 1);
}
#endif // CC_USE_JPEG
}

bool Image::initWithJpgData(const unsigned char * data, ssize_t dataLen)
{
#if CC_USE_WIC
return decodeWithWIC(data, dataLen);
#elif CC_USE_JPEG
/* these are standard libjpeg structures for reading(decompression) */
struct jpeg_decompress_struct cinfo;
/* We use our private extension JPEG error handler.
* Note that this struct must live as long as the main JPEG parameter
* struct, to avoid dangling-pointer problems.
*/
struct MyErrorMgr jerr;
/* libjpeg data structure for storing one row, that is, scanline of an image */
JSAMPROW row_pointer[1] = {0};
unsigned long location = 0;

bool ret = false;
do
{
/* We set up the normal JPEG error routines, then override error_exit. */
cinfo.err = jpeg_std_error(&jerr.pub);
jerr.pub.error_exit = myErrorExit;
/* Establish the setjmp return context for MyErrorExit to use. */
if (setjmp(jerr.setjmp_buffer))
{
/* If we get here, the JPEG code has signaled an error.
* We need to clean up the JPEG object, close the input file, and return.
*/
jpeg_destroy_decompress(&cinfo);
break;
}

/* setup decompression process and source, then read JPEG header */
jpeg_create_decompress( &cinfo );

#ifndef CC_TARGET_QT5
jpeg_mem_src(&cinfo, const_cast<unsigned char*>(data), dataLen);
#endif /* CC_TARGET_QT5 */

/* reading the image header which contains image information */
#if (JPEG_LIB_VERSION >= 90)
// libjpeg 0.9 adds stricter types.
jpeg_read_header(&cinfo, TRUE);
#else
jpeg_read_header(&cinfo, TRUE);
#endif

// we only support RGB or grayscale
if (cinfo.jpeg_color_space == JCS_GRAYSCALE)
{
_renderFormat = Image::PixelFormat::I8;
}else
{
cinfo.out_color_space = JCS_RGB;
_renderFormat = Image::PixelFormat::RGB888;
}

/* Start decompression jpeg here */
jpeg_start_decompress( &cinfo );

/* init image info */
_width = cinfo.output_width;
_height = cinfo.output_height;
_hasPremultipliedAlpha = false;

_dataLen = cinfo.output_width*cinfo.output_height*cinfo.output_components;
_data = static_cast<unsigned char*>(malloc(_dataLen * sizeof(unsigned char)));
CC_BREAK_IF(! _data);

/* now actually read the jpeg into the raw buffer */
/* read one scan line at a time */
while (cinfo.output_scanline < cinfo.output_height)
{
row_pointer[0] = _data + location;
location += cinfo.output_width*cinfo.output_components;
jpeg_read_scanlines(&cinfo, row_pointer, 1);
}

/* When read image file with broken data, jpeg_finish_decompress() may cause error.
* Besides, jpeg_destroy_decompress() shall deallocate and release all memory associated
* with the decompression object.
* So it doesn't need to call jpeg_finish_decompress().
*/
//jpeg_finish_decompress( &cinfo );
jpeg_destroy_decompress( &cinfo );
/* wrap up decompression, destroy objects, free pointers and close open files */
ret = true;
} while (0);

return ret;
#else
CCLOG("jpeg is not enabled, please enable it in ccConfig.h");
return false;
#endif // CC_USE_JPEG
}

bool Image::initWithPngData(const unsigned char * data, ssize_t dataLen)
{
#if CC_USE_WIC
return decodeWithWIC(data, dataLen);
#elif CC_USE_PNG
// length of bytes to check if it is a valid png file
#define PNGSIGSIZE 8
bool ret = false;
png_byte header[PNGSIGSIZE] = {0};
png_structp png_ptr = 0;
png_infop info_ptr = 0;

do
{
// png header len is 8 bytes
CC_BREAK_IF(dataLen < PNGSIGSIZE);

// check the data is png or not
memcpy(header, data, PNGSIGSIZE);
CC_BREAK_IF(png_sig_cmp(header, 0, PNGSIGSIZE));

// init png_struct
png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, 0, 0, 0);
CC_BREAK_IF(! png_ptr);

// init png_info
info_ptr = png_create_info_struct(png_ptr);
CC_BREAK_IF(!info_ptr);

#if (CC_TARGET_PLATFORM != CC_PLATFORM_BADA && CC_TARGET_PLATFORM != CC_PLATFORM_NACL)
CC_BREAK_IF(setjmp(png_jmpbuf(png_ptr)));
#endif

// set the read call back function
tImageSource imageSource;
imageSource.data = (unsigned char*)data;
imageSource.size = dataLen;
imageSource.offset = 0;
png_set_read_fn(png_ptr, &imageSource, pngReadCallback);

// read png header info

// read png file info
png_read_info(png_ptr, info_ptr);

_width = png_get_image_width(png_ptr, info_ptr);
_height = png_get_image_height(png_ptr, info_ptr);
png_byte bit_depth = png_get_bit_depth(png_ptr, info_ptr);
png_uint_32 color_type = png_get_color_type(png_ptr, info_ptr);

//CCLOG("color type %u", color_type);

// force palette images to be expanded to 24-bit RGB
// it may include alpha channel
if (color_type == PNG_COLOR_TYPE_PALETTE)
{
png_set_palette_to_rgb(png_ptr);
}
// low-bit-depth grayscale images are to be expanded to 8 bits
if (color_type == PNG_COLOR_TYPE_GRAY && bit_depth < 8)
{
bit_depth = 8;
png_set_expand_gray_1_2_4_to_8(png_ptr);
}
// expand any tRNS chunk data into a full alpha channel
if (png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS))
{
png_set_tRNS_to_alpha(png_ptr);
}
// reduce images with 16-bit samples to 8 bits
if (bit_depth == 16)
{
png_set_strip_16(png_ptr);
}

// Expanded earlier for grayscale, now take care of palette and rgb
if (bit_depth < 8)
{
png_set_packing(png_ptr);
}
// update info
png_read_update_info(png_ptr, info_ptr);
bit_depth = png_get_bit_depth(png_ptr, info_ptr);
color_type = png_get_color_type(png_ptr, info_ptr);

switch (color_type)
{
case PNG_COLOR_TYPE_GRAY:
_renderFormat = Image::PixelFormat::I8;
break;
case PNG_COLOR_TYPE_GRAY_ALPHA:
_renderFormat = Image::PixelFormat::AI88;
break;
case PNG_COLOR_TYPE_RGB:
_renderFormat = Image::PixelFormat::RGB888;
break;
case PNG_COLOR_TYPE_RGB_ALPHA:
_renderFormat = Image::PixelFormat::RGBA8888;
break;
default:
break;
}

// read png data
png_size_t rowbytes;
png_bytep* row_pointers = (png_bytep*)malloc( sizeof(png_bytep) * _height );

rowbytes = png_get_rowbytes(png_ptr, info_ptr);

_dataLen = rowbytes * _height;
_data = static_cast<unsigned char*>(malloc(_dataLen * sizeof(unsigned char)));
if (!_data)
{
if (row_pointers != nullptr)
{
free(row_pointers);
}
break;
}

for (unsigned short i = 0; i < _height; ++i)
{
row_pointers[i] = _data + i*rowbytes;
}
png_read_image(png_ptr, row_pointers);

png_read_end(png_ptr, nullptr);

// premultiplied alpha for RGBA8888
if (PNG_PREMULTIPLIED_ALPHA_ENABLED && color_type == PNG_COLOR_TYPE_RGB_ALPHA)
{
premultipliedAlpha();
}
else
{
_hasPremultipliedAlpha = false;
}

if (row_pointers != nullptr)
{
free(row_pointers);
}

ret = true;
} while (0);

if (png_ptr)
{
png_destroy_read_struct(&png_ptr, (info_ptr) ? &info_ptr : 0, 0);
}
return ret;
#else
CCLOG("png is not enabled, please enable it in ccConfig.h");
return false;
#endif //CC_USE_PNG
}

#if CC_USE_TIFF
namespace
{
static tmsize_t tiffReadProc(thandle_t fd, void* buf, tmsize_t size)
{
tImageSource* isource = (tImageSource*)fd;
uint8* ma;
uint64 mb;
unsigned long n;
unsigned long o;
tmsize_t p;
ma=(uint8*)buf;
mb=size;
p=0;
while (mb>0)
{
n=0x80000000UL;
if ((uint64)n>mb)
n=(unsigned long)mb;


if ((int)(isource->offset + n) <= isource->size)
{
memcpy(ma, isource->data+isource->offset, n);
isource->offset += n;
o = n;
}
else
{
return 0;
}

ma+=o;
mb-=o;
p+=o;
if (o!=n)
{
break;
}
}
return p;
}

static tmsize_t tiffWriteProc(thandle_t fd, void* buf, tmsize_t size)
{
CC_UNUSED_PARAM(fd);
CC_UNUSED_PARAM(buf);
CC_UNUSED_PARAM(size);
return 0;
}


static uint64 tiffSeekProc(thandle_t fd, uint64 off, int whence)
{
tImageSource* isource = (tImageSource*)fd;
uint64 ret = -1;
do
{
if (whence == SEEK_SET)
{
CC_BREAK_IF(off >= (uint64)isource->size);
ret = isource->offset = (uint32)off;
}
else if (whence == SEEK_CUR)
{
CC_BREAK_IF(isource->offset + off >= (uint64)isource->size);
ret = isource->offset += (uint32)off;
}
else if (whence == SEEK_END)
{
CC_BREAK_IF(off >= (uint64)isource->size);
ret = isource->offset = (uint32)(isource->size-1 - off);
}
else
{
CC_BREAK_IF(off >= (uint64)isource->size);
ret = isource->offset = (uint32)off;
}
} while (0);

return ret;
}

static uint64 tiffSizeProc(thandle_t fd)
{
tImageSource* imageSrc = (tImageSource*)fd;
return imageSrc->size;
}

static int tiffCloseProc(thandle_t fd)
{
CC_UNUSED_PARAM(fd);
return 0;
}

static int tiffMapProc(thandle_t fd, void** base, toff_t* size)
{
CC_UNUSED_PARAM(fd);
CC_UNUSED_PARAM(base);
CC_UNUSED_PARAM(size);
return 0;
}

static void tiffUnmapProc(thandle_t fd, void* base, toff_t size)
{
CC_UNUSED_PARAM(fd);
CC_UNUSED_PARAM(base);
CC_UNUSED_PARAM(size);
}
}
#endif // CC_USE_TIFF

bool Image::initWithTiffData(const unsigned char * data, ssize_t dataLen)
{
#if CC_USE_WIC
return decodeWithWIC(data, dataLen);
#elif CC_USE_TIFF
bool ret = false;
do
{
// set the read call back function
tImageSource imageSource;
imageSource.data = data;
imageSource.size = dataLen;
imageSource.offset = 0;

TIFF* tif = TIFFClientOpen("file.tif", "r", (thandle_t)&imageSource,
tiffReadProc, tiffWriteProc,
tiffSeekProc, tiffCloseProc, tiffSizeProc,
tiffMapProc,
tiffUnmapProc);

CC_BREAK_IF(nullptr == tif);

uint32 w = 0, h = 0;
uint16 bitsPerSample = 0, samplePerPixel = 0, planarConfig = 0;
size_t npixels = 0;

TIFFGetField(tif, TIFFTAG_IMAGEWIDTH, &w);
TIFFGetField(tif, TIFFTAG_IMAGELENGTH, &h);
TIFFGetField(tif, TIFFTAG_BITSPERSAMPLE, &bitsPerSample);
TIFFGetField(tif, TIFFTAG_SAMPLESPERPIXEL, &samplePerPixel);
TIFFGetField(tif, TIFFTAG_PLANARCONFIG, &planarConfig);

npixels = w * h;

_renderFormat = Image::PixelFormat::RGBA8888;
_width = w;
_height = h;

_dataLen = npixels * sizeof (uint32);
_data = static_cast<unsigned char*>(malloc(_dataLen * sizeof(unsigned char)));

uint32* raster = (uint32*) _TIFFmalloc(npixels * sizeof (uint32));
if (raster != nullptr)
{
if (TIFFReadRGBAImageOriented(tif, w, h, raster, ORIENTATION_TOPLEFT, 0))
{
/* the raster data is pre-multiplied by the alpha component
after invoking TIFFReadRGBAImageOriented*/
_hasPremultipliedAlpha = true;

memcpy(_data, raster, npixels*sizeof (uint32));
}

_TIFFfree(raster);
}


TIFFClose(tif);

ret = true;
} while (0);
return ret;
#else
CCLOG("tiff is not enabled, please enable it in ccConfig.h");
return false;
#endif //CC_USE_TIFF
}


namespace
{
bool testFormatForPvr2TCSupport(PVR2TexturePixelFormat format)
{
return true;
}

bool testFormatForPvr3TCSupport(PVR3TexturePixelFormat format)
{
switch (format) {
case PVR3TexturePixelFormat::BGRA8888:
return Configuration::getInstance()->supportsBGRA8888();

case PVR3TexturePixelFormat::PVRTC2BPP_RGB:
case PVR3TexturePixelFormat::PVRTC2BPP_RGBA:
case PVR3TexturePixelFormat::PVRTC4BPP_RGB:
case PVR3TexturePixelFormat::PVRTC4BPP_RGBA:
case PVR3TexturePixelFormat::ETC1:
case PVR3TexturePixelFormat::RGBA8888:
case PVR3TexturePixelFormat::RGBA4444:
case PVR3TexturePixelFormat::RGBA5551:
case PVR3TexturePixelFormat::RGB565:
case PVR3TexturePixelFormat::RGB888:
case PVR3TexturePixelFormat::A8:
case PVR3TexturePixelFormat::L8:
case PVR3TexturePixelFormat::LA88:
return true;

default:
return false;
}
}
}

bool Image::initWithPVRv2Data(const unsigned char * data, ssize_t dataLen)
{
int dataLength = 0, dataOffset = 0, dataSize = 0;
int blockSize = 0, widthBlocks = 0, heightBlocks = 0;
int width = 0, height = 0;

//Cast first sizeof(PVRTexHeader) bytes of data stream as PVRTexHeader
const PVRv2TexHeader *header = static_cast<const PVRv2TexHeader *>(static_cast<const void*>(data));

//Make sure that tag is in correct formatting
if (memcmp(&header->pvrTag, gPVRTexIdentifier, strlen(gPVRTexIdentifier)) != 0)
{
return false;
}

Configuration *configuration = Configuration::getInstance();

//can not detect the premultiplied alpha from pvr file, use _PVRHaveAlphaPremultiplied instead.
_hasPremultipliedAlpha = _PVRHaveAlphaPremultiplied;

unsigned int flags = CC_SWAP_INT32_LITTLE_TO_HOST(header->flags);
PVR2TexturePixelFormat formatFlags = static_cast<PVR2TexturePixelFormat>(flags & PVR_TEXTURE_FLAG_TYPE_MASK);
bool flipped = (flags & (unsigned int)PVR2TextureFlag::VerticalFlip) ? true : false;
if (flipped)
{
CCLOG("initWithPVRv2Data: WARNING: Image is flipped. Regenerate it using PVRTexTool");
}

if (! configuration->supportsNPOT() &&
(static_cast<int>(header->width) != utils::nextPOT(header->width)
|| static_cast<int>(header->height) != utils::nextPOT(header->height)))
{
CCLOG("initWithPVRv2Data: ERROR: Loading an NPOT texture (%dx%d) but is not supported on this device", header->width, header->height);
return false;
}

if (!testFormatForPvr2TCSupport(formatFlags))
{
CCLOG("initWithPVRv2Data: WARNING: Unsupported PVR Pixel Format: 0x%02X. Re-encode it with a OpenGL pixel format variant", (int)formatFlags);
return false;
}

if (v2_pixel_formathash.find(formatFlags) == v2_pixel_formathash.end())
{
CCLOG("initWithPVRv2Data: WARNING: Unsupported PVR Pixel Format: 0x%02X. Re-encode it with a OpenGL pixel format variant", (int)formatFlags);
return false;
}

auto it = getPixelFormatInfoMap().find(getDevicePixelFormat(v2_pixel_formathash.at(formatFlags)));

if (it == getPixelFormatInfoMap().end())
{
CCLOG("initWithPVRv2Data: WARNING: Unsupported PVR Pixel Format: 0x%02X. Re-encode it with a OpenGL pixel format variant", (int)formatFlags);
return false;
}

_renderFormat = it->first;
int bpp = it->second.bpp;

//Reset num of mipmaps
_numberOfMipmaps = 0;

//Get size of mipmap
_width = width = CC_SWAP_INT32_LITTLE_TO_HOST(header->width);
_height = height = CC_SWAP_INT32_LITTLE_TO_HOST(header->height);

//Get ptr to where data starts..
dataLength = CC_SWAP_INT32_LITTLE_TO_HOST(header->dataLength);

assert(Configuration::getInstance()->supportsPVRTC());

//Move by size of header
_dataLen = dataLen - sizeof(PVRv2TexHeader);
_data = static_cast<unsigned char*>(malloc(_dataLen * sizeof(unsigned char)));
memcpy(_data, (unsigned char*)data + sizeof(PVRv2TexHeader), _dataLen);

// Calculate the data size for each texture level and respect the minimum number of blocks
while (dataOffset < dataLength)
{
switch (formatFlags) {
case PVR2TexturePixelFormat::PVRTC2BPP_RGBA:
blockSize = 8 * 4; // Pixel by pixel block size for 2bpp
widthBlocks = width / 8;
heightBlocks = height / 4;
break;
case PVR2TexturePixelFormat::PVRTC4BPP_RGBA:
blockSize = 4 * 4; // Pixel by pixel block size for 4bpp
widthBlocks = width / 4;
heightBlocks = height / 4;
break;
case PVR2TexturePixelFormat::BGRA8888:
if (Configuration::getInstance()->supportsBGRA8888() == false)
{
CCLOG("initWithPVRv2Data: Image. BGRA8888 not supported on this device");
return false;
}
default:
blockSize = 1;
widthBlocks = width;
heightBlocks = height;
break;
}

// Clamp to minimum number of blocks
if (widthBlocks < 2)
{
widthBlocks = 2;
}
if (heightBlocks < 2)
{
heightBlocks = 2;
}

dataSize = widthBlocks * heightBlocks * ((blockSize * bpp) / 8);
int packetLength = (dataLength - dataOffset);
packetLength = packetLength > dataSize ? dataSize : packetLength;

//Make record to the mipmaps array and increment counter
_mipmaps[_numberOfMipmaps].address = _data + dataOffset;
_mipmaps[_numberOfMipmaps].offset = dataOffset;
_mipmaps[_numberOfMipmaps].len = packetLength;
_numberOfMipmaps++;

dataOffset += packetLength;

//Update width and height to the next lower power of two
width = std::max(width >> 1, 1);
height = std::max(height >> 1, 1);
}

return true;
}

bool Image::initWithPVRv3Data(const unsigned char * data, ssize_t dataLen)
{
if (static_cast<size_t>(dataLen) < sizeof(PVRv3TexHeader))
{
return false;
}

const PVRv3TexHeader *header = static_cast<const PVRv3TexHeader *>(static_cast<const void*>(data));

// validate version
if (CC_SWAP_INT32_BIG_TO_HOST(header->version) != 0x50565203)
{
CCLOG("initWithPVRv3Data: WARNING: pvr file version mismatch");
return false;
}

// parse pixel format
PVR3TexturePixelFormat pixelFormat = static_cast<PVR3TexturePixelFormat>(header->pixelFormat);

if (!testFormatForPvr3TCSupport(pixelFormat))
{
CCLOG("initWithPVRv3Data: WARNING: Unsupported PVR Pixel Format: 0x%016llX. Re-encode it with a OpenGL pixel format variant",
static_cast<unsigned long long>(pixelFormat));
return false;
}


if (v3_pixel_formathash.find(pixelFormat) == v3_pixel_formathash.end())
{
CCLOG("initWithPVRv3Data: WARNING: Unsupported PVR Pixel Format: 0x%016llX. Re-encode it with a OpenGL pixel format variant",
static_cast<unsigned long long>(pixelFormat));
return false;
}

auto it = getPixelFormatInfoMap().find(getDevicePixelFormat(v3_pixel_formathash.at(pixelFormat)));

if (it == getPixelFormatInfoMap().end())
{
CCLOG("initWithPVRv3Data: WARNING: Unsupported PVR Pixel Format: 0x%016llX. Re-encode it with a OpenGL pixel format variant",
static_cast<unsigned long long>(pixelFormat));
return false;
}

_renderFormat = it->first;
int bpp = it->second.bpp;

// flags
int flags = CC_SWAP_INT32_LITTLE_TO_HOST(header->flags);

// PVRv3 specifies premultiply alpha in a flag -- should always respect this in PVRv3 files
if (flags & (unsigned int)PVR3TextureFlag::PremultipliedAlpha)
{
_hasPremultipliedAlpha = true;
}
else
{
_hasPremultipliedAlpha = false;
}

// sizing
int width = CC_SWAP_INT32_LITTLE_TO_HOST(header->width);
int height = CC_SWAP_INT32_LITTLE_TO_HOST(header->height);
_width = width;
_height = height;
int dataOffset = 0, dataSize = 0;
int blockSize = 0, widthBlocks = 0, heightBlocks = 0;

assert(Configuration::getInstance()->supportsPVRTC());

_dataLen = dataLen - (sizeof(PVRv3TexHeader) + header->metadataLength);
_data = static_cast<unsigned char*>(malloc(_dataLen * sizeof(unsigned char)));
memcpy(_data, static_cast<const unsigned char*>(data) + sizeof(PVRv3TexHeader) + header->metadataLength, _dataLen);

_numberOfMipmaps = header->numberOfMipmaps;
CCASSERT(_numberOfMipmaps < MIPMAP_MAX, "Image: Maximum number of mimpaps reached. Increase the CC_MIPMAP_MAX value");

for (int i = 0; i < _numberOfMipmaps; i++)
{
switch ((PVR3TexturePixelFormat)pixelFormat)
{
case PVR3TexturePixelFormat::PVRTC2BPP_RGB :
case PVR3TexturePixelFormat::PVRTC2BPP_RGBA :
blockSize = 8 * 4; // Pixel by pixel block size for 2bpp
widthBlocks = width / 8;
heightBlocks = height / 4;
break;
case PVR3TexturePixelFormat::PVRTC4BPP_RGB :
case PVR3TexturePixelFormat::PVRTC4BPP_RGBA :
blockSize = 4 * 4; // Pixel by pixel block size for 4bpp
widthBlocks = width / 4;
heightBlocks = height / 4;
break;
case PVR3TexturePixelFormat::ETC1:
blockSize = 4 * 4; // Pixel by pixel block size for 4bpp
widthBlocks = width / 4;
heightBlocks = height / 4;
break;
case PVR3TexturePixelFormat::BGRA8888:
if (! Configuration::getInstance()->supportsBGRA8888())
{
CCLOG("initWithPVRv3Data: Image. BGRA8888 not supported on this device");
return false;
}
default:
blockSize = 1;
widthBlocks = width;
heightBlocks = height;
break;
}

// Clamp to minimum number of blocks
if (widthBlocks < 2)
{
widthBlocks = 2;
}
if (heightBlocks < 2)
{
heightBlocks = 2;
}

dataSize = widthBlocks * heightBlocks * ((blockSize * bpp) / 8);
auto packetLength = _dataLen - dataOffset;
packetLength = packetLength > dataSize ? dataSize : packetLength;

_mipmaps[i].address = _data + dataOffset;
_mipmaps[i].offset = dataOffset;
_mipmaps[i].len = static_cast<int>(packetLength);

dataOffset += packetLength;
CCASSERT(dataOffset <= _dataLen, "Image: Invalid length");


width = std::max(width >> 1, 1);
height = std::max(height >> 1, 1);
}

return true;
}

bool Image::initWithETCData(const unsigned char * data, ssize_t dataLen)
{
const etc1_byte* header = static_cast<const etc1_byte*>(data);

//check the data
if (! etc1_pkm_is_valid(header))
{
return false;
}

_width = etc1_pkm_get_width(header);
_height = etc1_pkm_get_height(header);

if (0 == _width || 0 == _height)
{
return false;
}

assert(Configuration::getInstance()->supportsETC());

//old opengl version has no define for GL_ETC1_RGB8_OES, add macro to make compiler happy.
#ifdef GL_ETC1_RGB8_OES
_renderFormat = Image::PixelFormat::ETC;
_dataLen = dataLen - ETC_PKM_HEADER_SIZE;
_data = static_cast<unsigned char*>(malloc(_dataLen * sizeof(unsigned char)));
memcpy(_data, static_cast<const unsigned char*>(data) + ETC_PKM_HEADER_SIZE, _dataLen);
return true;
#endif

return false;
}

bool Image::initWithETC2Data(const unsigned char * data, ssize_t dataLen)
{
const etc2_byte* header = static_cast<const etc2_byte*>(data);

//check the data
if (! etc2_pkm_is_valid(header))
{
return false;
}

_width = etc2_pkm_get_width(header);
_height = etc2_pkm_get_height(header);

if (0 == _width || 0 == _height)
{
return false;
}

assert(Configuration::getInstance()->supportsETC2());

etc2_uint32 format = etc2_pkm_get_format(header);
if (format == ETC2_RGB_NO_MIPMAPS)
{
_renderFormat = Image::PixelFormat::ETC2_RGB;
}
else
{
_renderFormat = Image::PixelFormat::ETC2_RGBA;
}

_dataLen = dataLen - ETC2_PKM_HEADER_SIZE;
_data = static_cast<unsigned char*>(malloc(_dataLen * sizeof(unsigned char)));
memcpy(_data, static_cast<const unsigned char*>(data) + ETC2_PKM_HEADER_SIZE, _dataLen);

return true;
}

bool Image::initWithTGAData(tImageTGA* tgaData)
{
bool ret = false;

do
{
CC_BREAK_IF(tgaData == nullptr);

// tgaLoadBuffer only support type 2, 3, 10
if (2 == tgaData->type || 10 == tgaData->type)
{
// true color
// unsupported RGB555
if (tgaData->pixelDepth == 16)
{
_renderFormat = Image::PixelFormat::RGB5A1;
}
else if(tgaData->pixelDepth == 24)
{
_renderFormat = Image::PixelFormat::RGB888;
}
else if(tgaData->pixelDepth == 32)
{
_renderFormat = Image::PixelFormat::RGBA8888;
}
else
{
CCLOG("Image WARNING: unsupported true color tga data pixel format. FILE: %s", _filePath.c_str());
break;
}
}
else if(3 == tgaData->type)
{
// gray
if (8 == tgaData->pixelDepth)
{
_renderFormat = Image::PixelFormat::I8;
}
else
{
// actually this won't happen, if it happens, maybe the image file is not a tga
CCLOG("Image WARNING: unsupported gray tga data pixel format. FILE: %s", _filePath.c_str());
break;
}
}

_width = tgaData->width;
_height = tgaData->height;
_data = tgaData->imageData;
_dataLen = _width * _height * tgaData->pixelDepth / 8;
_fileType = Format::TGA;

_hasPremultipliedAlpha = false;
ret = true;

}while(false);

if (ret)
{
if (FileUtils::getInstance()->getFileExtension(_filePath) != ".tga")
{
CCLOG("Image WARNING: the image file suffix is not tga, but parsed as a tga image file. FILE: %s", _filePath.c_str());
}
}
else
{
if (tgaData && tgaData->imageData != nullptr)
{
free(tgaData->imageData);
_data = nullptr;
}
}

return ret;
}

static uint32_t makeFourCC(char ch0, char ch1, char ch2, char ch3)
{
const uint32_t fourCC = ((uint32_t)(char)(ch0) | ((uint32_t)(char)(ch1) << 8) | ((uint32_t)(char)(ch2) << 16) | ((uint32_t)(char)(ch3) << 24 ));
return fourCC;
}

bool Image::initWithS3TCData(const unsigned char * data, ssize_t dataLen)
{
const uint32_t FOURCC_DXT1 = makeFourCC('D', 'X', 'T', '1');
const uint32_t FOURCC_DXT3 = makeFourCC('D', 'X', 'T', '3');
const uint32_t FOURCC_DXT5 = makeFourCC('D', 'X', 'T', '5');

/* load the .dds file */

S3TCTexHeader *header = (S3TCTexHeader *)data;
unsigned char *pixelData = static_cast<unsigned char*>(malloc((dataLen - sizeof(S3TCTexHeader)) * sizeof(unsigned char)));
memcpy((void *)pixelData, data + sizeof(S3TCTexHeader), dataLen - sizeof(S3TCTexHeader));

_width = header->ddsd.width;
_height = header->ddsd.height;
_numberOfMipmaps = MAX(1, header->ddsd.DUMMYUNIONNAMEN2.mipMapCount); //if dds header reports 0 mipmaps, set to 1 to force correct software decoding (if needed).
_dataLen = 0;
int blockSize = (FOURCC_DXT1 == header->ddsd.DUMMYUNIONNAMEN4.ddpfPixelFormat.fourCC) ? 8 : 16;

/* calculate the dataLen */

int width = _width;
int height = _height;

assert(Configuration::getInstance()->supportsS3TC());

_dataLen = dataLen - sizeof(S3TCTexHeader);
_data = static_cast<unsigned char*>(malloc(_dataLen * sizeof(unsigned char)));
memcpy((void *)_data,(void *)pixelData , _dataLen);

/* if hardware supports s3tc, set pixelformat before loading mipmaps, to support non-mipmapped textures */
//decode texture through hardware

if (FOURCC_DXT1 == header->ddsd.DUMMYUNIONNAMEN4.ddpfPixelFormat.fourCC)
{
_renderFormat = PixelFormat::S3TC_DXT1;
}
else if (FOURCC_DXT3 == header->ddsd.DUMMYUNIONNAMEN4.ddpfPixelFormat.fourCC)
{
_renderFormat = PixelFormat::S3TC_DXT3;
}
else if (FOURCC_DXT5 == header->ddsd.DUMMYUNIONNAMEN4.ddpfPixelFormat.fourCC)
{
_renderFormat = PixelFormat::S3TC_DXT5;
}

/* load the mipmaps */
int encodeOffset = 0;
width = _width;
height = _height;

for (int i = 0; i < _numberOfMipmaps && (width || height); ++i)
{
if (width == 0) width = 1;
if (height == 0) height = 1;

int size = ((width+3)/4)*((height+3)/4)*blockSize;


//decode texture through hardware
_mipmaps[i].address = (unsigned char *)_data + encodeOffset;
_mipmaps[i].offset = encodeOffset;
_mipmaps[i].len = size;

encodeOffset += size;
width >>= 1;
height >>= 1;
}

/* end load the mipmaps */

if (pixelData != nullptr)
{
free(pixelData);
}

return true;
}

bool Image::initWithPVRData(const unsigned char * data, ssize_t dataLen)
{
return initWithPVRv2Data(data, dataLen) || initWithPVRv3Data(data, dataLen);
}

bool Image::initWithWebpData(const unsigned char * data, ssize_t dataLen)
{
#if CC_USE_WEBP
bool ret = false;

#if (CC_TARGET_PLATFORM == CC_PLATFORM_WINRT)
CCLOG("WEBP image format not supported on WinRT or WP8");
#else
do
{
WebPDecoderConfig config;
if (WebPInitDecoderConfig(&config) == 0) break;
if (WebPGetFeatures(static_cast<const uint8_t*>(data), dataLen, &config.input) != VP8_STATUS_OK) break;
if (config.input.width == 0 || config.input.height == 0) break;

config.output.colorspace = config.input.has_alpha?MODE_rgbA:MODE_RGB;
_renderFormat = config.input.has_alpha?Image::PixelFormat::RGBA8888:Image::PixelFormat::RGB888;
_width = config.input.width;
_height = config.input.height;

//we ask webp to give data with premultiplied alpha
_hasPremultipliedAlpha = (config.input.has_alpha != 0);

_dataLen = _width * _height * (config.input.has_alpha?4:3);
_data = static_cast<unsigned char*>(malloc(_dataLen * sizeof(unsigned char)));

config.output.u.RGBA.rgba = static_cast<uint8_t*>(_data);
config.output.u.RGBA.stride = _width * (config.input.has_alpha?4:3);
config.output.u.RGBA.size = _dataLen;
config.output.is_external_memory = 1;

if (WebPDecode(static_cast<const uint8_t*>(data), dataLen, &config) != VP8_STATUS_OK)
{
free(_data);
_data = nullptr;
break;
}

ret = true;
} while (0);
#endif // (CC_TARGET_PLATFORM == CC_PLATFORM_WINRT)
return ret;
#else
CCLOG("webp is not enabled, please enable it in ccConfig.h");
return false;
#endif // CC_USE_WEBP
}

bool Image::initWithRawData(const unsigned char * data, ssize_t dataLen, int width, int height, int bitsPerComponent, bool preMulti)
{
bool ret = false;
do
{
CC_BREAK_IF(0 == width || 0 == height);

_height = height;
_width = width;
_hasPremultipliedAlpha = preMulti;
_renderFormat = Image::PixelFormat::RGBA8888;

// only RGBA8888 supported
int bytesPerComponent = 4;
_dataLen = height * width * bytesPerComponent;
_data = static_cast<unsigned char*>(malloc(_dataLen * sizeof(unsigned char)));
CC_BREAK_IF(! _data);
memcpy(_data, data, _dataLen);

ret = true;
} while (0);

return ret;
}


#if (CC_TARGET_PLATFORM != CC_PLATFORM_IOS)
bool Image::saveToFile(const std::string& filename, bool isToRGB)
{
//only support for Image::PixelFormat::RGB888 or Image::PixelFormat::RGBA8888 uncompressed data
if (isCompressed() || (_renderFormat != Image::PixelFormat::RGB888 && _renderFormat != Image::PixelFormat::RGBA8888))
{
CCLOG("saveToFile: Image: saveToFile is only support for Image::PixelFormat::RGB888 or Image::PixelFormat::RGBA8888 uncompressed data for now");
return false;
}

std::string fileExtension = FileUtils::getInstance()->getFileExtension(filename);

if (fileExtension == ".png")
{
return saveImageToPNG(filename, isToRGB);
}
else if (fileExtension == ".jpg")
{
return saveImageToJPG(filename);
}
else
{
CCLOG("saveToFile: Image: saveToFile no support file extension(only .png or .jpg) for file: %s", filename.c_str());
return false;
}
}
#endif // (CC_TARGET_PLATFORM != CC_PLATFORM_IOS)

bool Image::saveImageToPNG(const std::string& filePath, bool isToRGB)
{
#if CC_USE_WIC
return encodeWithWIC(filePath, isToRGB, GUID_ContainerFormatPng);
#elif CC_USE_PNG
bool ret = false;
do
{
FILE *fp;
png_structp png_ptr;
png_infop info_ptr;
png_colorp palette;
png_bytep *row_pointers;

fp = fopen(FileUtils::getInstance()->getSuitableFOpen(filePath).c_str(), "wb");
CC_BREAK_IF(nullptr == fp);

png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, nullptr, nullptr, nullptr);

if (nullptr == png_ptr)
{
fclose(fp);
break;
}

info_ptr = png_create_info_struct(png_ptr);
if (nullptr == info_ptr)
{
fclose(fp);
png_destroy_write_struct(&png_ptr, nullptr);
break;
}
#if (CC_TARGET_PLATFORM != CC_PLATFORM_BADA && CC_TARGET_PLATFORM != CC_PLATFORM_NACL)
if (setjmp(png_jmpbuf(png_ptr)))
{
fclose(fp);
png_destroy_write_struct(&png_ptr, &info_ptr);
break;
}
#endif
png_init_io(png_ptr, fp);

if (!isToRGB && hasAlpha())
{
png_set_IHDR(png_ptr, info_ptr, _width, _height, 8, PNG_COLOR_TYPE_RGB_ALPHA,
PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);
}
else
{
png_set_IHDR(png_ptr, info_ptr, _width, _height, 8, PNG_COLOR_TYPE_RGB,
PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);
}

palette = (png_colorp)png_malloc(png_ptr, PNG_MAX_PALETTE_LENGTH * sizeof (png_color));
png_set_PLTE(png_ptr, info_ptr, palette, PNG_MAX_PALETTE_LENGTH);

png_write_info(png_ptr, info_ptr);

png_set_packing(png_ptr);

row_pointers = (png_bytep *)malloc(_height * sizeof(png_bytep));
if(row_pointers == nullptr)
{
fclose(fp);
png_destroy_write_struct(&png_ptr, &info_ptr);
break;
}

if (!hasAlpha())
{
for (int i = 0; i < (int)_height; i++)
{
row_pointers[i] = (png_bytep)_data + i * _width * 3;
}

png_write_image(png_ptr, row_pointers);

free(row_pointers);
row_pointers = nullptr;
}
else
{
if (isToRGB)
{
unsigned char *tempData = static_cast<unsigned char*>(malloc(_width * _height * 3 * sizeof(unsigned char)));
if (nullptr == tempData)
{
fclose(fp);
png_destroy_write_struct(&png_ptr, &info_ptr);

free(row_pointers);
row_pointers = nullptr;
break;
}

for (int i = 0; i < _height; ++i)
{
for (int j = 0; j < _width; ++j)
{
tempData[(i * _width + j) * 3] = _data[(i * _width + j) * 4];
tempData[(i * _width + j) * 3 + 1] = _data[(i * _width + j) * 4 + 1];
tempData[(i * _width + j) * 3 + 2] = _data[(i * _width + j) * 4 + 2];
}
}

for (int i = 0; i < (int)_height; i++)
{
row_pointers[i] = (png_bytep)tempData + i * _width * 3;
}

png_write_image(png_ptr, row_pointers);

free(row_pointers);
row_pointers = nullptr;

if (tempData != nullptr)
{
free(tempData);
}
}
else
{
for (int i = 0; i < (int)_height; i++)
{
row_pointers[i] = (png_bytep)_data + i * _width * 4;
}

png_write_image(png_ptr, row_pointers);

free(row_pointers);
row_pointers = nullptr;
}
}

png_write_end(png_ptr, info_ptr);

png_free(png_ptr, palette);
palette = nullptr;

png_destroy_write_struct(&png_ptr, &info_ptr);

fclose(fp);

ret = true;
} while (0);
return ret;
#else
CCLOG("png is not enabled, please enable it in ccConfig.h");
return false;
#endif // CC_USE_PNG
}

bool Image::saveImageToJPG(const std::string& filePath)
{
#if CC_USE_WIC
return encodeWithWIC(filePath, false, GUID_ContainerFormatJpeg);
#elif CC_USE_JPEG
bool ret = false;
do
{
struct jpeg_compress_struct cinfo;
struct jpeg_error_mgr jerr;
FILE * outfile; /* target file */
JSAMPROW row_pointer[1]; /* pointer to JSAMPLE row[s] */
int row_stride; /* physical row width in image buffer */

cinfo.err = jpeg_std_error(&jerr);
/* Now we can initialize the JPEG compression object. */
jpeg_create_compress(&cinfo);

CC_BREAK_IF((outfile = fopen(FileUtils::getInstance()->getSuitableFOpen(filePath).c_str(), "wb")) == nullptr);

jpeg_stdio_dest(&cinfo, outfile);

cinfo.image_width = _width; /* image width and height, in pixels */
cinfo.image_height = _height;
cinfo.input_components = 3; /* # of color components per pixel */
cinfo.in_color_space = JCS_RGB; /* colorspace of input image */

jpeg_set_defaults(&cinfo);
jpeg_set_quality(&cinfo, 90, TRUE);

jpeg_start_compress(&cinfo, TRUE);

row_stride = _width * 3; /* JSAMPLEs per row in image_buffer */

if (hasAlpha())
{
unsigned char *tempData = static_cast<unsigned char*>(malloc(_width * _height * 3 * sizeof(unsigned char)));
if (nullptr == tempData)
{
jpeg_finish_compress(&cinfo);
jpeg_destroy_compress(&cinfo);
fclose(outfile);
break;
}

for (int i = 0; i < _height; ++i)
{
for (int j = 0; j < _width; ++j)

{
tempData[(i * _width + j) * 3] = _data[(i * _width + j) * 4];
tempData[(i * _width + j) * 3 + 1] = _data[(i * _width + j) * 4 + 1];
tempData[(i * _width + j) * 3 + 2] = _data[(i * _width + j) * 4 + 2];
}
}

while (cinfo.next_scanline < cinfo.image_height)
{
row_pointer[0] = & tempData[cinfo.next_scanline * row_stride];
(void) jpeg_write_scanlines(&cinfo, row_pointer, 1);
}

if (tempData != nullptr)
{
free(tempData);
}
}
else
{
while (cinfo.next_scanline < cinfo.image_height) {
row_pointer[0] = & _data[cinfo.next_scanline * row_stride];
(void) jpeg_write_scanlines(&cinfo, row_pointer, 1);
}
}

jpeg_finish_compress(&cinfo);
fclose(outfile);
jpeg_destroy_compress(&cinfo);

ret = true;
} while (0);
return ret;
#else
CCLOG("jpeg is not enabled, please enable it in ccConfig.h");
return false;
#endif // CC_USE_JPEG
}

void Image::premultipliedAlpha()
{
if (PNG_PREMULTIPLIED_ALPHA_ENABLED && _renderFormat == Image::PixelFormat::RGBA8888)
{
unsigned int* fourBytes = (unsigned int*)_data;
for(int i = 0; i < _width * _height; i++)
{
unsigned char* p = _data + i * 4;
fourBytes[i] = CC_RGB_PREMULTIPLY_ALPHA(p[0], p[1], p[2], p[3]);
}

_hasPremultipliedAlpha = true;
}
else
{
_hasPremultipliedAlpha = false;
return;
}
}


void Image::setPVRImagesHavePremultipliedAlpha(bool haveAlphaPremultiplied)
{
_PVRHaveAlphaPremultiplied = haveAlphaPremultiplied;
}

//! 下面是新加的
bool Image::isEncryptedPng(const unsigned char *data, ssize_t dataLen)
{
if (dataLen <= 7 || memcmp("galaxy2", data, 7) != 0) {
return false;
}
return true;
}

//! 下面是新加的
void Image::deEncryptPng(unsigned char **copyData, const char *key, ssize_t dataLen) {
static const unsigned char PNG_SIGNATURE[] = { 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a };
static const unsigned char PNG_IEND[] = { 0x00, 0x00, 0x00, 0x00, 0x49, 0x45, 0x4E, 0x44, 0xAE, 0x42, 0x60, 0x82 };
unsigned char* data = *copyData;
memcpy(data, PNG_SIGNATURE, 8);
memcpy(data + (dataLen - 12), PNG_IEND, 12);
unsigned char* destart = data + 8;
unsigned char* de_end = data + dataLen - 13;
ssize_t keyLen = strlen(key);
ssize_t keyIndex = 0;
for(; destart <= de_end; destart++, keyIndex++) {
if (keyIndex >= keyLen)
keyIndex = 0;
*destart ^= key[keyIndex];
}
}

NS_CC_END