/
gl_main.cpp
1538 lines (1290 loc) · 42.4 KB
/
gl_main.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_main.cpp GL-Graphics Subsystem
* @ingroup gl
*
* @authors Copyright © 2003-2017 Jaakko Keränen <jaakko.keranen@iki.fi>
* @authors Copyright © 2006-2014 Daniel Swanson <danij@dengine.net>
* @authors Copyright © 2006 Jamie Jones <jamie_jones_au@yahoo.com.au>
*
* @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>
*/
#ifdef UNIX
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif
#endif
#include "de_base.h"
#include "gl/gl_main.h"
#include <de/concurrency.h>
#include <de/App>
#include <de/Config>
#include <de/DisplayMode>
#include <de/GLInfo>
#include <de/GLState>
#include <de/LogBuffer>
#include <doomsday/console/cmd.h>
#include <doomsday/console/var.h>
#include <doomsday/defs/mapinfo.h>
#include <doomsday/filesys/fs_main.h>
#include <doomsday/resource/colorpalettes.h>
#include "clientapp.h"
#include "sys_system.h" // novideo
#include "world/map.h"
#include "world/p_object.h"
#include "world/p_players.h"
#include "gl/gl_tex.h"
#include "gl/gl_texmanager.h"
#include "gl/texturecontent.h"
#include "resource/hq2x.h"
#include "MaterialAnimator"
#include "MaterialVariantSpec"
#include "ClientTexture"
#include "api_render.h"
#include "render/rend_main.h"
#include "render/r_main.h"
#include "render/cameralensfx.h"
#include "render/rendersystem.h"
#include "render/rend_font.h"
#include "render/rend_model.h"
#include "render/rend_particle.h"
#include "render/vr.h"
#include "misc/r_util.h"
#include "ui/ui_main.h"
#include "ui/clientwindowsystem.h"
using namespace de;
extern dint maxnumnodes;
extern dd_bool fillOutlines;
dint numTexUnits = 1;
dd_bool envModAdd; ///< TexEnv: modulate and add is available.
dint test3dfx;
dint r_detail = true; ///< Draw detail textures (if available).
dfloat vid_gamma = 1.0f, vid_bright, vid_contrast = 1.0f;
dfloat glNearClip, glFarClip;
static dd_bool initGLOk;
static dd_bool initFullGLOk;
static dd_bool gamma_support;
static dfloat oldgamma, oldcontrast, oldbright;
static dint fogModeDefault;
//static viewport_t currentView;
static inline ClientResources &resSys()
{
return App_Resources();
}
dd_bool GL_IsInited()
{
return initGLOk;
}
dd_bool GL_IsFullyInited()
{
return initFullGLOk;
}
void GL_GetGammaRamp(DisplayColorTransfer *ramp)
{
if(!gamma_support) return;
DisplayMode_GetColorTransfer(ramp);
}
void GL_SetGammaRamp(DisplayColorTransfer const *ramp)
{
if(!gamma_support) return;
DisplayMode_SetColorTransfer(ramp);
}
/**
* Calculate a gamma ramp and write the result to the location pointed to.
*
* @todo Allow for finer control of the curves (separate red, green, blue).
*
* @param ramp Ptr to the ramp table to write to. Must point to a ushort[768] area of memory.
* @param gamma Non-linear factor (curvature; >1.0 multiplies).
* @param contrast Steepness.
* @param bright Brightness, uniform offset.
*/
void GL_MakeGammaRamp(ushort *ramp, dfloat gamma, dfloat contrast, dfloat bright)
{
DENG2_ASSERT(ramp);
ddouble ideal[256]; // After processing clamped to unsigned short.
// Don't allow stupid values.
if(contrast < 0.1f)
contrast = 0.1f;
if(bright > 0.8f) bright = 0.8f;
if(bright < -0.8f) bright = -0.8f;
// Init the ramp as a line with the steepness defined by contrast.
for(dint i = 0; i < 256; ++i)
{
ideal[i] = i * contrast - (contrast - 1) * 127;
}
// Apply the gamma curve.
if(gamma != 1)
{
if(gamma <= 0.1f) gamma = 0.1f;
ddouble norm = pow(255, 1 / ddouble( gamma ) - 1); // Normalizing factor.
for(dint i = 0; i < 256; ++i)
{
ideal[i] = pow(ideal[i], 1 / ddouble( gamma )) / norm;
}
}
// The last step is to add the brightness offset.
for(dint i = 0; i < 256; ++i)
{
ideal[i] += bright * 128;
}
// Clamp it and write the ramp table.
for(dint i = 0; i < 256; ++i)
{
ideal[i] *= 0x100; // Byte => word
if(ideal[i] < 0) ideal[i] = 0;
if(ideal[i] > 0xffff) ideal[i] = 0xffff;
ramp[i] = ramp[i + 256] = ramp[i + 512] = (dushort) ideal[i];
}
}
/**
* Updates the gamma ramp based on vid_gamma, vid_contrast and vid_bright.
*/
void GL_SetGamma()
{
DisplayColorTransfer myramp;
oldgamma = vid_gamma;
oldcontrast = vid_contrast;
oldbright = vid_bright;
GL_MakeGammaRamp(myramp.table, vid_gamma, vid_contrast, vid_bright);
GL_SetGammaRamp(&myramp);
}
void GL_FinishFrame()
{
if(ClientApp::vr().mode() == VRConfig::OculusRift) return;
// Check for color adjustment changes.
if(oldgamma != vid_gamma || oldcontrast != vid_contrast || oldbright != vid_bright)
{
GL_SetGamma();
}
DENG_ASSERT_IN_MAIN_THREAD();
DENG_ASSERT_GL_CONTEXT_ACTIVE();
// Wait until the right time to show the frame so that the realized
// frame rate is exactly right.
LIBGUI_GL.glFlush();
DD_WaitForOptimalUpdateTime();
// Blit screen to video.
//ClientWindow::main().swapBuffers();
}
static void printConfiguration()
{
LOG_GL_VERBOSE(_E(b) "Render configuration:");
//LOG_GL_VERBOSE(" Multisampling: %b") << GL_state.features.multisample;
/*if(GL_state.features.multisample)
{
LOG_GL_VERBOSE(" Multisampling format: %i") << GL_state.multisampleFormat;
}*/
LOG_GL_VERBOSE(" Multitexturing: %s") << (numTexUnits > 1? (envModAdd? "full" : "partial") : "not available");
LOG_GL_VERBOSE(" Texture Anisotropy: %s") << (GL_state.features.texFilterAniso? "variable" : "fixed");
LOG_GL_VERBOSE(" Texture Compression: %b") << GL_state.features.texCompression;
}
void GL_EarlyInit()
{
if(novideo) return;
if(initGLOk) return; // Already initialized.
LOG_GL_VERBOSE("Initializing Render subsystem...");
ClientApp::renderSystem().glInit();
gamma_support = !CommandLine_Check("-noramp");
// We are simple people; two texture units is enough.
numTexUnits = de::min(GLInfo::limits().maxTexUnits, MAX_TEX_UNITS);
envModAdd = (GLInfo::extensions().NV_texture_env_combine4 ||
GLInfo::extensions().ATI_texture_env_combine3);
GL_InitDeferredTask();
// Model renderer must be initialized early as it may need to configure
// gl-element arrays.
Rend_ModelInit();
// Check the maximum texture size.
if(GLInfo::limits().maxTexSize == 256)
{
LOG_GL_WARNING("Using restricted texture w/h ratio (1:8)");
ratioLimit = 8;
}
if(CommandLine_Check("-outlines"))
{
fillOutlines = false;
LOG_GL_NOTE("Textures have outlines");
}
renderTextures = !CommandLine_Exists("-notex");
printConfiguration();
// Initialize the renderer into a 2D state.
GL_Init2DState();
GL_SetVSync(App::config().getb("window.main.vsync"));
initGLOk = true;
}
void GL_Init()
{
if(novideo) return;
if(!initGLOk)
{
App_Error("GL_Init: GL_EarlyInit has not been done yet.\n");
}
// Set the gamma in accordance with vid-gamma, vid-bright and vid-contrast.
GL_SetGamma();
// Initialize one viewport.
R_SetupDefaultViewWindow(0);
R_SetViewGrid(1, 1);
}
void GL_InitRefresh()
{
if(novideo) return;
GL_InitTextureManager();
initFullGLOk = true;
}
void GL_ShutdownRefresh()
{
initFullGLOk = false;
}
void GL_Shutdown()
{
if(!initGLOk || !ClientWindow::mainExists())
return; // Not yet initialized fully.
DENG_ASSERT_IN_MAIN_THREAD();
DENG_ASSERT_GL_CONTEXT_ACTIVE();
// We won't be drawing anything further but we don't want to shutdown
// with the previous frame still visible as this can lead to unwanted
// artefacts during video context switches on some displays.
//
// Render a few black frames before we continue.
/*if(!novideo)
{
dint i = 0;
do
{
LIBGUI_GL.glClear(GL_COLOR_BUFFER_BIT);
GL_FinishFrame();
} while(++i < 3);
}*/
ClientApp::renderSystem().glDeinit();
GL_ShutdownDeferredTask();
FR_Shutdown();
Rend_ModelShutdown();
LensFx_Shutdown();
Rend_Reset();
GL_ShutdownRefresh();
// Shutdown OpenGL.
Sys_GLShutdown();
initGLOk = false;
}
void GL_Init2DState()
{
// The variables.
glNearClip = 5;
glFarClip = 16500;
DENG_ASSERT_IN_MAIN_THREAD();
DENG_ASSERT_GL_CONTEXT_ACTIVE();
// Here we configure the OpenGL state and set the projection matrix.
GLState::current()
.setCull(gl::None)
.setDepthTest(false)
.apply();
//glDisable(GL_TEXTURE_1D);
LIBGUI_GL.glDisable(GL_TEXTURE_2D);
LIBGUI_GL.glDisable(GL_TEXTURE_CUBE_MAP);
// The projection matrix.
LIBGUI_GL.glMatrixMode(GL_PROJECTION);
LIBGUI_GL.glLoadIdentity();
LIBGUI_GL.glOrtho(0, 320, 200, 0, -1, 1);
// Default state for the white fog is off.
fogParams.usingFog = false;
LIBGUI_GL.glDisable(GL_FOG);
LIBGUI_GL.glFogi(GL_FOG_MODE, (fogModeDefault == 0 ? GL_LINEAR :
fogModeDefault == 1 ? GL_EXP : GL_EXP2));
LIBGUI_GL.glFogf(GL_FOG_START, DEFAULT_FOG_START);
LIBGUI_GL.glFogf(GL_FOG_END, DEFAULT_FOG_END);
LIBGUI_GL.glFogf(GL_FOG_DENSITY, DEFAULT_FOG_DENSITY);
fogParams.fogColor[0] = DEFAULT_FOG_COLOR_RED;
fogParams.fogColor[1] = DEFAULT_FOG_COLOR_GREEN;
fogParams.fogColor[2] = DEFAULT_FOG_COLOR_BLUE;
fogParams.fogColor[3] = 1;
LIBGUI_GL.glFogfv(GL_FOG_COLOR, fogParams.fogColor);
}
Rangef GL_DepthClipRange()
{
return Rangef(glNearClip, glFarClip);
}
Matrix4f GL_GetProjectionMatrix()
{
dfloat const fov = Rend_FieldOfView();
//Vector2f const size(viewpw, viewph);
Vector2f const size = R_Console3DViewRect(displayPlayer).size();
yfov = vrCfg().verticalFieldOfView(fov, size);
return vrCfg().projectionMatrix(Rend_FieldOfView(), size, glNearClip, glFarClip) *
Matrix4f::scale(Vector3f(1, 1, -1));
}
void GL_ProjectionMatrix()
{
DENG_ASSERT_IN_MAIN_THREAD();
DENG_ASSERT_GL_CONTEXT_ACTIVE();
// Actually shift the player viewpoint
// We'd like to have a left-handed coordinate system.
LIBGUI_GL.glMatrixMode(GL_PROJECTION);
LIBGUI_GL.glLoadMatrixf(GL_GetProjectionMatrix().values());
}
void GL_SetupFogFromMapInfo(Record const *mapInfo)
{
if(mapInfo)
{
R_SetupFog(mapInfo->getf("fogStart"), mapInfo->getf("fogEnd"),
mapInfo->getf("fogDensity"),
Vector3f(mapInfo->get("fogColor")).data().baseAs<float>());
}
else
{
R_SetupFogDefaults();
}
if(mapInfo && !(mapInfo->geti("flags") & MIF_FOG))
{
GL_UseFog(false);
}
String fadeTable = (mapInfo? mapInfo->gets("fadeTable") : "");
if(!fadeTable.isEmpty())
{
LumpIndex const &lumps = App_FileSystem().nameIndex();
dint lumpNum = lumps.findLast(fadeTable + ".lmp");
if(lumpNum == lumps.findLast("COLORMAP.lmp"))
{
// We don't want fog in this case.
GL_UseFog(false);
}
// Probably fog ... don't use fullbright sprites.
else if(lumpNum == lumps.findLast("FOGMAP.lmp"))
{
GL_UseFog(true);
}
}
}
#undef GL_UseFog
DENG_EXTERN_C void GL_UseFog(dint yes)
{
fogParams.usingFog = yes;
}
void GL_SelectTexUnits(dint count)
{
DENG_ASSERT_IN_MAIN_THREAD();
DENG_ASSERT_GL_CONTEXT_ACTIVE();
for(dint i = numTexUnits - 1; i >= count; i--)
{
LIBGUI_GL.glActiveTexture(GL_TEXTURE0 + i);
LIBGUI_GL.glDisable(GL_TEXTURE_2D);
}
// Enable the selected units.
for(dint i = count - 1; i >= 0; i--)
{
if(i >= numTexUnits) continue;
LIBGUI_GL.glActiveTexture(GL_TEXTURE0 + i);
LIBGUI_GL.glEnable(GL_TEXTURE_2D);
}
}
void GL_TotalReset()
{
if(isDedicated) return;
// Update the secondary title and the game status.
//Rend_ConsoleUpdateTitle();
// Release all texture memory.
resSys().releaseAllGLTextures();
resSys().pruneUnusedTextureSpecs();
GL_LoadLightingSystemTextures();
GL_LoadFlareTextures();
Rend_ParticleLoadSystemTextures();
GL_ReleaseReservedNames();
#if _DEBUG
Z_CheckHeap();
#endif
}
void GL_TotalRestore()
{
if(isDedicated) return;
// Getting back up and running.
GL_ReserveNames();
GL_Init2DState();
// Choose fonts again.
UI_LoadFonts();
//Con_Resize();
// Restore the fog settings.
GL_SetupFogFromMapInfo(App_World().hasMap() ? &App_World().map().mapInfo() : nullptr);
#ifdef DENG2_DEBUG
Z_CheckHeap();
#endif
}
void GL_BlendMode(blendmode_t mode)
{
DENG_ASSERT_IN_MAIN_THREAD();
DENG_ASSERT_GL_CONTEXT_ACTIVE();
switch(mode)
{
case BM_ZEROALPHA:
GLState::current().setBlendOp(gl::Add)
.setBlendFunc(gl::One, gl::Zero)
.apply();
break;
case BM_ADD:
GLState::current().setBlendOp(gl::Add)
.setBlendFunc(gl::SrcAlpha, gl::One)
.apply();
break;
case BM_DARK:
GLState::current().setBlendOp(gl::Add)
.setBlendFunc(gl::DestColor, gl::OneMinusSrcAlpha)
.apply();
break;
case BM_SUBTRACT:
GLState::current().setBlendOp(gl::Subtract)
.setBlendFunc(gl::One, gl::SrcAlpha)
.apply();
break;
case BM_ALPHA_SUBTRACT:
GLState::current().setBlendOp(gl::Subtract)
.setBlendFunc(gl::SrcAlpha, gl::One)
.apply();
break;
case BM_REVERSE_SUBTRACT:
GLState::current().setBlendOp(gl::ReverseSubtract)
.setBlendFunc(gl::SrcAlpha, gl::One)
.apply();
break;
case BM_MUL:
GLState::current().setBlendOp(gl::Add)
.setBlendFunc(gl::Zero, gl::SrcColor)
.apply();
break;
case BM_INVERSE:
GLState::current().setBlendOp(gl::Add)
.setBlendFunc(gl::OneMinusDestColor, gl::OneMinusSrcColor)
.apply();
break;
case BM_INVERSE_MUL:
GLState::current().setBlendOp(gl::Add)
.setBlendFunc(gl::Zero, gl::OneMinusSrcColor)
.apply();
break;
default:
GLState::current().setBlendOp(gl::Add)
.setBlendFunc(gl::SrcAlpha, gl::OneMinusSrcAlpha)
.apply();
break;
}
}
GLenum GL_Filter(gl::Filter f)
{
switch(f)
{
case gl::Nearest: return GL_NEAREST;
case gl::Linear: return GL_LINEAR;
}
return GL_REPEAT;
}
GLenum GL_Wrap(gl::Wrapping w)
{
switch(w)
{
case gl::Repeat: return GL_REPEAT;
case gl::RepeatMirrored: return GL_MIRRORED_REPEAT;
case gl::ClampToEdge: return GL_CLAMP_TO_EDGE;
}
return GL_REPEAT;
}
dint GL_NumMipmapLevels(dint width, dint height)
{
dint numLevels = 0;
while(width > 1 || height > 1)
{
width /= 2;
height /= 2;
++numLevels;
}
return numLevels;
}
dd_bool GL_OptimalTextureSize(dint width, dint height, dd_bool noStretch, dd_bool isMipMapped,
dint *optWidth, dint *optHeight)
{
DENG2_ASSERT(optWidth && optHeight);
if (!isMipMapped)
{
*optWidth = width;
*optHeight = height;
}
else if (noStretch)
{
*optWidth = M_CeilPow2(width);
*optHeight = M_CeilPow2(height);
}
else
{
// Determine the most favorable size for the texture.
if(texQuality == TEXQ_BEST)
{
// At the best texture quality *opt, all textures are
// sized *upwards*, so no details are lost. This takes
// more memory, but naturally looks better.
*optWidth = M_CeilPow2(width);
*optHeight = M_CeilPow2(height);
}
else if(texQuality == 0)
{
// At the lowest quality, all textures are sized down to the
// nearest power of 2.
*optWidth = M_FloorPow2(width);
*optHeight = M_FloorPow2(height);
}
else
{
// At the other quality *opts, a weighted rounding is used.
*optWidth = M_WeightPow2(width, 1 - texQuality / dfloat( TEXQ_BEST ));
*optHeight = M_WeightPow2(height, 1 - texQuality / dfloat( TEXQ_BEST ));
}
}
// Hardware limitations may force us to modify the preferred size.
if(*optWidth > GLInfo::limits().maxTexSize)
{
*optWidth = GLInfo::limits().maxTexSize;
noStretch = false;
}
if(*optHeight > GLInfo::limits().maxTexSize)
{
*optHeight = GLInfo::limits().maxTexSize;
noStretch = false;
}
// Some GL drivers seem to have problems with VERY small textures.
if(*optWidth < MINTEXWIDTH)
*optWidth = MINTEXWIDTH;
if(*optHeight < MINTEXHEIGHT)
*optHeight = MINTEXHEIGHT;
if(ratioLimit)
{
if(*optWidth > *optHeight) // Wide texture.
{
if(*optHeight < *optWidth / ratioLimit)
*optHeight = *optWidth / ratioLimit;
}
else // Tall texture.
{
if(*optWidth < *optHeight / ratioLimit)
*optWidth = *optHeight / ratioLimit;
}
}
return noStretch;
}
dint GL_GetTexAnisoMul(dint level)
{
// Should anisotropic filtering be used?
if(!GL_state.features.texFilterAniso)
return 1;
if(level < 0)
{
// Go with the maximum!
return GLInfo::limits().maxTexFilterAniso;
}
// Convert from a DGL aniso-level to a multiplier.
dint mul;
switch(level)
{
default: mul = 1; break;
case 1: mul = 2; break;
case 2: mul = 4; break;
case 3: mul = 8; break;
case 4: mul = 16; break;
}
// Clamp.
return de::min(mul, GLInfo::limits().maxTexFilterAniso);
}
static void uploadContentUnmanaged(texturecontent_t const &content)
{
LOG_AS("uploadContentUnmanaged");
if(novideo) return;
gl::UploadMethod uploadMethod = GL_ChooseUploadMethod(&content);
if(uploadMethod == gl::Immediate)
{
LOGDEV_GL_XVERBOSE("Uploading texture (%i:%ix%i) while not busy! "
"Should have been precached in busy mode?",
content.name << content.width << content.height);
}
GL_UploadTextureContent(content, uploadMethod);
}
GLuint GL_NewTextureWithParams(dgltexformat_t format, dint width, dint height,
duint8 const *pixels, dint flags)
{
texturecontent_t c;
GL_InitTextureContent(&c);
c.name = GL_GetReservedTextureName();
c.format = format;
c.width = width;
c.height = height;
c.pixels = pixels;
c.flags = flags;
uploadContentUnmanaged(c);
return c.name;
}
GLuint GL_NewTextureWithParams(dgltexformat_t format, dint width, dint height,
uint8_t const *pixels, dint flags, dint grayMipmap, dint minFilter, dint magFilter,
dint anisoFilter, dint wrapS, dint wrapT)
{
texturecontent_t c;
GL_InitTextureContent(&c);
c.name = GL_GetReservedTextureName();
c.format = format;
c.width = width;
c.height = height;
c.pixels = pixels;
c.flags = flags;
c.grayMipmap = grayMipmap;
c.minFilter = minFilter;
c.magFilter = magFilter;
c.anisoFilter = anisoFilter;
c.wrap[0] = wrapS;
c.wrap[1] = wrapT;
uploadContentUnmanaged(c);
return c.name;
}
static inline MaterialVariantSpec const &uiMaterialSpec(gl::Wrapping wrapS, gl::Wrapping wrapT)
{
return resSys().materialSpec(UiContext, 0, 1, 0, 0, GL_Wrap(wrapS), GL_Wrap(wrapT),
0, 1, 0, false, false, false, false);
}
static inline MaterialVariantSpec const &pspriteMaterialSpec(dint tClass, dint tMap)
{
return resSys().materialSpec(PSpriteContext, 0, 1, tClass, tMap, GL_CLAMP_TO_EDGE, GL_CLAMP_TO_EDGE,
0, 1, 0, false, true, true, false);
}
void GL_SetMaterialUI2(world::Material *material, gl::Wrapping wrapS, gl::Wrapping wrapT)
{
if(!material) return; // @todo we need a "NULL material".
MaterialAnimator &matAnimator = static_cast<ClientMaterial *>(material)->getAnimator(uiMaterialSpec(wrapS, wrapT));
// Ensure we have up to date info about the material.
matAnimator.prepare();
GL_BindTexture(matAnimator.texUnit(MaterialAnimator::TU_LAYER0).texture);
}
void GL_SetMaterialUI(world::Material *mat)
{
GL_SetMaterialUI2(mat, gl::ClampToEdge, gl::ClampToEdge);
}
void GL_SetPSprite(world::Material *material, dint tClass, dint tMap)
{
if(!material) return;
MaterialAnimator &matAnimator = static_cast<ClientMaterial *>(material)->getAnimator(pspriteMaterialSpec(tClass, tMap));
// Ensure we have up to date info about the material.
matAnimator.prepare();
GL_BindTexture(matAnimator.texUnit(MaterialAnimator::TU_LAYER0).texture);
}
void GL_SetRawImage(lumpnum_t lumpNum, gl::Wrapping wrapS, gl::Wrapping wrapT)
{
if(rawtex_t *rawTex = ClientResources::get().declareRawTexture(lumpNum))
{
GL_BindTextureUnmanaged(GL_PrepareRawTexture(*rawTex), wrapS, wrapT,
(filterUI ? gl::Linear : gl::Nearest));
}
}
void GL_BindTexture(TextureVariant *vtexture)
{
if(ClientApp::busyRunner().inWorkerThread()) return;
// Ensure we have a prepared texture.
duint glTexName = vtexture? vtexture->prepare() : 0;
if(glTexName == 0)
{
GL_SetNoTexture();
return;
}
DENG_ASSERT_IN_MAIN_THREAD();
DENG_ASSERT_GL_CONTEXT_ACTIVE();
LIBGUI_GL.glBindTexture(GL_TEXTURE_2D, glTexName);
Sys_GLCheckError();
// Apply dynamic adjustments to the GL texture state according to our spec.
TextureVariantSpec const &spec = vtexture->spec();
if(spec.type == TST_GENERAL)
{
LIBGUI_GL.glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, spec.variant.wrapS);
LIBGUI_GL.glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, spec.variant.wrapT);
LIBGUI_GL.glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, spec.variant.glMagFilter());
if(GL_state.features.texFilterAniso)
{
LIBGUI_GL.glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT,
GL_GetTexAnisoMul(spec.variant.logicalAnisoLevel()));
}
}
}
void GL_BindTextureUnmanaged(GLuint glName, gl::Wrapping wrapS, gl::Wrapping wrapT,
gl::Filter filter)
{
if(ClientApp::busyRunner().inWorkerThread()) return;
if(glName == 0)
{
GL_SetNoTexture();
return;
}
DENG_ASSERT_IN_MAIN_THREAD();
DENG_ASSERT_GL_CONTEXT_ACTIVE();
LIBGUI_GL.glBindTexture(GL_TEXTURE_2D, glName);
Sys_GLCheckError();
LIBGUI_GL.glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_Wrap(wrapS));
LIBGUI_GL.glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_Wrap(wrapT));
LIBGUI_GL.glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_Filter(filter));
if(GL_state.features.texFilterAniso)
{
LIBGUI_GL.glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, GL_GetTexAnisoMul(texAniso));
}
}
void GL_Bind(GLTextureUnit const &glTU)
{
if(!glTU.hasTexture()) return;
if(!renderTextures)
{
GL_SetNoTexture();
return;
}
if(glTU.texture)
{
GL_BindTexture(glTU.texture);
}
else
{
GL_BindTextureUnmanaged(glTU.unmanaged.glName, glTU.unmanaged.wrapS,
glTU.unmanaged.wrapT, glTU.unmanaged.filter);
}
}
void GL_BindTo(GLTextureUnit const &glTU, dint unit)
{
if(!glTU.hasTexture()) return;
DENG_ASSERT_IN_MAIN_THREAD();
DENG_ASSERT_GL_CONTEXT_ACTIVE();
LIBGUI_GL.glActiveTexture(GL_TEXTURE0 + dbyte(unit));
GL_Bind(glTU);
}
void GL_SetNoTexture()
{
if(ClientApp::busyRunner().inWorkerThread()) return;
DENG_ASSERT_IN_MAIN_THREAD();
DENG_ASSERT_GL_CONTEXT_ACTIVE();
/// @todo Don't actually change the current binding. Instead we should disable
/// all currently enabled texture types.
LIBGUI_GL.glBindTexture(GL_TEXTURE_2D, 0);
}
dint GL_ChooseSmartFilter(dint width, dint height, dint /*flags*/)
{
if(width >= MINTEXWIDTH && height >= MINTEXHEIGHT)
return 2; // hq2x
return 1; // nearest neighbor.
}
duint8 *GL_SmartFilter(dint method, duint8 const *src, dint width, dint height,
dint flags, dint *outWidth, dint *outHeight)
{
dint newWidth, newHeight;
duint8 *out = nullptr;
switch(method)
{
default: // linear interpolation.
newWidth = width * 2;
newHeight = height * 2;
out = GL_ScaleBuffer(src, width, height, 4, newWidth, newHeight);
break;
case 1: // nearest neighbor.
newWidth = width * 2;
newHeight = height * 2;
out = GL_ScaleBufferNearest(src, width, height, 4, newWidth, newHeight);
break;
case 2: // hq2x
newWidth = width * 2;
newHeight = height * 2;
out = GL_SmartFilterHQ2x(src, width, height, flags);
break;
};
if(!out)
{
// Unchanged, return the source image.
if(outWidth) *outWidth = width;
if(outHeight) *outHeight = height;
return const_cast<duint8 *>(src);
}
if(outWidth) *outWidth = newWidth;
if(outHeight) *outHeight = newHeight;
return out;
}
duint8 *GL_ConvertBuffer(duint8 const *in, dint width, dint height, dint informat,
colorpaletteid_t paletteId, dint outformat)
{
DENG2_ASSERT(in);
if(informat == outformat)
{
// No conversion necessary.
return const_cast<duint8 *>(in);
}
if(width <= 0 || height <= 0)
{
App_Error("GL_ConvertBuffer: Attempt to convert zero-sized image.");
exit(1); // Unreachable.
}
res::ColorPalette *palette = (informat <= 2? &resSys().colorPalettes().colorPalette(paletteId) : nullptr);
auto *out = (duint8 *) M_Malloc(outformat * width * height);
// Conversion from pal8(a) to RGB(A).
if(informat <= 2 && outformat >= 3)
{