aboutsummaryrefslogtreecommitdiffstats
path: root/Samples/CommonSrc/Render/Render_GL_Device.cpp
blob: 64da492bca3d12de8c6809e873641df9610708bb (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
/************************************************************************************

Filename    :   Render_GL_Device.cpp
Content     :   RenderDevice implementation for OpenGL
Created     :   September 10, 2012
Authors     :   Andrew Reisse

Copyright   :   Copyright 2012 Oculus VR, LLC All Rights reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

************************************************************************************/

#include "../Render/Render_GL_Device.h"
#include "Kernel/OVR_Log.h"
#include "OVR_CAPI_GL.h"

namespace OVR { namespace Render { namespace GL {


#if !defined(OVR_OS_MAC)

// GL Hooks for PC.
#if defined(OVR_OS_WIN32)
    
PFNWGLCHOOSEPIXELFORMATARBPROC           wglChoosePixelFormatARB;
PFNWGLCREATECONTEXTATTRIBSARBPROC        wglCreateContextAttribsARB;
PFNWGLGETSWAPINTERVALEXTPROC             wglGetSwapIntervalEXT;
PFNWGLSWAPINTERVALEXTPROC                wglSwapIntervalEXT;
    
void* GetFunction(const char* functionName)
{
    return wglGetProcAddress(functionName);
}

#else

PFNGLXSWAPINTERVALEXTPROC                glXSwapIntervalEXT;

void (*GetFunction(const char *functionName))( void )
{
    return glXGetProcAddress((GLubyte*)functionName);
}

#endif

PFNGLGETSTRINGIPROC                      glGetStringi;
PFNGLGENFRAMEBUFFERSPROC                 glGenFramebuffers;
PFNGLDELETEFRAMEBUFFERSPROC              glDeleteFramebuffers;
PFNGLDELETESHADERPROC                    glDeleteShader;
PFNGLCHECKFRAMEBUFFERSTATUSPROC          glCheckFramebufferStatus;
PFNGLFRAMEBUFFERRENDERBUFFERPROC         glFramebufferRenderbuffer;
PFNGLFRAMEBUFFERTEXTURE2DPROC            glFramebufferTexture2D;
PFNGLBINDFRAMEBUFFERPROC                 glBindFramebuffer;
PFNGLACTIVETEXTUREPROC                   glActiveTexture;
PFNGLDISABLEVERTEXATTRIBARRAYPROC        glDisableVertexAttribArray;
PFNGLVERTEXATTRIBPOINTERPROC             glVertexAttribPointer;
PFNGLENABLEVERTEXATTRIBARRAYPROC         glEnableVertexAttribArray;
PFNGLBINDBUFFERPROC                      glBindBuffer;
PFNGLUNIFORMMATRIX3FVPROC                glUniformMatrix3fv;
PFNGLUNIFORMMATRIX4FVPROC                glUniformMatrix4fv;
PFNGLDELETEBUFFERSPROC                   glDeleteBuffers;
PFNGLBUFFERDATAPROC                      glBufferData;
PFNGLGENBUFFERSPROC                      glGenBuffers;
PFNGLMAPBUFFERPROC                       glMapBuffer;
PFNGLUNMAPBUFFERPROC                     glUnmapBuffer;
PFNGLGETSHADERINFOLOGPROC                glGetShaderInfoLog;
PFNGLGETSHADERIVPROC                     glGetShaderiv;
PFNGLCOMPILESHADERPROC                   glCompileShader;
PFNGLSHADERSOURCEPROC                    glShaderSource;
PFNGLCREATESHADERPROC                    glCreateShader;
PFNGLCREATEPROGRAMPROC                   glCreateProgram;
PFNGLATTACHSHADERPROC                    glAttachShader;
PFNGLDETACHSHADERPROC                    glDetachShader;
PFNGLDELETEPROGRAMPROC                   glDeleteProgram;
PFNGLUNIFORM1IPROC                       glUniform1i;
PFNGLGETUNIFORMLOCATIONPROC              glGetUniformLocation;
PFNGLGETACTIVEUNIFORMPROC                glGetActiveUniform;
PFNGLUSEPROGRAMPROC                      glUseProgram;
PFNGLGETPROGRAMINFOLOGPROC               glGetProgramInfoLog;
PFNGLGETPROGRAMIVPROC                    glGetProgramiv;
PFNGLLINKPROGRAMPROC                     glLinkProgram;
PFNGLBINDATTRIBLOCATIONPROC              glBindAttribLocation;
PFNGLUNIFORM4FVPROC                      glUniform4fv;
PFNGLUNIFORM3FVPROC                      glUniform3fv;
PFNGLUNIFORM2FVPROC                      glUniform2fv;
PFNGLUNIFORM1FVPROC                      glUniform1fv;
PFNGLCOMPRESSEDTEXIMAGE2DPROC            glCompressedTexImage2D;
PFNGLTEXIMAGE2DMULTISAMPLEPROC           glTexImage2DMultisample;
PFNGLRENDERBUFFERSTORAGEPROC             glRenderbufferStorage;
PFNGLBINDRENDERBUFFERPROC                glBindRenderbuffer;
PFNGLGENRENDERBUFFERSPROC                glGenRenderbuffers;
PFNGLDELETERENDERBUFFERSPROC             glDeleteRenderbuffers;
PFNGLGENVERTEXARRAYSPROC                 glGenVertexArrays;
PFNGLDELETEVERTEXARRAYSPROC              glDeleteVertexArrays;
PFNGLBINDVERTEXARRAYPROC                 glBindVertexArray;
PFNGLBLITFRAMEBUFFEREXTPROC              glBlitFramebuffer;

void InitGLExtensions()
{
    if (glGenFramebuffers)
        return;

#if defined(OVR_OS_WIN32)
    wglGetSwapIntervalEXT =             (PFNWGLGETSWAPINTERVALEXTPROC)             GetFunction("wglGetSwapIntervalEXT");
    wglSwapIntervalEXT =                (PFNWGLSWAPINTERVALEXTPROC)                GetFunction("wglSwapIntervalEXT");
#else
    glXSwapIntervalEXT =                (PFNGLXSWAPINTERVALEXTPROC)                GetFunction("glXSwapIntervalEXT");
#endif

    glGetStringi =                      (PFNGLGETSTRINGIPROC)                      GetFunction("glGetStringi");
    glGenFramebuffers =                 (PFNGLGENFRAMEBUFFERSPROC)                 GetFunction("glGenFramebuffersEXT");
    glDeleteFramebuffers =              (PFNGLDELETEFRAMEBUFFERSPROC)              GetFunction("glDeleteFramebuffersEXT");
    glDeleteShader =                    (PFNGLDELETESHADERPROC)                    GetFunction("glDeleteShader");
    glCheckFramebufferStatus =          (PFNGLCHECKFRAMEBUFFERSTATUSPROC)          GetFunction("glCheckFramebufferStatusEXT");
    glFramebufferRenderbuffer =         (PFNGLFRAMEBUFFERRENDERBUFFERPROC)         GetFunction("glFramebufferRenderbufferEXT");
    glFramebufferTexture2D =            (PFNGLFRAMEBUFFERTEXTURE2DPROC)            GetFunction("glFramebufferTexture2DEXT");
    glBindFramebuffer =                 (PFNGLBINDFRAMEBUFFERPROC)                 GetFunction("glBindFramebufferEXT");
    glActiveTexture =                   (PFNGLACTIVETEXTUREPROC)                   GetFunction("glActiveTexture");
    glDisableVertexAttribArray =        (PFNGLDISABLEVERTEXATTRIBARRAYPROC)        GetFunction("glDisableVertexAttribArray");
    glVertexAttribPointer =             (PFNGLVERTEXATTRIBPOINTERPROC)             GetFunction("glVertexAttribPointer");
    glEnableVertexAttribArray =         (PFNGLENABLEVERTEXATTRIBARRAYPROC)         GetFunction("glEnableVertexAttribArray");
    glBindBuffer =                      (PFNGLBINDBUFFERPROC)                      GetFunction("glBindBuffer");
    glUniformMatrix3fv =                (PFNGLUNIFORMMATRIX3FVPROC)                GetFunction("glUniformMatrix3fv");
    glUniformMatrix4fv =                (PFNGLUNIFORMMATRIX4FVPROC)                GetFunction("glUniformMatrix4fv");
    glDeleteBuffers =                   (PFNGLDELETEBUFFERSPROC)                   GetFunction("glDeleteBuffers");
    glBufferData =                      (PFNGLBUFFERDATAPROC)                      GetFunction("glBufferData");
    glGenBuffers =                      (PFNGLGENBUFFERSPROC)                      GetFunction("glGenBuffers");
    glMapBuffer =                       (PFNGLMAPBUFFERPROC)                       GetFunction("glMapBuffer");
    glUnmapBuffer =                     (PFNGLUNMAPBUFFERPROC)                     GetFunction("glUnmapBuffer");
    glGetShaderInfoLog =                (PFNGLGETSHADERINFOLOGPROC)                GetFunction("glGetShaderInfoLog");
    glGetShaderiv =                     (PFNGLGETSHADERIVPROC)                     GetFunction("glGetShaderiv");
    glCompileShader =                   (PFNGLCOMPILESHADERPROC)                   GetFunction("glCompileShader");
    glShaderSource =                    (PFNGLSHADERSOURCEPROC)                    GetFunction("glShaderSource");
    glCreateShader =                    (PFNGLCREATESHADERPROC)                    GetFunction("glCreateShader");
    glCreateProgram =                   (PFNGLCREATEPROGRAMPROC)                   GetFunction("glCreateProgram");
    glAttachShader =                    (PFNGLATTACHSHADERPROC)                    GetFunction("glAttachShader");
    glDetachShader =                    (PFNGLDETACHSHADERPROC)                    GetFunction("glDetachShader");
    glDeleteProgram =                   (PFNGLDELETEPROGRAMPROC)                   GetFunction("glDeleteProgram");
    glUniform1i =                       (PFNGLUNIFORM1IPROC)                       GetFunction("glUniform1i");
    glGetUniformLocation =              (PFNGLGETUNIFORMLOCATIONPROC)              GetFunction("glGetUniformLocation");
    glGetActiveUniform =                (PFNGLGETACTIVEUNIFORMPROC)                GetFunction("glGetActiveUniform");
    glUseProgram =                      (PFNGLUSEPROGRAMPROC)                      GetFunction("glUseProgram");
    glGetProgramInfoLog =               (PFNGLGETPROGRAMINFOLOGPROC)               GetFunction("glGetProgramInfoLog");
    glGetProgramiv =                    (PFNGLGETPROGRAMIVPROC)                    GetFunction("glGetProgramiv");
    glLinkProgram =                     (PFNGLLINKPROGRAMPROC)                     GetFunction("glLinkProgram");
    glBindAttribLocation =              (PFNGLBINDATTRIBLOCATIONPROC)              GetFunction("glBindAttribLocation");
    glUniform4fv =                      (PFNGLUNIFORM4FVPROC)                      GetFunction("glUniform4fv");
    glUniform3fv =                      (PFNGLUNIFORM3FVPROC)                      GetFunction("glUniform3fv");
    glUniform2fv =                      (PFNGLUNIFORM2FVPROC)                      GetFunction("glUniform2fv");
    glUniform1fv =                      (PFNGLUNIFORM1FVPROC)                      GetFunction("glUniform1fv");
    glCompressedTexImage2D =            (PFNGLCOMPRESSEDTEXIMAGE2DPROC)            GetFunction("glCompressedTexImage2D");
    glTexImage2DMultisample =           (PFNGLTEXIMAGE2DMULTISAMPLEPROC)           GetFunction("glTexImage2DMultisample");
    glRenderbufferStorage =             (PFNGLRENDERBUFFERSTORAGEPROC)             GetFunction("glRenderbufferStorageEXT");
    glBindRenderbuffer =                (PFNGLBINDRENDERBUFFERPROC)                GetFunction("glBindRenderbufferEXT");
    glGenRenderbuffers =                (PFNGLGENRENDERBUFFERSPROC)                GetFunction("glGenRenderbuffersEXT");
    glDeleteRenderbuffers =             (PFNGLDELETERENDERBUFFERSPROC)             GetFunction("glDeleteRenderbuffersEXT");
    glGenVertexArrays =                 (PFNGLGENVERTEXARRAYSPROC)                 GetFunction("glGenVertexArrays");
    glDeleteVertexArrays =              (PFNGLDELETEVERTEXARRAYSPROC)              GetFunction("glDeleteVertexArrays");
    glBindVertexArray =                 (PFNGLBINDVERTEXARRAYPROC)                 GetFunction("glBindVertexArray");
    glBlitFramebuffer =                 (PFNGLBLITFRAMEBUFFEREXTPROC)              GetFunction("glBlitFramebufferEXT");
}

#endif

static const char* StdVertexShaderSrc =
"#version 110\n"

    "uniform mat4 Proj;\n"
    "uniform mat4 View;\n"
    
    "attribute vec4 Position;\n"
    "attribute vec4 Color;\n"
    "attribute vec2 TexCoord;\n"
    "attribute vec2 TexCoord1;\n"
    "attribute vec3 Normal;\n"
    
    "varying vec4 oColor;\n"
    "varying vec2 oTexCoord;\n"
    "varying vec2 oTexCoord1;\n"
    "varying vec3 oNormal;\n"
    "varying vec3 oVPos;\n"
    
    "void main()\n"
    "{\n"
    "   gl_Position = Proj * (View * Position);\n"
    "   oNormal = vec3(View * vec4(Normal,0));\n"
    "   oVPos = vec3(View * Position);\n"
    "   oTexCoord = TexCoord;\n"
    "   oTexCoord1 = TexCoord1;\n"
    "   oColor = Color;\n"
    "}\n";

static const char* DirectVertexShaderSrc =
    "#version 110\n"
    
    "uniform mat4 View;\n"
    
    "attribute vec4 Position;\n"
    "attribute vec4 Color;\n"
    "attribute vec2 TexCoord;\n"
    "attribute vec3 Normal;\n"
    
    "varying vec4 oColor;\n"
    "varying vec2 oTexCoord;\n"
    "varying vec3 oNormal;\n"
    
    "void main()\n"
    "{\n"
    "   gl_Position = View * Position;\n"
    "   oTexCoord = TexCoord;\n"
    "   oColor = Color;\n"
    "   oNormal = vec3(View * vec4(Normal,0));\n"
    "}\n";

static const char* SolidFragShaderSrc =
    "#version 110\n"
    
    "uniform vec4 Color;\n"
    
    "void main()\n"
    "{\n"
    "   gl_FragColor = Color;\n"
    "}\n";

static const char* GouraudFragShaderSrc =
    "#version 110\n"
    
    "varying vec4 oColor;\n"
    
    "void main()\n"
    "{\n"
    "   gl_FragColor = oColor;\n"
    "}\n";

static const char* TextureFragShaderSrc =
    "#version 110\n"
    
    "uniform sampler2D Texture0;\n"
    
    "varying vec4 oColor;\n"
    "varying vec2 oTexCoord;\n"
    
    "void main()\n"
    "{\n"
    "   gl_FragColor = oColor * texture2D(Texture0, oTexCoord);\n"
    "   if (gl_FragColor.a < 0.4)\n"
    "       discard;\n"
    "}\n";

#define LIGHTING_COMMON                                                          \
    "#version 110\n"                                                    \
    "uniform   vec3 Ambient;\n"                                                   \
    "uniform   vec4 LightPos[8];\n"                                                \
    "uniform   vec4 LightColor[8];\n"                                               \
    "uniform   float LightCount;\n"                                                  \
    "varying   vec4 oColor;\n"                                                  \
    "varying   vec2 oTexCoord;\n"                                               \
    "varying   vec3 oNormal;\n"                                                 \
    "varying   vec3 oVPos;\n"                                                   \
    "vec4 DoLight()\n"                                                                    \
    "{\n"                                                                                  \
    "   vec3 norm = normalize(oNormal);\n"                                                  \
    "   vec3 light = Ambient;\n"                                                             \
    "   for (int i = 0; i < int(LightCount); i++)\n"                                          \
    "   {\n"                                                                                   \
    "       vec3 ltp = (LightPos[i].xyz - oVPos);\n"                                            \
    "       float  ldist = length(ltp);\n"                                                       \
    "       ltp = normalize(ltp);\n"                                                              \
    "       light += clamp(LightColor[i].rgb * oColor.rgb * (dot(norm, ltp) / ldist), 0.0,1.0);\n" \
    "   }\n"                                                                                        \
    "   return vec4(light, oColor.a);\n"                                                             \
    "}\n"

static const char* LitSolidFragShaderSrc =
    LIGHTING_COMMON
    
    "void main()\n"
    "{\n"
    "   gl_FragColor = DoLight() * oColor;\n"
    "}\n";

static const char* LitTextureFragShaderSrc =
    LIGHTING_COMMON
    
    "uniform sampler2D Texture0;\n"
    
    "void main()\n"
    "{\n"
    "   gl_FragColor = DoLight() * texture2D(Texture0, oTexCoord);\n"
    "}\n";

static const char* AlphaTextureFragShaderSrc =
    "#version 110\n"
    
    "uniform sampler2D Texture0;\n"
    
    "varying vec4 oColor;\n"
    "varying vec2 oTexCoord;\n"
    
    "void main()\n"
    "{\n"
    "   gl_FragColor = oColor * vec4(1,1,1,texture2D(Texture0, oTexCoord).r);\n"
    "}\n";

static const char* AlphaBlendedTextureFragShaderSrc =
    "#version 110\n"

    "uniform sampler2D Texture0;\n"

    "varying vec4 oColor;\n"
    "varying vec2 oTexCoord;\n"
    
    "void main()\n"
    "{\n"
    "   vec4 finalColor = oColor;\n"
    "   finalColor *= texture2D(Texture0, oTexCoord);\n"
    // Blend state expects premultiplied alpha
    "   finalColor.rgb *= finalColor.a;\n"
    "   gl_FragColor = finalColor;\n"
    "}\n";

static const char* MultiTextureFragShaderSrc =
    "#version 110\n"
    
    "uniform sampler2D Texture0;\n"
    "uniform sampler2D Texture1;\n"
    
    "varying vec4 oColor;\n"
    "varying vec2 oTexCoord;\n"
    "varying vec2 oTexCoord1;\n"
    
    "void main()\n"
    "{\n"
    "    vec4 color = texture2D(Texture0, oTexCoord);\n"
    
    "    gl_FragColor = texture2D(Texture1, oTexCoord1);\n"
    "    gl_FragColor.rgb = gl_FragColor.rgb * mix(1.9, 1.2, clamp(length(gl_FragColor.rgb),0.0,1.0));\n"
    
    "    gl_FragColor = color * gl_FragColor;\n"
    
    "   if (gl_FragColor.a <= 0.6)\n"
    "        discard;\n"
    "}\n";

static const char* PostProcessMeshFragShaderSrc =
    "#version 110\n"
    
    "uniform sampler2D Texture;\n"
    
    "varying vec4 oColor;\n"
    "varying vec2 oTexCoord0;\n"
    "varying vec2 oTexCoord1;\n"
    "varying vec2 oTexCoord2;\n"
    
    "void main()\n"
    "{\n"
    "   gl_FragColor.r = oColor.r * texture2D(Texture, oTexCoord0).r;\n"
    "   gl_FragColor.g = oColor.g * texture2D(Texture, oTexCoord1).g;\n"
    "   gl_FragColor.b = oColor.b * texture2D(Texture, oTexCoord2).b;\n"
    "   gl_FragColor.a = 1.0;\n"
    "}\n";

static const char* PostProcessMeshTimewarpFragShaderSrc = PostProcessMeshFragShaderSrc;
static const char* PostProcessMeshPositionalTimewarpFragShaderSrc = PostProcessMeshFragShaderSrc;
static const char* PostProcessHeightmapTimewarpFragShaderSrc = PostProcessMeshFragShaderSrc;

static const char* PostProcessVertexShaderSrc =
    "#version 110\n"
    
    "uniform mat4 View;\n"
    "uniform mat4 Texm;\n"
    
    "attribute vec4 Position;\n"
    "attribute vec2 TexCoord;\n"
    
    "varying vec2 oTexCoord;\n"
    
    "void main()\n"
    "{\n"
    "   gl_Position = View * Position;\n"
    "   oTexCoord = vec2(Texm * vec4(TexCoord,0,1));\n"
    "}\n";

static const char* PostProcessMeshVertexShaderSrc =
    "#version 110\n"
    
    "uniform vec2 EyeToSourceUVScale;\n"
    "uniform vec2 EyeToSourceUVOffset;\n"

    "attribute vec2 Position;\n"
    "attribute vec4 Color;\n"
    "attribute vec2 TexCoord0;\n"
    "attribute vec2 TexCoord1;\n"
    "attribute vec2 TexCoord2;\n"

    "varying vec4 oColor;\n"
    "varying vec2 oTexCoord0;\n"
    "varying vec2 oTexCoord1;\n"
    "varying vec2 oTexCoord2;\n"

    "void main()\n"
    "{\n"
    "   gl_Position.x = Position.x;\n"
    "   gl_Position.y = Position.y;\n"
    "   gl_Position.z = 0.5;\n"
    "   gl_Position.w = 1.0;\n"
    // Vertex inputs are in TanEyeAngle space for the R,G,B channels (i.e. after chromatic aberration and distortion).
    // Scale them into the correct [0-1],[0-1] UV lookup space (depending on eye)
    "   oTexCoord0 = TexCoord0 * EyeToSourceUVScale + EyeToSourceUVOffset;\n"
    "   oTexCoord0.y = 1.0-oTexCoord0.y;\n"
    "   oTexCoord1 = TexCoord1 * EyeToSourceUVScale + EyeToSourceUVOffset;\n"
    "   oTexCoord1.y = 1.0-oTexCoord1.y;\n"
    "   oTexCoord2 = TexCoord2 * EyeToSourceUVScale + EyeToSourceUVOffset;\n"
    "   oTexCoord2.y = 1.0-oTexCoord2.y;\n"
    "   oColor = Color;\n"              // Used for vignette fade.
    "}\n";

static const char* PostProcessMeshTimewarpVertexShaderSrc =
    "#version 110\n"
    
    "uniform vec2 EyeToSourceUVScale;\n"
    "uniform vec2 EyeToSourceUVOffset;\n"
    "uniform mat4 EyeRotationStart;\n"
    "uniform mat4 EyeRotationEnd;\n"

    "attribute vec2 Position;\n"
    "attribute vec4 Color;\n"
    "attribute vec2 TexCoord0;\n"
    "attribute vec2 TexCoord1;\n"
    "attribute vec2 TexCoord2;\n"

    "varying vec4 oColor;\n"
    "varying vec2 oTexCoord0;\n"
    "varying vec2 oTexCoord1;\n"
    "varying vec2 oTexCoord2;\n"

    "void main()\n"
    "{\n"
    "   gl_Position.x = Position.x;\n"
    "   gl_Position.y = Position.y;\n"
    "   gl_Position.z = 0.0;\n"
    "   gl_Position.w = 1.0;\n"

    // Vertex inputs are in TanEyeAngle space for the R,G,B channels (i.e. after chromatic aberration and distortion).
    // These are now "real world" vectors in direction (x,y,1) relative to the eye of the HMD.
    "   vec3 TanEyeAngleR = vec3 ( TexCoord0.x, TexCoord0.y, 1.0 );\n"
    "   vec3 TanEyeAngleG = vec3 ( TexCoord1.x, TexCoord1.y, 1.0 );\n"
    "   vec3 TanEyeAngleB = vec3 ( TexCoord2.x, TexCoord2.y, 1.0 );\n"

    // Accurate time warp lerp vs. faster
#if 0
    // Apply the two 3x3 timewarp rotations to these vectors.
    "   vec3 TransformedRStart = (EyeRotationStart * vec4(TanEyeAngleR, 0)).xyz;\n"
    "   vec3 TransformedGStart = (EyeRotationStart * vec4(TanEyeAngleG, 0)).xyz;\n"
    "   vec3 TransformedBStart = (EyeRotationStart * vec4(TanEyeAngleB, 0)).xyz;\n"
    "   vec3 TransformedREnd   = (EyeRotationEnd * vec4(TanEyeAngleR, 0)).xyz;\n"
    "   vec3 TransformedGEnd   = (EyeRotationEnd * vec4(TanEyeAngleG, 0)).xyz;\n"
    "   vec3 TransformedBEnd   = (EyeRotationEnd * vec4(TanEyeAngleB, 0)).xyz;\n"
    // And blend between them.
    "   vec3 TransformedR = mix ( TransformedRStart, TransformedREnd, Color.a );\n"
    "   vec3 TransformedG = mix ( TransformedGStart, TransformedGEnd, Color.a );\n"
    "   vec3 TransformedB = mix ( TransformedBStart, TransformedBEnd, Color.a );\n"
#else
    "   mat3 EyeRotation;\n"
    "   EyeRotation[0] = mix ( EyeRotationStart[0], EyeRotationEnd[0], Color.a ).xyz;\n"
    "   EyeRotation[1] = mix ( EyeRotationStart[1], EyeRotationEnd[1], Color.a ).xyz;\n"
    "   EyeRotation[2] = mix ( EyeRotationStart[2], EyeRotationEnd[2], Color.a ).xyz;\n"
    "   vec3 TransformedR   = EyeRotation * TanEyeAngleR;\n"
    "   vec3 TransformedG   = EyeRotation * TanEyeAngleG;\n"
    "   vec3 TransformedB   = EyeRotation * TanEyeAngleB;\n"
#endif

    // Project them back onto the Z=1 plane of the rendered images.
    "   float RecipZR = 1.0 / TransformedR.z;\n"
    "   float RecipZG = 1.0 / TransformedG.z;\n"
    "   float RecipZB = 1.0 / TransformedB.z;\n"
    "   vec2 FlattenedR = vec2 ( TransformedR.x * RecipZR, TransformedR.y * RecipZR );\n"
    "   vec2 FlattenedG = vec2 ( TransformedG.x * RecipZG, TransformedG.y * RecipZG );\n"
    "   vec2 FlattenedB = vec2 ( TransformedB.x * RecipZB, TransformedB.y * RecipZB );\n"

    // These are now still in TanEyeAngle space.
    // Scale them into the correct [0-1],[0-1] UV lookup space (depending on eye)
    "   vec2 SrcCoordR = FlattenedR * EyeToSourceUVScale + EyeToSourceUVOffset;\n"
    "   vec2 SrcCoordG = FlattenedG * EyeToSourceUVScale + EyeToSourceUVOffset;\n"
    "   vec2 SrcCoordB = FlattenedB * EyeToSourceUVScale + EyeToSourceUVOffset;\n"
    "   oTexCoord0 = SrcCoordR;\n"
    "   oTexCoord0.y = 1.0-oTexCoord0.y;\n"
    "   oTexCoord1 = SrcCoordG;\n"
    "   oTexCoord1.y = 1.0-oTexCoord1.y;\n"
    "   oTexCoord2 = SrcCoordB;\n"
    "   oTexCoord2.y = 1.0-oTexCoord2.y;\n"
    "   oColor = vec4(Color.r, Color.r, Color.r, Color.r);\n"              // Used for vignette fade.
    "}\n";

static const char* PostProcessMeshPositionalTimewarpVertexShaderSrc =
#if 1 //TODO: Disabled until we fix positional timewarp and layering on GL.
PostProcessMeshTimewarpVertexShaderSrc;
#else
    "#version 150\n"

    "uniform sampler2D Texture0;\n"
    "uniform vec2 EyeToSourceUVScale;\n"
    "uniform vec2 EyeToSourceUVOffset;\n"
    "uniform vec2 DepthProjector;\n"
    "uniform vec2 DepthDimSize;\n"
    "uniform mat4 EyeRotationStart;\n"
    "uniform mat4 EyeRotationEnd;\n"

    "attribute vec2 Position;\n"
    "attribute vec4 Color;\n"
    "attribute vec2 TexCoord0;\n"
    "attribute vec2 TexCoord1;\n"
    "attribute vec2 TexCoord2;\n"

    "varying vec4 oColor;\n"
    "varying vec2 oTexCoord0;\n"
    "varying vec2 oTexCoord1;\n"
    "varying vec2 oTexCoord2;\n"

    "vec4 PositionFromDepth(vec2 inTexCoord)\n"
    "{\n"
    "   vec2 eyeToSourceTexCoord = inTexCoord * EyeToSourceUVScale + EyeToSourceUVOffset;\n"
    "   eyeToSourceTexCoord.y = 1.0 - eyeToSourceTexCoord.y;\n"
    "   float depth = texelFetch(Texture0, ivec2(eyeToSourceTexCoord * DepthDimSize), 0).x;\n" //FIXME: Use Texture2DLod for #version 110 support.
    "   float linearDepth = DepthProjector.y / (depth - DepthProjector.x);\n"
    "   vec4 retVal = vec4(inTexCoord, 1, 1);\n"
    "   retVal.xyz *= linearDepth;\n"
    "   return retVal;\n"
    "}\n"

    "vec2 TimewarpTexCoordToWarpedPos(vec2 inTexCoord, float a)\n"
    "{\n"
    // Vertex inputs are in TanEyeAngle space for the R,G,B channels (i.e. after chromatic aberration and distortion).
    // These are now "real world" vectors in direction (x,y,1) relative to the eye of the HMD.
    // Apply the 4x4 timewarp rotation to these vectors.
    "   vec4 inputPos = PositionFromDepth(inTexCoord);\n"
    "   vec3 transformed = mix ( EyeRotationStart * inputPos,  EyeRotationEnd * inputPos, a ).xyz;\n"
    // Project them back onto the Z=1 plane of the rendered images.
    "   vec2 flattened = transformed.xy / transformed.z;\n"
    // Scale them into ([0,0.5],[0,1]) or ([0.5,0],[0,1]) UV lookup space (depending on eye)
    "   vec2 noDepthUV = flattened * EyeToSourceUVScale + EyeToSourceUVOffset;\n"
    //"   float depth = texture2D(Texture0, noDepthUV).r;\n"
    "   return noDepthUV.xy;\n"
    "}\n"

    "void main()\n"
    "{\n"
    "   gl_Position.x = Position.x;\n"
    "   gl_Position.y = Position.y;\n"
    "   gl_Position.z = 0.0;\n"
    "   gl_Position.w = 1.0;\n"

    // warped positions are a bit more involved, hence a separate function
    "   oTexCoord0 = TimewarpTexCoordToWarpedPos(TexCoord0, Color.a);\n"
    "   oTexCoord0.y = 1.0 - oTexCoord0.y;\n"
    "   oTexCoord1 = TimewarpTexCoordToWarpedPos(TexCoord1, Color.a);\n"
    "   oTexCoord1.y = 1.0 - oTexCoord1.y;\n"
    "   oTexCoord2 = TimewarpTexCoordToWarpedPos(TexCoord2, Color.a);\n"
    "   oTexCoord2.y = 1.0 - oTexCoord2.y;\n"

    "   oColor = vec4(Color.r, Color.r, Color.r, Color.r);  // Used for vignette fade.\n"
    "}\n";
#endif


static const char* PostProcessHeightmapTimewarpVertexShaderSrc =
#if 1 //TODO: Disabled until we fix positional timewarp and layering on GL.
PostProcessMeshTimewarpVertexShaderSrc;
#else
    "#version 150\n"

    "uniform sampler2D Texture0;\n"
    "uniform vec2 EyeToSourceUVScale;\n"
    "uniform vec2 EyeToSourceUVOffset;\n"
    "uniform vec2 DepthDimSize;\n"
    "uniform mat4 EyeXformStart;\n"
    "uniform mat4 EyeXformEnd;\n"
    //"uniform mat4 Projection;\n"
    "uniform mat4 InvProjection;\n"

    "attribute vec2 Position;\n"
    "attribute vec3 TexCoord0;\n"

    "varying vec2 oTexCoord0;\n"

    "vec4 PositionFromDepth(vec2 position, vec2 inTexCoord)\n"
    "{\n"
    "   float depth = texelFetch(Texture0, ivec2(inTexCoord * DepthDimSize), 0).x;\n" //FIXME: Use Texture2DLod for #version 110 support.
    "   vec4 retVal = vec4(position, depth, 1);\n"
    "   return retVal;\n"
    "}\n"

    "vec4 TimewarpPos(vec2 position, vec2 inTexCoord, mat4 rotMat)\n"
    "{\n"
    // Apply the 4x4 timewarp rotation to these vectors.
    "   vec4 transformed = PositionFromDepth(position, inTexCoord);\n"
    "   transformed = InvProjection * transformed;\n"
    "   transformed = rotMat * transformed;\n"
    //"   transformed = mul ( Projection, transformed );\n"
    "   return transformed;\n"
    "}\n"

    "void main()\n"
    "{\n"
    "   vec2 eyeToSrcTexCoord = TexCoord0.xy * EyeToSourceUVScale + EyeToSourceUVOffset;\n"
    "   oTexCoord0 = eyeToSrcTexCoord;\n"

    "   float timewarpLerpFactor = TexCoord0.z;\n"
    "   mat4 lerpedEyeRot;  // GL cannot mix() matrices :-( \n"
    "   lerpedEyeRot[0] = mix(EyeXformStart[0], EyeXformEnd[0], timewarpLerpFactor);\n"
    "   lerpedEyeRot[1] = mix(EyeXformStart[1], EyeXformEnd[1], timewarpLerpFactor);\n"
    "   lerpedEyeRot[2] = mix(EyeXformStart[2], EyeXformEnd[2], timewarpLerpFactor);\n"
    "   lerpedEyeRot[3] = mix(EyeXformStart[3], EyeXformEnd[3], timewarpLerpFactor);\n"
    //"    float4x4 lerpedEyeRot = EyeXformStart;\n"

    // warped positions are a bit more involved, hence a separate function
    "   gl_Position = TimewarpPos(Position.xy, oTexCoord0, lerpedEyeRot);\n"
    "}\n";
#endif
    
// Shader with lens distortion and chromatic aberration correction.
static const char* PostProcessFragShaderWithChromAbSrc =
    "#version 110\n"
    
    "uniform sampler2D Texture;\n"
    "uniform vec3 DistortionClearColor;\n"
    "uniform float EdgeFadeScale;\n"
    "uniform vec2 EyeToSourceUVScale;\n"
    "uniform vec2 EyeToSourceUVOffset;\n"
    "uniform vec2 EyeToSourceNDCScale;\n"
    "uniform vec2 EyeToSourceNDCOffset;\n"
    "uniform vec2 TanEyeAngleScale;\n"
    "uniform vec2 TanEyeAngleOffset;\n"
    "uniform vec4 HmdWarpParam;\n"
    "uniform vec4 ChromAbParam;\n"

    "varying vec4 oPosition;\n"
    "varying vec2 oTexCoord;\n"
    
    "void main()\n"
    "{\n"
    // Input oTexCoord is [-1,1] across the half of the screen used for a single eye.
    "   vec2 TanEyeAngleDistorted = oTexCoord * TanEyeAngleScale + TanEyeAngleOffset;\n" // Scales to tan(thetaX),tan(thetaY), but still distorted (i.e. only the center is correct)
    "   float  RadiusSq = TanEyeAngleDistorted.x * TanEyeAngleDistorted.x + TanEyeAngleDistorted.y * TanEyeAngleDistorted.y;\n"
    "   float Distort = 1.0 / ( 1.0 + RadiusSq * ( HmdWarpParam.y + RadiusSq * ( HmdWarpParam.z + RadiusSq * ( HmdWarpParam.w ) ) ) );\n"
    "   float DistortR = Distort * ( ChromAbParam.x + RadiusSq * ChromAbParam.y );\n"
    "   float DistortG = Distort;\n"
    "   float DistortB = Distort * ( ChromAbParam.z + RadiusSq * ChromAbParam.w );\n"
    "   vec2 TanEyeAngleR = DistortR * TanEyeAngleDistorted;\n"
    "   vec2 TanEyeAngleG = DistortG * TanEyeAngleDistorted;\n"
    "   vec2 TanEyeAngleB = DistortB * TanEyeAngleDistorted;\n"

    // These are now in "TanEyeAngle" space.
    // The vectors (TanEyeAngleRGB.x, TanEyeAngleRGB.y, 1.0) are real-world vectors pointing from the eye to where the components of the pixel appear to be.
    // If you had a raytracer, you could just use them directly.

    // Scale them into ([0,0.5],[0,1]) or ([0.5,0],[0,1]) UV lookup space (depending on eye)
    "   vec2 SourceCoordR = TanEyeAngleR * EyeToSourceUVScale + EyeToSourceUVOffset;\n"
    "    SourceCoordR.y = 1.0 - SourceCoordR.y;\n"
    "   vec2 SourceCoordG = TanEyeAngleG * EyeToSourceUVScale + EyeToSourceUVOffset;\n"
    "    SourceCoordG.y = 1.0 - SourceCoordG.y;\n"
    "   vec2 SourceCoordB = TanEyeAngleB * EyeToSourceUVScale + EyeToSourceUVOffset;\n"
    "    SourceCoordB.y = 1.0 - SourceCoordB.y;\n"

    // Find the distance to the nearest edge.
    "   vec2 NDCCoord = TanEyeAngleG * EyeToSourceNDCScale + EyeToSourceNDCOffset;\n"
    "   float EdgeFadeIn = clamp ( EdgeFadeScale, 0.0, 1e5 ) * ( 1.0 - max ( abs ( NDCCoord.x ), abs ( NDCCoord.y ) ) );\n"
    "   if ( EdgeFadeIn < 0.0 )\n"
    "   {\n"
    "       gl_FragColor = vec4(DistortionClearColor.r, DistortionClearColor.g, DistortionClearColor.b, 1.0);\n"
    "       return;\n"
    "   }\n"
    "   EdgeFadeIn = clamp ( EdgeFadeIn, 0.0, 1.0 );\n"

    // Actually do the lookups.
    "   float ResultR = texture2D(Texture, SourceCoordR).r;\n"
    "   float ResultG = texture2D(Texture, SourceCoordG).g;\n"
    "   float ResultB = texture2D(Texture, SourceCoordB).b;\n"

    "   gl_FragColor = vec4(ResultR * EdgeFadeIn, ResultG * EdgeFadeIn, ResultB * EdgeFadeIn, 1.0);\n"
    "}\n";



static const char* VShaderSrcs[VShader_Count] =
{
    DirectVertexShaderSrc,
    StdVertexShaderSrc,
    PostProcessVertexShaderSrc,
    PostProcessMeshVertexShaderSrc,
    PostProcessMeshTimewarpVertexShaderSrc,
    PostProcessMeshPositionalTimewarpVertexShaderSrc,
    PostProcessHeightmapTimewarpVertexShaderSrc,
};
static const char* FShaderSrcs[FShader_Count] =
{
    SolidFragShaderSrc,
    GouraudFragShaderSrc,
    TextureFragShaderSrc,
    AlphaTextureFragShaderSrc,
    AlphaBlendedTextureFragShaderSrc,
    PostProcessFragShaderWithChromAbSrc,
    LitSolidFragShaderSrc,
    LitTextureFragShaderSrc,
    MultiTextureFragShaderSrc,
    PostProcessMeshFragShaderSrc,
    PostProcessMeshTimewarpFragShaderSrc,
    PostProcessMeshPositionalTimewarpFragShaderSrc,
    PostProcessHeightmapTimewarpFragShaderSrc
};


RenderDevice::RenderDevice(const RendererParams&)
  : VertexShaders(),
    FragShaders(),
    DefaultFill(),
    Proj(),
    Vao(0),
    CurRenderTarget(),
    DepthBuffers(),
    CurrentFbo(0),
    MsaaFbo(0),
    GLVersionInfo(),
    DebugCallbackControl(),
    Lighting(NULL)
{
    DebugCallbackControl.Initialize();

    GetGLVersionAndExtensions(GLVersionInfo);

    OVR_ASSERT(GLVersionInfo.MajorVersion >= 2);
    
    for (int i = 0; i < VShader_Count; i++)
    {
        OVR_ASSERT ( VShaderSrcs[i] != NULL );      // You forgot a shader!
        VertexShaders[i] = *new Shader(this, Shader_Vertex, VShaderSrcs[i]);
    }

    for (int i = 0; i < FShader_Count; i++)
    {
        OVR_ASSERT ( FShaderSrcs[i] != NULL );      // You forgot a shader!
        FragShaders[i] = *new Shader(this, Shader_Fragment, FShaderSrcs[i]);
    }
    
    Ptr<ShaderSet> gouraudShaders = *new ShaderSet();
    gouraudShaders->SetShader(VertexShaders[VShader_MVP]);
    gouraudShaders->SetShader(FragShaders[FShader_Gouraud]);
    DefaultFill = *new ShaderFill(gouraudShaders);

    glGenFramebuffers(1, &CurrentFbo);
    glGenFramebuffers(1, &MsaaFbo);
    
    if (GLVersionInfo.SupportsVAO)
    {
        glGenVertexArrays(1, &Vao);
    }
}

RenderDevice::~RenderDevice()
{
    Shutdown();
}

void RenderDevice::Shutdown()
{
    // Release any other resources first.
    OVR::Render::RenderDevice::Shutdown();
    
    // This runs before the subclass's Shutdown(), where the context, etc, may be deleted.

    glDeleteFramebuffers(1, &CurrentFbo);
    glDeleteFramebuffers(1, &MsaaFbo);
    
    if (GLVersionInfo.SupportsVAO)
    {
        glDeleteVertexArrays(1, &Vao);
    }
    
    for (int i = 0; i < VShader_Count; ++i)
    {
        VertexShaders[i].Clear();
    }

    for (int i = 0; i < FShader_Count; ++i)
    {
        FragShaders[i].Clear();
    }

    DefaultFill.Clear();
    DepthBuffers.Clear();

    DebugCallbackControl.Shutdown();
}


void RenderDevice::FillTexturedRect(float left, float top, float right, float bottom, float ul, float vt, float ur, float vb, Color c, Ptr<OVR::Render::Texture> tex)
{
	Render::RenderDevice::FillTexturedRect(left, top, right, bottom, ul, vt, ur, vb, c, tex);
}


Shader *RenderDevice::LoadBuiltinShader(ShaderStage stage, int shader)
{
    switch (stage)
    {
    case Shader_Vertex: return VertexShaders[shader];
    case Shader_Fragment: return FragShaders[shader];
    default:
        return NULL;
    }
}


void RenderDevice::BeginRendering()
{
    glEnable(GL_DEPTH_TEST);
    glEnable(GL_CULL_FACE);
    glFrontFace(GL_CW);

    glEnable(GL_LINE_SMOOTH);
    glEnable(GL_BLEND);
    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
}

void RenderDevice::SetDepthMode(bool enable, bool write, CompareFunc func)
{
    if (enable)
    {
        glEnable(GL_DEPTH_TEST);
        glDepthMask(write);
        switch (func)
        {
        case Compare_Always:  glDepthFunc(GL_ALWAYS); break;
        case Compare_Less:    glDepthFunc(GL_LESS); break;
        case Compare_Greater: glDepthFunc(GL_GREATER); break;
        default: assert(0);
        }
    }
    else
        glDisable(GL_DEPTH_TEST);
}

void RenderDevice::SetViewport(const Recti& vp)
{
	glViewport(vp.x, vp.y, vp.w, vp.h);
}

void RenderDevice::Flush()
{
    glFlush();
}

void RenderDevice::WaitUntilGpuIdle()
{
    glFlush();
    glFinish();
}

void RenderDevice::Clear(float r, float g, float b, float a, float depth, bool clearColor /*= true*/, bool clearDepth /*= true*/)
{
    glClearColor(r,g,b,a);
    glClearDepth(depth);
    glClear(
        ( clearColor ? ( GL_COLOR_BUFFER_BIT ) : 0 ) |
        ( clearDepth ? ( GL_DEPTH_BUFFER_BIT ) : 0 )
        );
}

Texture* RenderDevice::GetDepthBuffer(int w, int h, int ms)
{
    for (unsigned i = 0; i < DepthBuffers.GetSize(); i++)
        if (w == DepthBuffers[i]->Width && h == DepthBuffers[i]->Height && ms == DepthBuffers[i]->GetSamples())
            return DepthBuffers[i];

    Ptr<Texture> newDepth = *CreateTexture(Texture_Depth|Texture_RenderTarget|ms, w, h, NULL);
    DepthBuffers.PushBack(newDepth);
    return newDepth.GetPtr();
}

void RenderDevice::ResolveMsaa(OVR::Render::Texture* msaaTex, OVR::Render::Texture* outputTex)
{
    bool isMsaaTarget = msaaTex->GetSamples() > 1;
    glBindFramebuffer( GL_READ_FRAMEBUFFER, MsaaFbo );
    glFramebufferTexture2D( GL_READ_FRAMEBUFFER, GL_COLOR_ATTACHMENT0,
                            isMsaaTarget ? GL_TEXTURE_2D_MULTISAMPLE : GL_TEXTURE_2D,
                            ((Texture*)msaaTex)->TexId, 0);
    glFramebufferRenderbuffer(GL_READ_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, 0);
    OVR_ASSERT(glCheckFramebufferStatus(GL_READ_FRAMEBUFFER) == GL_FRAMEBUFFER_COMPLETE);

    glBindFramebuffer( GL_DRAW_FRAMEBUFFER, CurrentFbo );
    glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, ((Texture*)outputTex)->TexId, 0);
    glFramebufferRenderbuffer(GL_DRAW_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, 0);

    OVR_ASSERT(glCheckFramebufferStatus(GL_DRAW_FRAMEBUFFER) == GL_FRAMEBUFFER_COMPLETE);

    //glReadBuffer(GL_TEXTURE_2D_MULTISAMPLE);
    //glDrawBuffer(GL_COLOR_ATTACHMENT0);
    glBlitFramebuffer( 0, 0, msaaTex->GetWidth(), msaaTex->GetHeight(),
                       0, 0, outputTex->GetWidth(), outputTex->GetHeight(), GL_COLOR_BUFFER_BIT, GL_NEAREST );
    glBindFramebuffer( GL_FRAMEBUFFER, 0 );
    GLint err = glGetError();
    OVR_ASSERT(!err); OVR_UNUSED(err);
}

void RenderDevice::SetRenderTarget(Render::Texture* color, Render::Texture* depth, Render::Texture* stencil)
{
    OVR_UNUSED(stencil);

    CurRenderTarget = (Texture*)color;
    if (color == NULL)
    {
        glBindFramebuffer(GL_FRAMEBUFFER, 0);
        return;
    }

    int sampleCount = CurRenderTarget->GetSamples();

    if (depth == NULL)
        depth = GetDepthBuffer(color->GetWidth(), color->GetHeight(), sampleCount);

    glBindFramebuffer(GL_FRAMEBUFFER, CurrentFbo);

    GLenum texTarget = (sampleCount > 1) ? GL_TEXTURE_2D_MULTISAMPLE : GL_TEXTURE_2D;

    glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, texTarget, ((Texture*)color)->TexId, 0);
    if (depth)
        glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, texTarget, ((Texture*)depth)->TexId, 0);
    else
        glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, 0);

    GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER);
    if (status != GL_FRAMEBUFFER_COMPLETE)
        OVR_DEBUG_LOG(("framebuffer not complete: %x", status));
}


