This repository has been archived by the owner on Jan 25, 2023. It is now read-only.
/
Image.cpp
2418 lines (2069 loc) · 75.9 KB
/
Image.cpp
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
// Copyright (c) 2008-2023 the Urho3D project
// License: MIT
#include "../Precompiled.h"
#include "../Core/Context.h"
#include "../Core/Profiler.h"
#include "../IO/File.h"
#include "../IO/FileSystem.h"
#include "../IO/Log.h"
#include "../Resource/Decompress.h"
#include <SDL/SDL_surface.h>
#define STB_IMAGE_IMPLEMENTATION
#include <STB/stb_image.h>
#define STB_IMAGE_WRITE_IMPLEMENTATION
#include <STB/stb_image_write.h>
#ifdef URHO3D_WEBP
#include <webp/decode.h>
#include <webp/encode.h>
#include <webp/mux.h>
#endif
#include "../DebugNew.h"
#ifndef MAKEFOURCC
#define MAKEFOURCC(ch0, ch1, ch2, ch3) ((unsigned)(ch0) | ((unsigned)(ch1) << 8) | ((unsigned)(ch2) << 16) | ((unsigned)(ch3) << 24))
#endif
#define FOURCC_DXT1 (MAKEFOURCC('D','X','T','1'))
#define FOURCC_DXT2 (MAKEFOURCC('D','X','T','2'))
#define FOURCC_DXT3 (MAKEFOURCC('D','X','T','3'))
#define FOURCC_DXT4 (MAKEFOURCC('D','X','T','4'))
#define FOURCC_DXT5 (MAKEFOURCC('D','X','T','5'))
#define FOURCC_DX10 (MAKEFOURCC('D','X','1','0'))
#define FOURCC_ETC1 (MAKEFOURCC('E', 'T', 'C', '1'))
#define FOURCC_ETC2 (MAKEFOURCC('E', 'T', 'C', '2'))
#define FOURCC_ETC2A (MAKEFOURCC('E', 'T', '2', 'A'))
static const unsigned DDSCAPS_COMPLEX = 0x00000008U;
static const unsigned DDSCAPS_TEXTURE = 0x00001000U;
static const unsigned DDSCAPS_MIPMAP = 0x00400000U;
static const unsigned DDSCAPS2_VOLUME = 0x00200000U;
static const unsigned DDSCAPS2_CUBEMAP = 0x00000200U;
static const unsigned DDSCAPS2_CUBEMAP_POSITIVEX = 0x00000400U;
static const unsigned DDSCAPS2_CUBEMAP_NEGATIVEX = 0x00000800U;
static const unsigned DDSCAPS2_CUBEMAP_POSITIVEY = 0x00001000U;
static const unsigned DDSCAPS2_CUBEMAP_NEGATIVEY = 0x00002000U;
static const unsigned DDSCAPS2_CUBEMAP_POSITIVEZ = 0x00004000U;
static const unsigned DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x00008000U;
static const unsigned DDSCAPS2_CUBEMAP_ALL_FACES = 0x0000FC00U;
// DX10 flags
static const unsigned DDS_DIMENSION_TEXTURE1D = 2;
static const unsigned DDS_DIMENSION_TEXTURE2D = 3;
static const unsigned DDS_DIMENSION_TEXTURE3D = 4;
static const unsigned DDS_RESOURCE_MISC_TEXTURECUBE = 0x4;
static const unsigned DDS_DXGI_FORMAT_R8G8B8A8_UNORM = 28;
static const unsigned DDS_DXGI_FORMAT_R8G8B8A8_UNORM_SRGB = 26;
static const unsigned DDS_DXGI_FORMAT_BC1_UNORM = 71;
static const unsigned DDS_DXGI_FORMAT_BC1_UNORM_SRGB = 72;
static const unsigned DDS_DXGI_FORMAT_BC2_UNORM = 74;
static const unsigned DDS_DXGI_FORMAT_BC2_UNORM_SRGB = 75;
static const unsigned DDS_DXGI_FORMAT_BC3_UNORM = 77;
static const unsigned DDS_DXGI_FORMAT_BC3_UNORM_SRGB = 78;
namespace Urho3D
{
/// DirectDraw color key definition.
struct DDColorKey
{
unsigned dwColorSpaceLowValue_;
unsigned dwColorSpaceHighValue_;
};
/// DirectDraw pixel format definition.
struct DDPixelFormat
{
unsigned dwSize_;
unsigned dwFlags_;
unsigned dwFourCC_;
union
{
unsigned dwRGBBitCount_;
unsigned dwYUVBitCount_;
unsigned dwZBufferBitDepth_;
unsigned dwAlphaBitDepth_;
unsigned dwLuminanceBitCount_;
unsigned dwBumpBitCount_;
unsigned dwPrivateFormatBitCount_;
};
union
{
unsigned dwRBitMask_;
unsigned dwYBitMask_;
unsigned dwStencilBitDepth_;
unsigned dwLuminanceBitMask_;
unsigned dwBumpDuBitMask_;
unsigned dwOperations_;
};
union
{
unsigned dwGBitMask_;
unsigned dwUBitMask_;
unsigned dwZBitMask_;
unsigned dwBumpDvBitMask_;
struct
{
unsigned short wFlipMSTypes_;
unsigned short wBltMSTypes_;
} multiSampleCaps_;
};
union
{
unsigned dwBBitMask_;
unsigned dwVBitMask_;
unsigned dwStencilBitMask_;
unsigned dwBumpLuminanceBitMask_;
};
union
{
unsigned dwRGBAlphaBitMask_;
unsigned dwYUVAlphaBitMask_;
unsigned dwLuminanceAlphaBitMask_;
unsigned dwRGBZBitMask_;
unsigned dwYUVZBitMask_;
};
};
/// DirectDraw surface capabilities.
struct DDSCaps2
{
unsigned dwCaps_;
unsigned dwCaps2_;
unsigned dwCaps3_;
union
{
unsigned dwCaps4_;
unsigned dwVolumeDepth_;
};
};
struct DDSHeader10
{
unsigned dxgiFormat;
unsigned resourceDimension;
unsigned miscFlag;
unsigned arraySize;
unsigned reserved;
};
/// DirectDraw surface description.
struct DDSurfaceDesc2
{
unsigned dwSize_;
unsigned dwFlags_;
unsigned dwHeight_;
unsigned dwWidth_;
union
{
unsigned lPitch_;
unsigned dwLinearSize_;
};
union
{
unsigned dwBackBufferCount_;
unsigned dwDepth_;
};
union
{
unsigned dwMipMapCount_;
unsigned dwRefreshRate_;
unsigned dwSrcVBHandle_;
};
unsigned dwAlphaBitDepth_;
unsigned dwReserved_;
unsigned lpSurface_; // Do not define as a void pointer, as it is 8 bytes in a 64bit build
union
{
DDColorKey ddckCKDestOverlay_;
unsigned dwEmptyFaceColor_;
};
DDColorKey ddckCKDestBlt_;
DDColorKey ddckCKSrcOverlay_;
DDColorKey ddckCKSrcBlt_;
union
{
DDPixelFormat ddpfPixelFormat_;
unsigned dwFVF_;
};
DDSCaps2 ddsCaps_;
unsigned dwTextureStage_;
};
bool CompressedLevel::Decompress(unsigned char* dest) const
{
if (!data_)
return false;
switch (format_)
{
case CF_DXT1:
case CF_DXT3:
case CF_DXT5:
DecompressImageDXT(dest, data_, width_, height_, depth_, format_);
return true;
// ETC2 format is compatible with ETC1, so we just use the same function.
case CF_ETC1:
case CF_ETC2_RGB:
DecompressImageETC(dest, data_, width_, height_, false);
return true;
case CF_ETC2_RGBA:
DecompressImageETC(dest, data_, width_, height_, true);
return true;
case CF_PVRTC_RGB_2BPP:
case CF_PVRTC_RGBA_2BPP:
case CF_PVRTC_RGB_4BPP:
case CF_PVRTC_RGBA_4BPP:
DecompressImagePVRTC(dest, data_, width_, height_, format_);
return true;
default:
// Unknown format
return false;
}
}
Image::Image(Context* context) :
Resource(context)
{
}
Image::~Image() = default;
void Image::RegisterObject(Context* context)
{
context->RegisterFactory<Image>();
}
bool Image::BeginLoad(Deserializer& source)
{
// Check for DDS, KTX or PVR compressed format
String fileID = source.ReadFileID();
if (fileID == "DDS ")
{
// DDS compressed format
DDSurfaceDesc2 ddsd; // NOLINT(hicpp-member-init)
source.Read(&ddsd, sizeof(ddsd));
// DDS DX10+
const bool hasDXGI = ddsd.ddpfPixelFormat_.dwFourCC_ == FOURCC_DX10;
DDSHeader10 dxgiHeader; // NOLINT(hicpp-member-init)
if (hasDXGI)
source.Read(&dxgiHeader, sizeof(dxgiHeader));
unsigned fourCC = ddsd.ddpfPixelFormat_.dwFourCC_;
// If the DXGI header is available then remap formats and check sRGB
if (hasDXGI)
{
switch (dxgiHeader.dxgiFormat)
{
case DDS_DXGI_FORMAT_BC1_UNORM:
case DDS_DXGI_FORMAT_BC1_UNORM_SRGB:
fourCC = FOURCC_DXT1;
break;
case DDS_DXGI_FORMAT_BC2_UNORM:
case DDS_DXGI_FORMAT_BC2_UNORM_SRGB:
fourCC = FOURCC_DXT3;
break;
case DDS_DXGI_FORMAT_BC3_UNORM:
case DDS_DXGI_FORMAT_BC3_UNORM_SRGB:
fourCC = FOURCC_DXT5;
break;
case DDS_DXGI_FORMAT_R8G8B8A8_UNORM:
case DDS_DXGI_FORMAT_R8G8B8A8_UNORM_SRGB:
fourCC = 0;
break;
default:
URHO3D_LOGERROR("Unrecognized DDS DXGI image format");
return false;
}
// Check the internal sRGB formats
if (dxgiHeader.dxgiFormat == DDS_DXGI_FORMAT_BC1_UNORM_SRGB ||
dxgiHeader.dxgiFormat == DDS_DXGI_FORMAT_BC2_UNORM_SRGB ||
dxgiHeader.dxgiFormat == DDS_DXGI_FORMAT_BC3_UNORM_SRGB ||
dxgiHeader.dxgiFormat == DDS_DXGI_FORMAT_R8G8B8A8_UNORM_SRGB)
{
sRGB_ = true;
}
}
switch (fourCC)
{
case FOURCC_DXT1:
compressedFormat_ = CF_DXT1;
components_ = 3;
break;
case FOURCC_DXT3:
compressedFormat_ = CF_DXT3;
components_ = 4;
break;
case FOURCC_DXT5:
compressedFormat_ = CF_DXT5;
components_ = 4;
break;
case FOURCC_ETC1:
compressedFormat_ = CF_ETC1;
components_ = 3;
break;
case FOURCC_ETC2:
compressedFormat_ = CF_ETC2_RGB;
components_ = 3;
break;
case FOURCC_ETC2A:
compressedFormat_ = CF_ETC2_RGBA;
components_ = 4;
break;
case 0:
if (ddsd.ddpfPixelFormat_.dwRGBBitCount_ != 32 && ddsd.ddpfPixelFormat_.dwRGBBitCount_ != 24 &&
ddsd.ddpfPixelFormat_.dwRGBBitCount_ != 16)
{
URHO3D_LOGERROR("Unsupported DDS pixel byte size");
return false;
}
compressedFormat_ = CF_RGBA;
components_ = 4;
break;
default:
URHO3D_LOGERROR("Unrecognized DDS image format");
return false;
}
// Is it a cube map or texture array? If so determine the size of the image chain.
cubemap_ = (ddsd.ddsCaps_.dwCaps2_ & DDSCAPS2_CUBEMAP_ALL_FACES) != 0 || (hasDXGI && (dxgiHeader.miscFlag & DDS_RESOURCE_MISC_TEXTURECUBE) != 0);
unsigned imageChainCount = 1;
if (cubemap_)
imageChainCount = 6;
else if (hasDXGI && dxgiHeader.arraySize > 1)
{
imageChainCount = dxgiHeader.arraySize;
array_ = true;
}
// Calculate the size of the data
unsigned dataSize = 0;
if (compressedFormat_ != CF_RGBA)
{
const unsigned blockSize = compressedFormat_ == CF_DXT1 ? 8 : 16; //DXT1/BC1 is 8 bytes, DXT3/BC2 and DXT5/BC3 are 16 bytes
// Add 3 to ensure valid block: ie 2x2 fits uses a whole 4x4 block
unsigned blocksWide = (ddsd.dwWidth_ + 3) / 4;
unsigned blocksHeight = (ddsd.dwHeight_ + 3) / 4;
dataSize = blocksWide * blocksHeight * blockSize;
// Calculate mip data size
unsigned x = ddsd.dwWidth_ / 2;
unsigned y = ddsd.dwHeight_ / 2;
unsigned z = ddsd.dwDepth_ / 2;
for (unsigned level = ddsd.dwMipMapCount_; level > 1; x /= 2, y /= 2, z /= 2, --level)
{
blocksWide = (Max(x, 1U) + 3) / 4;
blocksHeight = (Max(y, 1U) + 3) / 4;
dataSize += blockSize * blocksWide * blocksHeight * Max(z, 1U);
}
}
else
{
dataSize = (ddsd.ddpfPixelFormat_.dwRGBBitCount_ / 8) * ddsd.dwWidth_ * ddsd.dwHeight_ * Max(ddsd.dwDepth_, 1U);
// Calculate mip data size
unsigned x = ddsd.dwWidth_ / 2;
unsigned y = ddsd.dwHeight_ / 2;
unsigned z = ddsd.dwDepth_ / 2;
for (unsigned level = ddsd.dwMipMapCount_; level > 1; x /= 2, y /= 2, z /= 2, --level)
dataSize += (ddsd.ddpfPixelFormat_.dwRGBBitCount_ / 8) * Max(x, 1U) * Max(y, 1U) * Max(z, 1U);
}
// Do not use a shared ptr here, in case nothing is refcounting the image outside this function.
// A raw pointer is fine as the image chain (if needed) uses shared ptr's properly
Image* currentImage = this;
for (unsigned faceIndex = 0; faceIndex < imageChainCount; ++faceIndex)
{
currentImage->data_ = new unsigned char[dataSize];
currentImage->cubemap_ = cubemap_;
currentImage->array_ = array_;
currentImage->components_ = components_;
currentImage->compressedFormat_ = compressedFormat_;
currentImage->width_ = ddsd.dwWidth_;
currentImage->height_ = ddsd.dwHeight_;
currentImage->depth_ = ddsd.dwDepth_;
currentImage->numCompressedLevels_ = ddsd.dwMipMapCount_;
if (!currentImage->numCompressedLevels_)
currentImage->numCompressedLevels_ = 1;
// Memory use needs to be exact per image as it's used for verifying the data size in GetCompressedLevel()
// even though it would be more proper for the first image to report the size of all siblings combined
currentImage->SetMemoryUse(dataSize);
source.Read(currentImage->data_.Get(), dataSize);
if (faceIndex < imageChainCount - 1)
{
// Build the image chain
SharedPtr<Image> nextImage(new Image(context_));
currentImage->nextSibling_ = nextImage;
currentImage = nextImage;
}
}
// If uncompressed DDS, convert the data to 8bit RGBA as the texture classes can not currently use eg. RGB565 format
if (compressedFormat_ == CF_RGBA)
{
URHO3D_PROFILE(ConvertDDSToRGBA);
currentImage = this;
while (currentImage)
{
unsigned sourcePixelByteSize = ddsd.ddpfPixelFormat_.dwRGBBitCount_ >> 3;
unsigned numPixels = dataSize / sourcePixelByteSize;
#define ADJUSTSHIFT(mask, l, r) \
if ((mask) >= 0x100) \
{ \
while (((mask) >> (r)) >= 0x100) \
++(r); \
} \
else if ((mask) && (mask) < 0x80) \
{ \
while (((mask) << (l)) < 0x80) \
++(l); \
}
unsigned rShiftL = 0, gShiftL = 0, bShiftL = 0, aShiftL = 0;
unsigned rShiftR = 0, gShiftR = 0, bShiftR = 0, aShiftR = 0;
unsigned rMask = ddsd.ddpfPixelFormat_.dwRBitMask_;
unsigned gMask = ddsd.ddpfPixelFormat_.dwGBitMask_;
unsigned bMask = ddsd.ddpfPixelFormat_.dwBBitMask_;
unsigned aMask = ddsd.ddpfPixelFormat_.dwRGBAlphaBitMask_;
ADJUSTSHIFT(rMask, rShiftL, rShiftR)
ADJUSTSHIFT(gMask, gShiftL, gShiftR)
ADJUSTSHIFT(bMask, bShiftL, bShiftR)
ADJUSTSHIFT(aMask, aShiftL, aShiftR)
SharedArrayPtr<unsigned char> rgbaData(new unsigned char[numPixels * 4]);
switch (sourcePixelByteSize)
{
case 4:
{
auto* src = (unsigned*)currentImage->data_.Get();
unsigned char* dest = rgbaData.Get();
while (numPixels--)
{
unsigned pixels = *src++;
*dest++ = ((pixels & rMask) << rShiftL) >> rShiftR;
*dest++ = ((pixels & gMask) << gShiftL) >> gShiftR;
*dest++ = ((pixels & bMask) << bShiftL) >> bShiftR;
*dest++ = ((pixels & aMask) << aShiftL) >> aShiftR;
}
}
break;
case 3:
{
unsigned char* src = currentImage->data_.Get();
unsigned char* dest = rgbaData.Get();
while (numPixels--)
{
unsigned pixels = src[0] | (src[1] << 8) | (src[2] << 16);
src += 3;
*dest++ = ((pixels & rMask) << rShiftL) >> rShiftR;
*dest++ = ((pixels & gMask) << gShiftL) >> gShiftR;
*dest++ = ((pixels & bMask) << bShiftL) >> bShiftR;
*dest++ = ((pixels & aMask) << aShiftL) >> aShiftR;
}
}
break;
default:
{
auto* src = (unsigned short*)currentImage->data_.Get();
unsigned char* dest = rgbaData.Get();
while (numPixels--)
{
unsigned short pixels = *src++;
*dest++ = ((pixels & rMask) << rShiftL) >> rShiftR;
*dest++ = ((pixels & gMask) << gShiftL) >> gShiftR;
*dest++ = ((pixels & bMask) << bShiftL) >> bShiftR;
*dest++ = ((pixels & aMask) << aShiftL) >> aShiftR;
}
}
break;
}
// Replace with converted data
currentImage->data_ = rgbaData;
currentImage->SetMemoryUse(numPixels * 4);
currentImage = currentImage->GetNextSibling();
}
}
}
else if (fileID == "\253KTX")
{
source.Seek(12);
unsigned endianness = source.ReadU32();
unsigned type = source.ReadU32();
/* unsigned typeSize = */ source.ReadU32();
unsigned format = source.ReadU32();
unsigned internalFormat = source.ReadU32();
/* unsigned baseInternalFormat = */ source.ReadU32();
unsigned width = source.ReadU32();
unsigned height = source.ReadU32();
unsigned depth = source.ReadU32();
/* unsigned arrayElements = */ source.ReadU32();
unsigned faces = source.ReadU32();
unsigned mipmaps = source.ReadU32();
unsigned keyValueBytes = source.ReadU32();
if (endianness != 0x04030201)
{
URHO3D_LOGERROR("Big-endian KTX files not supported");
return false;
}
if (type != 0 || format != 0)
{
URHO3D_LOGERROR("Uncompressed KTX files not supported");
return false;
}
if (faces > 1 || depth > 1)
{
URHO3D_LOGERROR("3D or cube KTX files not supported");
return false;
}
if (mipmaps == 0)
{
URHO3D_LOGERROR("KTX files without explicitly specified mipmap count not supported");
return false;
}
switch (internalFormat)
{
case 0x83f1:
compressedFormat_ = CF_DXT1;
components_ = 4;
break;
case 0x83f2:
compressedFormat_ = CF_DXT3;
components_ = 4;
break;
case 0x83f3:
compressedFormat_ = CF_DXT5;
components_ = 4;
break;
case 0x8d64:
compressedFormat_ = CF_ETC1;
components_ = 3;
break;
case 0x9274:
compressedFormat_ = CF_ETC2_RGB;
components_ = 3;
break;
case 0x9278:
compressedFormat_ = CF_ETC2_RGBA;
components_ = 4;
break;
case 0x8c00:
compressedFormat_ = CF_PVRTC_RGB_4BPP;
components_ = 3;
break;
case 0x8c01:
compressedFormat_ = CF_PVRTC_RGB_2BPP;
components_ = 3;
break;
case 0x8c02:
compressedFormat_ = CF_PVRTC_RGBA_4BPP;
components_ = 4;
break;
case 0x8c03:
compressedFormat_ = CF_PVRTC_RGBA_2BPP;
components_ = 4;
break;
default:
compressedFormat_ = CF_NONE;
break;
}
if (compressedFormat_ == CF_NONE)
{
URHO3D_LOGERROR("Unsupported texture format in KTX file");
return false;
}
source.Seek(source.GetPosition() + keyValueBytes);
auto dataSize = (unsigned)(source.GetSize() - source.GetPosition() - mipmaps * sizeof(unsigned));
data_ = new unsigned char[dataSize];
width_ = width;
height_ = height;
numCompressedLevels_ = mipmaps;
unsigned dataOffset = 0;
for (unsigned i = 0; i < mipmaps; ++i)
{
unsigned levelSize = source.ReadU32();
if (levelSize + dataOffset > dataSize)
{
URHO3D_LOGERROR("KTX mipmap level data size exceeds file size");
return false;
}
source.Read(&data_[dataOffset], levelSize);
dataOffset += levelSize;
if (source.GetPosition() & 3)
source.Seek((source.GetPosition() + 3) & 0xfffffffc);
}
SetMemoryUse(dataSize);
}
else if (fileID == "PVR\3")
{
/* unsigned flags = */ source.ReadU32();
unsigned pixelFormatLo = source.ReadU32();
/* unsigned pixelFormatHi = */ source.ReadU32();
/* unsigned colourSpace = */ source.ReadU32();
/* unsigned channelType = */ source.ReadU32();
unsigned height = source.ReadU32();
unsigned width = source.ReadU32();
unsigned depth = source.ReadU32();
/* unsigned numSurfaces = */ source.ReadU32();
unsigned numFaces = source.ReadU32();
unsigned mipmapCount = source.ReadU32();
unsigned metaDataSize = source.ReadU32();
if (depth > 1 || numFaces > 1)
{
URHO3D_LOGERROR("3D or cube PVR files not supported");
return false;
}
if (mipmapCount == 0)
{
URHO3D_LOGERROR("PVR files without explicitly specified mipmap count not supported");
return false;
}
switch (pixelFormatLo)
{
case 0:
compressedFormat_ = CF_PVRTC_RGB_2BPP;
components_ = 3;
break;
case 1:
compressedFormat_ = CF_PVRTC_RGBA_2BPP;
components_ = 4;
break;
case 2:
compressedFormat_ = CF_PVRTC_RGB_4BPP;
components_ = 3;
break;
case 3:
compressedFormat_ = CF_PVRTC_RGBA_4BPP;
components_ = 4;
break;
case 6:
compressedFormat_ = CF_ETC1;
components_ = 3;
break;
case 7:
compressedFormat_ = CF_DXT1;
components_ = 4;
break;
case 9:
compressedFormat_ = CF_DXT3;
components_ = 4;
break;
case 11:
compressedFormat_ = CF_DXT5;
components_ = 4;
break;
// .pvr files also support ETC2 texture format.
case 22:
compressedFormat_ = CF_ETC2_RGB;
components_ = 3;
break;
case 23:
compressedFormat_ = CF_ETC2_RGBA;
components_ = 4;
break;
default:
compressedFormat_ = CF_NONE;
break;
}
if (compressedFormat_ == CF_NONE)
{
URHO3D_LOGERROR("Unsupported texture format in PVR file");
return false;
}
source.Seek(source.GetPosition() + metaDataSize);
unsigned dataSize = source.GetSize() - source.GetPosition();
data_ = new unsigned char[dataSize];
width_ = width;
height_ = height;
numCompressedLevels_ = mipmapCount;
source.Read(data_.Get(), dataSize);
SetMemoryUse(dataSize);
}
#ifdef URHO3D_WEBP
else if (fileID == "RIFF")
{
// WebP: https://developers.google.com/speed/webp/docs/api
// RIFF layout is:
// Offset tag
// 0...3 "RIFF" 4-byte tag
// 4...7 size of image data (including metadata) starting at offset 8
// 8...11 "WEBP" our form-type signature
const uint8_t TAG_SIZE(4);
source.Seek(8);
uint8_t fourCC[TAG_SIZE];
memset(&fourCC, 0, sizeof(uint8_t) * TAG_SIZE);
unsigned bytesRead(source.Read(&fourCC, TAG_SIZE));
if (bytesRead != TAG_SIZE)
{
// Truncated.
URHO3D_LOGERROR("Truncated RIFF data");
return false;
}
const uint8_t WEBP[TAG_SIZE] = {'W', 'E', 'B', 'P'};
if (memcmp(fourCC, WEBP, TAG_SIZE) != 0)
{
// VP8_STATUS_BITSTREAM_ERROR
URHO3D_LOGERROR("Invalid header");
return false;
}
// Read the file to buffer.
size_t dataSize(source.GetSize());
SharedArrayPtr<uint8_t> data(new uint8_t[dataSize]);
memset(data.Get(), 0, sizeof(uint8_t) * dataSize);
source.Seek(0);
source.Read(data.Get(), dataSize);
WebPBitstreamFeatures features;
if (WebPGetFeatures(data.Get(), dataSize, &features) != VP8_STATUS_OK)
{
URHO3D_LOGERROR("Error reading WebP image: " + source.GetName());
return false;
}
size_t imgSize = (size_t)features.width * features.height * (features.has_alpha ? 4 : 3);
SharedArrayPtr<uint8_t> pixelData(new uint8_t[imgSize]);
bool decodeError(false);
if (features.has_alpha)
{
decodeError = WebPDecodeRGBAInto(data.Get(), dataSize, pixelData.Get(), imgSize, 4 * features.width) == nullptr;
}
else
{
decodeError = WebPDecodeRGBInto(data.Get(), dataSize, pixelData.Get(), imgSize, 3 * features.width) == nullptr;
}
if (decodeError)
{
URHO3D_LOGERROR("Error decoding WebP image:" + source.GetName());
return false;
}
SetSize(features.width, features.height, features.has_alpha ? 4 : 3);
SetData(pixelData);
}
#endif
else
{
// Not DDS, KTX or PVR, use STBImage to load other image formats as uncompressed
source.Seek(0);
int width, height;
unsigned components;
unsigned char* pixelData = GetImageData(source, width, height, components);
if (!pixelData)
{
URHO3D_LOGERROR("Could not load image " + source.GetName() + ": " + String(stbi_failure_reason()));
return false;
}
SetSize(width, height, components);
SetData(pixelData);
FreeImageData(pixelData);
}
return true;
}
bool Image::Save(Serializer& dest) const
{
URHO3D_PROFILE(SaveImage);
if (IsCompressed())
{
URHO3D_LOGERROR("Can not save compressed image " + GetName());
return false;
}
if (!data_)
{
URHO3D_LOGERROR("Can not save zero-sized image " + GetName());
return false;
}
int len;
unsigned char* png = stbi_write_png_to_mem(data_.Get(), 0, width_, height_, components_, &len);
bool success = dest.Write(png, (unsigned)len) == (unsigned)len;
free(png); // NOLINT(hicpp-no-malloc)
return success;
}
bool Image::SaveFile(const String& fileName) const
{
if (fileName.EndsWith(".dds", false))
return SaveDDS(fileName);
else if (fileName.EndsWith(".bmp", false))
return SaveBMP(fileName);
else if (fileName.EndsWith(".jpg", false) || fileName.EndsWith(".jpeg", false))
return SaveJPG(fileName, 100);
else if (fileName.EndsWith(".tga", false))
return SaveTGA(fileName);
#ifdef URHO3D_WEBP
else if (fileName.EndsWith(".webp", false))
return SaveWEBP(fileName, 100.0f);
#endif
else
return SavePNG(fileName);
}
bool Image::SetSize(int width, int height, unsigned components)
{
return SetSize(width, height, 1, components);
}
bool Image::SetSize(int width, int height, int depth, unsigned components)
{
if (width == width_ && height == height_ && depth == depth_ && components == components_)
return true;
if (width <= 0 || height <= 0 || depth <= 0)
return false;
if (components > 4)
{
URHO3D_LOGERROR("More than 4 color components are not supported");
return false;
}
data_ = new unsigned char[width * height * depth * components];
width_ = width;
height_ = height;
depth_ = depth;
components_ = components;
compressedFormat_ = CF_NONE;
numCompressedLevels_ = 0;
nextLevel_.Reset();
SetMemoryUse(width * height * depth * components);
return true;
}
void Image::SetPixel(int x, int y, const Color& color)
{
SetPixelInt(x, y, 0, color.ToU32());
}
void Image::SetPixel(int x, int y, int z, const Color& color)
{
SetPixelInt(x, y, z, color.ToU32());
}
void Image::SetPixelInt(int x, int y, unsigned uintColor)
{
SetPixelInt(x, y, 0, uintColor);
}
void Image::SetPixelInt(int x, int y, int z, unsigned uintColor)
{
if (!data_ || x < 0 || x >= width_ || y < 0 || y >= height_ || z < 0 || z >= depth_ || IsCompressed())
return;
unsigned char* dest = data_ + (z * width_ * height_ + y * width_ + x) * components_;
auto* src = (unsigned char*)&uintColor;
switch (components_)
{
case 4:
dest[3] = src[3];
[[fallthrough]];
case 3:
dest[2] = src[2];
[[fallthrough]];
case 2:
dest[1] = src[1];
[[fallthrough]];
default:
dest[0] = src[0];
break;
}
}
void Image::SetData(const unsigned char* pixelData)
{
if (!data_)
return;
if (IsCompressed())
{
URHO3D_LOGERROR("Can not set new pixel data for a compressed image");
return;
}
auto size = (size_t)width_ * height_ * depth_ * components_;
if (pixelData)
memcpy(data_.Get(), pixelData, size);
else
memset(data_.Get(), 0, size);
nextLevel_.Reset();
}
bool Image::LoadColorLUT(Deserializer& source)
{
String fileID = source.ReadFileID();
if (fileID == "DDS " || fileID == "\253KTX" || fileID == "PVR\3")
{
URHO3D_LOGERROR("Invalid image format, can not load image");
return false;
}
source.Seek(0);
int width, height;
unsigned components;
unsigned char* pixelDataIn = GetImageData(source, width, height, components);
if (!pixelDataIn)
{
URHO3D_LOGERROR("Could not load image " + source.GetName() + ": " + String(stbi_failure_reason()));
return false;
}
if (components != 3)
{
URHO3D_LOGERROR("Invalid image format, can not load image");
return false;
}
SetSize(COLOR_LUT_SIZE, COLOR_LUT_SIZE, COLOR_LUT_SIZE, components);