/
gl_tex.c
3569 lines (3119 loc) · 97.6 KB
/
gl_tex.c
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
//**************************************************************************
//**
//** GL_TEX.C
//**
//** A lot of this stuff actually belongs in Refresh.
//**
//**************************************************************************
// HEADER FILES ------------------------------------------------------------
//#define DD_PROFILE
#include <stdlib.h>
#include <math.h>
#include "de_base.h"
#include "de_console.h"
#include "de_system.h"
#include "de_refresh.h"
#include "de_graphics.h"
#include "de_render.h"
#include "de_misc.h"
// MACROS ------------------------------------------------------------------
BEGIN_PROF_TIMERS()
PROF_UPLOAD_START,
PROF_UPLOAD_STRETCH,
PROF_UPLOAD_NO_STRETCHING,
PROF_UPLOAD_STRETCHING,
PROF_UPLOAD_NEWTEX,
PROF_UPLOAD_TEXIMAGE,
PROF_PNG_LOAD,
PROF_SCALE_1,
PROF_SCALE_2,
PROF_SCALE_MAG,
PROF_SCALE_MIN,
PROF_SCALE_NO_CHANGE
END_PROF_TIMERS()
#define TEXQ_BEST 8
#define NUM_FLARES 3
#define RGB18(r, g, b) ((r)+((g)<<6)+((b)<<12))
// TYPES -------------------------------------------------------------------
// A translated sprite.
typedef struct {
int patch;
DGLuint tex;
unsigned char *table;
} transspr_t;
// Sky texture topline colors.
typedef struct {
int texidx;
unsigned char rgb[3];
} skycol_t;
// Model skin.
typedef struct {
char path[256];
DGLuint tex;
} skintex_t;
// Detail texture instance.
typedef struct dtexinst_s {
struct dtexinst_s *next;
int lump;
float contrast;
DGLuint tex;
} dtexinst_t;
// EXTERNAL FUNCTION PROTOTYPES --------------------------------------------
// PUBLIC FUNCTION PROTOTYPES ----------------------------------------------
void averageColorIdx(rgbcol_t *sprcol, byte *data, int w, int h, byte *palette, boolean has_alpha);
void averageColorRGB(rgbcol_t *col, byte *data, int w, int h);
byte* GL_LoadHighResFlat(image_t *img, char *name);
void GL_DeleteDetailTexture(detailtex_t *dtex);
// PRIVATE FUNCTION PROTOTYPES ---------------------------------------------
// EXTERNAL DATA DECLARATIONS ----------------------------------------------
extern int maxTexSize; // Maximum supported texture size.
extern int ratioLimit;
extern boolean palettedTextureExtAvailable;
extern boolean s3tcAvailable;
// PUBLIC DATA DEFINITIONS -------------------------------------------------
boolean filloutlines = true;
boolean loadExtAlways = false; // Always check for extres (cvar)
boolean paletted = false; // Use GL_EXT_paletted_texture (cvar)
boolean load8bit = false; // Load textures as 8 bit? (with paltex)
// Convert a 18-bit RGB (666) value to a playpal index.
// FIXME: 256kb - Too big?
byte pal18to8[262144];
int mipmapping = 3, linearRaw = 1, texQuality = TEXQ_BEST;
int filterSprites = true;
int pallump;
// Properties of the current texture.
float texw = 1, texh = 1;
int texmask = 0;
DGLuint curtex = 0;
detailinfo_t *texdetail;
skycol_t *skytop_colors = NULL;
int num_skytop_colors = 0;
DGLuint dltexname; // Name of the dynamic light texture.
DGLuint glowtexname;
// PRIVATE DATA DEFINITIONS ------------------------------------------------
static boolean texInited = false; // Init done.
static boolean allowMaskedTexEnlarge = false;
static boolean noHighResTex = false;
static boolean noHighResPatches = false;
static boolean highResWithPWAD = false;
// Raw screen lumps (just lump numbers).
static int *rawlumps, numrawlumps;
// Skinnames will only *grow*. It will never be destroyed, not even
// at resets. The skin textures themselves will be deleted, though.
// This is because we want to have permanent ID numbers for skins,
// and the ID numbers are the same as indices to the skinnames array.
// Created in r_model.c, when registering the skins.
static int numskinnames;
static skintex_t *skinnames;
// Linked list of detail texture instances. A unique texture is generated
// for each (rounded) contrast level.
static dtexinst_t *dtinstances;
// The translated sprites.
static transspr_t *transsprites;
static int numtranssprites;
static DGLuint flaretexnames[NUM_FLARES];
//static boolean gammaSupport = false;
static int glmode[6] = // Indexed by 'mipmapping'.
{
DGL_NEAREST,
DGL_LINEAR,
DGL_NEAREST_MIPMAP_NEAREST,
DGL_LINEAR_MIPMAP_NEAREST,
DGL_NEAREST_MIPMAP_LINEAR,
DGL_LINEAR_MIPMAP_LINEAR
};
// CODE --------------------------------------------------------------------
//===========================================================================
// CeilPow2
// Finds the power of 2 that is equal to or greater than
// the specified number.
//===========================================================================
int CeilPow2(int num)
{
int cumul;
for(cumul = 1; num > cumul; cumul <<= 1);
return cumul;
}
//===========================================================================
// FloorPow2
// Finds the power of 2 that is less than or equal to
// the specified number.
//===========================================================================
int FloorPow2(int num)
{
int fl = CeilPow2(num);
if(fl > num) fl >>= 1;
return fl;
}
//===========================================================================
// RoundPow2
// Finds the power of 2 that is nearest the specified number.
// In ambiguous cases, the smaller number is returned.
//===========================================================================
int RoundPow2(int num)
{
int cp2 = CeilPow2(num), fp2 = FloorPow2(num);
return (cp2-num >= num-fp2)? fp2 : cp2;
}
//===========================================================================
// WeightPow2
// Weighted rounding. Weight determines the point where the number
// is still rounded down (0..1).
//===========================================================================
int WeightPow2(int num, float weight)
{
int fp2 = FloorPow2(num);
float frac = (num - fp2) / (float) fp2;
if(frac <= weight) return fp2; else return (fp2<<1);
}
//===========================================================================
// pixBlt
// Copies a rectangular region of the source buffer to the destination
// buffer. Doesn't perform clipping, so be careful.
// Yeah, 13 parameters...
//===========================================================================
void pixBlt(byte *src, int srcWidth, int srcHeight, byte *dest,
int destWidth, int destHeight,
int alpha, int srcRegX, int srcRegY, int destRegX, int destRegY,
int regWidth, int regHeight)
{
int y; // Y in the copy region.
int srcNumPels = srcWidth*srcHeight;
int destNumPels = destWidth*destHeight;
for(y = 0; y < regHeight; y++) // Copy line by line.
{
// The color index data.
memcpy(dest + destRegX + (y+destRegY)*destWidth,
src + srcRegX + (y+srcRegY)*srcWidth,
regWidth);
if(alpha)
{
// Alpha channel data.
memcpy(dest + destNumPels + destRegX + (y+destRegY)*destWidth,
src + srcNumPels + srcRegX + (y+srcRegY)*srcWidth,
regWidth);
}
}
}
//===========================================================================
// LookupPal18to8
// Prepare the pal18to8 table.
// A time-consuming operation (64 * 64 * 64 * 256!).
//===========================================================================
static void LookupPal18to8(byte *palette)
{
int r, g, b, i;
byte palRGB[3];
unsigned int diff, smallestDiff, closestIndex;
for(r = 0; r < 64; r++)
for(g = 0; g < 64; g++)
for(b = 0; b < 64; b++)
{
// We must find the color index that most closely
// resembles this RGB combination.
smallestDiff = -1;
for(i = 0; i < 256; i++)
{
memcpy(palRGB, palette + 3*i, 3);
diff = (palRGB[0]-(r<<2))*(palRGB[0]-(r<<2))
+ (palRGB[1]-(g<<2))*(palRGB[1]-(g<<2))
+ (palRGB[2]-(b<<2))*(palRGB[2]-(b<<2));
if(diff < smallestDiff)
{
smallestDiff = diff;
closestIndex = i;
}
}
pal18to8[RGB18(r, g, b)] = closestIndex;
}
if(ArgCheck("-dump_pal18to8"))
{
FILE *file = fopen("Pal18to8.lmp", "wb");
fwrite(pal18to8, sizeof(pal18to8), 1, file);
fclose(file);
}
}
//===========================================================================
// LoadPalette
//===========================================================================
static void LoadPalette()
{
byte *playpal = W_CacheLumpNum(
pallump = W_GetNumForName("PLAYPAL"), PU_CACHE);
byte paldata[256 * 3];
int i, c, gammalevel = /*gammaSupport? 0 : */usegamma;
// Prepare the color table.
for(i = 0; i < 256; i++)
{
// Adjust the values for the appropriate gamma level.
for(c = 0; c < 3; c++)
paldata[i*3 + c] = gammatable[gammalevel][playpal[i*3 + c]];
}
gl.Palette(DGL_RGB, paldata);
}
//===========================================================================
// GL_InitPalettedTexture
// Initializes the paletted texture extension.
// Returns true iff successful.
//===========================================================================
int GL_InitPalettedTexture()
{
// Should the extension be used?
if(!paletted && !ArgCheck("-paltex"))
return true;
gl.Enable(DGL_PALETTED_TEXTURES);
// Check if the operation was a success.
if(gl.GetInteger(DGL_PALETTED_TEXTURES) == DGL_FALSE)
{
Con_Message("\nPaletted textures init failed!\n");
return false;
}
// Textures must be uploaded as 8-bit, now.
load8bit = true;
return true;
}
//===========================================================================
// GL_InitTextureManager
// This should be cleaned up once and for all.
//===========================================================================
void GL_InitTextureManager(void)
{
int i;
if(novideo) return;
// The -bigmtex option allows the engine to enlarge masked textures
// that have taller patches than they are themselves.
allowMaskedTexEnlarge = ArgExists("-bigmtex");
// Disable the use of 'high resolution' textures?
noHighResTex = ArgExists("-nohightex");
noHighResPatches = ArgExists("-nohighpat");
// Should we allow using external resources with PWAD textures?
highResWithPWAD = ArgExists("-pwadtex");
transsprites = 0;
numtranssprites = 0;
// Raw screen lump book-keeping.
rawlumps = 0;
numrawlumps = 0;
// The palette lump, for color information (really??!!?!?!).
pallump = W_GetNumForName("PLAYPAL");
// Do we need to generate a pal18to8 table?
if(ArgCheck("-dump_pal18to8"))
LookupPal18to8(W_CacheLumpName("PLAYPAL", PU_CACHE));
GL_InitPalettedTexture();
// DGL needs the palette information regardless of whether the
// paletted textures are enabled or not.
LoadPalette();
// Load the pal18to8 table from the lump PAL18TO8. We need it
// when resizing textures.
if((i = W_CheckNumForName("PAL18TO8")) == -1)
LookupPal18to8(W_CacheLumpNum(pallump, PU_CACHE));
else
memcpy(pal18to8, W_CacheLumpNum(i, PU_CACHE), sizeof(pal18to8));
memset(flaretexnames, 0, sizeof(flaretexnames));
// Detail textures.
dtinstances = NULL;
// System textures loaded in GL_LoadSystemTextures.
dltexname = glowtexname = 0;
// Initialization done.
texInited = true;
}
//===========================================================================
// GL_ShutdownTextureManager
// Call this if a full cleanup of the textures is required (engine update).
//===========================================================================
void GL_ShutdownTextureManager()
{
if(!texInited) return;
PRINT_PROF( PROF_UPLOAD_START );
PRINT_PROF( PROF_UPLOAD_STRETCH );
PRINT_PROF( PROF_UPLOAD_NO_STRETCHING );
PRINT_PROF( PROF_UPLOAD_STRETCHING );
PRINT_PROF( PROF_UPLOAD_NEWTEX );
PRINT_PROF( PROF_UPLOAD_TEXIMAGE );
PRINT_PROF( PROF_PNG_LOAD );
PRINT_PROF( PROF_SCALE_1 );
PRINT_PROF( PROF_SCALE_2 );
PRINT_PROF( PROF_SCALE_MAG );
PRINT_PROF( PROF_SCALE_MIN );
PRINT_PROF( PROF_SCALE_NO_CHANGE );
GL_ClearTextureMemory();
// Destroy all bookkeeping -- into the shredder, I say!!
free(skytop_colors);
skytop_colors = 0;
num_skytop_colors = 0;
texInited = false;
}
//===========================================================================
// GL_DestroySkinNames
// This is called at final shutdown.
//===========================================================================
void GL_DestroySkinNames(void)
{
free(skinnames);
skinnames = 0;
numskinnames = 0;
}
//===========================================================================
// GL_LoadLightMap
// Lightmaps should be monochrome images.
//===========================================================================
void GL_LoadLightMap(ded_lightmap_t *map)
{
image_t image;
char resource[256];
if(map->tex) return; // Already loaded.
// Default texture name.
map->tex = dltexname;
if(!strcmp(map->id, "-"))
{
// No lightmap, if we don't know where to find the map.
map->tex = 0;
}
else if(map->id[0]) // Not an empty string.
{
// Search an external resource.
if(R_FindResource(RC_LIGHTMAP, map->id, "-ck", resource)
&& GL_LoadImage(&image, resource, false))
{
if(!image.isMasked)
{
// An alpha channel is required. If one is not in the
// image data, we'll generate it.
GL_ConvertToAlpha(&image);
}
map->tex = gl.NewTexture();
// Upload the texture.
// No mipmapping or resizing is needed, upload directly.
gl.TexImage(image.pixelSize == 2? DGL_LUMINANCE_PLUS_A8
: image.pixelSize == 3? DGL_RGB : DGL_RGBA,
image.width, image.height, 0, image.pixels);
GL_DestroyImage(&image);
gl.TexParameter(DGL_MIN_FILTER, DGL_LINEAR);
gl.TexParameter(DGL_MAG_FILTER, DGL_LINEAR);
gl.TexParameter(DGL_WRAP_S, DGL_CLAMP);
gl.TexParameter(DGL_WRAP_T, DGL_CLAMP);
// Copy this to all defs with the same lightmap.
Def_LightMapLoaded(map->id, map->tex);
}
}
}
//===========================================================================
// GL_DeleteLightMap
//===========================================================================
void GL_DeleteLightMap(ded_lightmap_t *map)
{
if(map->tex != dltexname)
{
gl.DeleteTextures(1, &map->tex);
}
map->tex = 0;
}
//===========================================================================
// GL_LoadSystemTextures
// Prepares all the system textures (dlight, ptcgens).
//===========================================================================
void GL_LoadSystemTextures(void)
{
int i, k;
ded_decor_t *decor;
if(!texInited) return;
dltexname = GL_PrepareLightTexture();
glowtexname = GL_PrepareGlowTexture();
// Load lightmaps.
for(i = 0; i < defs.count.lights.num; i++)
{
GL_LoadLightMap(&defs.lights[i].up);
GL_LoadLightMap(&defs.lights[i].down);
GL_LoadLightMap(&defs.lights[i].sides);
}
for(i = 0, decor = defs.decorations; i < defs.count.decorations.num;
i++, decor++)
{
for(k = 0; k < DED_DECOR_NUM_LIGHTS; k++)
{
if(!R_IsValidLightDecoration(&decor->lights[k]))
break;
GL_LoadLightMap(&decor->lights[k].up);
GL_LoadLightMap(&decor->lights[k].down);
GL_LoadLightMap(&decor->lights[k].sides);
}
}
// Load particle textures.
PG_InitTextures();
}
//===========================================================================
// GL_ClearSystemTextures
// System textures are loaded at startup and remain in memory all the time.
// After clearing they must be manually reloaded.
//===========================================================================
void GL_ClearSystemTextures(void)
{
int i, k;
ded_decor_t *decor;
if(!texInited) return;
for(i = 0; i < defs.count.lights.num; i++)
{
GL_DeleteLightMap(&defs.lights[i].up);
GL_DeleteLightMap(&defs.lights[i].down);
GL_DeleteLightMap(&defs.lights[i].sides);
}
for(i = 0, decor = defs.decorations; i < defs.count.decorations.num;
i++, decor++)
{
for(k = 0; k < DED_DECOR_NUM_LIGHTS; k++)
{
if(!R_IsValidLightDecoration(&decor->lights[k]))
break;
GL_DeleteLightMap(&decor->lights[k].up);
GL_DeleteLightMap(&decor->lights[k].down);
GL_DeleteLightMap(&decor->lights[k].sides);
}
}
gl.DeleteTextures(1, &dltexname);
gl.DeleteTextures(1, &glowtexname);
dltexname = 0;
glowtexname = 0;
// Delete the particle textures.
PG_ShutdownTextures();
}
//===========================================================================
// GL_ClearRuntimeTextures
// Runtime textures are not loaded until precached or actually needed.
// They may be cleared, in which case they will be reloaded when needed.
//===========================================================================
void GL_ClearRuntimeTextures(void)
{
dtexinst_t *dtex;
int i;
if(!texInited) return;
// The rendering lists contain persistent references to texture names.
// Which, obviously, can't persist any longer...
RL_DeleteLists();
// Textures and sprite lumps.
for(i = 0; i < numtextures; i++) GL_DeleteTexture(i);
for(i = 0; i < numspritelumps; i++) GL_DeleteSprite(i);
// The translated sprite textures.
for(i = 0; i < numtranssprites; i++)
{
gl.DeleteTextures(1, &transsprites[i].tex);
transsprites[i].tex = 0;
}
free(transsprites);
transsprites = 0;
numtranssprites = 0;
// Delete skins.
for(i = 0; i < numskinnames; i++)
{
gl.DeleteTextures(1, &skinnames[i].tex);
skinnames[i].tex = 0;
}
// Delete detail textures.
i = 0;
while(dtinstances)
{
dtex = dtinstances->next;
gl.DeleteTextures(1, &dtinstances->tex);
M_Free(dtinstances);
dtinstances = dtex;
i++;
}
VERBOSE( Con_Message("GL_ClearRuntimeTextures: %i detail texture "
"instances.\n", i) );
for(i = 0; i < defs.count.details.num; i++)
details[i].gltex = 0;
// Flare textures.
gl.DeleteTextures(NUM_FLARES, flaretexnames);
memset(flaretexnames, 0, sizeof(flaretexnames));
GL_DeleteRawImages();
// Delete any remaining lump textures (e.g. flats).
for(i = 0; i < numlumptexinfo; i++)
{
gl.DeleteTextures(2, lumptexinfo[i].tex);
memset(lumptexinfo[i].tex, 0, sizeof(lumptexinfo[i].tex));
}
}
//===========================================================================
// GL_ClearTextureMemory
//===========================================================================
void GL_ClearTextureMemory(void)
{
if(!texInited) return;
// Delete runtime textures (textures, flats, ...)
GL_ClearRuntimeTextures();
// Delete system textures.
GL_ClearSystemTextures();
}
//===========================================================================
// GL_UpdateGamma
//===========================================================================
void GL_UpdateGamma(void)
{
/*if(gammaSupport)
{
// The driver knows how to update the gamma directly.
gl.Gamma(DGL_TRUE, gammatable[usegamma]);
}
else
{*/
LoadPalette();
GL_ClearRuntimeTextures();
//}
}
//===========================================================================
// GL_BindTexture
// Binds the texture if necessary.
//===========================================================================
void GL_BindTexture(DGLuint texname)
{
/*if(curtex != texname)
{*/
gl.Bind(texname);
curtex = texname;
//}
}
//===========================================================================
// PalIdxToRGB
//===========================================================================
void PalIdxToRGB(byte *pal, int idx, byte *rgb)
{
int c;
int gammalevel = /*gammaSupport? 0 : */usegamma;
for(c = 0; c < 3; c++) // Red, green and blue.
rgb[c] = gammatable[gammalevel][pal[idx*3 + c]];
}
//===========================================================================
// GL_ConvertBuffer
// in/outformat:
// 1 = palette indices
// 2 = palette indices followed by alpha values
// 3 = RGB
// 4 = RGBA
//===========================================================================
void GL_ConvertBuffer(int width, int height, int informat, int outformat,
byte *in, byte *out, boolean gamma)
{
byte *palette = W_CacheLumpName("playpal", PU_CACHE);
int inSize = informat==2? 1 : informat;
int outSize = outformat==2? 1 : outformat;
int i, numPixels = width * height, a;
if(informat == outformat)
{
// No conversion necessary.
memcpy(out, in, numPixels * informat);
return;
}
// Conversion from pal8(a) to RGB(A).
if(informat <= 2 && outformat >= 3)
{
for(i = 0; i < numPixels; i++, in += inSize, out += outSize)
{
// Copy the RGB values in every case.
if(gamma)
{
for(a = 0; a < 3; a++)
out[a] = gammatable[usegamma][*(palette + 3*(*in) + a)];
}
else
{
memcpy(out, palette + 3*(*in), 3);
}
// Will the alpha channel be necessary?
a = 0;
if(informat == 2) a = in[numPixels*inSize];
if(outformat == 4) out[3] = a;
}
}
// Conversion from RGB(A) to pal8(a), using pal18to8.
else if(informat >= 3 && outformat <= 2)
{
for(i = 0; i < numPixels; i++, in += inSize, out += outSize)
{
// Convert the color value.
*out = pal18to8[RGB18(in[0]>>2, in[1]>>2, in[2]>>2)];
// Alpha channel?
a = 0;
if(informat == 4) a = in[3];
if(outformat == 2) out[numPixels*outSize] = a;
}
}
else if(informat == 3 && outformat == 4)
{
for(i = 0; i < numPixels; i++, in += inSize, out += outSize)
{
memcpy(out, in, 3);
out[3] = 0;
}
}
}
//===========================================================================
// scaleLine
// Len is measured in out units. Comps is the number of components per
// pixel, or rather the number of bytes per pixel (3 or 4). The strides
// must be byte-aligned anyway, though; not in pixels.
// FIXME: Probably could be optimized.
//===========================================================================
static void scaleLine(byte *in, int inStride, byte *out, int outStride,
int outLen, int inLen, int comps)
{
int i, c;
float inToOutScale = outLen / (float) inLen;
if(inToOutScale > 1)
{
// Magnification is done using linear interpolation.
fixed_t inPosDelta = (FRACUNIT*(inLen-1))/(outLen-1), inPos = inPosDelta;
byte *col1, *col2;
int weight, invWeight;
BEGIN_PROF( PROF_SCALE_MAG );
// The first pixel.
memcpy(out, in, comps);
out += outStride;
// Step at each out pixel between the first and last ones.
for(i = 1; i < outLen - 1; i++, out += outStride, inPos += inPosDelta)
{
col1 = in + (inPos >> FRACBITS) * inStride;
col2 = col1 + inStride;
weight = inPos & 0xffff;
invWeight = 0x10000 - weight;
out[0] = (col1[0]*invWeight + col2[0]*weight) >> 16;
out[1] = (col1[1]*invWeight + col2[1]*weight) >> 16;
out[2] = (col1[2]*invWeight + col2[2]*weight) >> 16;
if(comps == 4)
out[3] = (col1[3]*invWeight + col2[3]*weight) >> 16;
}
// The last pixel.
memcpy(out, in + (inLen - 1)*inStride, comps);
END_PROF( PROF_SCALE_MAG );
}
else if(inToOutScale < 1)
{
// Minification needs to calculate the average of each of
// the pixels contained by the out pixel.
unsigned int cumul[4] = {0, 0, 0, 0}, count = 0;
int outpos = 0;
BEGIN_PROF( PROF_SCALE_MIN );
for(i = 0; i < inLen; i++, in += inStride)
{
if((int) (i*inToOutScale) != outpos)
{
outpos = (int) i*inToOutScale;
for(c = 0; c < comps; c++)
{
out[c] = cumul[c] / count;
cumul[c] = 0;
}
count = 0;
out += outStride;
}
for(c = 0; c < comps; c++) cumul[c] += in[c];
count++;
}
// Fill in the last pixel, too.
if(count) for(c = 0; c < comps; c++) out[c] = cumul[c] / count;
END_PROF( PROF_SCALE_MIN );
}
else
{
BEGIN_PROF( PROF_SCALE_NO_CHANGE );
// No need for scaling.
if(comps == 3)
{
for(i = outLen; i > 0; i--, out += outStride, in += inStride)
{
out[0] = in[0];
out[1] = in[1];
out[2] = in[2];
}
}
else if(comps == 4)
{
for(i = outLen; i > 0; i--, out += outStride, in += inStride)
{
out[0] = in[0];
out[1] = in[1];
out[2] = in[2];
out[3] = in[3];
}
}
END_PROF( PROF_SCALE_NO_CHANGE );
}
}
//===========================================================================
// ScaleBuffer32
//===========================================================================
static void ScaleBuffer32(byte *in, int inWidth, int inHeight,
byte *out, int outWidth, int outHeight, int comps)
{
int i;
byte *temp;// = Z_Malloc(outWidth * inHeight * comps, PU_STATIC, 0);
BEGIN_PROF( PROF_SCALE_1 );
temp = Z_Malloc(outWidth * inHeight * comps, PU_STATIC, 0);
// First scale horizontally, to outWidth, into the temporary buffer.
for(i = 0; i < inHeight; i++)
{
scaleLine(in + inWidth*comps*i, comps, temp + outWidth*comps*i,
comps, outWidth, inWidth, comps);
}
END_PROF( PROF_SCALE_1 );
BEGIN_PROF( PROF_SCALE_2 );
// Then scale vertically, to outHeight, into the out buffer.
for(i = 0; i < outWidth; i++)
{
scaleLine(temp + comps*i, outWidth*comps, out + comps*i,
outWidth*comps, outHeight, inHeight, comps);
}
Z_Free(temp);
END_PROF( PROF_SCALE_2 );
}
//===========================================================================
// GL_DownMipmap32
// Works within the given data, reducing the size of the picture to half
// its original. Width and height must be powers of two.
//===========================================================================
void GL_DownMipmap32(byte *in, int width, int height, int comps)
{
byte *out;
int x, y, c, outW = width >> 1, outH = height >> 1;
if(width == 1 && height == 1)
{
#if _DEBUG
Con_Error("GL_DownMipmap32 can't be called for a 1x1 image.\n");
#endif
return;
}
if(!outW || !outH) // Limited, 1x2|2x1 -> 1x1 reduction?
{
int outDim = width > 1? outW : outH;
out = in;
for(x = 0; x < outDim; x++, in += comps*2)
for(c = 0; c < comps; c++, out++)
*out = (in[c] + in[comps+c]) >> 1;
}
else // Unconstrained, 2x2 -> 1x1 reduction?
{
out = in;
for(y = 0; y < outH; y++, in += width*comps)
for(x = 0; x < outW; x++, in += comps*2)
for(c = 0; c < comps; c++, out++)
*out = (in[c] + in[comps + c] + in[comps*width + c] + in[comps*(width+1) + c]) >> 2;
}
}
//===========================================================================
// GL_UploadTexture
// Can be rather time-consuming.
// Returns the name of the texture.
// The texture parameters will NOT be set here.
// 'data' contains indices to the playpal. If 'alphachannel' is true,
// 'data' also contains the alpha values (after the indices).
//===========================================================================
DGLuint GL_UploadTexture
(byte *data, int width, int height, boolean alphaChannel,
boolean generateMipmaps, boolean RGBData, boolean noStretch)
{
int i, levelWidth, levelHeight; // width and height at the current level
int comps;
byte *buffer, *rgbaOriginal, *idxBuffer;
DGLuint texName;
boolean freeOriginal;
boolean freeBuffer;
BEGIN_PROF( PROF_UPLOAD_START );
if(noStretch)
{
levelWidth = CeilPow2(width);
levelHeight = CeilPow2(height);
// MaxTexSize may prevent using noStretch.
if(levelWidth > maxTexSize)
{
levelWidth = maxTexSize;
noStretch = false;
}
if(levelHeight > maxTexSize)
{
levelHeight = maxTexSize;
noStretch = false;
}
}
else
{
// Determine the most favorable size for the texture.
if(texQuality == TEXQ_BEST) // The best quality.
{
// At the best texture quality level, all textures are
// sized *upwards*, so no details are lost. This takes
// more memory, but naturally looks better.
levelWidth = CeilPow2(width);
levelHeight = CeilPow2(height);
}
else if(texQuality == 0)
{
// At the lowest quality, all textures are sized down
// to the nearest power of 2.
levelWidth = FloorPow2(width);
levelHeight = FloorPow2(height);
}
else
{
// At the other quality levels, a weighted rounding
// is used.
levelWidth = WeightPow2(width, 1 - texQuality/(float)TEXQ_BEST);
levelHeight = WeightPow2(height, 1 - texQuality/(float)TEXQ_BEST);