void RenderDevice::SetWorldUniforms(const Matrix4f& proj)
{
    Proj = proj.Transposed();
}

void RenderDevice::SetTexture(Render::ShaderStage, int slot, const Texture* t)
{
    glActiveTexture(GL_TEXTURE0 + slot);
    glBindTexture((t->GetSamples() > 1) ? GL_TEXTURE_2D_MULTISAMPLE : GL_TEXTURE_2D, ((Texture*)t)->TexId);
}

Buffer* RenderDevice::CreateBuffer()
{
    return new Buffer(this);
}

Fill* RenderDevice::CreateSimpleFill(int flags)
{
    OVR_UNUSED(flags);
    return DefaultFill;
}
    
void RenderDevice::Render(const Matrix4f& matrix, Model* model)
{
    if (GLVersionInfo.SupportsVAO)
    {
        glBindVertexArray(Vao);
    }

    // Store data in buffers if not already
    if (!model->VertexBuffer)
    {
        Ptr<Render::Buffer> vb = *CreateBuffer();
        vb->Data(Buffer_Vertex | Buffer_ReadOnly, &model->Vertices[0], model->Vertices.GetSize() * sizeof(Vertex));
        model->VertexBuffer = vb;
    }

    if (!model->IndexBuffer)
    {
        Ptr<Render::Buffer> ib = *CreateBuffer();
        ib->Data(Buffer_Index | Buffer_ReadOnly, &model->Indices[0], model->Indices.GetSize() * 2);
        model->IndexBuffer = ib;
    }

    Render(model->Fill ? (const Fill*)model->Fill : (const Fill*)DefaultFill,
           model->VertexBuffer, model->IndexBuffer,
           matrix, 0, (int)model->Indices.GetSize(), model->GetPrimType());
}

