-
Notifications
You must be signed in to change notification settings - Fork 8
/
r_texture.cpp
1114 lines (998 loc) · 40.1 KB
/
r_texture.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
#include "engine.h"
#include "c_console.h"
#include "r_texture.h"
#include "u_file.h"
#include "u_algorithm.h"
#include "u_misc.h"
#include "u_zip.h"
#include "u_log.h"
#include "m_const.h"
VAR(int, r_tex_compress, "use texture compression", 0, 1, 1);
VAR(int, r_tex_compress_cache, "cache compressed textures (improve loading times for subsequent loads)", 0, 1, 1);
VAR(int, r_aniso, "anisotropic filtering", 0, 16, 4);
VAR(int, r_bilinear, "bilinear filtering", 0, 1, 1);
VAR(int, r_trilinear, "trilinear filtering", 0, 1, 1);
VAR(int, r_mipmaps, "use mipamps", 0, 1, 1);
VAR(int, r_dxt_optimize, "optimize endpoints in DXT textures (improves on disk compression ratio and performance for older GPUs)", 0, 1, 1);
#if defined(DXT_COMPRESSOR)
VAR(int, r_dxt_compressor, "use our DXT compressor (typically improves loading times)", 0, 1, 1);
#else
VAR(int, r_dxt_compressor, "use our DXT compressor (typically improves loading times)", 0, 0, 0);
#endif
VAR(float, r_tex_quality, "texture quality", 0.0f, 1.0f, 1.0f);
namespace r {
// Singleton texture cache
static u::zip gTextureCache;
#if defined(GL_UNSIGNED_INT_8_8_8_8_REV)
# define R_TEX_DATA_RGBA GL_UNSIGNED_INT_8_8_8_8_REV
#else
# define R_TEX_DATA_RGBA GL_UNSINGED_BYTE
#endif
#if defined(GL_UNSIGNED_INT_8_8_8_8)
# define R_TEX_DATA_BGRA GL_UNSIGNED_INT_8_8_8_8
#else
# define R_TEX_DATA_BGRA GL_UNSIGNED_BYTE
#endif
#define R_TEX_DATA_RGB GL_UNSIGNED_BYTE
#define R_TEX_DATA_BGR GL_UNSIGNED_BYTE
#define R_TEX_DATA_LUMINANCE GL_UNSIGNED_BYTE
#define R_TEX_DATA_RG GL_UNSIGNED_BYTE
enum dxtType {
kDXT1,
kDXT5
};
enum dxtColor {
kDXTColor33,
kDXTColor66,
kDXTColor50
};
struct dxtBlock {
uint16_t color0;
uint16_t color1;
uint32_t pixels;
};
static uint16_t dxtPack565(uint16_t &r, uint16_t &g, uint16_t &b) {
return ((r & 0xF8) << 8) | ((g & 0xFC) << 3) | (b >> 3);
}
static void dxtUnpack565(uint16_t src, uint16_t &r, uint16_t &g, uint16_t &b) {
r = (((src>>11)&0x1F)*527 + 15) >> 6;
g = (((src>>5)&0x3F)*259 + 35) >> 6;
b = ((src&0x1F)*527 + 15) >> 6;
}
template <dxtColor E>
static uint16_t dxtCalcColor(uint16_t color0, uint16_t color1) {
uint16_t r[3], g[3], b[3];
dxtUnpack565(color0, r[0], g[0], b[0]);
dxtUnpack565(color1, r[1], g[1], b[1]);
if (E == kDXTColor33) {
r[2] = (2*r[0] + r[1]) / 3;
g[2] = (2*g[0] + g[1]) / 3;
b[2] = (2*b[0] + b[1]) / 3;
} else if (E == kDXTColor66) {
r[2] = (r[0] + 2*r[1]) / 3;
g[2] = (g[0] + 2*g[1]) / 3;
b[2] = (b[0] + 2*b[1]) / 3;
} else if (E == kDXTColor50) {
r[2] = (r[0] + r[1]) / 2;
g[2] = (g[0] + g[1]) / 2;
b[2] = (b[0] + b[1]) / 2;
}
return dxtPack565(r[2], g[2], b[2]);
}
template <dxtType T>
static size_t dxtOptimize(unsigned char *data, size_t width, size_t height) {
size_t count = 0;
const size_t numBlocks = (width / 4) * (height / 4);
dxtBlock *block = ((dxtBlock*)data) + (T == kDXT5); // DXT5: alpha block is first
for (size_t i = 0; i != numBlocks; ++i, block += (T == kDXT1 ? 1 : 2)) {
const uint16_t color0 = block->color0;
const uint16_t color1 = block->color1;
const uint32_t pixels = block->pixels;
if (pixels == 0) {
// Solid color0
block->color1 = 0;
count++;
} else if (pixels == 0x55555555u) {
// Solid color1, fill with color0 instead, possibly encoding the block
// as 1-bit alpha if color1 is black.
block->color0 = color1;
block->color1 = 0;
block->pixels = 0;
count++;
} else if (pixels == 0xAAAAAAAAu) {
// Solid color2, fill with color0 instead, possibly encoding the block
// as 1-bit alpha if color2 is black.
block->color0 = (color0 > color1 || T == kDXT5)
? dxtCalcColor<kDXTColor33>(color0, color1)
: dxtCalcColor<kDXTColor50>(color0, color1);
block->color1 = 0;
block->pixels = 0;
count++;
} else if (pixels == 0xFFFFFFFFu) {
// Solid color3
if (color0 > color1 || T == kDXT5) {
// Fill with color0 instead, possibly encoding the block as 1-bit
// alpha if color3 is black.
block->color0 = dxtCalcColor<kDXTColor66>(color0, color1);
block->color1 = 0;
block->pixels = 0;
count++;
} else {
// Transparent / solid black
block->color0 = 0;
block->color1 = T == kDXT1 ? 0xFFFFu : 0; // kDXT1: Transparent black
if (T == kDXT5) // Solid black
block->pixels = 0;
count++;
}
} else if (T == kDXT5 && (pixels & 0xAAAAAAAAu) == 0xAAAAAAAAu) {
// Only interpolated colors are used, not the endpoints
block->color0 = dxtCalcColor<kDXTColor66>(color0, color1);
block->color1 = dxtCalcColor<kDXTColor33>(color0, color1);
block->pixels = ~pixels;
count++;
} else if (T == kDXT5 && color0 < color1) {
// Otherwise, ensure the colors are always in the same order
block->color0 = color1;
block->color1 = color0;
block->pixels ^= 0x55555555u;
count++;
}
}
return count;
}
#if defined(DXT_COMPRESSOR)
#if defined(DXT_HIGHP)
typedef double real;
#else
typedef float real;
#endif
// Color line refinement iterations:
// Minimum is 1
// Default is 3
//
// The maximum really has a lot to do with how much error you'll eventually
// introduce due to precision of the `real' type used in the color line algorithm.
//
// It's suggested you use #define DXT_HIGHP if you want to increase this.
static constexpr size_t kRefineIterations = 3;
template <size_t C>
static inline void dxtComputeColorLine(const unsigned char *const uncompressed,
float (&point)[3], float (&direction)[3])
{
static constexpr real kSixteen = real(16.0);
static constexpr real kOne = real(1.0);
static constexpr real kZero = real(0.0);
static constexpr real kInv16 = kOne / kSixteen;
real sumR = kZero, sumG = kZero, sumB = kZero;
real sumRR = kZero, sumGG = kZero, sumBB = kZero;
real sumRG = kZero, sumRB = kZero, sumGB = kZero;
for (size_t i = 0; i < 16*C; i += C) {
sumR += uncompressed[i+0];
sumG += uncompressed[i+1];
sumB += uncompressed[i+2];
sumRR += uncompressed[i+0] * uncompressed[i+0];
sumGG += uncompressed[i+1] * uncompressed[i+1];
sumBB += uncompressed[i+2] * uncompressed[i+2];
sumRG += uncompressed[i+0] * uncompressed[i+1];
sumRB += uncompressed[i+0] * uncompressed[i+2];
sumGB += uncompressed[i+1] * uncompressed[i+2];
}
// Average all sums
sumR *= kInv16;
sumG *= kInv16;
sumB *= kInv16;
// Convert squares to squares of the value minus their average
sumRR -= kSixteen * sumR * sumR;
sumGG -= kSixteen * sumG * sumG;
sumBB -= kSixteen * sumB * sumB;
sumRG -= kSixteen * sumR * sumG;
sumRB -= kSixteen * sumR * sumB;
sumGB -= kSixteen * sumG * sumB;
// The point on the color line is the average
point[0] = sumR;
point[1] = sumG;
point[2] = sumB;
// RYGDXT covariance matrix
direction[0] = real(1.0);
direction[1] = real(2.718281828);
direction[2] = real(3.141592654);
for (size_t i = 0; i < kRefineIterations; ++i) {
sumR = direction[0];
sumG = direction[1];
sumB = direction[2];
direction[0] = float(sumR*sumRR + sumG*sumRG + sumB*sumRB);
direction[1] = float(sumR*sumRG + sumG*sumGG + sumB*sumGB);
direction[2] = float(sumR*sumRB + sumG*sumGB + sumB*sumBB);
}
}
template <size_t C>
static inline void dxtLSEMasterColorsClamp(uint16_t (&colors)[2],
const unsigned char *const uncompressed)
{
float sumx1[] = { 0.0f, 0.0f, 0.0f };
float sumx2[] = { 0.0f, 0.0f, 0.0f };
dxtComputeColorLine<C>(uncompressed, sumx1, sumx2);
const float length = 1.0f / (0.00001f + sumx2[0]*sumx2[0] + sumx2[1]*sumx2[1] + sumx2[2]*sumx2[2]);
// Calcualte range for vector values
float dotMax = sumx2[0] * uncompressed[0] +
sumx2[1] * uncompressed[1] +
sumx2[2] * uncompressed[2];
float dotMin = dotMax;
for (size_t i = 1; i < 16; ++i) {
const float dot = sumx2[0] * uncompressed[i*C+0] +
sumx2[1] * uncompressed[i*C+1] +
sumx2[2] * uncompressed[i*C+2];
if (dot < dotMin)
dotMin = dot;
else if (dot > dotMax)
dotMax = dot;
}
// Calculate offset from the average location
const float dot = sumx2[0]*sumx1[0] + sumx2[1]*sumx1[1] + sumx2[2]*sumx1[2];
dotMin -= dot;
dotMax -= dot;
dotMin *= length;
dotMax *= length;
// Build the master colors
uint16_t c0[3];
uint16_t c1[3];
for (size_t i = 0; i < 3; ++i) {
c0[i] = m::clamp(int(0.5f + sumx1[i] + dotMax * sumx2[i]), 0, 255);
c1[i] = m::clamp(int(0.5f + sumx1[i] + dotMin * sumx2[i]), 0, 255);
}
// Down sample the master colors to RGB565
const uint16_t i = dxtPack565(c0[0], c0[1], c0[2]);
const uint16_t j = dxtPack565(c1[0], c1[1], c1[2]);
if (i > j)
colors[0] = i, colors[1] = j;
else
colors[1] = i, colors[0] = j;
}
template <size_t C>
static inline void dxtCompressColorBlock(const unsigned char *const uncompressed, unsigned char (&compressed)[8]) {
uint16_t encodeColor[2];
dxtLSEMasterColorsClamp<C>(encodeColor, uncompressed);
// Store 565 color
compressed[0] = encodeColor[0] & 255;
compressed[1] = (encodeColor[0] >> 8) & 255;
compressed[2] = encodeColor[1] & 255;
compressed[3] = (encodeColor[1] >> 8) & 255;
for (size_t i = 4; i < 8; i++)
compressed[i] = 0;
// Reconstitute master color vectors
uint16_t c0[3];
uint16_t c1[3];
dxtUnpack565(encodeColor[0], c0[0], c0[1], c0[2]);
dxtUnpack565(encodeColor[1], c1[0], c1[1], c1[2]);
float colorLine[] = { 0.0f, 0.0f, 0.0f, 0.0f };
float length = 0.0f;
for (size_t i = 0; i < 3; ++i) {
colorLine[i] = float(c1[i] - c0[i]);
length += colorLine[i] * colorLine[i];
}
if (length > 0.0f)
length = 1.0f / length;
// Scaling
for (size_t i = 0; i < 3; i++)
colorLine[i] *= length;
// Offset portion of dot product
const float dotOffset = colorLine[0]*c0[0] + colorLine[1]*c0[1] + colorLine[2]*c0[2];
// Store rest of bits
size_t nextBit = 8*4;
for (size_t i = 0; i < 16; ++i) {
// Find the dot product for this color, to place it on the line with
// A range of [-1, 1]
const float dotProduct = colorLine[0] * uncompressed[i*C+0] +
colorLine[1] * uncompressed[i*C+1] +
colorLine[2] * uncompressed[i*C+2] - dotOffset;
// Map to [0, 3]
const int nextValue = m::clamp(int(dotProduct * 3.0f + 0.5f), 0, 3);
compressed[nextBit >> 3] |= "\x0\x2\x3\x1"[nextValue] << (nextBit & 7);
nextBit += 2;
}
}
static inline void dxtCompressAlphaBlock(const unsigned char *const uncompressed, unsigned char (&compressed)[8]) {
unsigned char a0 = uncompressed[3];
unsigned char a1 = uncompressed[3];
for (size_t i = 4+3; i < 16*4; i += 4) {
if (uncompressed[i] > a0)
a0 = uncompressed[i];
if (uncompressed[i] < a1)
a1 = uncompressed[i];
}
compressed[0] = a0;
compressed[1] = a1;
for (size_t i = 2; i < 8; i++)
compressed[i] = 0;
size_t nextBit = 8*2;
const float scale = 7.9999f / (a0 - a1);
for (size_t i = 3; i < 16*4; i += 4) {
const unsigned char value = "\x1\x7\x6\x5\x4\x3\x2\x0"[size_t((uncompressed[i] - a1) * scale) & 7];
compressed[nextBit >> 3] |= value << (nextBit & 7);
// Spans two bytes
if ((nextBit & 7) > 5)
compressed[1 + (nextBit >> 3)] |= value >> (8 - (nextBit & 7));
nextBit += 3;
}
}
// Note: `uncompressed' is assumed to be a RGB8 data stream when T == kDXT1 and
// RGBA8 data stream when T == kDXT5
template <dxtType T>
static u::vector<unsigned char> dxtCompress(const unsigned char *const uncompressed,
size_t width, size_t height, size_t channels)
{
size_t index = 0;
const size_t chanStep = channels < 3 ? 0 : 1;
const int hasAlpha = 1 - (channels & 1);
const size_t outSize = ((width + 3) >> 2) * ((height + 3) >> 2) * (T == kDXT1 ? 8 : 16);
u::vector<unsigned char> compressed(outSize);
unsigned char ublock[16 * (T == kDXT1 ? 3 : 4)];
unsigned char cblock[8];
for (size_t j = 0; j < height; j += 4) {
for (size_t i = 0; i < width; i += 4) {
size_t z = 0;
const size_t my = j + 4 >= height ? height - j : 4;
const size_t mx = i + 4 >= width ? width - i : 4;
for (size_t y = 0; y < my; ++y) {
for (size_t x = 0; x < mx; ++x) {
for (size_t p = 0; p < 3; ++p)
ublock[z++] = uncompressed[((((j+y)*width)*channels)+((i+x)*channels))+(chanStep * p)];
if (T == kDXT5)
ublock[z++] = hasAlpha * uncompressed[(j+y)*width*channels+(i+x)*channels+channels-1] + (1 - hasAlpha) * 255;
}
for (size_t x = mx; x < 4; ++x)
for (size_t p = 0; p < (T == kDXT1 ? 3 : 4); ++p)
ublock[z++] = ublock[p];
}
for (size_t y = my; y < 4; ++y)
for (size_t x = 0; x < 4; ++x)
for (size_t p = 0; p < (T == kDXT1 ? 3 : 4); ++p)
ublock[z++] = ublock[p];
if (T == kDXT5) {
dxtCompressAlphaBlock(ublock, cblock);
for (size_t x = 0; x < 8; ++x)
compressed[index++] = cblock[x];
}
dxtCompressColorBlock<(T == kDXT1 ? 3 : 4)>(ublock, cblock);
for (size_t x = 0; x < 8; ++x)
compressed[index++] = cblock[x];
}
}
return compressed;
}
template u::vector<unsigned char> dxtCompress<kDXT1>(const unsigned char *const uncompressed,
size_t width, size_t height, size_t channels);
template u::vector<unsigned char> dxtCompress<kDXT5>(const unsigned char *const uncompressed,
size_t width, size_t height, size_t channels);
#endif //! DXT_COMPRESSOR
static const unsigned char kTextureCacheVersion = 0x07;
struct textureCacheHeader {
uint8_t version;
uint8_t mips;
uint16_t format;
uint16_t width;
uint16_t height;
uint32_t internal;
void endianSwap();
};
void textureCacheHeader::endianSwap() {
format = u::endianSwap(format);
width = u::endianSwap(width);
height = u::endianSwap(height);
internal = u::endianSwap(internal);
}
static const char *cacheFormat(GLuint internal) {
switch (internal) {
case GL_COMPRESSED_RGBA_BPTC_UNORM_ARB:
return "RGBA_BPTC_UNORM";
case GL_COMPRESSED_RGB_BPTC_SIGNED_FLOAT_ARB:
return "RGB_BPTC_SIGNED_FLOAT";
case GL_COMPRESSED_RGBA_S3TC_DXT5_EXT:
return "RGBA_S3TC_DXT5";
case GL_COMPRESSED_RGBA_S3TC_DXT1_EXT:
return "RGBA_S3TC_DXT1";
case GL_COMPRESSED_RED_GREEN_RGTC2_EXT:
return "RED_GREEN_RGTC2";
case GL_COMPRESSED_RED_RGTC1_EXT:
return "RED_RGTC1";
}
return "";
}
static bool mountCache() {
if (gTextureCache.opened())
return true;
const auto cacheFile = neoUserPath() + "cache/textures.zip";
if (u::exists(cacheFile)) {
// Cache already exists: open
if (!gTextureCache.open(cacheFile))
return false;
u::Log::out("[cache] => mounted texture cache `%s'\n", cacheFile);
return true;
}
// Cache does not exist: create the file
if (!gTextureCache.create(cacheFile)) {
u::Log::err("[cache] failed crearting texture cache `%s'\n", cacheFile);
return false;
}
u::Log::out("[cache] => created texture cache `%s'\n", cacheFile);
return true;
}
static bool readCache(Texture &tex, GLuint &internal) {
if (!r_tex_compress)
return false;
// If the texture is not on disk then don't cache the compressed version
// of it to disk.
if (!(tex.flags() & kTexFlagDisk))
return false;
// If no compression was specified then don't read a cached compressed version
// of it.
if (tex.flags() & kTexFlagNoCompress)
return false;
// Load the cache from disk.
const auto cacheName = tex.hashString();
auto load = gTextureCache.read(cacheName);
if (!load)
return false;
// Parse header
const auto &vec = *load;
textureCacheHeader head;
memcpy(&head, &vec[0], sizeof head);
head.endianSwap();
if (head.version != kTextureCacheVersion) {
gTextureCache.remove(tex.hashString());
return false;
}
// Make sure we even support the format before using it
switch (head.internal) {
case GL_COMPRESSED_RGBA_BPTC_UNORM_ARB:
case GL_COMPRESSED_RGB_BPTC_SIGNED_FLOAT_ARB:
if (!gl::has(gl::ARB_texture_compression_bptc))
return false;
break;
case GL_COMPRESSED_RGBA_S3TC_DXT5_EXT:
case GL_COMPRESSED_RGBA_S3TC_DXT1_EXT:
if (!gl::has(gl::EXT_texture_compression_s3tc))
return false;
break;
case GL_COMPRESSED_RED_GREEN_RGTC2_EXT:
case GL_COMPRESSED_RED_RGTC1_EXT:
if (!gl::has(gl::EXT_texture_compression_rgtc))
return false;
break;
}
const unsigned char *const data = &vec[0] + sizeof head;
const size_t length = vec.size() - sizeof head;
internal = head.internal;
// Now swap!
tex.unload();
tex.from(data, length, head.width, head.height, false, TextureFormat(head.format), head.mips);
u::Log::out("[cache] => loaded (texture) %s %s (%s)\n", cacheName,
cacheFormat(head.internal), u::sizeMetric(length));
return true;
}
static bool writeCacheData(TextureFormat format,
size_t texSize,
const u::string &hash,
unsigned char *compressedData,
size_t compressedWidth,
size_t compressedHeight,
size_t compressedSize,
size_t mips,
GLuint internal,
const char *from = "driver")
{
// Build the header
textureCacheHeader head;
head.version = kTextureCacheVersion;
// Note: the explicit casts are needed to match the textureCacheHeader types
// so that the type-deduction for u::endianSwap actually works.
head.width = compressedWidth;
head.height = compressedHeight;
head.internal = internal;
head.format = format;
head.mips = mips;
head.endianSwap();
// Apply DXT optimizations if we can
const bool dxt = internal == GL_COMPRESSED_RGBA_S3TC_DXT1_EXT ||
internal == GL_COMPRESSED_RGBA_S3TC_DXT5_EXT;
size_t dxtOptimCount = 0;
if (r_dxt_optimize && dxt) {
size_t offset = 0;
size_t mipWidth = compressedWidth;
size_t mipHeight = compressedHeight;
const size_t blockSize = internal == GL_COMPRESSED_RGBA_S3TC_DXT1_EXT ? 8 : 16;
// Run the optimizer on each level
for (size_t i = 0; i < mips; i++) {
const size_t mipSize = ((mipWidth + 3) / 4) * ((mipHeight + 3) / 4) * blockSize;
const size_t count = (internal == GL_COMPRESSED_RGBA_S3TC_DXT1_EXT)
? dxtOptimize<kDXT1>(compressedData + offset, mipWidth, mipHeight)
: dxtOptimize<kDXT5>(compressedData + offset, mipWidth, mipHeight);
// Only report for the base level
if (i == 0)
dxtOptimCount = count;
gl::CompressedTexImage2D(GL_TEXTURE_2D, i, internal, mipWidth,
mipHeight, 0, mipSize, compressedData + offset);
offset += mipSize;
mipWidth = u::max(mipWidth >> 1, 1_z);
mipHeight = u::max(mipHeight >> 1, 1_z);
}
}
// prepare file data
u::vector<unsigned char> data(sizeof head + compressedSize);
memcpy(&data[0], &head, sizeof head);
memcpy(&data[0] + sizeof head, compressedData, compressedSize);
u::Log::out("[cache] => wrote (texture) %s %s (compressed %s to %s with %s compressor)",
hash,
cacheFormat(internal),
u::sizeMetric(texSize * 1.33f), // 33% for mip levels
u::sizeMetric(compressedSize),
from );
if (dxt && dxtOptimCount) {
const float blockCount = (compressedWidth / 4.0f) * (compressedHeight / 4.0f);
const float blockDifference = blockCount - dxtOptimCount;
const float blockPercent = (blockDifference / blockCount) * 100.0f;
u::Log::out(" (optimized endpoints in %.2f%% of blocks)", blockPercent);
}
u::Log::out("\n");
// Write it out
return gTextureCache.write(hash, data);
}
static bool writeCache(const Texture &tex, GLuint internal, GLuint handle, size_t mips) {
auto &r_debug_tex = c::Console::value<int>("r_debug_tex");
if (r_debug_tex)
return false;
if (!r_tex_compress_cache)
return false;
// Don't cache already disk-compressed textures
if (tex.flags() & kTexFlagCompressed)
return false;
// Only cache compressed textures
switch (internal) {
case GL_COMPRESSED_RGBA_S3TC_DXT5_EXT:
case GL_COMPRESSED_RGBA_S3TC_DXT1_EXT:
case GL_COMPRESSED_RGBA_BPTC_UNORM_ARB:
case GL_COMPRESSED_RGB_BPTC_SIGNED_FLOAT_ARB:
case GL_COMPRESSED_RED_GREEN_RGTC2_EXT:
case GL_COMPRESSED_RED_RGTC1_EXT:
break;
default:
return false;
}
// Some drivers just don't do online compression
GLint compressed = 0;
gl::GetTexLevelParameteriv(GL_TEXTURE_2D, 0, GL_TEXTURE_COMPRESSED, &compressed);
if (compressed == 0)
return false;
// Don't bother caching if we already have it
if (gTextureCache.exists(tex.hashString()))
return false;
// Query the compressed texture size
gl::BindTexture(GL_TEXTURE_2D, handle);
size_t mipWidth = tex.width();
size_t mipHeight = tex.height();
size_t totalSize = 0;
size_t totalMips = 0;
for (size_t i = 0; i < mips; i++, totalMips++) {
GLint size;
gl::GetTexLevelParameteriv(GL_TEXTURE_2D, i, GL_TEXTURE_COMPRESSED_IMAGE_SIZE, &size);
totalSize += size;
if (u::max(mipWidth, mipHeight) <= 1)
break;
mipWidth = u::max(mipWidth >> 1, 1_z);
mipHeight = u::max(mipHeight >> 1, 1_z);
}
// Query the compressed height and width (driver may add padding)
GLint compressedWidth;
GLint compressedHeight;
gl::GetTexLevelParameteriv(GL_TEXTURE_2D, 0, GL_TEXTURE_WIDTH, &compressedWidth);
gl::GetTexLevelParameteriv(GL_TEXTURE_2D, 0, GL_TEXTURE_HEIGHT, &compressedHeight);
u::vector<unsigned char> compressedData(totalSize);
unsigned char *dest = &compressedData[0];
for (size_t i = 0; i < totalMips; i++) {
GLint size;
gl::GetTexLevelParameteriv(GL_TEXTURE_2D, i, GL_TEXTURE_COMPRESSED_IMAGE_SIZE, &size);
gl::GetCompressedTexImage(GL_TEXTURE_2D, i, dest);
dest += size;
}
return writeCacheData(tex.format(), tex.size(), tex.hashString(), &compressedData[0],
compressedWidth, compressedHeight, compressedData.size(), totalMips, internal);
}
struct queryFormat {
constexpr queryFormat()
: format(0)
, data(0)
, internal(0)
{
}
constexpr queryFormat(GLenum format, GLenum data, GLenum internal)
: format(format)
, data(data)
, internal(internal)
{
}
GLenum format;
GLenum data;
GLenum internal;
};
static size_t textureAlignment(const Texture &tex) {
const unsigned char *data = tex.data();
const size_t width = tex.width();
const size_t bpp = tex.bpp();
const size_t address = size_t(data) | (width * bpp);
if (address & 1) return 1;
if (address & 2) return 2;
if (address & 4) return 4;
return 8;
}
// Given a source texture the following function finds the best way to present
// that texture to the hardware. This function will also favor texture compression
// if the hardware supports it by converting the texture if it needs to.
static u::optional<queryFormat> getBestFormat(Texture &tex) {
auto checkSupport = [](size_t what) {
if (!gl::has(what))
neoFatal("No support for `%s'", gl::extensionString(what));
};
// The texture is compressed?
if (tex.flags() & kTexFlagCompressed) {
switch (tex.format()) {
case kTexFormatDXT1:
checkSupport(gl::EXT_texture_compression_s3tc);
return queryFormat { GL_RGBA, R_TEX_DATA_RGBA, GL_COMPRESSED_RGBA_S3TC_DXT1_EXT };
case kTexFormatDXT3:
checkSupport(gl::EXT_texture_compression_s3tc);
return queryFormat { GL_RGBA, R_TEX_DATA_RGBA, GL_COMPRESSED_RGBA_S3TC_DXT3_EXT };
case kTexFormatDXT5:
checkSupport(gl::EXT_texture_compression_s3tc);
return queryFormat { GL_RGBA, R_TEX_DATA_RGBA, GL_COMPRESSED_RGBA_S3TC_DXT5_EXT };
case kTexFormatBC4U:
checkSupport(gl::EXT_texture_compression_rgtc);
return queryFormat { GL_RED, R_TEX_DATA_LUMINANCE, GL_COMPRESSED_RED_RGTC1_EXT };
case kTexFormatBC4S:
checkSupport(gl::EXT_texture_compression_rgtc);
return queryFormat { GL_RED, R_TEX_DATA_LUMINANCE, GL_COMPRESSED_SIGNED_RED_RGTC1_EXT };
case kTexFormatBC5U:
checkSupport(gl::EXT_texture_compression_rgtc);
return queryFormat { GL_RG, R_TEX_DATA_RG, GL_COMPRESSED_RED_GREEN_RGTC2_EXT };
case kTexFormatBC5S:
checkSupport(gl::EXT_texture_compression_rgtc);
return queryFormat { GL_RG, R_TEX_DATA_RG, GL_COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT };
default:
break;
}
U_UNREACHABLE();
}
if (tex.flags() & kTexFlagNormal)
tex.convert<kTexFormatRG>();
else if (tex.flags() & kTexFlagGrey)
tex.convert<kTexFormatLuminance>();
// Texture compression?
if (r_tex_compress && !(tex.flags() & kTexFlagNoCompress)) {
const bool bptc = gl::has(gl::ARB_texture_compression_bptc);
const bool s3tc = gl::has(gl::EXT_texture_compression_s3tc);
const bool rgtc = gl::has(gl::EXT_texture_compression_rgtc);
// Deal with conversion from BGR[A] space to RGB[A] space for compression
// While falling through to the correct internal format for the compression
if (bptc || s3tc || rgtc) {
switch (tex.format()) {
case kTexFormatBGRA:
tex.convert<kTexFormatRGBA>();
case kTexFormatRGBA:
if (bptc) return queryFormat { GL_RGBA, R_TEX_DATA_RGBA, GL_COMPRESSED_RGBA_BPTC_UNORM_ARB };
if (s3tc) return queryFormat { GL_RGBA, R_TEX_DATA_RGBA, GL_COMPRESSED_RGBA_S3TC_DXT5_EXT };
break;
case kTexFormatBGR:
tex.convert<kTexFormatRGB>();
case kTexFormatRGB:
if (bptc) return queryFormat { GL_RGB,R_TEX_DATA_RGB, GL_COMPRESSED_RGB_BPTC_SIGNED_FLOAT_ARB };
if (s3tc) return queryFormat { GL_RGB,R_TEX_DATA_RGB, GL_COMPRESSED_RGBA_S3TC_DXT1_EXT };
break;
case kTexFormatRG:
if (rgtc) return queryFormat { GL_RG, R_TEX_DATA_RG, GL_COMPRESSED_RED_GREEN_RGTC2_EXT };
break;
case kTexFormatLuminance:
if (rgtc) return queryFormat { GL_RED,R_TEX_DATA_LUMINANCE, GL_COMPRESSED_RED_RGTC1_EXT };
break;
default:
break;
}
}
}
// If we made it here then no compression is possible so use a raw internal
// format.
switch (tex.format()) {
case kTexFormatRGBA:
return queryFormat { GL_RGBA, R_TEX_DATA_RGBA,GL_RGBA };
case kTexFormatRGB:
return queryFormat { GL_RGB, R_TEX_DATA_RGB, GL_RGBA };
case kTexFormatBGRA:
return queryFormat { GL_BGRA, R_TEX_DATA_BGRA,GL_RGBA };
case kTexFormatBGR:
return queryFormat { GL_BGR, R_TEX_DATA_BGR, GL_RGBA };
case kTexFormatRG:
return queryFormat { GL_RG, R_TEX_DATA_RG, GL_RG8 };
case kTexFormatLuminance:
return queryFormat { GL_RED, R_TEX_DATA_LUMINANCE, GL_RED };
default:
U_UNREACHABLE();
break;
}
return u::none;
}
texture2D::texture2D(bool mipmaps, int filter)
: m_uploaded(false)
, m_textureHandle(0)
, m_mipmaps(mipmaps ? 1 : 0)
, m_memory(0)
, m_filter(filter)
{
//
}
texture2D::texture2D(Texture &tex, bool mipmaps, int filter)
: texture2D::texture2D(mipmaps, filter)
{
m_texture = u::move(tex);
}
texture2D::~texture2D() {
if (m_uploaded)
gl::DeleteTextures(1, &m_textureHandle);
}
bool texture2D::useCache() {
GLuint internalFormat = 0;
if (!readCache(m_texture, internalFormat))
return false;
size_t offset = 0;
size_t mipWidth = m_texture.width();
size_t mipHeight = m_texture.height();
size_t blockSize = 0;
switch (internalFormat) {
case GL_COMPRESSED_RGBA_BPTC_UNORM_ARB:
case GL_COMPRESSED_RGBA_S3TC_DXT5_EXT:
case GL_COMPRESSED_RGB_BPTC_SIGNED_FLOAT_ARB:
case GL_COMPRESSED_RED_GREEN_RGTC2_EXT:
blockSize = 16;
break;
case GL_COMPRESSED_RGBA_S3TC_DXT1_EXT:
case GL_COMPRESSED_RED_RGTC1_EXT:
blockSize = 8;
break;
}
// Load all mip levels
gl::TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, m_mipmaps - 1);
for (size_t i = 0; i < m_mipmaps; i++) {
const size_t mipSize = ((mipWidth + 3) / 4) * ((mipHeight + 3) / 4) * blockSize;
gl::CompressedTexImage2D(GL_TEXTURE_2D, i, internalFormat, mipWidth,
mipHeight, 0, mipSize, m_texture.data() + offset);
mipWidth = u::max(mipWidth >> 1, 1_z);
mipHeight = u::max(mipHeight >> 1, 1_z);
offset += mipSize;
}
return true;
}
void texture2D::colorize(uint32_t color) {
m_texture.colorize(color);
}
static inline void getTexParams(bool bilinear, bool mipmaps, bool trilinear, GLenum &min, GLenum &mag) {
const unsigned char index = bilinear | (mipmaps << 1) | (trilinear << 2);
mag = (index & 1) ? GL_LINEAR : GL_NEAREST;
static const GLenum kMinLookup[] = {
GL_NEAREST, GL_LINEAR, GL_NEAREST_MIPMAP_NEAREST, GL_LINEAR_MIPMAP_NEAREST,
GL_NEAREST, GL_LINEAR, GL_NEAREST_MIPMAP_LINEAR, GL_LINEAR_MIPMAP_LINEAR
};
U_ASSERT(index < sizeof kMinLookup / sizeof *kMinLookup);
min = kMinLookup[index];
}
void texture2D::applyFilter() {
const bool aniso = r_aniso && (m_filter & kFilterAniso);
const bool bilinear = r_bilinear && (m_filter & kFilterBilinear);
const bool trilinear = r_trilinear && (m_filter & kFilterTrilinear);
GLenum min = GL_NEAREST;
GLenum mag = GL_NEAREST;
getTexParams(bilinear, m_mipmaps, trilinear, min, mag);
gl::TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, min);
gl::TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, mag);
if (aniso)
gl::TexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, float(r_aniso));
}
bool texture2D::cache(GLuint internal) {
return writeCache(m_texture, internal, m_textureHandle, m_mipmaps);
}
bool texture2D::load(const u::string &file, bool preserveQuality, bool mipmaps, bool debug) {
const bool status = m_texture.load(file, preserveQuality ? 1.0f : r_tex_quality);
if (status) {
if (mipmaps)
m_mipmaps = u::log2(u::max(m_texture.width(), m_texture.height())) + 1;
else
m_mipmaps = 1;
m_memory = m_texture.size() + (m_mipmaps > 1 ? m_texture.size() / 3 : 0);
if (debug) {
// For debugging draw the file name and other information into
// the texture. This will silently truncate if the information
// cannot fit into the texture space
size_t line = 0;
m_texture.drawString(line, file.c_str());
m_texture.drawString(line, u::format("%zux%zu",
m_texture.width(), m_texture.height()).c_str());
m_texture.drawString(line, u::sizeMetric(m_memory).c_str());
m_texture.drawString(line, u::format("%s%zu",
m_texture.components(), m_texture.bpp()).c_str());
if (m_mipmaps > 1) {
m_texture.drawString(line, u::format("%zu mips",
m_mipmaps - 1).c_str());
}
}
// Ensure texture cache is mounted
return mountCache();
}
return false;
}
bool texture2D::upload(GLint wrap) {
if (m_uploaded)
return true;
gl::GenTextures(1, &m_textureHandle);
gl::BindTexture(GL_TEXTURE_2D, m_textureHandle);
// If the texture is compressed on disk then load it in ignoring cache
if (m_texture.flags() & kTexFlagCompressed) {
gl::TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER,
(m_texture.mips() > 1 && r_mipmaps) ? GL_LINEAR_MIPMAP_LINEAR : GL_LINEAR);
gl::TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
size_t offset = 0;
size_t mipWidth = m_texture.width();
size_t mipHeight = m_texture.height();
size_t blockSize = 0;
switch (m_texture.format()) {
case kTexFormatDXT1:
case kTexFormatBC4U:
case kTexFormatBC4S:
blockSize = 8;
break;
case kTexFormatDXT3:
case kTexFormatDXT5:
case kTexFormatBC5U:
case kTexFormatBC5S:
blockSize = 16;
break;
default:
return false;
}
auto query = getBestFormat(m_texture);
if (!query)
return false;
queryFormat format = *query;
// Load all mip levels
m_memory = 0;
for (size_t i = 0; i < m_mipmaps; i++) {
const size_t mipSize = ((mipWidth + 3) / 4) * ((mipHeight + 3) / 4) * blockSize;
gl::CompressedTexImage2D(GL_TEXTURE_2D, i, format.internal, mipWidth,
mipHeight, 0, mipSize, m_texture.data() + offset);
mipWidth = u::max(mipWidth >> 1, 1_z);
mipHeight = u::max(mipHeight >> 1, 1_z);
offset += mipSize;
m_memory += mipSize;
}
gl::TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, wrap);
gl::TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, wrap);
} else {
// Don't attempt to cache debug textures
auto &r_debug_tex = c::Console::value<int>("r_debug_tex");
queryFormat format;
bool needsCache = !useCache();
if (needsCache) {
auto query = getBestFormat(m_texture);
if (!query)
return false;
format = *query;
#if defined(DXT_COMPRESSOR)
// Use our DXT compressor instead of the driver
if (r_dxt_compressor &&
!r_debug_tex &&
(format.internal == GL_COMPRESSED_RGBA_S3TC_DXT1_EXT ||
format.internal == GL_COMPRESSED_RGBA_S3TC_DXT5_EXT))
{
needsCache = false;
u::vector<unsigned char> compressed;
Texture resize = m_texture;
size_t mipWidth = m_texture.width();