/
gl_texmanager.cpp
2722 lines (2319 loc) · 88.1 KB
/
gl_texmanager.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
/** @file gl_texmanager.cpp GL-Texture management
*
* @todo This file needs to be split into smaller portions.
*
* @authors Copyright © 1999-2013 Jaakko Keränen <jaakko.keranen@iki.fi>
* @authors Copyright © 2005-2013 Daniel Swanson <danij@dengine.net>
* @authors Copyright © 2002 Graham Jackson <no contact email published>
*
* @par License
* GPL: http://www.gnu.org/licenses/gpl.html
*
* <small>This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version. This program is distributed in the hope that it
* will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty
* of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
* Public License for more details. You should have received a copy of the GNU
* General Public License along with this program; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA</small>
*/
#include <cstdlib>
#include <cstring> // memset, memcpy
#include <cctype>
#include <cmath>
#ifdef UNIX
# include "de_platform.h"
#endif
#include "de_base.h"
#include "de_console.h"
#include "de_system.h"
#include "de_filesys.h"
#include "de_graphics.h"
#include "de_render.h"
#include "de_resource.h"
#include "de_play.h"
#include "de_ui.h"
#include "clientapp.h"
#include "def_main.h"
#include "resource/hq2x.h"
#include <QSize>
#include <de/ByteRefArray>
#include <de/mathutil.h>
#include <de/memory.h>
#include <de/memoryzone.h>
using namespace de;
int mipmapping = 5;
int filterUI = 1;
int texQuality = TEXQ_BEST;
struct texturevariantspecificationlist_node_t
{
texturevariantspecificationlist_node_t *next;
texturevariantspecification_t *spec;
};
typedef texturevariantspecificationlist_node_t variantspecificationlist_t;
D_CMD(LowRes);
D_CMD(MipMap);
D_CMD(TexReset);
void GL_DoResetDetailTextures();
void GL_DoTexReset();
void GL_DoUpdateTexGamma();
void GL_DoUpdateTexParams();
static int hashDetailVariantSpecification(detailvariantspecification_t const &spec);
static TexSource loadExternalTexture(image_t &image, String searchPath, String optionalSuffix = "");
static TexSource loadFlat(image_t &image, de::FileHandle &file);
static TexSource loadPatch(image_t &image, de::FileHandle &file, int tclass = 0, int tmap = 0, int border = 0);
static TexSource loadDetail(image_t &image, de::FileHandle &file);
static TexSource loadRaw(image_t &image, rawtex_t const &raw);
static TexSource loadPatchComposite(image_t &image, Texture const &tex,
bool zeroMask = false, bool useZeroOriginIfOneComponent = false);
int ratioLimit = 0; // Zero if none.
boolean fillOutlines = true;
int useSmartFilter = 0; // Smart filter mode (cvar: 1=hq2x)
int filterSprites = true;
int texMagMode = 1; // Linear.
int texAniso = -1; // Use best.
boolean noHighResTex = false;
boolean noHighResPatches = false;
boolean highResWithPWAD = false;
byte loadExtAlways = false; // Always check for extres (cvar)
float texGamma = 0;
int glmode[6] = // Indexed by 'mipmapping'.
{
GL_NEAREST,
GL_LINEAR,
GL_NEAREST_MIPMAP_NEAREST,
GL_LINEAR_MIPMAP_NEAREST,
GL_NEAREST_MIPMAP_LINEAR,
GL_LINEAR_MIPMAP_LINEAR
};
// Names of the dynamic light textures.
DGLuint lightingTextures[NUM_LIGHTING_TEXTURES];
// Names of the flare textures (halos).
DGLuint sysFlareTextures[NUM_SYSFLARE_TEXTURES];
static boolean initedOk = false; // Init done.
static variantspecificationlist_t *variantSpecs;
/// @c TST_DETAIL type specifications are stored separately into a set of
/// buckets. Bucket selection is determined by their quantized contrast value.
#define DETAILVARIANT_CONTRAST_HASHSIZE (DETAILTEXTURE_CONTRAST_QUANTIZATION_FACTOR+1)
static variantspecificationlist_t *detailVariantSpecs[DETAILVARIANT_CONTRAST_HASHSIZE];
void GL_TexRegister()
{
C_VAR_INT ("rend-tex", &renderTextures, CVF_NO_ARCHIVE, 0, 2);
C_VAR_INT ("rend-tex-detail", &r_detail, 0, 0, 1);
C_VAR_INT ("rend-tex-detail-multitex", &useMultiTexDetails, 0, 0, 1);
C_VAR_FLOAT ("rend-tex-detail-scale", &detailScale, CVF_NO_MIN | CVF_NO_MAX, 0, 0);
C_VAR_FLOAT2("rend-tex-detail-strength", &detailFactor, 0, 0, 5, GL_DoResetDetailTextures);
C_VAR_BYTE2 ("rend-tex-external-always", &loadExtAlways, 0, 0, 1, GL_DoTexReset);
C_VAR_INT ("rend-tex-filter-anisotropic", &texAniso, 0, -1, 4);
C_VAR_INT ("rend-tex-filter-mag", &texMagMode, 0, 0, 1);
C_VAR_INT2 ("rend-tex-filter-smart", &useSmartFilter, 0, 0, 1, GL_DoTexReset);
C_VAR_INT ("rend-tex-filter-sprite", &filterSprites, 0, 0, 1);
C_VAR_INT ("rend-tex-filter-ui", &filterUI, 0, 0, 1);
C_VAR_FLOAT2("rend-tex-gamma", &texGamma, 0, 0, 1, GL_DoUpdateTexGamma);
C_VAR_INT2 ("rend-tex-mipmap", &mipmapping, CVF_PROTECTED, 0, 5, GL_DoTexReset);
C_VAR_INT2 ("rend-tex-quality", &texQuality, 0, 0, 8, GL_DoTexReset);
C_CMD_FLAGS ("lowres", "", LowRes, CMDF_NO_DEDICATED);
C_CMD_FLAGS ("mipmap", "i", MipMap, CMDF_NO_DEDICATED);
C_CMD_FLAGS ("texreset", "", TexReset, CMDF_NO_DEDICATED);
}
GLint GL_MinFilterForVariantSpec(variantspecification_t const &spec)
{
if(spec.minFilter >= 0) // Constant logical value.
{
return (spec.mipmapped? GL_NEAREST_MIPMAP_NEAREST : GL_NEAREST) + spec.minFilter;
}
// "No class" preference.
return spec.mipmapped? glmode[mipmapping] : GL_LINEAR;
}
GLint GL_MagFilterForVariantSpec(variantspecification_t const &spec)
{
if(spec.magFilter >= 0) // Constant logical value.
{
return GL_NEAREST + spec.magFilter;
}
// Preference for texture class id.
switch(abs(spec.magFilter)-1)
{
case 1: // Sprite class.
return filterSprites? GL_LINEAR : GL_NEAREST;
case 2: // UI class.
return filterUI? GL_LINEAR : GL_NEAREST;
default: // "No class" preference.
return glmode[texMagMode];
}
}
int GL_LogicalAnisoLevelForVariantSpec(variantspecification_t const &spec)
{
return spec.anisoFilter < 0? texAniso : spec.anisoFilter;
}
static void unlinkVariantSpecification(texturevariantspecification_t &spec)
{
variantspecificationlist_t **listHead;
DENG_ASSERT(initedOk);
// Select list head according to variant specification type.
switch(spec.type)
{
case TST_GENERAL: listHead = &variantSpecs; break;
case TST_DETAIL: {
int hash = hashDetailVariantSpecification(TS_DETAIL(spec));
listHead = &detailVariantSpecs[hash];
break; }
default:
Con_Error("unlinkVariantSpecification: Invalid spec type %i.", spec.type);
exit(1); // Unreachable.
}
if(*listHead)
{
texturevariantspecificationlist_node_t *node = 0;
if((*listHead)->spec == &spec)
{
node = (*listHead);
*listHead = (*listHead)->next;
}
else
{
// Find the previous node.
texturevariantspecificationlist_node_t *prevNode = (*listHead);
while(prevNode->next && prevNode->next->spec != &spec)
{
prevNode = prevNode->next;
}
if(prevNode)
{
node = prevNode->next;
prevNode->next = prevNode->next->next;
}
}
M_Free(node);
}
}
static void destroyVariantSpecification(texturevariantspecification_t &spec)
{
unlinkVariantSpecification(spec);
if(spec.type == TST_GENERAL && (TS_GENERAL(spec).flags & TSF_HAS_COLORPALETTE_XLAT))
{
M_Free(TS_GENERAL(spec).translated);
}
M_Free(&spec);
}
static texturevariantspecification_t *copyVariantSpecification(
texturevariantspecification_t const &tpl)
{
texturevariantspecification_t *spec = (texturevariantspecification_t *) M_Malloc(sizeof(*spec));
if(!spec) Con_Error("Textures::copyVariantSpecification: Failed on allocation of %lu bytes for new TextureVariantSpecification.", (unsigned long) sizeof(*spec));
std::memcpy(spec, &tpl, sizeof(texturevariantspecification_t));
if(TS_GENERAL(tpl).flags & TSF_HAS_COLORPALETTE_XLAT)
{
colorpalettetranslationspecification_t *cpt = (colorpalettetranslationspecification_t *) M_Malloc(sizeof(*cpt));
if(!cpt) Con_Error("Textures::copyVariantSpecification: Failed on allocation of %lu bytes for new ColorPaletteTranslationSpecification.", (unsigned long) sizeof(*cpt));
std::memcpy(cpt, TS_GENERAL(tpl).translated, sizeof(colorpalettetranslationspecification_t));
TS_GENERAL(*spec).translated = cpt;
}
return spec;
}
static texturevariantspecification_t *copyDetailVariantSpecification(
texturevariantspecification_t const &tpl)
{
texturevariantspecification_t *spec = (texturevariantspecification_t *) M_Malloc(sizeof(*spec));
if(!spec) Con_Error("Textures::copyDetailVariantSpecification: Failed on allocation of %lu bytes for new TextureVariantSpecification.", (unsigned long) sizeof(*spec));
std::memcpy(spec, &tpl, sizeof(texturevariantspecification_t));
return spec;
}
static colorpalettetranslationspecification_t *applyColorPaletteTranslationSpecification(
colorpalettetranslationspecification_t *spec, int tClass, int tMap)
{
DENG_ASSERT(initedOk && spec);
LOG_AS("applyColorPaletteTranslationSpecification");
spec->tClass = MAX_OF(0, tClass);
spec->tMap = MAX_OF(0, tMap);
#if _DEBUG
if(0 == tClass && 0 == tMap)
LOG_WARNING("Applied unnecessary zero-translation (tClass:0 tMap:0).");
#endif
return spec;
}
static variantspecification_t &applyVariantSpecification(
variantspecification_t &spec, texturevariantusagecontext_t tc, int flags,
byte border, colorpalettetranslationspecification_t *colorPaletteTranslationSpec,
int wrapS, int wrapT, int minFilter, int magFilter, int anisoFilter, boolean mipmapped,
boolean gammaCorrection, boolean noStretch, boolean toAlpha)
{
DENG_ASSERT(initedOk && (tc == TC_UNKNOWN || VALID_TEXTUREVARIANTUSAGECONTEXT(tc)));
flags &= ~TSF_INTERNAL_MASK;
spec.context = tc;
spec.flags = flags;
spec.border = (flags & TSF_UPSCALE_AND_SHARPEN)? 1 : border;
spec.mipmapped = mipmapped;
spec.wrapS = wrapS;
spec.wrapT = wrapT;
spec.minFilter = MINMAX_OF(-1, minFilter, spec.mipmapped? 3:1);
spec.magFilter = MINMAX_OF(-3, magFilter, 1);
spec.anisoFilter = MINMAX_OF(-1, anisoFilter, 4);
spec.gammaCorrection = gammaCorrection;
spec.noStretch = noStretch;
spec.toAlpha = toAlpha;
if(colorPaletteTranslationSpec)
{
spec.flags |= TSF_HAS_COLORPALETTE_XLAT;
spec.translated = colorPaletteTranslationSpec;
}
else
{
spec.translated = NULL;
}
return spec;
}
static detailvariantspecification_t &applyDetailVariantSpecification(
detailvariantspecification_t &spec, float contrast)
{
int const quantFactor = DETAILTEXTURE_CONTRAST_QUANTIZATION_FACTOR;
spec.contrast = 255 * (int)MINMAX_OF(0, contrast * quantFactor + .5f, quantFactor) * (1 / float(quantFactor));
return spec;
}
static int hashDetailVariantSpecification(detailvariantspecification_t const &spec)
{
return (spec.contrast * (1/255.f) * DETAILTEXTURE_CONTRAST_QUANTIZATION_FACTOR + .5f);
}
static texturevariantspecification_t &linkVariantSpecification(
texturevariantspecificationtype_t type, texturevariantspecification_t &spec)
{
texturevariantspecificationlist_node_t *node;
DENG_ASSERT(initedOk && VALID_TEXTUREVARIANTSPECIFICATIONTYPE(type));
node = (texturevariantspecificationlist_node_t *) M_Malloc(sizeof(*node));
if(!node) Con_Error("Textures::linkVariantSpecification: Failed on allocation of %lu bytes for new TextureVariantSpecificationListNode.", (unsigned long) sizeof(*node));
node->spec = &spec;
switch(type)
{
case TST_GENERAL:
node->next = variantSpecs;
variantSpecs = (variantspecificationlist_t *)node;
break;
case TST_DETAIL: {
int hash = hashDetailVariantSpecification(TS_DETAIL(spec));
node->next = detailVariantSpecs[hash];
detailVariantSpecs[hash] = (variantspecificationlist_t *)node;
break; }
}
return spec;
}
static texturevariantspecification_t *findVariantSpecification(
texturevariantspecificationtype_t type, texturevariantspecification_t const &tpl,
bool canCreate)
{
texturevariantspecificationlist_node_t *node;
DENG_ASSERT(initedOk && VALID_TEXTUREVARIANTSPECIFICATIONTYPE(type));
// Select list head according to variant specification type.
switch(type)
{
case TST_GENERAL: node = variantSpecs; break;
case TST_DETAIL: {
int hash = hashDetailVariantSpecification(TS_DETAIL(tpl));
node = detailVariantSpecs[hash];
break; }
default:
Con_Error("findVariantSpecification: Invalid spec type %i.", type);
exit(1); // Unreachable.
}
// Do we already have a concrete version of the template specification?
for(; node; node = node->next)
{
if(TextureVariantSpec_Compare(node->spec, &tpl))
return node->spec;
}
// Not found, can we create?
if(canCreate)
switch(type)
{
case TST_GENERAL: return &linkVariantSpecification(type, *copyVariantSpecification(tpl));
case TST_DETAIL: return &linkVariantSpecification(type, *copyDetailVariantSpecification(tpl));
}
return NULL;
}
static texturevariantspecification_t *getVariantSpecificationForContext(
texturevariantusagecontext_t tc, int flags, byte border, int tClass,
int tMap, int wrapS, int wrapT, int minFilter, int magFilter, int anisoFilter,
boolean mipmapped, boolean gammaCorrection, boolean noStretch, boolean toAlpha)
{
static texturevariantspecification_t tpl;
static colorpalettetranslationspecification_t cptTpl;
boolean haveCpt = false;
DENG_ASSERT(initedOk);
tpl.type = TST_GENERAL;
if(0 != tClass || 0 != tMap)
{
// A color palette translation spec is required.
applyColorPaletteTranslationSpecification(&cptTpl, tClass, tMap);
haveCpt = true;
}
applyVariantSpecification(TS_GENERAL(tpl), tc, flags, border, haveCpt? &cptTpl : NULL,
wrapS, wrapT, minFilter, magFilter, anisoFilter, mipmapped, gammaCorrection,
noStretch, toAlpha);
// Retrieve a concrete version of the rationalized specification.
return findVariantSpecification(tpl.type, tpl, true);
}
static texturevariantspecification_t *getDetailVariantSpecificationForContext(
float contrast)
{
static texturevariantspecification_t tpl;
DENG_ASSERT(initedOk);
tpl.type = TST_DETAIL;
applyDetailVariantSpecification(TS_DETAIL(tpl), contrast);
return findVariantSpecification(tpl.type, tpl, true);
}
static void emptyVariantSpecificationList(variantspecificationlist_t *list)
{
texturevariantspecificationlist_node_t* node = (texturevariantspecificationlist_node_t *) list;
DENG_ASSERT(initedOk);
while(node)
{
texturevariantspecificationlist_node_t *next = node->next;
destroyVariantSpecification(*node->spec);
node = next;
}
}
static bool variantSpecInUse(texturevariantspecification_t const &spec)
{
foreach(Texture *texture, App_Textures().all())
foreach(TextureVariant *variant, texture->variants())
{
if(&variant->spec() == &spec)
{
return true; // Found one; stop.
}
}
return false;
}
static int pruneUnusedVariantSpecificationsInList(variantspecificationlist_t *list)
{
texturevariantspecificationlist_node_t *node = list;
int numPruned = 0;
while(node)
{
texturevariantspecificationlist_node_t *next = node->next;
if(!variantSpecInUse(*node->spec))
{
destroyVariantSpecification(*node->spec);
++numPruned;
}
node = next;
}
return numPruned;
}
static int pruneUnusedVariantSpecifications(texturevariantspecificationtype_t specType)
{
DENG_ASSERT(initedOk);
switch(specType)
{
case TST_GENERAL: return pruneUnusedVariantSpecificationsInList(variantSpecs);
case TST_DETAIL: {
int numPruned = 0;
for(int i = 0; i < DETAILVARIANT_CONTRAST_HASHSIZE; ++i)
{
numPruned += pruneUnusedVariantSpecificationsInList(detailVariantSpecs[i]);
}
return numPruned; }
default:
Con_Error("Textures::pruneUnusedVariantSpecifications: Invalid variant spec type %i.", (int) specType);
exit(1); // Unreachable.
}
}
static void destroyVariantSpecifications()
{
DENG_ASSERT(initedOk);
emptyVariantSpecificationList(variantSpecs); variantSpecs = 0;
for(int i = 0; i < DETAILVARIANT_CONTRAST_HASHSIZE; ++i)
{
emptyVariantSpecificationList(detailVariantSpecs[i]); detailVariantSpecs[i] = 0;
}
}
GLUploadMethod GL_ChooseUploadMethod(texturecontent_t const &content)
{
// Must the operation be carried out immediately?
if((content.flags & TXCF_NEVER_DEFER) || !BusyMode_Active())
{
return Immediate;
}
// We can defer.
return Deferred;
}
static int releaseVariantGLTexture(TextureVariant &variant, texturevariantspecification_t *spec = 0)
{
if(!spec || spec == &variant.spec())
{
variant.release();
if(spec) return true; // We're done.
}
return 0; // Continue iteration.
}
static void uploadContentUnmanaged(texturecontent_t const &content)
{
LOG_AS("uploadContentUnmanaged");
if(novideo) return;
GLUploadMethod uploadMethod = GL_ChooseUploadMethod(content);
if(uploadMethod == Immediate)
{
LOG_DEBUG("Uploading texture (%i:%ix%i) while not busy! Should be precached in busy mode?")
<< content.name << content.width << content.height;
}
GL_UploadTextureContent(content, uploadMethod);
}
TexSource GL_LoadSourceImage(image_t &image, Texture const &tex,
texturevariantspecification_t const &spec)
{
TexSource source = TEXS_NONE;
variantspecification_t const &vspec = TS_GENERAL(spec);
if(!tex.manifest().schemeName().compareWithoutCase("Textures"))
{
// Attempt to load an external replacement for this composite texture?
if(!noHighResTex && (loadExtAlways || highResWithPWAD || !tex.isFlagged(Texture::Custom)))
{
// First try the textures scheme.
de::Uri uri = tex.manifest().composeUri();
source = loadExternalTexture(image, uri.compose(), "-ck");
}
if(source == TEXS_NONE)
{
if(TC_SKYSPHERE_DIFFUSE != vspec.context)
{
source = loadPatchComposite(image, tex);
}
else
{
bool const zeroMask = (vspec.flags & TSF_ZEROMASK) != 0;
bool const useZeroOriginIfOneComponent = true;
source = loadPatchComposite(image, tex, zeroMask, useZeroOriginIfOneComponent);
}
}
}
else if(!tex.manifest().schemeName().compareWithoutCase("Flats"))
{
// Attempt to load an external replacement for this flat?
if(!noHighResTex && (loadExtAlways || highResWithPWAD || !tex.isFlagged(Texture::Custom)))
{
// First try the flats scheme.
de::Uri uri = tex.manifest().composeUri();
source = loadExternalTexture(image, uri.compose(), "-ck");
if(source == TEXS_NONE)
{
// How about the old-fashioned "flat-name" in the textures scheme?
source = loadExternalTexture(image, "Textures:flat-" + uri.path().toStringRef(), "-ck");
}
}
if(source == TEXS_NONE)
{
if(tex.manifest().hasResourceUri())
{
de::Uri resourceUri = tex.manifest().resourceUri();
if(!resourceUri.scheme().compareWithoutCase("LumpIndex"))
{
try
{
lumpnum_t lumpNum = resourceUri.path().toString().toInt();
de::File1 &lump = App_FileSystem().nameIndex().lump(lumpNum);
de::FileHandle &hndl = App_FileSystem().openLump(lump);
source = loadFlat(image, hndl);
App_FileSystem().releaseFile(hndl.file());
delete &hndl;
}
catch(LumpIndex::NotFoundError const&)
{} // Ignore this error.
}
}
}
}
else if(!tex.manifest().schemeName().compareWithoutCase("Patches"))
{
int tclass = 0, tmap = 0;
if(vspec.flags & TSF_HAS_COLORPALETTE_XLAT)
{
DENG_ASSERT(vspec.translated);
tclass = vspec.translated->tClass;
tmap = vspec.translated->tMap;
}
// Attempt to load an external replacement for this patch?
if(!noHighResTex && (loadExtAlways || highResWithPWAD || !tex.isFlagged(Texture::Custom)))
{
de::Uri uri = tex.manifest().composeUri();
source = loadExternalTexture(image, uri.compose(), "-ck");
}
if(source == TEXS_NONE)
{
if(tex.manifest().hasResourceUri())
{
de::Uri resourceUri = tex.manifest().resourceUri();
if(!resourceUri.scheme().compareWithoutCase("LumpIndex"))
{
try
{
lumpnum_t lumpNum = resourceUri.path().toString().toInt();
de::File1 &lump = App_FileSystem().nameIndex().lump(lumpNum);
de::FileHandle &hndl = App_FileSystem().openLump(lump);
source = loadPatch(image, hndl, tclass, tmap, vspec.border);
App_FileSystem().releaseFile(hndl.file());
delete &hndl;
}
catch(LumpIndex::NotFoundError const&)
{} // Ignore this error.
}
}
}
}
else if(!tex.manifest().schemeName().compareWithoutCase("Sprites"))
{
int tclass = 0, tmap = 0;
if(vspec.flags & TSF_HAS_COLORPALETTE_XLAT)
{
DENG_ASSERT(vspec.translated);
tclass = vspec.translated->tClass;
tmap = vspec.translated->tMap;
}
// Attempt to load an external replacement for this sprite?
if(!noHighResPatches)
{
de::Uri uri = tex.manifest().composeUri();
// Prefer psprite or translated versions if available.
if(TC_PSPRITE_DIFFUSE == vspec.context)
{
source = loadExternalTexture(image, "Patches:" + uri.path() + "-hud", "-ck");
}
else if(tclass || tmap)
{
source = loadExternalTexture(image, "Patches:" + uri.path() + String("-table%1%2").arg(tclass).arg(tmap), "-ck");
}
if(!source)
{
source = loadExternalTexture(image, "Patches:" + uri.path(), "-ck");
}
}
if(source == TEXS_NONE)
{
if(tex.manifest().hasResourceUri())
{
de::Uri resourceUri = tex.manifest().resourceUri();
if(!resourceUri.scheme().compareWithoutCase("LumpIndex"))
{
try
{
lumpnum_t lumpNum = resourceUri.path().toString().toInt();
de::File1 &lump = App_FileSystem().nameIndex().lump(lumpNum);
de::FileHandle &hndl = App_FileSystem().openLump(lump);
source = loadPatch(image, hndl, tclass, tmap, vspec.border);
App_FileSystem().releaseFile(hndl.file());
delete &hndl;
}
catch(LumpIndex::NotFoundError const&)
{} // Ignore this error.
}
}
}
}
else if(!tex.manifest().schemeName().compareWithoutCase("Details"))
{
if(tex.manifest().hasResourceUri())
{
de::Uri resourceUri = tex.manifest().resourceUri();
if(resourceUri.scheme().compareWithoutCase("Lumps"))
{
source = loadExternalTexture(image, resourceUri.compose());
}
else
{
lumpnum_t lumpNum = App_FileSystem().lumpNumForName(resourceUri.path());
try
{
de::File1 &lump = App_FileSystem().nameIndex().lump(lumpNum);
de::FileHandle &hndl = App_FileSystem().openLump(lump);
source = loadDetail(image, hndl);
App_FileSystem().releaseFile(hndl.file());
delete &hndl;
}
catch(LumpIndex::NotFoundError const&)
{} // Ignore this error.
}
}
}
else
{
if(tex.manifest().hasResourceUri())
{
de::Uri resourceUri = tex.manifest().resourceUri();
source = loadExternalTexture(image, resourceUri.compose());
}
}
return source;
}
/**
* Prepares the image for use as a GL texture in accordance with the given
* specification.
*
* @param image The image to prepare (in place).
* @param spec Specification describing any transformations which should
* be applied to the image.
*
* @return The DGL texture format determined for the image.
*/
static dgltexformat_t prepareImageAsTexture(image_t &image,
variantspecification_t const &spec)
{
DENG_ASSERT(image.pixels);
bool const monochrome = (spec.flags & TSF_MONOCHROME) != 0;
bool const scaleSharp = (spec.flags & TSF_UPSCALE_AND_SHARPEN) != 0;
if(spec.toAlpha)
{
if(0 != image.paletteId)
{
// Paletted.
uint8_t *newPixels = GL_ConvertBuffer(image.pixels, image.size.width, image.size.height,
((image.flags & IMGF_IS_MASKED)? 2 : 1),
R_ToColorPalette(image.paletteId), 3);
M_Free(image.pixels);
image.pixels = newPixels;
image.pixelSize = 3;
image.paletteId = 0;
image.flags &= ~IMGF_IS_MASKED;
}
Image_ConvertToLuminance(&image, false);
long total = image.size.width * image.size.height;
for(long i = 0; i < total; ++i)
{
image.pixels[total + i] = image.pixels[i];
image.pixels[i] = 255;
}
image.pixelSize = 2;
}
else if(0 != image.paletteId)
{
if(fillOutlines && (image.flags & IMGF_IS_MASKED))
ColorOutlinesIdx(image.pixels, image.size.width, image.size.height);
if(monochrome && !scaleSharp)
GL_DeSaturatePalettedImage(image.pixels, R_ToColorPalette(image.paletteId),
image.size.width, image.size.height);
if(scaleSharp)
{
int scaleMethod = GL_ChooseSmartFilter(image.size.width, image.size.height, 0);
bool origMasked = (image.flags & IMGF_IS_MASKED) != 0;
colorpaletteid_t origPaletteId = image.paletteId;
uint8_t *newPixels = GL_ConvertBuffer(image.pixels, image.size.width, image.size.height,
((image.flags & IMGF_IS_MASKED)? 2 : 1),
R_ToColorPalette(image.paletteId), 4);
if(newPixels != image.pixels)
{
M_Free(image.pixels);
image.pixels = newPixels;
image.pixelSize = 4;
image.paletteId = 0;
image.flags &= ~IMGF_IS_MASKED;
}
if(monochrome)
Desaturate(image.pixels, image.size.width, image.size.height, image.pixelSize);
newPixels = GL_SmartFilter(scaleMethod, image.pixels, image.size.width, image.size.height,
0, &image.size.width, &image.size.height);
if(newPixels != image.pixels)
{
M_Free(image.pixels);
image.pixels = newPixels;
}
EnhanceContrast(image.pixels, image.size.width, image.size.height, image.pixelSize);
//SharpenPixels(image.pixels, image.size.width, image.size.height, image.pixelSize);
//BlackOutlines(image.pixels, image.size.width, image.size.height, image.pixelSize);
// Back to paletted+alpha?
if(monochrome)
{
// No. We'll convert from RGB(+A) to Luminance(+A) and upload as is.
// Replace the old buffer.
Image_ConvertToLuminance(&image, true);
AmplifyLuma(image.pixels, image.size.width, image.size.height, image.pixelSize == 2);
}
else
{ // Yes. Quantize down from RGA(+A) to Paletted(+A), replacing the old image.
newPixels = GL_ConvertBuffer(image.pixels, image.size.width, image.size.height,
(origMasked? 2 : 1), R_ToColorPalette(origPaletteId), 4);
if(newPixels != image.pixels)
{
M_Free(image.pixels);
image.pixels = newPixels;
image.pixelSize = (origMasked? 2 : 1);
image.paletteId = origPaletteId;
if(origMasked)
image.flags |= IMGF_IS_MASKED;
}
}
}
}
else if(image.pixelSize > 2)
{
if(monochrome)
{
Image_ConvertToLuminance(&image, true);
AmplifyLuma(image.pixels, image.size.width, image.size.height, image.pixelSize == 2);
}
}
/*
* Choose the final GL texture format.
*/
if(monochrome)
{
return image.pixelSize == 2? DGL_LUMINANCE_PLUS_A8 : DGL_LUMINANCE;
}
if(image.paletteId)
{
return (image.flags & IMGF_IS_MASKED)? DGL_COLOR_INDEX_8_PLUS_A8 : DGL_COLOR_INDEX_8;
}
return image.pixelSize == 2 ? DGL_LUMINANCE_PLUS_A8
: image.pixelSize == 3 ? DGL_RGB
: image.pixelSize == 4 ? DGL_RGBA : DGL_LUMINANCE;
}
/**
* Prepares the image for use as a detail GL texture in accordance with the
* given specification.
*
* @param image The image to prepare (in place).
* @param spec Specification describing any transformations which should
* be applied to the image.
*
* Return values:
* @param baMul Luminance equalization balance factor is written here.
* @param hiMul Luminance equalization white-shift factor is written here.
* @param loMul Luminance equalization black-shift factor is written here.
*
* @return The DGL texture format determined for the image.
*/
static dgltexformat_t prepareImageAsDetailTexture(image_t &image,
detailvariantspecification_t const &spec, float *baMul, float *hiMul, float *loMul)
{
DENG_UNUSED(spec);
// We want a luminance map.
if(image.pixelSize > 2)
{
Image_ConvertToLuminance(&image, false);
}
// Try to normalize the luminance data so it works expectedly as a detail texture.
EqualizeLuma(image.pixels, image.size.width, image.size.height, baMul, hiMul, loMul);
return DGL_LUMINANCE;
}
void GL_InitTextureManager()
{
if(initedOk)
{
GL_LoadSystemTextures();
return; // Already been here.
}
// Disable the use of 'high resolution' textures and/or patches?
noHighResTex = CommandLine_Exists("-nohightex");
noHighResPatches = CommandLine_Exists("-nohighpat");
// Should we allow using external resources with PWAD textures?
highResWithPWAD = CommandLine_Exists("-pwadtex");
// System textures loaded in GL_LoadSystemTextures.
std::memset(sysFlareTextures, 0, sizeof(sysFlareTextures));
std::memset(lightingTextures, 0, sizeof(lightingTextures));
variantSpecs = NULL;
memset(detailVariantSpecs, 0, sizeof(detailVariantSpecs));
GL_InitSmartFilterHQ2x();
// Initialization done.
initedOk = true;
}
void GL_ResetTextureManager()
{
if(!initedOk) return;
GL_ReleaseTextures();
GL_PruneTextureVariantSpecifications();
GL_LoadSystemTextures();
}
static String nameForGLTextureWrapMode(int mode)
{
if(mode == GL_REPEAT) return "repeat";
if(mode == GL_CLAMP) return "clamp";
if(mode == GL_CLAMP_TO_EDGE) return "clamp_edge";
return "(unknown)";
}
String texturevariantspecification_t::asText() const
{
static String const textureUsageContextNames[1 + TEXTUREVARIANTUSAGECONTEXT_COUNT] = {
/* TC_UNKNOWN */ "unknown",
/* TC_UI */ "ui",
/* TC_MAPSURFACE_DIFFUSE */ "mapsurface_diffuse",
/* TC_MAPSURFACE_REFLECTION */ "mapsurface_reflection",
/* TC_MAPSURFACE_REFLECTIONMASK */ "mapsurface_reflectionmask",
/* TC_MAPSURFACE_LIGHTMAP */ "mapsurface_lightmap",
/* TC_SPRITE_DIFFUSE */ "sprite_diffuse",
/* TC_MODELSKIN_DIFFUSE */ "modelskin_diffuse",
/* TC_MODELSKIN_REFLECTION */ "modelskin_reflection",
/* TC_HALO_LUMINANCE */ "halo_luminance",
/* TC_PSPRITE_DIFFUSE */ "psprite_diffuse",
/* TC_SKYSPHERE_DIFFUSE */ "skysphere_diffuse"
};
static String const textureSpecificationTypeNames[TEXTUREVARIANTSPECIFICATIONTYPE_COUNT] = {
/* TST_GENERAL */ "general",
/* TST_DETAIL */ "detail"
};
static String const filterModeNames[] = { "ui", "sprite", "noclass", "const" };
static String const glFilterNames[] = {
"nearest", "linear", "nearest_mipmap_nearest", "linear_mipmap_nearest",
"nearest_mipmap_linear", "linear_mipmap_linear"
};
String text = String("Type:%1").arg(textureSpecificationTypeNames[type]);
switch(type)
{
case TST_DETAIL: {
detailvariantspecification_t const &spec = data.detailvariant;
text += " Contrast:" + String::number(int(.5f + spec.contrast / 255.f * 100)) + "%";
break; }
case TST_GENERAL: {
variantspecification_t const &spec = data.variant;
texturevariantusagecontext_t tc = spec.context;
DENG_ASSERT(tc == TC_UNKNOWN || VALID_TEXTUREVARIANTUSAGECONTEXT(tc));
int glMinFilterNameIdx;
if(spec.minFilter >= 0) // Constant logical value.
{
glMinFilterNameIdx = (spec.mipmapped? 2 : 0) + spec.minFilter;