void RenderDevice::Render(const Fill* fill, Render::Buffer* vertices, Render::Buffer* indices,
                      const Matrix4f& matrix, int offset, int count, PrimitiveType rprim, MeshType meshType /*= Mesh_Scene*/)
{
    ShaderSet* shaders = (ShaderSet*) ((ShaderFill*)fill)->GetShaders();

    GLenum prim;
    switch (rprim)
    {
    case Prim_Triangles:
        prim = GL_TRIANGLES;
        break;
    case Prim_Lines:
        prim = GL_LINES;
        break;
    case Prim_TriangleStrip:
        prim = GL_TRIANGLE_STRIP;
        break;
    default:
        assert(0);
        return;
    }

    fill->Set();
    if (shaders->ProjLoc >= 0)
        glUniformMatrix4fv(shaders->ProjLoc, 1, 0, &Proj.M[0][0]);
    if (shaders->ViewLoc >= 0)
        glUniformMatrix4fv(shaders->ViewLoc, 1, 0, &matrix.Transposed().M[0][0]);

    if (shaders->UsesLighting && Lighting->Version != shaders->LightingVer)
    {
        shaders->LightingVer = Lighting->Version;
        Lighting->Set(shaders);
    }

    glBindBuffer(GL_ARRAY_BUFFER, ((Buffer*)vertices)->GLBuffer);
    for (int i = 0; i < 5; i++)
        glEnableVertexAttribArray(i);

    switch (meshType)
    {
    case Mesh_Distortion:
        glVertexAttribPointer(0, 2, GL_FLOAT, false, sizeof(DistortionVertex), reinterpret_cast<char*>(offset) + offsetof(DistortionVertex, Pos));
        glVertexAttribPointer(1, 4, GL_UNSIGNED_BYTE, true, sizeof(DistortionVertex), reinterpret_cast<char*>(offset) + offsetof(DistortionVertex, Col));
        glVertexAttribPointer(2, 2, GL_FLOAT, false, sizeof(DistortionVertex), reinterpret_cast<char*>(offset) + offsetof(DistortionVertex, TexR));
        glVertexAttribPointer(3, 2, GL_FLOAT, false, sizeof(DistortionVertex), reinterpret_cast<char*>(offset) + offsetof(DistortionVertex, TexG));
        glVertexAttribPointer(4, 2, GL_FLOAT, false, sizeof(DistortionVertex), reinterpret_cast<char*>(offset) + offsetof(DistortionVertex, TexB));
        break;

    case Mesh_Heightmap:
        glVertexAttribPointer(0, 2, GL_FLOAT, false, sizeof(HeightmapVertex), reinterpret_cast<char*>(offset) + offsetof(HeightmapVertex, Pos));
        glVertexAttribPointer(1, 2, GL_FLOAT, false, sizeof(HeightmapVertex), reinterpret_cast<char*>(offset) + offsetof(HeightmapVertex, Tex));
        break;

    default:
        glVertexAttribPointer(0, 3, GL_FLOAT, false, sizeof(Vertex), reinterpret_cast<char*>(offset) + offsetof(Vertex, Pos));
        glVertexAttribPointer(1, 4, GL_UNSIGNED_BYTE, true, sizeof(Vertex), reinterpret_cast<char*>(offset) + offsetof(Vertex, C));
        glVertexAttribPointer(2, 2, GL_FLOAT, false, sizeof(Vertex), reinterpret_cast<char*>(offset) + offsetof(Vertex, U));
        glVertexAttribPointer(3, 2, GL_FLOAT, false, sizeof(Vertex), reinterpret_cast<char*>(offset) + offsetof(Vertex, U2));
        glVertexAttribPointer(4, 3, GL_FLOAT, false, sizeof(Vertex), reinterpret_cast<char*>(offset) + offsetof(Vertex, Norm));
    }

    if (indices)
    {
        glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ((Buffer*)indices)->GLBuffer);
        glDrawElements(prim, count, GL_UNSIGNED_SHORT, NULL);
    }
    else
    {
        glDrawArrays(prim, 0, count);
    }

    for (int i = 0; i < 5; i++)
        glDisableVertexAttribArray(i);
}

void RenderDevice::RenderWithAlpha(const Fill* fill, Render::Buffer* vertices, Render::Buffer* indices,
                                   const Matrix4f& matrix, int offset, int count, PrimitiveType rprim)
{
    //glEnable(GL_BLEND);
    Render(fill, vertices, indices, matrix, offset, count, rprim);
    //glDisable(GL_BLEND);
}

void RenderDevice::SetLighting(const LightingParams* lt)
{
    Lighting = lt;
}

Buffer::~Buffer()
{
    if (GLBuffer)
        glDeleteBuffers(1, &GLBuffer);
}

bool Buffer::Data(int use, const void* buffer, size_t size)
{
    switch (use & Buffer_TypeMask)
    {
    case Buffer_Index:     Use = GL_ELEMENT_ARRAY_BUFFER; break;
    default:               Use = GL_ARRAY_BUFFER; break;
    }

    if (!GLBuffer)
        glGenBuffers(1, &GLBuffer);

    int mode = GL_DYNAMIC_DRAW;
    if (use & Buffer_ReadOnly)
        mode = GL_STATIC_DRAW;

    glBindBuffer(Use, GLBuffer);
    glBufferData(Use, size, buffer, mode);
    return 1;
}

void* Buffer::Map(size_t, size_t, int)
{
    int mode = GL_WRITE_ONLY;
    //if (flags & Map_Unsynchronized)
    //    mode |= GL_MAP_UNSYNCHRONIZED;
    
    glBindBuffer(Use, GLBuffer);
    void* v = glMapBuffer(Use, mode);
    return v;
}

bool Buffer::Unmap(void*)
{
    glBindBuffer(Use, GLBuffer);
    int r = glUnmapBuffer(Use);
    return r != 0;
}

Shader::~Shader()
{
    if (GLShader)
        glDeleteShader(GLShader);
}

bool Shader::Compile(const char* src)
{
    if (!GLShader)
        GLShader = glCreateShader(GLStage());

    glShaderSource(GLShader, 1, &src, 0);
    glCompileShader(GLShader);
    GLint r;
    glGetShaderiv(GLShader, GL_COMPILE_STATUS, &r);
    if (!r)
    {
        GLchar msg[1024];
        glGetShaderInfoLog(GLShader, sizeof(msg), 0, msg);
        if (msg[0])
            OVR_DEBUG_LOG(("Compiling shader\n%s\nfailed: %s\n", src, msg));
        if (!r)
            return 0;
    }
    return 1;
}

ShaderSet::ShaderSet() :
  //Prog(0),
    UniformInfo(),
    ProjLoc(0),
    ViewLoc(0),
  //TexLoc[8];
    UsesLighting(false),
    LightingVer(0)
{
    memset(TexLoc, 0, sizeof(TexLoc));
    Prog = glCreateProgram();
}
ShaderSet::~ShaderSet()
{
    glDeleteProgram(Prog);
}

void ShaderSet::SetShader(Render::Shader *s)
{
    Shaders[s->GetStage()] = s;
    Shader* gls = (Shader*)s;
    glAttachShader(Prog, gls->GLShader);
    if (Shaders[Shader_Vertex] && Shaders[Shader_Fragment])
        Link();
}

void ShaderSet::UnsetShader(int stage)
{
    Shader* gls = (Shader*)(Render::Shader*)Shaders[stage];
    if (gls)
        glDetachShader(Prog, gls->GLShader);
    Shaders[stage] = NULL;
}

bool ShaderSet::Link()
{
    glBindAttribLocation(Prog, 0, "Position");
    glBindAttribLocation(Prog, 1, "Color");
    glBindAttribLocation(Prog, 2, "TexCoord");
    glBindAttribLocation(Prog, 3, "TexCoord1");
    glBindAttribLocation(Prog, 4, "Normal");

    glLinkProgram(Prog);
    GLint r;
    glGetProgramiv(Prog, GL_LINK_STATUS, &r);
    if (!r)
    {
        GLchar msg[1024];
        glGetProgramInfoLog(Prog, sizeof(msg), 0, msg);
        OVR_DEBUG_LOG(("Linking shaders failed: %s\n", msg));
        if (!r)
            return 0;
    }
    glUseProgram(Prog);

    UniformInfo.Clear();
    LightingVer = 0;
    UsesLighting = 0;

    GLint uniformCount = 0;
    glGetProgramiv(Prog, GL_ACTIVE_UNIFORMS, &uniformCount);
    OVR_ASSERT(uniformCount >= 0);

    for(GLuint i = 0; i < (GLuint)uniformCount; i++)
    {
        GLsizei namelen;
        GLint size = 0;
        GLenum type;
        GLchar name[32];
        glGetActiveUniform(Prog, i, sizeof(name), &namelen, &size, &type, name);

        if (size)
        {
            int l = glGetUniformLocation(Prog, name);
            char *np = name;
            while (*np)
            {
                if (*np == '[')
                    *np = 0;
                np++;
            }
            Uniform u;
            u.Name = name;
            u.Location = l;
            u.Size = size;
            switch (type)
            {
            case GL_FLOAT:      u.Type = 1; break;
            case GL_FLOAT_VEC2: u.Type = 2; break;
            case GL_FLOAT_VEC3: u.Type = 3; break;
            case GL_FLOAT_VEC4: u.Type = 4; break;
            case GL_FLOAT_MAT3: u.Type = 12; break;
            case GL_FLOAT_MAT4: u.Type = 16; break;
            default:
                continue;
            }
            UniformInfo.PushBack(u);
            if (!strcmp(name, "LightCount"))
                UsesLighting = 1;
        }
        else
            break;
    }

    ProjLoc = glGetUniformLocation(Prog, "Proj");
    ViewLoc = glGetUniformLocation(Prog, "View");
    for (int i = 0; i < 8; i++)
    {
        char texv[32];
        OVR_sprintf(texv, 10, "Texture%d", i);
        TexLoc[i] = glGetUniformLocation(Prog, texv);
        if (TexLoc[i] < 0)
            break;

        glUniform1i(TexLoc[i], i);
    }
    if (UsesLighting)
        OVR_ASSERT(ProjLoc >= 0 && ViewLoc >= 0);
    return 1;
}

void ShaderSet::Set(PrimitiveType) const
{
    glUseProgram(Prog);
}

bool ShaderSet::SetUniform(const char* name, int n, const float* v)
{
    for (unsigned int i = 0; i < UniformInfo.GetSize(); i++)
        if (!strcmp(UniformInfo[i].Name.ToCStr(), name))
        {
            OVR_ASSERT(UniformInfo[i].Location >= 0);
            glUseProgram(Prog);
            switch (UniformInfo[i].Type)
            {
            case 1:   glUniform1fv(UniformInfo[i].Location, n, v); break;
            case 2:   glUniform2fv(UniformInfo[i].Location, n/2, v); break;
            case 3:   glUniform3fv(UniformInfo[i].Location, n/3, v); break;
            case 4:   glUniform4fv(UniformInfo[i].Location, n/4, v); break;
            case 12:  glUniformMatrix3fv(UniformInfo[i].Location, 1, 1, v); break;
            case 16:  glUniformMatrix4fv(UniformInfo[i].Location, 1, 1, v); break;
            default: OVR_ASSERT(0);
            }
            return 1;
        }

    OVR_DEBUG_LOG(("Warning: uniform %s not present in selected shader", name));
    return 0;
}

bool ShaderSet::SetUniform4x4f(const char* name, const Matrix4f& m)
{
    for (unsigned int i = 0; i < UniformInfo.GetSize(); i++)
        if (!strcmp(UniformInfo[i].Name.ToCStr(), name))
        {
            glUseProgram(Prog);
            glUniformMatrix4fv(UniformInfo[i].Location, 1, 1, &m.M[0][0]);
            return 1;
        }

    OVR_DEBUG_LOG(("Warning: uniform %s not present in selected shader", name));
    return 0;
}

Texture::Texture(RenderDevice* r, int w, int h, int samples) : Ren(r), Width(w), Height(h), Samples(samples)
{
    glGenTextures(1, &TexId);
}

Texture::~Texture()
{
    if (TexId)
        glDeleteTextures(1, &TexId);
}

void Texture::Set(int slot, Render::ShaderStage stage) const
{
    Ren->SetTexture(stage, slot, this);
}

void Texture::SetSampleMode(int sm)
{
    glBindTexture((GetSamples() > 1) ? GL_TEXTURE_2D_MULTISAMPLE : GL_TEXTURE_2D, TexId);
    switch (sm & Sample_FilterMask)
    {
    case Sample_Linear:
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, 1);
        break;

    case Sample_Anisotropic:
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, 4);
        break;

    case Sample_Nearest:
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, 1);
        break;
    }

    switch (sm & Sample_AddressMask)
    {
    case Sample_Repeat:
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
        break;

    case Sample_Clamp:
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
        break;

    case Sample_ClampBorder:
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER);
        break;
    }
}

ovrTexture Texture::Get_ovrTexture()
{
    ovrTexture tex;
    OVR::Sizei newRTSize(Width, Height);

    ovrGLTextureData* texData = (ovrGLTextureData*)&tex;
    texData->Header.API            = ovrRenderAPI_OpenGL;
    texData->Header.TextureSize    = newRTSize;
    texData->Header.RenderViewport = Recti(newRTSize);
    texData->TexId                 = TexId;

    return tex;
}

Texture* RenderDevice::CreateTexture(int format, int width, int height, const void* data, int mipcount)
{
    GLenum   glformat, gltype = GL_UNSIGNED_BYTE;
    switch(format & Texture_TypeMask)
    {
    case Texture_RGBA:  glformat = GL_RGBA; break;
    case Texture_R:     glformat = GL_RED; break;
    case Texture_Depth: glformat = GL_DEPTH_COMPONENT; gltype = GL_FLOAT; break;
    case Texture_DXT1:  glformat = GL_COMPRESSED_RGBA_S3TC_DXT1_EXT; break;
    case Texture_DXT3:  glformat = GL_COMPRESSED_RGBA_S3TC_DXT3_EXT; break;
    case Texture_DXT5:  glformat = GL_COMPRESSED_RGBA_S3TC_DXT5_EXT; break;
    default:
        return NULL;
    }
    int samples = format & Texture_SamplesMask;
    if(samples < 1 ||
        GLVersionInfo.WholeVersion < 302) // disallow MSAA for low GL context versions
    {
        samples = 1;
    }

    GLenum textureTarget = (samples > 1) ? GL_TEXTURE_2D_MULTISAMPLE : GL_TEXTURE_2D;

    Texture* NewTex = new Texture(this, width, height, samples);
    glBindTexture(textureTarget, NewTex->TexId);
    GLint err = glGetError();

    #if ! defined(OVR_OS_MAC)
    OVR_ASSERT(!err);
    #endif

    if( err )
    {
        printf("RenderDevice::CreateTexture glGetError result: %d\n", err);
    }
    
    if (format & Texture_Compressed)
    {
        const unsigned char* level = (const unsigned char*)data;
        int w = width, h = height;
        for (int i = 0; i < mipcount; i++)
        {
            int mipsize = GetTextureSize(format, w, h);
            glCompressedTexImage2D(GL_TEXTURE_2D, i, glformat, w, h, 0, mipsize, level);

            level += mipsize;
            w >>= 1;
            h >>= 1;
            if (w < 1) w = 1;
            if (h < 1) h = 1;
        }
    }
    else
    {
        bool isSRGB = ((format & Texture_TypeMask) == Texture_RGBA && (format & Texture_SRGB) != 0);
        bool isDepth = ((format & Texture_Depth) != 0);
        GLenum internalFormat = (isSRGB) ? GL_SRGB8_ALPHA8 : (isDepth) ? GL_DEPTH_COMPONENT32F : glformat;

        if (samples > 1)
            glTexImage2DMultisample(GL_TEXTURE_2D_MULTISAMPLE, samples, internalFormat, width, height, false);
        else
            glTexImage2D(GL_TEXTURE_2D, 0, internalFormat, width, height, 0, glformat, gltype, data);
    }

    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);

    if (format == (Texture_RGBA|Texture_GenMipmaps)) // not render target
    {
        int srcw = width, srch = height;
        int level = 0;
        uint8_t* mipmaps = NULL;
        do
        {
            level++;
            int mipw = srcw >> 1; if (mipw < 1) mipw = 1;
            int miph = srch >> 1; if (miph < 1) miph = 1;
            if (mipmaps == NULL)
                mipmaps = (uint8_t*)OVR_ALLOC(mipw * miph * 4);
            FilterRgba2x2(level == 1 ? (const uint8_t*)data : mipmaps, srcw, srch, mipmaps);
            glTexImage2D(GL_TEXTURE_2D, level, glformat, mipw, miph, 0, glformat, gltype, mipmaps);
            srcw = mipw;
            srch = miph;
        } while (srcw > 1 || srch > 1);
        if (mipmaps)
            OVR_FREE(mipmaps);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, level);
    }
    else
    {
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, mipcount-1);
    }

    OVR_ASSERT(!glGetError());
    return NewTex;
}

RBuffer::RBuffer(GLenum format, GLint w, GLint h)
{
    Width = w;
    Height = h;
    glGenRenderbuffers(1, &BufId);
    glBindRenderbuffer(GL_RENDERBUFFER, BufId);
    glRenderbufferStorage(GL_RENDERBUFFER, format, w, h);
    glBindRenderbuffer(GL_RENDERBUFFER, 0);
}

RBuffer::~RBuffer()
{
    if (BufId)
        glDeleteRenderbuffers(1, &BufId);
}






DebugCallback::DebugCallback()
  : Initialized(false),
    MinLogSeverity(SeverityHigh),
    MinAssertSeverity(SeverityHigh),
    glDebugMessageCallback(NULL),
    glDebugMessageControl(NULL),
    glDebugMessageCallbackARB(NULL),
    glDebugMessageControlARB(NULL),
    glDebugMessageCallbackAMD(NULL),
    glDebugMessageControlAMD(NULL)
{
}


DebugCallback::~DebugCallback()
{
    Shutdown();
}


bool DebugCallback::GetGLDebugCallback(PFNGLDEBUGMESSAGECALLBACKPROC* debugCallback, const void** userParam) const
{
    // Curiously, the KHR and ARB callbacks use the same glGetPointerv defines, which means you can only have 
    // one of them active concurrently. This also implies that an OpenGL implementation which implements both
    // KHR and ARB implements the latter as simply a passthrough (or alias) of the former.
    #if defined(GL_ARB_debug_output) || defined(GL_KHR_debug)
        // glGetPointerv requires at least OpenGL 4.3 headers and implementation, 
        // but will be present in the headers if GL_ARB_debug_output or GL_KHR_debug are.
        if(glDebugMessageCallback || glDebugMessageCallbackARB)
        {
            glGetPointerv(GL_DEBUG_CALLBACK_FUNCTION, reinterpret_cast<GLvoid**>(debugCallback));
            glGetPointerv(GL_DEBUG_CALLBACK_USER_PARAM, const_cast<GLvoid**>(userParam));
            return true;
        }
    #endif

    // AMD_debug_output doesn't provide an option to get the debug callback.
    debugCallback = NULL;
    userParam = NULL;
    return false;
}


void DebugCallback::DebugCallbackInternal(Severity s, const char* pSource, const char* pType, GLuint id, const char* pSeverity, const char* message)
{
    if(s >= MinLogSeverity)
    {
        OVR::LogError("{ERR-xxxx} [GL Error] %s %s %#x %s: %s", pSource, pType, id, pSeverity, message);
    }

    if(s >= MinAssertSeverity)
    {
        OVR_ASSERT(s < MinAssertSeverity); // Unilateral fail.
    }
}


void DebugCallback::Initialize()
{
    if(!Initialized)
    {
        Initialized = true;

        int err = glGetError();
        OVR_UNUSED(err);

        // Used to see if a callback was already registered.
        PFNGLDEBUGMESSAGECALLBACKPROC debugCallbackPrev = NULL;
        const void* userParamPrev = NULL;

        // Try getting the KHR interface.
        #if defined(OVR_OS_MAC) // With Mac OpenGL, functions aren't dynamically linked. They are only directly called.
          //glDebugMessageCallback = ::glDebugMessageCallback; // We can enable this some day when Apple includes support 
          //glDebugMessageControl  = ::glDebugMessageControl;  // for glDebugMessageCallback in their headers and SDK.
        #else
            glDebugMessageCallback = (PFNGLDEBUGMESSAGECALLBACKPROC) GetFunction("glDebugMessageCallback");
            glDebugMessageControl  = (PFNGLDEBUGMESSAGECONTROLPROC) GetFunction("glDebugMessageControl");
        #endif

        if(glDebugMessageCallback) 
        {
            GetGLDebugCallback(&debugCallbackPrev, &userParamPrev);

            if(!debugCallbackPrev) // If a callback isn't already registered...
            {
                glDebugMessageCallback(GLDEBUGPROC(DebugMessageCallback), this);
                err = glGetError();
                if(err)
                {
                	glDebugMessageCallback = NULL;
                	glDebugMessageControl = NULL;
                	OVR_DEBUG_LOG(("glDebugMessageCallback error: %x (%d)\n", err, err));
            	}

                glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS);
                err = glGetError();
                if(err)
                {
                	OVR_DEBUG_LOG(("GL_DEBUG_OUTPUT_SYNCHRONOUS error: %x (%d)\n", err, err));
                }

                // To consider: disable marker/push/pop
                // glDebugMessageControl(GL_DEBUG_SOURCE_APPLICATION, GL_DEBUG_TYPE_MARKER,     GL_DONT_CARE, 0, NULL, GL_FALSE);
                // glDebugMessageControl(GL_DEBUG_SOURCE_APPLICATION, GL_DEBUG_TYPE_PUSH_GROUP, GL_DONT_CARE, 0, NULL, GL_FALSE);
                // glDebugMessageControl(GL_DEBUG_SOURCE_APPLICATION, GL_DEBUG_TYPE_POP_GROUP,  GL_DONT_CARE, 0, NULL, GL_FALSE);
            }
        }

        if(!glDebugMessageCallback) // If KHR_debug wasn't found, try ARB_debug_output.
        {
            #if !defined(OVR_OS_MAC)
                glDebugMessageCallbackARB = (PFNGLDEBUGMESSAGECALLBACKARBPROC) GetFunction("glDebugMessageCallbackARB");
                glDebugMessageControlARB  = (PFNGLDEBUGMESSAGECONTROLARBPROC) GetFunction("glDebugMessageControlARB");
            #endif

            if(glDebugMessageCallbackARB)
            {
                GetGLDebugCallback(&debugCallbackPrev, &userParamPrev);

                if(!debugCallbackPrev) // If a callback isn't already registered...
                {
                    glDebugMessageCallbackARB(GLDEBUGPROCARB(DebugMessageCallback), this);
                    err = glGetError();
                    if(err)
                    {
                    	glDebugMessageCallbackARB = NULL;
                    	glDebugMessageControlARB = NULL;
                    	OVR_DEBUG_LOG(("glDebugMessageCallbackARB error: %x (%d)\n", err, err));
                	}

                    glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS);
                    err = glGetError();
                    if(err)
                    {
                    	OVR_DEBUG_LOG(("GL_DEBUG_OUTPUT_SYNCHRONOUS error: %x (%d)\n", err, err));
                    }

                    // To consider: disable marker/push/pop
                    // glDebugMessageControlARB(GL_DEBUG_SOURCE_APPLICATION, GL_DEBUG_TYPE_MARKER,     GL_DONT_CARE, 0, NULL, GL_FALSE);
                    // glDebugMessageControlARB(GL_DEBUG_SOURCE_APPLICATION, GL_DEBUG_TYPE_PUSH_GROUP, GL_DONT_CARE, 0, NULL, GL_FALSE);
                    // glDebugMessageControlARB(GL_DEBUG_SOURCE_APPLICATION, GL_DEBUG_TYPE_POP_GROUP,  GL_DONT_CARE, 0, NULL, GL_FALSE);
                }
            }
        }

		if(!glDebugMessageCallback && !glDebugMessageCallbackARB)// If ARB_debug_output also wasn't found, try AMD_debug_output.
		{
			#if !defined(OVR_OS_MAC)
				glDebugMessageCallbackAMD = (PFNGLDEBUGMESSAGECALLBACKAMDPROC) GetFunction("glDebugMessageCallbackAMD");
				glDebugMessageControlAMD  = (PFNGLDEBUGMESSAGEENABLEAMDPROC) GetFunction("glDebugMessageControlAMD");
			#endif

			if(glDebugMessageCallbackAMD)
			{
				if(!debugCallbackPrev) // If a callback isn't already registered...
				{
					glDebugMessageCallbackAMD(GLDEBUGPROCAMD(DebugMessageCallbackAMD), this);
                    err = glGetError();
                    if(err)
                    {
                    	glDebugMessageCallbackAMD = NULL;
                    	glDebugMessageControlAMD = NULL;
                    	OVR_DEBUG_LOG(("glDebugMessageCallbackAMD error: %x (%d)\n", err, err));
                	}
					// There is no control for synchronous/asynchronous with AMD_debug_output.
				}
			}
		}
    }
}


void DebugCallback::Shutdown()
{
    if(Initialized)
    {
        if(glDebugMessageCallbackAMD)
        {
            glDebugMessageCallbackAMD(NULL, NULL);
            glDebugMessageCallbackAMD = NULL;
        }

        if(glDebugMessageCallbackARB)
        {
            glDebugMessageCallbackARB(NULL, NULL);
            glDebugMessageCallbackARB = NULL;
        }

        if(glDebugMessageCallback)
        {
            glDebugMessageCallback(NULL, NULL);
            glDebugMessageCallback = NULL;
        }

        Initialized = false;
    }
}


void DebugCallback::SetMinSeverity(Severity minLogSeverity, Severity minAssertSeverity)
{
    MinLogSeverity    = minLogSeverity;
    MinAssertSeverity = minAssertSeverity;
}


DebugCallback::Implementation DebugCallback::GetImplementation() const
{
    if(glDebugMessageCallbackAMD)
        return ImplementationAMD;

    if(glDebugMessageCallbackARB)
        return ImplementationARB;

    if(glDebugMessageCallback)
        return ImplementationKHR;

    return ImplementationNone;
}


void DebugCallback::DebugMessageCallback(GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei /*length*/, const GLchar* message, GLvoid* userParam)
{
    const char* pSource   = GetSource(source);
    const char* pType     = GetType(type);
    const char* pSeverity = GetSeverity(severity);
    Severity    s;

    switch(severity)
    {
        default:
        case GL_DEBUG_SEVERITY_NOTIFICATION:
            s = SeverityNotification;
            break;
        case GL_DEBUG_SEVERITY_LOW:
            s = SeverityLow;
            break;
        case GL_DEBUG_SEVERITY_MEDIUM:
            s = SeverityMedium;
            break;
        case GL_DEBUG_SEVERITY_HIGH:
            s = SeverityHigh;
            break;
    }

    DebugCallback* pThis = reinterpret_cast<DebugCallback*>(userParam);
    pThis->DebugCallbackInternal(s, pSource, pType, id, pSeverity, message);
}


const char* DebugCallback::GetSource(GLenum Source)
{
    // There is one contiguous section of GL_DEBUG_SOURCE values.
    static_assert((GL_DEBUG_SOURCE_OTHER - GL_DEBUG_SOURCE_API) == 5, "GL_DEBUG_SOURCE constants are not contiguous.");

    static const char* GL_SourceStrings[] =
    {
        "API",             // GL_DEBUG_SOURCE_API
        "System",          // GL_DEBUG_SOURCE_WINDOW_SYSTEM
        "ShaderCompiler",  // GL_DEBUG_SOURCE_SHADER_COMPILER
        "ThirdParty",      // GL_DEBUG_SOURCE_THIRD_PARTY
        "Application",     // GL_DEBUG_SOURCE_APPLICATION
        "Other"            // GL_DEBUG_SOURCE_OTHER
    };
    
    if ((Source >= GL_DEBUG_SOURCE_API) && (Source <= GL_DEBUG_SOURCE_OTHER))
        return GL_SourceStrings[Source - GL_DEBUG_SOURCE_API];
        
    return "Unknown";
}



const char* DebugCallback::GetType(GLenum Type)
{
    // There are two contiguous sections of GL_DEBUG_TYPE values.
    static_assert((GL_DEBUG_TYPE_OTHER - GL_DEBUG_TYPE_ERROR) == 5, "GL_DEBUG_TYPE constants are not contiguous.");
    static const char* TypeStrings[] =
    {
        "Error",                // GL_DEBUG_TYPE_ERROR
        "Deprecated",           // GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR
        "UndefinedBehavior",    // GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR
        "Portability",          // GL_DEBUG_TYPE_PORTABILITY
        "Performance",          // GL_DEBUG_TYPE_PERFORMANCE
        "Other"                 // GL_DEBUG_TYPE_OTHER
    };

    if ((Type >= GL_DEBUG_TYPE_ERROR) && (Type <= GL_DEBUG_TYPE_OTHER))
        return TypeStrings[Type - GL_DEBUG_TYPE_ERROR];

    // KHR_debug marker/push/pop functionality.
    static_assert((GL_DEBUG_TYPE_POP_GROUP - GL_DEBUG_TYPE_MARKER) == 2, "GL_DEBUG_TYPE constants are not contiguous.");
    static const char* TypeStrings2[] =
    {
        "Marker",       // GL_DEBUG_TYPE_MARKER
        "PushGroup",    // GL_DEBUG_TYPE_PUSH_GROUP
        "PopGroup",     // GL_DEBUG_TYPE_POP_GROUP
    };

    if ((Type >= GL_DEBUG_TYPE_MARKER) && (Type <= GL_DEBUG_TYPE_POP_GROUP))
        return TypeStrings2[Type - GL_DEBUG_TYPE_MARKER];

    return "Unknown";
}


const char* DebugCallback::GetSeverity(GLenum Severity)
{
    // There are two sections of GL_DEBUG_SEVERITY.
    static_assert((GL_DEBUG_SEVERITY_LOW - GL_DEBUG_SEVERITY_HIGH) == 2, "GL_DEBUG_SEVERITY constants are not contiguous.");
    static const char* SeverityStrings[] =
    {
        "High",
        "Medium",
        "Low"
    };

    if ((Severity >= GL_DEBUG_SEVERITY_HIGH) && (Severity <= GL_DEBUG_SEVERITY_LOW))
        return SeverityStrings[Severity - GL_DEBUG_SEVERITY_HIGH];

    // There is just one value in this second section.
    if(Severity == GL_DEBUG_SEVERITY_NOTIFICATION)
        return "Notification";

    return "Unknown";
}


void DebugCallback::DebugMessageCallbackAMD(GLuint id, GLenum category, GLenum severity, GLsizei /*length*/, const GLchar *message, GLvoid *userParam)
{
    static_assert(GL_DEBUG_SEVERITY_LOW_AMD == GL_DEBUG_SEVERITY_LOW, "Severity mismatch"); // Verify that AMD_debug_output severity constants are identical to KHR_debug severity contstants.

    const char* pSource   = GetCategoryAMD(category);
    const char* pSeverity = GetSeverity(severity);
    Severity    s;

    switch(severity)
    {
        default:
        case GL_DEBUG_SEVERITY_NOTIFICATION:
            s = SeverityNotification;
            break;
        case GL_DEBUG_SEVERITY_LOW:
            s = SeverityLow;
            break;
        case GL_DEBUG_SEVERITY_MEDIUM:
            s = SeverityMedium;
            break;
        case GL_DEBUG_SEVERITY_HIGH:
            s = SeverityHigh;
            break;
    }

    DebugCallback* pThis = reinterpret_cast<DebugCallback*>(userParam);
    pThis->DebugCallbackInternal(s, pSource, "Other", id, pSeverity, message);
}


const char* DebugCallback::GetCategoryAMD(GLenum Category)
{
    static_assert((GL_DEBUG_CATEGORY_OTHER_AMD - GL_DEBUG_CATEGORY_API_ERROR_AMD) == 7, "GL_DEBUG_CATEGORY constants are not contiguous.");
    static const char* CategoryStrings[] =
    {
        "API",                  // GL_DEBUG_CATEGORY_API_ERROR_AMD
        "System",               // GL_DEBUG_CATEGORY_WINDOW_SYSTEM_AMD
        "Deprecation",          // GL_DEBUG_CATEGORY_DEPRECATION_AMD
        "UndefinedBehavior",    // GL_DEBUG_CATEGORY_UNDEFINED_BEHAVIOR_AMD
        "Performance",          // GL_DEBUG_CATEGORY_PERFORMANCE_AMD
        "ShaderCompiler",       // GL_DEBUG_CATEGORY_SHADER_COMPILER_AMD
        "Application",          // GL_DEBUG_CATEGORY_APPLICATION_AMD
        "Other"                 // GL_DEBUG_CATEGORY_OTHER_AMD
    };

    if((Category >= GL_DEBUG_CATEGORY_API_ERROR_AMD) && (Category <= GL_DEBUG_CATEGORY_OTHER_AMD))
        return CategoryStrings[Category - GL_DEBUG_CATEGORY_API_ERROR_AMD];

    return "Unknown";
}








void GLVersionAndExtensions::ParseGLVersion()
{
    const char* version = (const char*)glGetString(GL_VERSION);
    int fields = 0, major = 0, minor = 0;
    bool isGLES = false;

    OVR_ASSERT(version);
    if (version)
    {
        OVR_DEBUG_LOG(("GL_VERSION: %s", (const char*)version));

        // Skip all leading non-digits before reading %d.
        // Example GL_VERSION strings:
        //   "1.5 ATI-1.4.18"
        //   "OpenGL ES-CM 3.2"
        OVR_DISABLE_MSVC_WARNING(4996) // "scanf may be unsafe"
        fields = sscanf(version, isdigit(*version) ? "%d.%d" : "%*[^0-9]%d.%d", &major, &minor);
        isGLES = (strstr(version, "OpenGL ES") != NULL);
        OVR_RESTORE_MSVC_WARNING()
    }
    else
    {
        LogText("Warning: GL_VERSION was NULL\n");
    }

    // If two fields were not found,
    if (fields != 2)
    {
        static_assert(sizeof(major) == sizeof(GLint), "type mis-match");

        glGetIntegerv(GL_MAJOR_VERSION, &major);
        glGetIntegerv(GL_MINOR_VERSION, &minor);
    }

    // Write version data
    MajorVersion = major;
    MinorVersion = minor;
    WholeVersion = (major * 100) + minor;
    IsGLES = isGLES;
    IsCoreProfile = (MajorVersion >= 3); // Until we get a better way to detect core profiles, we err on the conservative side and set to true if the version is >= 3.
}


bool GLVersionAndExtensions::HasGLExtension(const char* searchKey) const
{
    if (Extensions && Extensions[0]) // If we have an extension string to search for individual extensions...
    {
        const int searchKeyLen = (int)strlen(searchKey);
        const char* p = Extensions;

        for (;;)
        {
            p = strstr(p, searchKey);

            // If not found,
            if (p == NULL)
            {
                break;
            }

            // Only match full string
            if ((p == Extensions || p[-1] == ' ') &&
                (p[searchKeyLen] == '\0' || p[searchKeyLen] == ' '))
            {
                return true;
            }

            // Skip ahead
            p += searchKeyLen;
        }
    }
    else
    {
        if (MajorVersion >= 3) // If glGetIntegerv(GL_NUM_EXTENSIONS, ...) is supported...
        {
            GLint extensionCount = 0;
            glGetIntegerv(GL_NUM_EXTENSIONS, &extensionCount);
            GLenum err = glGetError();

            if (err == 0)
            {
                for (GLint i = 0; i != extensionCount; ++i)
                {
                    const char* extension = (const char*)glGetStringi(GL_EXTENSIONS, (GLuint)i);

                    if (extension) // glGetStringi returns NULL upon error.
                    {
                        if (strcmp(extension, searchKey) == 0)
                            return true;
                    }
                    else
                        break;
                }
            }
        }
    }

    return false;
}

void GLVersionAndExtensions::ParseGLExtensions()
{
    if (MajorVersion >= 3)
    {
        // Set to empty because we need to use glGetStringi to read extensions on recent OpenGL.
        Extensions = "";
    }
    else
    {
        const char* extensions = (const char*)glGetString(GL_EXTENSIONS);

        OVR_ASSERT(extensions);
        if (!extensions)
        {
            extensions = ""; // Note: glGetString() can return null
            LogText("Warning: GL_EXTENSIONS was NULL\n");
        }
        else
        {
            // Cannot print this to debug log: It's too long!
            //OVR_DEBUG_LOG(("GL_EXTENSIONS: %s", (const char*)extensions));
        }

        Extensions = extensions;
    }

    // To do: revise the code below to loop through calls to glGetStringi(GL_EXTENSIONS, ...) so that all extensions below 
    // can be searched with a single pass over the extensions instead of a full loop per HasGLExtensionCall. 

    if (MajorVersion >= 3)
    {
        SupportsVAO = true;
    }
    else
    {
        SupportsVAO =
            HasGLExtension("GL_ARB_vertex_array_object") ||
            HasGLExtension("GL_APPLE_vertex_array_object");
    }

    SupportsDrawBuffers = HasGLExtension("GL_EXT_draw_buffers2");

    // Add more extension checks here...
}

void GetGLVersionAndExtensions(GLVersionAndExtensions& versionInfo)
{
    versionInfo.ParseGLVersion();
    // GL Version must be parsed before parsing extensions:
    versionInfo.ParseGLExtensions();
    // To consider: Call to glGetStringi(GL_SHADING_LANGUAGE_VERSION, ...) check/validate the GLSL support.
}


}}} // namespace OVR::Render::GL