summaryrefslogtreecommitdiff
path: root/src/mesa/drivers/windows/gldirect/dglcontext.c
blob: 4ad7a76e67f6d1217009463d1d9585256771a16a (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
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
/****************************************************************************
*
*                        Mesa 3-D graphics library
*                        Direct3D Driver Interface
*
*  ========================================================================
*
*   Copyright (C) 1991-2004 SciTech Software, Inc. All rights reserved.
*
*   Permission is hereby granted, free of charge, to any person obtaining a
*   copy of this software and associated documentation files (the "Software"),
*   to deal in the Software without restriction, including without limitation
*   the rights to use, copy, modify, merge, publish, distribute, sublicense,
*   and/or sell copies of the Software, and to permit persons to whom the
*   Software is furnished to do so, subject to the following conditions:
*
*   The above copyright notice and this permission notice shall be included
*   in all copies or substantial portions of the Software.
*
*   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
*   OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
*   FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
*   SCITECH SOFTWARE INC BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
*   WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF
*   OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
*   SOFTWARE.
*
*  ======================================================================
*
* Language:     ANSI C
* Environment:  Windows 9x (Win32)
*
* Description:  Context handling.
*
****************************************************************************/

#include "dglcontext.h"

// Get compile errors without this. KeithH
//#include "scitech.h"	// ibool, etc.

#ifdef _USE_GLD3_WGL
#include "gld_driver.h"

extern void _gld_mesa_warning(GLcontext *, char *);
extern void _gld_mesa_fatal(GLcontext *, char *);
#endif // _USE_GLD3_WGL

// TODO: Clean out old DX6-specific code from GLD 2.x CAD driver
// if it is no longer being built as part of GLDirect. (DaveM)

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

#define GLDERR_NONE     0
#define GLDERR_MEM      1
#define GLDERR_DDRAW    2
#define GLDERR_D3D      3
#define GLDERR_BPP      4

char szResourceWarning[] =
"GLDirect does not have enough video memory resources\n"
"to support the requested OpenGL rendering context.\n\n"
"You may have to reduce the current display resolution\n"
"to obtain satisfactory OpenGL performance.\n";

char szDDrawWarning[] =
"GLDirect is unable to initialize DirectDraw for the\n"
"requested OpenGL rendering context.\n\n"
"You will have to check the DirectX control panel\n"
"for further information.\n";

char szD3DWarning[] =
"GLDirect is unable to initialize Direct3D for the\n"
"requested OpenGL rendering context.\n\n"
"You may have to change the display mode resolution\n"
"color depth or check the DirectX control panel for\n"
"further information.\n";

char szBPPWarning[] =
"GLDirect is unable to use the selected color depth for\n"
"the requested OpenGL rendering context.\n\n"
"You will have to change the display mode resolution\n"
"color depth with the Display Settings control panel.\n";

int nContextError = GLDERR_NONE;

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

#define VENDORID_ATI 0x1002

static DWORD devATIRagePro[] = {
	0x4742, // 3D RAGE PRO BGA AGP 1X/2X
	0x4744, // 3D RAGE PRO BGA AGP 1X only
	0x4749, // 3D RAGE PRO BGA PCI 33 MHz
	0x4750, // 3D RAGE PRO PQFP PCI 33 MHz
	0x4751, // 3D RAGE PRO PQFP PCI 33 MHz limited 3D
	0x4C42, // 3D RAGE LT PRO BGA-312 AGP 133 MHz
	0x4C44, // 3D RAGE LT PRO BGA-312 AGP 66 MHz
	0x4C49, // 3D RAGE LT PRO BGA-312 PCI 33 MHz
	0x4C50, // 3D RAGE LT PRO BGA-256 PCI 33 MHz
	0x4C51, // 3D RAGE LT PRO BGA-256 PCI 33 MHz limited 3D
};

static DWORD devATIRageIIplus[] = {
	0x4755, // 3D RAGE II+
	0x4756, // 3D RAGE IIC PQFP PCI
	0x4757, // 3D RAGE IIC BGA AGP
	0x475A, // 3D RAGE IIC PQFP AGP
	0x4C47, // 3D RAGE LT-G
};

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

#ifndef _USE_GLD3_WGL
extern DGL_mesaFuncs mesaFuncs;
#endif

extern DWORD dwLogging;

#ifdef GLD_THREADS
#pragma message("compiling DGLCONTEXT.C vars for multi-threaded support")
CRITICAL_SECTION CriticalSection;		// for serialized access
DWORD		dwTLSCurrentContext = 0xFFFFFFFF;	// TLS index for current context
DWORD		dwTLSPixelFormat = 0xFFFFFFFF;		// TLS index for current pixel format
#endif
HGLRC		iCurrentContext = 0;		// Index of current context (static)
BOOL		bContextReady = FALSE;		// Context state ready ?

DGL_ctx		ctxlist[DGL_MAX_CONTEXTS];	// Context list

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

static BOOL bHaveWin95 = FALSE;
static BOOL bHaveWinNT = FALSE;
static BOOL bHaveWin2K = FALSE;

/****************************************************************************
REMARKS:
Detect the installed OS type.
****************************************************************************/
static void DetectOS(void)
{
    OSVERSIONINFO VersionInformation;
    LPOSVERSIONINFO lpVersionInformation = &VersionInformation;

    VersionInformation.dwOSVersionInfoSize = sizeof(VersionInformation);

	GetVersionEx(lpVersionInformation);

    switch (VersionInformation.dwPlatformId) {
    	case VER_PLATFORM_WIN32_WINDOWS:
			bHaveWin95 = TRUE;
			bHaveWinNT = FALSE;
			bHaveWin2K = FALSE;
            break;
    	case VER_PLATFORM_WIN32_NT:
			bHaveWin95 = FALSE;
			if (VersionInformation.dwMajorVersion <= 4) {
				bHaveWinNT = TRUE;
				bHaveWin2K = FALSE;
                }
            else {
				bHaveWinNT = FALSE;
				bHaveWin2K = TRUE;
                }
			break;
		case VER_PLATFORM_WIN32s:
			bHaveWin95 = FALSE;
			bHaveWinNT = FALSE;
			bHaveWin2K = FALSE;
			break;
        }
}

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

HWND hWndEvent = NULL;					// event monitor window
HWND hWndLastActive = NULL;				// last active client window
LONG __stdcall GLD_EventWndProc(HWND hwnd,UINT msg,WPARAM wParam,LPARAM lParam);

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

// Checks if the HGLRC is valid in range of context list.
BOOL dglIsValidContext(
	HGLRC a)
{
	return ((int)a > 0 && (int)a <= DGL_MAX_CONTEXTS);
}

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

// Convert a HGLRC to a pointer into the context list.
DGL_ctx* dglGetContextAddress(
	const HGLRC a)
{
	if (dglIsValidContext(a))
		return &ctxlist[(int)a-1];
	return NULL;
}

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

// Return the current HGLRC (however it may be stored for multi-threading).
HGLRC dglGetCurrentContext(void)
{
#ifdef GLD_THREADS
	HGLRC hGLRC;
	// load from thread-specific instance
	if (glb.bMultiThreaded) {
		// protect against calls from arbitrary threads
		__try {
			hGLRC = (HGLRC)TlsGetValue(dwTLSCurrentContext);
		}
		__except(EXCEPTION_EXECUTE_HANDLER) {
			hGLRC = iCurrentContext;
		}
	}
	// load from global static var
	else {
		hGLRC = iCurrentContext;
	}
	return hGLRC;
#else
	return iCurrentContext;
#endif
}

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

// Set the current HGLRC (however it may be stored for multi-threading).
void dglSetCurrentContext(HGLRC hGLRC)
{
#ifdef GLD_THREADS
	// store in thread-specific instance
	if (glb.bMultiThreaded) {
		// protect against calls from arbitrary threads
		__try {
			TlsSetValue(dwTLSCurrentContext, (LPVOID)hGLRC);
		}
		__except(EXCEPTION_EXECUTE_HANDLER) {
			iCurrentContext = hGLRC;
		}
	}
	// store in global static var
	else {
		iCurrentContext = hGLRC;
	}
#else
	iCurrentContext = hGLRC;
#endif
}

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

// Return the current HDC only for a currently active HGLRC.
HDC dglGetCurrentDC(void)
{
	HGLRC hGLRC;
	DGL_ctx* lpCtx;

	hGLRC = dglGetCurrentContext();
	if (hGLRC) {
		lpCtx = dglGetContextAddress(hGLRC);
		return lpCtx->hDC;
	}
	return 0;
}

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

void dglInitContextState()
{
	int i;
	WNDCLASS wc;

#ifdef GLD_THREADS
	// Allocate thread local storage indexes for current context and pixel format
	dwTLSCurrentContext = TlsAlloc();
	dwTLSPixelFormat = TlsAlloc();
#endif

	dglSetCurrentContext(NULL); // No current rendering context

	 // Clear all context data
	ZeroMemory(ctxlist, sizeof(ctxlist[0]) * DGL_MAX_CONTEXTS);

	for (i=0; i<DGL_MAX_CONTEXTS; i++)
		ctxlist[i].bAllocated = FALSE; // Flag context as unused

	// This section of code crashes the dll in circumstances where the app
	// creates and destroys contexts.
/*
	// Register the class for our event monitor window
	wc.style = 0;
	wc.lpfnWndProc = GLD_EventWndProc;
	wc.cbClsExtra = 0;
	wc.cbWndExtra = 0;
	wc.hInstance = GetModuleHandle(NULL);
	wc.hIcon = LoadIcon(GetModuleHandle(NULL), IDI_APPLICATION);
	wc.hCursor = LoadCursor(NULL, IDC_ARROW);
	wc.hbrBackground = (HBRUSH)GetStockObject(BLACK_BRUSH);
	wc.lpszMenuName = NULL;
	wc.lpszClassName = "GLDIRECT";
	RegisterClass(&wc);

	// Create the non-visible window to monitor all broadcast messages
	hWndEvent = CreateWindowEx(
		WS_EX_TOOLWINDOW,"GLDIRECT","GLDIRECT",WS_POPUP,
		0,0,0,0,
		NULL,NULL,GetModuleHandle(NULL),NULL);
*/

#ifdef GLD_THREADS
	// Create a critical section object for serializing access to
	// DirectDraw and DDStereo create/destroy functions in multiple threads
	if (glb.bMultiThreaded)
		InitializeCriticalSection(&CriticalSection);
#endif

	// Context state is now initialized and ready
	bContextReady = TRUE;
}

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

void dglDeleteContextState()
{
	int i;
	static BOOL bOnceIsEnough = FALSE;

	// Only call once, from either DGL_exitDriver(), or DLL_PROCESS_DETACH
	if (bOnceIsEnough)
		return;
	bOnceIsEnough = TRUE;

	for (i=0; i<DGL_MAX_CONTEXTS; i++) {
		if (ctxlist[i].bAllocated == TRUE) {
			ddlogPrintf(DDLOG_WARN, "** Context %i not deleted - cleaning up.", (i+1));
			dglDeleteContext((HGLRC)(i+1));
		}
	}

	// Context state is no longer ready
	bContextReady = FALSE;

    // If executed when DLL unloads, DDraw objects may be invalid.
    // So catch any page faults with this exception handler.
__try {

	// Release final DirectDraw interfaces
	if (glb.bDirectDrawPersistant) {
//		RELEASE(glb.lpGlobalPalette);
//		RELEASE(glb.lpDepth4);
//		RELEASE(glb.lpBack4);
//		RELEASE(glb.lpPrimary4);
//	    RELEASE(glb.lpDD4);
    }
}
__except(EXCEPTION_EXECUTE_HANDLER) {
    ddlogPrintf(DDLOG_WARN, "Exception raised in dglDeleteContextState.");
}

	// Destroy our event monitor window
	if (hWndEvent) {
		DestroyWindow(hWndEvent);
		hWndEvent = hWndLastActive = NULL;
	}

#ifdef GLD_THREADS
	// Destroy the critical section object
	if (glb.bMultiThreaded)
		DeleteCriticalSection(&CriticalSection);

	// Release thread local storage indexes for current HGLRC and pixel format
	TlsFree(dwTLSPixelFormat);
	TlsFree(dwTLSCurrentContext);
#endif
}

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

// Application Window message handler interception
static LONG __stdcall dglWndProc(
	HWND hwnd,
	UINT msg,
	WPARAM wParam,
	LPARAM lParam)
{
	DGL_ctx* 	lpCtx = NULL;
	LONG 		lpfnWndProc = 0L;
	int  		i;
	HGLRC 		hGLRC;
	RECT 		rect;
	PAINTSTRUCT	ps;
    BOOL        bQuit = FALSE;
    BOOL        bMain = FALSE;
    LONG        rc;

    // Get the window's message handler *before* it is unhooked in WM_DESTROY

    // Is this the main window?
    if (hwnd == glb.hWndActive) {
        bMain = TRUE;
        lpfnWndProc = glb.lpfnWndProc;
    }
    // Search for DGL context matching window handle
    for (i=0; i<DGL_MAX_CONTEXTS; i++) {
	    if (ctxlist[i].hWnd == hwnd) {
	        lpCtx = &ctxlist[i];
	        lpfnWndProc = lpCtx->lpfnWndProc;
		    break;
        }
    }
	// Not one of ours...
	if (!lpfnWndProc)
	    return DefWindowProc(hwnd, msg, wParam, lParam);

    // Intercept messages amd process *before* passing on to window
	switch (msg) {
#ifdef _USE_GLD3_WGL
	case WM_DISPLAYCHANGE:
		glb.bPixelformatsDirty = TRUE;
		break;
#endif
	case WM_ACTIVATEAPP:
		glb.bAppActive = (BOOL)wParam;
		ddlogPrintf(DDLOG_INFO, "Calling app has been %s", glb.bAppActive ? "activated" : "de-activated");
		break;
	case WM_ERASEBKGND:
		// Eat the GDI erase event for the GL window
        if (!lpCtx || !lpCtx->bHasBeenCurrent)
            break;
		lpCtx->bGDIEraseBkgnd = TRUE;
		return TRUE;
	case WM_PAINT:
		// Eat the invalidated update region if render scene is in progress
        if (!lpCtx || !lpCtx->bHasBeenCurrent)
            break;
		if (lpCtx->bFrameStarted) {
			if (GetUpdateRect(hwnd, &rect, FALSE)) {
				BeginPaint(hwnd, &ps);
				EndPaint(hwnd, &ps);
				ValidateRect(hwnd, &rect);
				return TRUE;
				}
			}
		break;
	}
	// Call the appropriate window message handler
	rc = CallWindowProc((WNDPROC)lpfnWndProc, hwnd, msg, wParam, lParam);

    // Intercept messages and process *after* passing on to window
	switch (msg) {
    case WM_QUIT:
	case WM_DESTROY:
        bQuit = TRUE;
		if (lpCtx && lpCtx->bAllocated) {
			ddlogPrintf(DDLOG_WARN, "WM_DESTROY detected for HWND=%X, HDC=%X, HGLRC=%d", hwnd, lpCtx->hDC, i+1);
			dglDeleteContext((HGLRC)(i+1));
		}
		break;
#if 0
	case WM_SIZE:
		// Resize surfaces to fit window but not viewport (in case app did not bother)
        if (!lpCtx || !lpCtx->bHasBeenCurrent)
            break;
		w = LOWORD(lParam);
		h = HIWORD(lParam);
		if (lpCtx->dwWidth < w || lpCtx->dwHeight < h) {
			if (!dglWglResizeBuffers(lpCtx->glCtx, TRUE))
                 dglWglResizeBuffers(lpCtx->glCtx, FALSE);
        }
		break;
#endif
    }

    // If the main window is quitting, then so should we...
    if (bMain && bQuit) {
		ddlogPrintf(DDLOG_SYSTEM, "shutting down after WM_DESTROY detected for main HWND=%X", hwnd);
        dglDeleteContextState();
        dglExitDriver();
    }

    return rc;
}

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

// Driver Window message handler
static LONG __stdcall GLD_EventWndProc(
	HWND hwnd,
	UINT msg,
	WPARAM wParam,
	LPARAM lParam)
{
	switch (msg) {
        // May be sent by splash screen dialog on exit
        case WM_ACTIVATE:
            if (LOWORD(wParam) == WA_ACTIVE && glb.hWndActive) {
                SetForegroundWindow(glb.hWndActive);
                return 0;
                }
            break;
	}
	return DefWindowProc(hwnd, msg, wParam, lParam);
}

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

// Intercepted Keyboard handler for detecting hot keys.
LRESULT CALLBACK dglKeyProc(
	int code,
	WPARAM wParam,
	LPARAM lParam)
{
	HWND hWnd, hWndFrame;
	HGLRC hGLRC = NULL;
	DGL_ctx* lpCtx = NULL;
	int cmd = 0, dx1 = 0, dx2 = 0, i;
	static BOOL bAltPressed = FALSE;
	static BOOL bCtrlPressed = FALSE;
	static BOOL bShiftPressed = FALSE;
    RECT r, rf, rc;
    POINT pt;
    BOOL bForceReshape = FALSE;

	return CallNextHookEx(hKeyHook, code, wParam, lParam);
}

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

HWND hWndMatch;

// Window handle enumeration procedure.
BOOL CALLBACK dglEnumChildProc(
    HWND hWnd,
    LPARAM lParam)
{
    RECT rect;

    // Find window handle with matching client rect.
    GetClientRect(hWnd, &rect);
    if (EqualRect(&rect, (RECT*)lParam)) {
        hWndMatch = hWnd;
        return FALSE;
        }
    // Continue with next child window.
    return TRUE;
}

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

// Find window handle with matching client rect.
HWND dglFindWindowRect(
    RECT* pRect)
{
    hWndMatch = NULL;
    EnumChildWindows(GetForegroundWindow(), dglEnumChildProc, (LPARAM)pRect);
    return hWndMatch;
}

// ***********************************************************************
#ifndef _USE_GLD3_WGL
void dglChooseDisplayMode(
	DGL_ctx *lpCtx)
{
	// Note: Choose an exact match if possible.

	int				i;
	DWORD			area;
	DWORD			bestarea;
	DDSURFACEDESC2	*lpDDSD		= NULL;	// Mode list pointer
	DDSURFACEDESC2	*lpBestDDSD = NULL;	// Pointer to best

	lpDDSD = glb.lpDisplayModes;
	for (i=0; i<glb.nDisplayModeCount; i++, lpDDSD++) {
		if ((lpDDSD->dwWidth == lpCtx->dwWidth) &&
			(lpDDSD->dwHeight == lpCtx->dwHeight))
			goto matched; // Mode has been exactly matched
		// Choose modes that are larger in both dimensions than
		// the window, but smaller in area than the current best.
		if ( (lpDDSD->dwWidth >= lpCtx->dwWidth) &&
			 (lpDDSD->dwHeight >= lpCtx->dwHeight))
		{
			if (lpBestDDSD == NULL) {
				lpBestDDSD = lpDDSD;
				bestarea = lpDDSD->dwWidth * lpDDSD->dwHeight;
				continue;
			}
			area = lpDDSD->dwWidth * lpDDSD->dwHeight;
			if (area < bestarea) {
				lpBestDDSD = lpDDSD;
				bestarea = area;
			}
		}
	}

	// Safety check
	if (lpBestDDSD == NULL) {
		ddlogMessage(DDLOG_CRITICAL, "dglChooseDisplayMode");
		return;
	}

	lpCtx->dwModeWidth = lpBestDDSD->dwWidth;
	lpCtx->dwModeHeight = lpBestDDSD->dwHeight;
matched:
	ddlogPrintf(DDLOG_INFO, "Matched (%ldx%ld) to (%ldx%ld)",
		lpCtx->dwWidth, lpCtx->dwHeight, lpCtx->dwModeWidth, lpCtx->dwModeHeight);
}
#endif // _USE_GLD3_WGL
// ***********************************************************************

static BOOL IsDevice(
	DWORD *lpDeviceIdList,
	DWORD dwDeviceId,
	int count)
{
	int i;

	for (i=0; i<count; i++)
		if (dwDeviceId == lpDeviceIdList[i])
			return TRUE;

	return FALSE;
}

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

void dglTestForBrokenCards(
	DGL_ctx *lpCtx)
{
#ifndef _GLD3
	DDDEVICEIDENTIFIER	dddi; // DX6 device identifier

	// Sanity check.
	if (lpCtx == NULL) {
		// Testing for broken cards is sensitive area, so we don't want
		// anything saying "broken cards" in the error message. ;)
		ddlogMessage(DDLOG_ERROR, "Null context passed to TFBC\n");
		return;
	}

	if (lpCtx->lpDD4 == NULL) {
		// Testing for broken cards is sensitive area, so we don't want
		// anything saying "broken cards" in the error message. ;)
		ddlogMessage(DDLOG_ERROR, "Null DD4 passed to TFBC\n");
		return;
	}

	// Microsoft really fucked up with the GetDeviceIdentifier function
	// on Windows 2000, since it locks up on stock driers on the CD. Updated
	// drivers from vendors appear to work, but we can't identify the drivers
	// without this function!!! For now we skip these tests on Windows 2000.
	if ((GetVersion() & 0x80000000UL) == 0)
		return;

	// Obtain device info
	if (FAILED(IDirectDraw4_GetDeviceIdentifier(lpCtx->lpDD4, &dddi, 0)))
		return;

	// Useful info. Log it.
	ddlogPrintf(DDLOG_INFO, "DirectDraw: VendorId=0x%x, DeviceId=0x%x", dddi.dwVendorId, dddi.dwDeviceId);

	// Vendor 1: ATI
	if (dddi.dwVendorId == VENDORID_ATI) {
		// Test A: ATI Rage PRO
		if (IsDevice(devATIRagePro, dddi.dwDeviceId, sizeof(devATIRagePro)))
			glb.bUseMipmaps = FALSE;
		// Test B: ATI Rage II+
		if (IsDevice(devATIRageIIplus, dddi.dwDeviceId, sizeof(devATIRageIIplus)))
			glb.bEmulateAlphaTest = TRUE;
	}

	// Vendor 2: Matrox
	if (dddi.dwVendorId == 0x102B) {
		// Test: Matrox G400 stencil buffer support does not work for AutoCAD
		if (dddi.dwDeviceId == 0x0525) {
			lpCtx->lpPF->pfd.cStencilBits = 0;
			if (lpCtx->lpPF->iZBufferPF != -1) {
				glb.lpZBufferPF[lpCtx->lpPF->iZBufferPF].dwStencilBitDepth = 0;
				glb.lpZBufferPF[lpCtx->lpPF->iZBufferPF].dwStencilBitMask = 0;
				glb.lpZBufferPF[lpCtx->lpPF->iZBufferPF].dwFlags &= ~DDPF_STENCILBUFFER;
			}
		}
	}
#endif // _GLD3
}

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

BOOL dglCreateContextBuffers(
	HDC a,
	DGL_ctx *lpCtx,
	BOOL bFallback)
{
	HRESULT				hResult;

	int					i;
//	HGLRC				hGLRC;
//	DGL_ctx*			lpCtx;

#ifndef _USE_GLD3_WGL
	DWORD				dwFlags;
	DDSURFACEDESC2		ddsd2;
	DDSCAPS2			ddscaps2;
	LPDIRECTDRAWCLIPPER	lpddClipper;
	D3DDEVICEDESC		D3DHWDevDesc;	// Direct3D Hardware description
	D3DDEVICEDESC		D3DHELDevDesc;	// Direct3D Hardware Emulation Layer
#endif // _USE_GLD3_WGL

	float				inv_aspect;

	GLenum				bDoubleBuffer;	// TRUE if double buffer required
	GLenum				bDepthBuffer;	// TRUE if depth buffer required

	const PIXELFORMATDESCRIPTOR	*lpPFD = &lpCtx->lpPF->pfd;

	// Vars for Mesa visual
	DWORD				dwDepthBits		= 0;
	DWORD				dwStencilBits	= 0;
	DWORD				dwAlphaBits		= 0;
	DWORD				bAlphaSW		= GL_FALSE;
	DWORD				bDouble			= GL_FALSE;

	DDSURFACEDESC2 		ddsd2DisplayMode;
	BOOL				bFullScrnWin	= FALSE;	// fullscreen-size window ?
	DDBLTFX 			ddbltfx;
	DWORD				dwMemoryType 	= (bFallback) ? DDSCAPS_SYSTEMMEMORY : glb.dwMemoryType;
	BOOL				bBogusWindow	= FALSE;	// non-drawable window ?
	DWORD               dwColorRef      = 0;        // GDI background color
	RECT				rcDst;						// GDI window rect
	POINT				pt;							// GDI window point

	// Palette used for creating default global palette
	PALETTEENTRY	ppe[256];

#ifndef _USE_GLD3_WGL
	// Vertex buffer description. Used for creation of vertex buffers
	D3DVERTEXBUFFERDESC vbufdesc;
#endif // _USE_GLD3_WGL

#define DDLOG_CRITICAL_OR_WARN	(bFallback ? DDLOG_CRITICAL : DDLOG_WARN)

	ddlogPrintf(DDLOG_SYSTEM, "dglCreateContextBuffers for HDC=%X", a);
    nContextError = GLDERR_NONE;

#ifdef GLD_THREADS
	// Serialize access to DirectDraw object creation or DDS start
	if (glb.bMultiThreaded)
		EnterCriticalSection(&CriticalSection);
#endif

	// Check for back buffer
	bDoubleBuffer = GL_TRUE; //(lpPFD->dwFlags & PFD_DOUBLEBUFFER) ? GL_TRUE : GL_FALSE;
	// Since we always do back buffering, check if we emulate front buffering
	lpCtx->EmulateSingle =
		(lpPFD->dwFlags & PFD_DOUBLEBUFFER) ? FALSE : TRUE;
#if 0	// Don't have to mimic MS OpenGL behavior for front-buffering (DaveM)
	lpCtx->EmulateSingle |=
		(lpPFD->dwFlags & PFD_SUPPORT_GDI) ? TRUE : FALSE;
#endif

	// Check for depth buffer
	bDepthBuffer = (lpPFD->cDepthBits) ? GL_TRUE : GL_FALSE;

	lpCtx->bDoubleBuffer = bDoubleBuffer;
	lpCtx->bDepthBuffer = bDepthBuffer;

	// Set the Fullscreen flag for the context.
//	lpCtx->bFullscreen = glb.bFullscreen;

	// Obtain the dimensions of the rendering window
	lpCtx->hDC = a; // Cache DC
	lpCtx->hWnd = WindowFromDC(lpCtx->hDC);
	// Check for non-window DC = memory DC ?
	if (lpCtx->hWnd == NULL) {
        // bitmap memory contexts are always single-buffered
        lpCtx->EmulateSingle = TRUE;
		bBogusWindow = TRUE;
		ddlogPrintf(DDLOG_INFO, "Non-Window Memory Device Context");
		if (GetClipBox(lpCtx->hDC, &lpCtx->rcScreenRect) == ERROR) {
			ddlogMessage(DDLOG_WARN, "GetClipBox failed in dglCreateContext\n");
			SetRect(&lpCtx->rcScreenRect, 0, 0, 0, 0);
		}
	}
	else if (!GetClientRect(lpCtx->hWnd, &lpCtx->rcScreenRect)) {
		bBogusWindow = TRUE;
		ddlogMessage(DDLOG_WARN, "GetClientRect failed in dglCreateContext\n");
		SetRect(&lpCtx->rcScreenRect, 0, 0, 0, 0);
	}
	lpCtx->dwWidth = lpCtx->rcScreenRect.right - lpCtx->rcScreenRect.left;
	lpCtx->dwHeight = lpCtx->rcScreenRect.bottom - lpCtx->rcScreenRect.top;

	ddlogPrintf(DDLOG_INFO, "Input window %X: w=%i, h=%i",
							lpCtx->hWnd, lpCtx->dwWidth, lpCtx->dwHeight);

	// What if app only zeroes one dimension instead of both? (DaveM)
	if ( (lpCtx->dwWidth == 0) || (lpCtx->dwHeight == 0) ) {
		// Make the buffer size something sensible
		lpCtx->dwWidth = 8;
		lpCtx->dwHeight = 8;
	}

	// Set defaults
	lpCtx->dwModeWidth = lpCtx->dwWidth;
	lpCtx->dwModeHeight = lpCtx->dwHeight;
/*
	// Find best display mode for fullscreen
	if (glb.bFullscreen || !glb.bPrimary) {
		dglChooseDisplayMode(lpCtx);
	}
*/
	// Misc initialisation
	lpCtx->bCanRender = FALSE; // No rendering allowed yet
	lpCtx->bSceneStarted = FALSE;
	lpCtx->bFrameStarted = FALSE;

	// Detect OS (specifically 'Windows 2000' or 'Windows XP')
	DetectOS();

	// NOTE: WinNT not supported
	ddlogPrintf(DDLOG_INFO, "OS: %s", bHaveWin95 ? "Win9x" : (bHaveWin2K ? "Win2000/XP" : "Unsupported") );

	// Test for Fullscreen
	if (bHaveWin95) { // Problems with fullscreen on Win2K/XP
		if ((GetSystemMetrics(SM_CXSCREEN) == lpCtx->dwWidth) && 
			(GetSystemMetrics(SM_CYSCREEN) == lpCtx->dwHeight))
		{
			// Workaround for some apps that crash when going fullscreen.
			//lpCtx->bFullscreen = TRUE;
		}
		
	}

#ifdef _USE_GLD3_WGL
	_gldDriver.CreateDrawable(lpCtx, glb.bDirectDrawPersistant, glb.bPersistantBuffers);
#else
	// Check if DirectDraw has already been created by original GLRC (DaveM)
	if (glb.bDirectDrawPersistant && glb.bDirectDraw) {
		lpCtx->lpDD4 = glb.lpDD4;
		IDirectDraw4_AddRef(lpCtx->lpDD4);
		goto SkipDirectDrawCreate;
	}

	// Create DirectDraw object
	if (glb.bPrimary)
		hResult = DirectDrawCreate(NULL, &lpCtx->lpDD1, NULL);
	else {
		// A non-primary device is to be used.
		// Force context to be Fullscreen, secondary adaptors can not
		// be used in a window.
		hResult = DirectDrawCreate(&glb.ddGuid, &lpCtx->lpDD1, NULL);
		lpCtx->bFullscreen = TRUE;
	}
	if (FAILED(hResult)) {
		MessageBox(NULL, "Unable to initialize DirectDraw", "GLDirect", MB_OK);
		ddlogError(DDLOG_CRITICAL_OR_WARN, "Unable to create DirectDraw interface", hResult);
        nContextError = GLDERR_DDRAW;
		goto return_with_error;
	}

	// Query for DX6 IDirectDraw4.
	hResult = IDirectDraw_QueryInterface(lpCtx->lpDD1,
										 &IID_IDirectDraw4,
										 (void**)&lpCtx->lpDD4);
	if (FAILED(hResult)) {
		MessageBox(NULL, "GLDirect requires DirectX 6.0 or above", "GLDirect", MB_OK);
		ddlogError(DDLOG_CRITICAL_OR_WARN, "Unable to create DirectDraw4 interface", hResult);
        nContextError = GLDERR_DDRAW;
		goto return_with_error;
	}

	// Cache DirectDraw interface for subsequent GLRCs
	if (glb.bDirectDrawPersistant && !glb.bDirectDraw) {
		glb.lpDD4 = lpCtx->lpDD4;
		IDirectDraw4_AddRef(glb.lpDD4);
		glb.bDirectDraw = TRUE;
	}
SkipDirectDrawCreate:

	// Now we have a DD4 interface we can check for broken cards
	dglTestForBrokenCards(lpCtx);

	// Test if primary device can use flipping instead of blitting
	ZeroMemory(&ddsd2DisplayMode, sizeof(ddsd2DisplayMode));
	ddsd2DisplayMode.dwSize = sizeof(ddsd2DisplayMode);
	hResult = IDirectDraw4_GetDisplayMode(
					lpCtx->lpDD4,
					&ddsd2DisplayMode);
	if (SUCCEEDED(hResult)) {
		if ( (lpCtx->dwWidth == ddsd2DisplayMode.dwWidth) &&
				 (lpCtx->dwHeight == ddsd2DisplayMode.dwHeight) ) {
			// We have a fullscreen-size window
			bFullScrnWin = TRUE;
			// OK to use DirectDraw fullscreen mode ?
			if (glb.bPrimary && !glb.bFullscreenBlit && !lpCtx->EmulateSingle && !glb.bDirectDrawPersistant) {
				lpCtx->bFullscreen = TRUE;
				ddlogMessage(DDLOG_INFO, "Primary upgraded to page flipping.\n");
			}
		}
		// Cache the display mode dimensions
		lpCtx->dwModeWidth = ddsd2DisplayMode.dwWidth;
		lpCtx->dwModeHeight = ddsd2DisplayMode.dwHeight;
	}

	// Clamp the effective window dimensions to primary surface.
	// We need to do this for D3D viewport dimensions even if wide
	// surfaces are supported. This also is a good idea for handling
	// whacked-out window dimensions passed for non-drawable windows
	// like Solid Edge. (DaveM)
	if (lpCtx->dwWidth > ddsd2DisplayMode.dwWidth)
		lpCtx->dwWidth = ddsd2DisplayMode.dwWidth;
	if (lpCtx->dwHeight > ddsd2DisplayMode.dwHeight)
		lpCtx->dwHeight = ddsd2DisplayMode.dwHeight;

	// Check for non-RGB desktop resolution
	if (!lpCtx->bFullscreen && ddsd2DisplayMode.ddpfPixelFormat.dwRGBBitCount <= 8) {
		ddlogPrintf(DDLOG_CRITICAL_OR_WARN, "Desktop color depth %d bpp not supported",
			ddsd2DisplayMode.ddpfPixelFormat.dwRGBBitCount);
        nContextError = GLDERR_BPP;
		goto return_with_error;
	}
#endif // _USE_GLD3_WGL

	ddlogPrintf(DDLOG_INFO, "Window: w=%i, h=%i (%s)",
							lpCtx->dwWidth,
							lpCtx->dwHeight,
							lpCtx->bFullscreen ? "fullscreen" : "windowed");

#ifndef _USE_GLD3_WGL
	// Obtain ddraw caps
    ZeroMemory(&lpCtx->ddCaps, sizeof(DDCAPS));
	lpCtx->ddCaps.dwSize = sizeof(DDCAPS);
	if (glb.bHardware) {
		// Get HAL caps
		IDirectDraw4_GetCaps(lpCtx->lpDD4, &lpCtx->ddCaps, NULL);
	} else {
		// Get HEL caps
		IDirectDraw4_GetCaps(lpCtx->lpDD4, NULL, &lpCtx->ddCaps);
	}

	// If this flag is present then we can't default to Mesa
	// SW rendering between BeginScene() and EndScene().
	if (lpCtx->ddCaps.dwCaps2 & DDCAPS2_NO2DDURING3DSCENE) {
		ddlogMessage(DDLOG_INFO,
			"Warning          : No 2D allowed during 3D scene.\n");
	}

	// Query for DX6 Direct3D3 interface
	hResult = IDirectDraw4_QueryInterface(lpCtx->lpDD4,
										  &IID_IDirect3D3,
										  (void**)&lpCtx->lpD3D3);
	if (FAILED(hResult)) {
		MessageBox(NULL, "Unable to initialize Direct3D", "GLDirect", MB_OK);
		ddlogError(DDLOG_CRITICAL_OR_WARN, "Unable to create Direct3D interface", hResult);
        nContextError = GLDERR_D3D;
		goto return_with_error;
	}

	// Context creation
	if (lpCtx->bFullscreen) {
		// FULLSCREEN

        // Disable warning popups when in fullscreen mode
        ddlogWarnOption(FALSE);

		// Have to release persistant primary surface if fullscreen mode
		if (glb.bDirectDrawPersistant && glb.bDirectDrawPrimary) {
			RELEASE(glb.lpPrimary4);
			glb.bDirectDrawPrimary = FALSE;
		}

		dwFlags = DDSCL_EXCLUSIVE | DDSCL_FULLSCREEN | DDSCL_ALLOWREBOOT;
		if (glb.bFastFPU)
			dwFlags |= DDSCL_FPUSETUP;	// fast FPU setup optional (DaveM)
		hResult = IDirectDraw4_SetCooperativeLevel(lpCtx->lpDD4, lpCtx->hWnd, dwFlags);
		if (FAILED(hResult)) {
			ddlogError(DDLOG_CRITICAL_OR_WARN, "Unable to set Exclusive Fullscreen mode", hResult);
			goto return_with_error;
		}

		hResult = IDirectDraw4_SetDisplayMode(lpCtx->lpDD4,
											  lpCtx->dwModeWidth,
											  lpCtx->dwModeHeight,
											  lpPFD->cColorBits,
											  0,
											  0);
		if (FAILED(hResult)) {
			ddlogError(DDLOG_CRITICAL_OR_WARN, "SetDisplayMode failed", hResult);
			goto return_with_error;
		}

		// ** The display mode has changed, so dont use MessageBox! **

		ZeroMemory(&ddsd2, sizeof(ddsd2));
		ddsd2.dwSize = sizeof(ddsd2);

		if (bDoubleBuffer) {
			// Double buffered
			// Primary surface
			ddsd2.dwFlags = DDSD_CAPS | DDSD_BACKBUFFERCOUNT;
			ddsd2.ddsCaps.dwCaps = DDSCAPS_PRIMARYSURFACE |
								   DDSCAPS_FLIP |
								   DDSCAPS_COMPLEX |
								   DDSCAPS_3DDEVICE |
								   dwMemoryType;
			ddsd2.dwBackBufferCount = 1;

			hResult = IDirectDraw4_CreateSurface(lpCtx->lpDD4, &ddsd2, &lpCtx->lpFront4, NULL);
			if (FAILED(hResult)) {
				ddlogError(DDLOG_CRITICAL_OR_WARN, "CreateSurface (primary) failed", hResult);
                nContextError = GLDERR_MEM;
				goto return_with_error;
			}

			// Render target surface
			ZeroMemory(&ddscaps2, sizeof(ddscaps2)); // Clear the entire struct.
			ddscaps2.dwCaps = DDSCAPS_BACKBUFFER;
			hResult = IDirectDrawSurface4_GetAttachedSurface(lpCtx->lpFront4, &ddscaps2, &lpCtx->lpBack4);
			if (FAILED(hResult)) {
				ddlogError(DDLOG_CRITICAL_OR_WARN, "GetAttachedSurface failed", hResult);
                nContextError = GLDERR_MEM;
				goto return_with_error;
			}
		} else {
			// Single buffered
			// Primary surface
			ddsd2.dwFlags = DDSD_CAPS;
			ddsd2.ddsCaps.dwCaps = DDSCAPS_PRIMARYSURFACE |
								   //DDSCAPS_3DDEVICE |
								   dwMemoryType;

			hResult = IDirectDraw4_CreateSurface(lpCtx->lpDD4, &ddsd2, &lpCtx->lpFront4, NULL);
			if (FAILED(hResult)) {
				ddlogError(DDLOG_CRITICAL_OR_WARN, "CreateSurface (primary) failed", hResult);
                nContextError = GLDERR_MEM;
				goto return_with_error;
			}

			lpCtx->lpBack4 = NULL;
		}
	} else {
		// WINDOWED

        // OK to enable warning popups in windowed mode
        ddlogWarnOption(glb.bMessageBoxWarnings);

		dwFlags = DDSCL_NORMAL;
		if (glb.bMultiThreaded)
			dwFlags |= DDSCL_MULTITHREADED;
		if (glb.bFastFPU)
			dwFlags |= DDSCL_FPUSETUP;	// fast FPU setup optional (DaveM)
		hResult = IDirectDraw4_SetCooperativeLevel(lpCtx->lpDD4,
												  lpCtx->hWnd,
												  dwFlags);
		if (FAILED(hResult)) {
			ddlogError(DDLOG_CRITICAL_OR_WARN, "Unable to set Normal coop level", hResult);
			goto return_with_error;
		}
		// Has Primary surface already been created for original GLRC ?
		// Note this can only be applicable for windowed modes
		if (glb.bDirectDrawPersistant && glb.bDirectDrawPrimary) {
			lpCtx->lpFront4 = glb.lpPrimary4;
			IDirectDrawSurface4_AddRef(lpCtx->lpFront4);
			// Update the window on the default clipper
			IDirectDrawSurface4_GetClipper(lpCtx->lpFront4, &lpddClipper);
			IDirectDrawClipper_SetHWnd(lpddClipper, 0, lpCtx->hWnd);
			IDirectDrawClipper_Release(lpddClipper);
			goto SkipPrimaryCreate;
		}

		// Primary surface
		ZeroMemory(&ddsd2, sizeof(ddsd2));
		ddsd2.dwSize = sizeof(ddsd2);
		ddsd2.dwFlags = DDSD_CAPS;
		ddsd2.ddsCaps.dwCaps = DDSCAPS_PRIMARYSURFACE;
		hResult = IDirectDraw4_CreateSurface(lpCtx->lpDD4, &ddsd2, &lpCtx->lpFront4, NULL);
		if (FAILED(hResult)) {
			ddlogError(DDLOG_CRITICAL_OR_WARN, "CreateSurface (primary) failed", hResult);
            nContextError = GLDERR_MEM;
			goto return_with_error;
		}

		// Cache Primary surface for subsequent GLRCs
		// Note this can only be applicable to subsequent windowed modes
		if (glb.bDirectDrawPersistant && !glb.bDirectDrawPrimary) {
			glb.lpPrimary4 = lpCtx->lpFront4;
			IDirectDrawSurface4_AddRef(glb.lpPrimary4);
			glb.bDirectDrawPrimary = TRUE;
		}

		// Clipper object
		hResult = DirectDrawCreateClipper(0, &lpddClipper, NULL);
		if (FAILED(hResult)) {
			ddlogError(DDLOG_CRITICAL_OR_WARN, "CreateClipper failed", hResult);
			goto return_with_error;
		}
		hResult = IDirectDrawClipper_SetHWnd(lpddClipper, 0, lpCtx->hWnd);
		if (FAILED(hResult)) {
			RELEASE(lpddClipper);
			ddlogError(DDLOG_CRITICAL_OR_WARN, "SetHWnd failed", hResult);
			goto return_with_error;
		}
		hResult = IDirectDrawSurface4_SetClipper(lpCtx->lpFront4, lpddClipper);
		RELEASE(lpddClipper); // We have finished with it.
		if (FAILED(hResult)) {
			ddlogError(DDLOG_CRITICAL_OR_WARN, "SetClipper failed", hResult);
			goto return_with_error;
		}
SkipPrimaryCreate:

		if (bDoubleBuffer) {
			// Render target surface
			ZeroMemory(&ddsd2, sizeof(ddsd2));
			ddsd2.dwSize = sizeof(ddsd2);
			ddsd2.dwFlags        = DDSD_CAPS | DDSD_WIDTH | DDSD_HEIGHT;
			ddsd2.dwWidth        = lpCtx->dwWidth;
			ddsd2.dwHeight       = lpCtx->dwHeight;
			ddsd2.ddsCaps.dwCaps = DDSCAPS_3DDEVICE |
								   DDSCAPS_OFFSCREENPLAIN |
								   dwMemoryType;

			// Reserve the entire desktop size for persistant buffers option
			if (glb.bDirectDrawPersistant && glb.bPersistantBuffers) {
				ddsd2.dwWidth = ddsd2DisplayMode.dwWidth;
				ddsd2.dwHeight = ddsd2DisplayMode.dwHeight;
			}
			// Re-use original back buffer if persistant buffers exist
			if (glb.bDirectDrawPersistant && glb.bPersistantBuffers && glb.lpBack4)
				hResult = IDirectDrawSurface4_AddRef(lpCtx->lpBack4 = glb.lpBack4);
			else
				hResult = IDirectDraw4_CreateSurface(lpCtx->lpDD4, &ddsd2, &lpCtx->lpBack4, NULL);
			if (FAILED(hResult)) {
				ddlogError(DDLOG_CRITICAL_OR_WARN, "Create Backbuffer failed", hResult);
                nContextError = GLDERR_MEM;
				goto return_with_error;
			}
			if (glb.bDirectDrawPersistant && glb.bPersistantBuffers && !glb.lpBack4)
				IDirectDrawSurface4_AddRef(glb.lpBack4 = lpCtx->lpBack4);
		} else {
			lpCtx->lpBack4 = NULL;
		}
	}

	//
	// Now create the Z-buffer
	//
	lpCtx->bStencil = FALSE; // Default to no stencil buffer
	if (bDepthBuffer && (lpCtx->lpPF->iZBufferPF != -1)) {
		// Get z-buffer dimensions from the render target
		// Setup the surface desc for the z-buffer.
		ZeroMemory(&ddsd2, sizeof(ddsd2));
		ddsd2.dwSize = sizeof(ddsd2);
		ddsd2.dwFlags = DDSD_CAPS | DDSD_WIDTH | DDSD_HEIGHT | DDSD_PIXELFORMAT;
		ddsd2.ddsCaps.dwCaps = DDSCAPS_ZBUFFER | dwMemoryType;
		ddsd2.dwWidth = lpCtx->dwWidth;
		ddsd2.dwHeight = lpCtx->dwHeight;
		memcpy(&ddsd2.ddpfPixelFormat,
			&glb.lpZBufferPF[lpCtx->lpPF->iZBufferPF],
			sizeof(DDPIXELFORMAT) );

		// Reserve the entire desktop size for persistant buffers option
		if (glb.bDirectDrawPersistant && glb.bPersistantBuffers) {
			ddsd2.dwWidth = ddsd2DisplayMode.dwWidth;
			ddsd2.dwHeight = ddsd2DisplayMode.dwHeight;
		}

		// Create a z-buffer
		if (glb.bDirectDrawPersistant && glb.bPersistantBuffers && glb.lpDepth4)
			hResult = IDirectDrawSurface4_AddRef(lpCtx->lpDepth4 = glb.lpDepth4);
		else
			hResult = IDirectDraw4_CreateSurface(lpCtx->lpDD4, &ddsd2, &lpCtx->lpDepth4, NULL);
		if (FAILED(hResult)) {
			ddlogError(DDLOG_CRITICAL_OR_WARN, "CreateSurface (ZBuffer) failed", hResult);
            nContextError = GLDERR_MEM;
			goto return_with_error;
		}
		if (glb.bDirectDrawPersistant && glb.bPersistantBuffers && !glb.lpDepth4)
			IDirectDrawSurface4_AddRef(glb.lpDepth4 = lpCtx->lpDepth4);
		else if (glb.bDirectDrawPersistant && glb.bPersistantBuffers && glb.lpDepth4 && glb.lpBack4)
			IDirectDrawSurface4_DeleteAttachedSurface(glb.lpBack4, 0, glb.lpDepth4);

		// Attach Zbuffer to render target
		TRY(IDirectDrawSurface4_AddAttachedSurface(
			bDoubleBuffer ? lpCtx->lpBack4 : lpCtx->lpFront4,
			lpCtx->lpDepth4),
			"dglCreateContext: Attach Zbuffer");
		if (glb.lpZBufferPF[lpCtx->lpPF->iZBufferPF].dwFlags & DDPF_STENCILBUFFER) {
			lpCtx->bStencil = TRUE;
			ddlogMessage(DDLOG_INFO, "Depth buffer has stencil\n");
		}
	}

	// Clear all back buffers and Z-buffers in case of memory recycling.
	ZeroMemory(&ddbltfx, sizeof(ddbltfx));
	ddbltfx.dwSize = sizeof(ddbltfx);
	IDirectDrawSurface4_Blt(lpCtx->lpBack4, NULL, NULL, NULL,
		DDBLT_COLORFILL | DDBLT_WAIT, &ddbltfx);
	if (lpCtx->lpDepth4)
		IDirectDrawSurface4_Blt(lpCtx->lpDepth4, NULL, NULL, NULL,
			DDBLT_COLORFILL | DDBLT_WAIT, &ddbltfx);

	// Now that we have a Z-buffer we can create the 3D device
	hResult = IDirect3D3_CreateDevice(lpCtx->lpD3D3,
									  &glb.d3dGuid,
									  bDoubleBuffer ? lpCtx->lpBack4 : lpCtx->lpFront4,
									  &lpCtx->lpDev3,
									  NULL);
	if (FAILED(hResult)) {
		ddlogError(DDLOG_CRITICAL_OR_WARN, "Unable to create Direct3D device", hResult);
        nContextError = GLDERR_D3D;
		goto return_with_error;
	}

	// We must do this as soon as the device is created
	dglInitStateCaches(lpCtx);

	// Obtain the D3D Device Description
	D3DHWDevDesc.dwSize = D3DHELDevDesc.dwSize = sizeof(D3DDEVICEDESC);
	TRY(IDirect3DDevice3_GetCaps(lpCtx->lpDev3,
								 &D3DHWDevDesc,
								 &D3DHELDevDesc),
								 "dglCreateContext: GetCaps failed");

	// Choose the relevant description and cache it in the context.
	// We will use this description later for caps checking
	memcpy(	&lpCtx->D3DDevDesc,
			glb.bHardware ? &D3DHWDevDesc : &D3DHELDevDesc,
			sizeof(D3DDEVICEDESC));

	// Now we can examine the texture formats
	if (!dglBuildTextureFormatList(lpCtx->lpDev3)) {
		ddlogMessage(DDLOG_CRITICAL_OR_WARN, "dglBuildTextureFormatList failed\n");
		goto return_with_error;
	}

	// Get the pixel format of the back buffer
	lpCtx->ddpfRender.dwSize = sizeof(lpCtx->ddpfRender);
	if (bDoubleBuffer)
		hResult = IDirectDrawSurface4_GetPixelFormat(
					lpCtx->lpBack4,
					&lpCtx->ddpfRender);
	else
		hResult = IDirectDrawSurface4_GetPixelFormat(
					lpCtx->lpFront4,
					&lpCtx->ddpfRender);

	if (FAILED(hResult)) {
		ddlogError(DDLOG_CRITICAL_OR_WARN, "GetPixelFormat failed", hResult);
		goto return_with_error;
	}
	// Find a pixel packing function suitable for this surface
	pxClassifyPixelFormat(&lpCtx->ddpfRender,
						  &lpCtx->fnPackFunc,
						  &lpCtx->fnUnpackFunc,
						  &lpCtx->fnPackSpanFunc);

	// Viewport
	hResult = IDirect3D3_CreateViewport(lpCtx->lpD3D3, &lpCtx->lpViewport3, NULL);
	if (FAILED(hResult)) {
		ddlogError(DDLOG_CRITICAL_OR_WARN, "CreateViewport failed", hResult);
		goto return_with_error;
	}

	hResult = IDirect3DDevice3_AddViewport(lpCtx->lpDev3, lpCtx->lpViewport3);
	if (FAILED(hResult)) {
		ddlogError(DDLOG_CRITICAL_OR_WARN, "AddViewport failed", hResult);
		goto return_with_error;
	}

	// Initialise the viewport
	// Note screen coordinates are used for viewport clipping since D3D
	// transform operations are not used in the GLD CAD driver. (DaveM)
	inv_aspect = (float)lpCtx->dwHeight/(float)lpCtx->dwWidth;

	lpCtx->d3dViewport.dwSize = sizeof(lpCtx->d3dViewport);
	lpCtx->d3dViewport.dwX = 0;
	lpCtx->d3dViewport.dwY = 0;
	lpCtx->d3dViewport.dwWidth = lpCtx->dwWidth;
	lpCtx->d3dViewport.dwHeight = lpCtx->dwHeight;
	lpCtx->d3dViewport.dvClipX = 0; // -1.0f;
	lpCtx->d3dViewport.dvClipY = 0; // inv_aspect;
	lpCtx->d3dViewport.dvClipWidth = lpCtx->dwWidth; // 2.0f;
	lpCtx->d3dViewport.dvClipHeight = lpCtx->dwHeight; // 2.0f * inv_aspect;
	lpCtx->d3dViewport.dvMinZ = 0.0f;
	lpCtx->d3dViewport.dvMaxZ = 1.0f;
	TRY(IDirect3DViewport3_SetViewport2(lpCtx->lpViewport3, &lpCtx->d3dViewport), "dglCreateContext: SetViewport2");

	hResult = IDirect3DDevice3_SetCurrentViewport(lpCtx->lpDev3, lpCtx->lpViewport3);
	if (FAILED(hResult)) {
		ddlogError(DDLOG_CRITICAL_OR_WARN, "SetCurrentViewport failed", hResult);
		goto return_with_error;
	}

	lpCtx->dwBPP = lpPFD->cColorBits;
	lpCtx->iZBufferPF = lpCtx->lpPF->iZBufferPF;

	// Set last texture to NULL
	for (i=0; i<MAX_TEXTURE_UNITS; i++) {
		lpCtx->ColorOp[i] = D3DTOP_DISABLE;
		lpCtx->AlphaOp[i] = D3DTOP_DISABLE;
		lpCtx->tObj[i] = NULL;
	}

	// Default to perspective correct texture mapping
	dglSetRenderState(lpCtx, D3DRENDERSTATE_TEXTUREPERSPECTIVE, TRUE, "TexturePersp");

	// Set the default culling mode
	lpCtx->cullmode = D3DCULL_NONE;
	dglSetRenderState(lpCtx, D3DRENDERSTATE_CULLMODE, D3DCULL_NONE, "CullMode");

	// Disable specular
	dglSetRenderState(lpCtx, D3DRENDERSTATE_SPECULARENABLE, FALSE, "SpecularEnable");
	// Disable subpixel correction
//	dglSetRenderState(lpCtx, D3DRENDERSTATE_SUBPIXEL, FALSE, "SubpixelEnable");
	// Disable dithering
	dglSetRenderState(lpCtx, D3DRENDERSTATE_DITHERENABLE, FALSE, "DitherEnable");

	// Initialise the primitive caches
//	lpCtx->dwNextLineVert	= 0;
//	lpCtx->dwNextTriVert	= 0;

	// Init the global texture palette
	lpCtx->lpGlobalPalette = NULL;

	// Init the HW/SW usage counters
//	lpCtx->dwHWUsageCount = lpCtx->dwSWUsageCount = 0L;

	//
	// Create two D3D vertex buffers.
	// One will hold the pre-transformed data with the other one
	// being used to hold the post-transformed & clipped verts.
	//
#if 0  // never used (DaveM)
	vbufdesc.dwSize = sizeof(D3DVERTEXBUFFERDESC);
	vbufdesc.dwCaps = D3DVBCAPS_WRITEONLY;
	if (glb.bHardware == FALSE)
		vbufdesc.dwCaps = D3DVBCAPS_SYSTEMMEMORY;
	vbufdesc.dwNumVertices = 32768; // For the time being

	// Source vertex buffer
	vbufdesc.dwFVF = DGL_LVERTEX;
	hResult = IDirect3D3_CreateVertexBuffer(lpCtx->lpD3D3, &vbufdesc, &lpCtx->m_vbuf, 0, NULL);
	if (FAILED(hResult)) {
		ddlogError(DDLOG_CRITICAL_OR_WARN, "CreateVertexBuffer(src) failed", hResult);
		goto return_with_error;
	}

	// Destination vertex buffer
	vbufdesc.dwFVF = (glb.bMultitexture == FALSE) ? D3DFVF_TLVERTEX : (D3DFVF_XYZRHW | D3DFVF_DIFFUSE | D3DFVF_TEX2);
	hResult = IDirect3D3_CreateVertexBuffer(lpCtx->lpD3D3, &vbufdesc, &lpCtx->m_pvbuf, 0, NULL);
	if(FAILED(hResult)) {
		ddlogError(DDLOG_CRITICAL_OR_WARN, "CreateVertexBuffer(dst) failed", hResult);
		goto return_with_error;
	}
#endif

#endif _USE_GLD3_WGL

	//
	//	Now create the Mesa context
	//

	// Create the Mesa visual
	if (lpPFD->cDepthBits)
		dwDepthBits = 16;
	if (lpPFD->cStencilBits)
		dwStencilBits = 8;
	if (lpPFD->cAlphaBits) {
		dwAlphaBits = 8;
		bAlphaSW = GL_TRUE;
	}
	if (lpPFD->dwFlags & PFD_DOUBLEBUFFER)
		bDouble = GL_TRUE;
//	lpCtx->EmulateSingle =
//		(lpPFD->dwFlags & PFD_DOUBLEBUFFER) ? FALSE : TRUE;

#ifdef _USE_GLD3_WGL
	lpCtx->glVis = _mesa_create_visual(
		GL_TRUE,		// RGB mode
		bDouble,    /* double buffer */
		GL_FALSE,			// stereo
		lpPFD->cRedBits,
		lpPFD->cGreenBits,
		lpPFD->cBlueBits,
		dwAlphaBits,
		0,				// index bits
		dwDepthBits,
		dwStencilBits,
		lpPFD->cAccumRedBits,	// accum bits
		lpPFD->cAccumGreenBits,	// accum bits
		lpPFD->cAccumBlueBits,	// accum bits
		lpPFD->cAccumAlphaBits,	// accum alpha bits
		1				// num samples
		);
#else // _USE_GLD3_WGL
	lpCtx->glVis = (*mesaFuncs.gl_create_visual)(
		GL_TRUE,			// RGB mode
		bAlphaSW,			// Is an alpha buffer required?
		bDouble,			// Is an double-buffering required?
		GL_FALSE,			// stereo
		dwDepthBits,		// depth_size
		dwStencilBits,		// stencil_size
		lpPFD->cAccumBits,	// accum_size
		0,					// colour-index bits
		lpPFD->cRedBits,	// Red bit count
		lpPFD->cGreenBits,	// Green bit count
		lpPFD->cBlueBits,	// Blue bit count
		dwAlphaBits			// Alpha bit count
		);
#endif // _USE_GLD3_WGL

	if (lpCtx->glVis == NULL) {
		ddlogMessage(DDLOG_CRITICAL_OR_WARN, "gl_create_visual failed\n");
		goto return_with_error;
	}

#ifdef _USE_GLD3_WGL
	lpCtx->glCtx = _mesa_create_context(lpCtx->glVis, NULL, (void *)lpCtx, GL_TRUE);
#else
	// Create the Mesa context
	lpCtx->glCtx = (*mesaFuncs.gl_create_context)(
					lpCtx->glVis,	// Mesa visual
					NULL,			// share list context
					(void *)lpCtx,	// Pointer to our driver context
					GL_TRUE			// Direct context flag
				   );
#endif // _USE_GLD3_WGL

	if (lpCtx->glCtx == NULL) {
		ddlogMessage(DDLOG_CRITICAL_OR_WARN, "gl_create_context failed\n");
		goto return_with_error;
	}

	// Create the Mesa framebuffer
#ifdef _USE_GLD3_WGL
	lpCtx->glBuffer = _mesa_create_framebuffer(
		lpCtx->glVis,
		lpCtx->glVis->depthBits > 0,
		lpCtx->glVis->stencilBits > 0,
		lpCtx->glVis->accumRedBits > 0,
		GL_FALSE //swalpha
		);
#else
	lpCtx->glBuffer = (*mesaFuncs.gl_create_framebuffer)(lpCtx->glVis);
#endif // _USE_GLD3_WGL

	if (lpCtx->glBuffer == NULL) {
		ddlogMessage(DDLOG_CRITICAL_OR_WARN, "gl_create_framebuffer failed\n");
		goto return_with_error;
	}

#ifdef _USE_GLD3_WGL
	// Init Mesa internals
	_swrast_CreateContext( lpCtx->glCtx );
	_vbo_CreateContext( lpCtx->glCtx );
	_tnl_CreateContext( lpCtx->glCtx );
	_swsetup_CreateContext( lpCtx->glCtx );

	_gldDriver.InitialiseMesa(lpCtx);
	
	lpCtx->glCtx->imports.warning	= _gld_mesa_warning;
	lpCtx->glCtx->imports.fatal		= _gld_mesa_fatal;

#else
	// Tell Mesa how many texture stages we have
	glb.wMaxSimultaneousTextures = lpCtx->D3DDevDesc.wMaxSimultaneousTextures;
	// Only use as many Units as the spec requires
	if (glb.wMaxSimultaneousTextures > MAX_TEXTURE_UNITS)
		glb.wMaxSimultaneousTextures = MAX_TEXTURE_UNITS;
	lpCtx->glCtx->Const.MaxTextureUnits = glb.wMaxSimultaneousTextures;
	ddlogPrintf(DDLOG_INFO, "Texture stages   : %d", glb.wMaxSimultaneousTextures);

	// Set the max texture size.
	// NOTE: clamped to a max of 1024 for extra performance!
	lpCtx->dwMaxTextureSize = (lpCtx->D3DDevDesc.dwMaxTextureWidth <= 1024) ? lpCtx->D3DDevDesc.dwMaxTextureWidth : 1024;

// Texture resize takes place elsewhere. KH
// NOTE: This was added to workaround an issue with the Intel app.
#if 0
	lpCtx->glCtx->Const.MaxTextureSize = lpCtx->dwMaxTextureSize;
#else
	lpCtx->glCtx->Const.MaxTextureSize = 1024;
#endif

	// Setup the Display Driver pointers
	dglSetupDDPointers(lpCtx->glCtx);

	// Initialise all the Direct3D renderstates
	dglInitStateD3D(lpCtx->glCtx);

#if 0
	// Signal a reload of texture state on next glBegin
	lpCtx->m_texHandleValid = FALSE;
	lpCtx->m_mtex = FALSE;
	lpCtx->m_texturing = FALSE;
#else
	// Set default texture unit state
//	dglSetTexture(lpCtx, 0, NULL);
//	dglSetTexture(lpCtx, 1, NULL);
#endif

	//
	// Set the global texture palette to default values.
	//

	// Clear the entire palette
	ZeroMemory(ppe, sizeof(PALETTEENTRY) * 256);

	// Fill the palette with a default colour.
	// A garish colour is used to catch bugs. Here Magenta is used.
	for (i=0; i < 256; i++) {
		ppe[i].peRed	= 255;
		ppe[i].peGreen	= 0;
		ppe[i].peBlue	= 255;
	}

	RELEASE(lpCtx->lpGlobalPalette);

	if (glb.bDirectDrawPersistant && glb.bPersistantBuffers && glb.lpGlobalPalette)
		hResult = IDirectDrawPalette_AddRef(lpCtx->lpGlobalPalette = glb.lpGlobalPalette);
	else
		hResult = IDirectDraw4_CreatePalette(
				lpCtx->lpDD4,
				DDPCAPS_INITIALIZE | DDPCAPS_8BIT | DDPCAPS_ALLOW256,
				ppe,
				&(lpCtx->lpGlobalPalette),
				NULL);
	if (FAILED(hResult)) {
		ddlogError(DDLOG_ERROR, "Default CreatePalette failed\n", hResult);
		lpCtx->lpGlobalPalette = NULL;
		goto return_with_error;
	}
	if (glb.bDirectDrawPersistant && glb.bPersistantBuffers && !glb.lpGlobalPalette)
		IDirectDrawPalette_AddRef(glb.lpGlobalPalette = lpCtx->lpGlobalPalette);

#endif // _USE_GLD3_WGL

	// ** If we have made it to here then we can enable rendering **
	lpCtx->bCanRender = TRUE;

//	ddlogMessage(DDLOG_SYSTEM, "dglCreateContextBuffers succeded\n");

#ifdef GLD_THREADS
	// Release serialized access
	if (glb.bMultiThreaded)
		LeaveCriticalSection(&CriticalSection);
#endif

	return TRUE;

return_with_error:
	// Clean up before returning.
	// This is critical for secondary devices.

	lpCtx->bCanRender = FALSE;

#ifdef _USE_GLD3_WGL
	// Destroy the Mesa context
	if (lpCtx->glBuffer)
		_mesa_destroy_framebuffer(lpCtx->glBuffer);
	if (lpCtx->glCtx)
		_mesa_destroy_context(lpCtx->glCtx);
	if (lpCtx->glVis)
		_mesa_destroy_visual(lpCtx->glVis);

	// Destroy driver data
	_gldDriver.DestroyDrawable(lpCtx);
#else
	// Destroy the Mesa context
	if (lpCtx->glBuffer)
		(*mesaFuncs.gl_destroy_framebuffer)(lpCtx->glBuffer);
	if (lpCtx->glCtx)
		(*mesaFuncs.gl_destroy_context)(lpCtx->glCtx);
	if (lpCtx->glVis)
		(*mesaFuncs.gl_destroy_visual)(lpCtx->glVis);

	RELEASE(lpCtx->m_pvbuf); // Release D3D vertex buffer
	RELEASE(lpCtx->m_vbuf); // Release D3D vertex buffer

	if (lpCtx->lpViewport3) {
		if (lpCtx->lpDev3) IDirect3DDevice3_DeleteViewport(lpCtx->lpDev3, lpCtx->lpViewport3);
		RELEASE(lpCtx->lpViewport3);
		lpCtx->lpViewport3 = NULL;
	}

	RELEASE(lpCtx->lpDev3);
	if (lpCtx->lpDepth4) {
		if (lpCtx->lpBack4)
			IDirectDrawSurface4_DeleteAttachedSurface(lpCtx->lpBack4, 0L, lpCtx->lpDepth4);
		else
			IDirectDrawSurface4_DeleteAttachedSurface(lpCtx->lpFront4, 0L, lpCtx->lpDepth4);
		RELEASE(lpCtx->lpDepth4);
		lpCtx->lpDepth4 = NULL;
	}
	RELEASE(lpCtx->lpBack4);
	RELEASE(lpCtx->lpFront4);
	else
	if (lpCtx->bFullscreen) {
		IDirectDraw4_RestoreDisplayMode(lpCtx->lpDD4);
		IDirectDraw4_SetCooperativeLevel(lpCtx->lpDD4, NULL, DDSCL_NORMAL);
	}
	RELEASE(lpCtx->lpD3D3);
	RELEASE(lpCtx->lpDD4);
	RELEASE(lpCtx->lpDD1);
#endif // _USE_GLD3_WGL

	lpCtx->bAllocated = FALSE;

#ifdef GLD_THREADS
	// Release serialized access
	if (glb.bMultiThreaded)
		LeaveCriticalSection(&CriticalSection);
#endif

	return FALSE;

#undef DDLOG_CRITICAL_OR_WARN
}

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

HGLRC dglCreateContext(
	HDC a,
	const DGL_pixelFormat *lpPF)
{
	int i;
	HGLRC				hGLRC;
	DGL_ctx*			lpCtx;
	static BOOL			bWarnOnce = TRUE;
	DWORD				dwThreadId = GetCurrentThreadId();
    char                szMsg[256];
    HWND                hWnd;
    LONG                lpfnWndProc;

	// Validate license
	if (!dglValidate())
		return NULL;

	// Is context state ready ?
	if (!bContextReady)
		return NULL;

	ddlogPrintf(DDLOG_SYSTEM, "dglCreateContext for HDC=%X, ThreadId=%X", a, dwThreadId);

	// Find next free context.
	// Also ensure that only one Fullscreen context is created at any one time.
	hGLRC = 0; // Default to Not Found
	for (i=0; i<DGL_MAX_CONTEXTS; i++) {
		if (ctxlist[i].bAllocated) {
			if (/*glb.bFullscreen && */ctxlist[i].bFullscreen)
				break;
		} else {
			hGLRC = (HGLRC)(i+1);
			break;
		}
	}

	// Bail if no GLRC was found
	if (!hGLRC)
		return NULL;

	// Set the context pointer
	lpCtx = dglGetContextAddress(hGLRC);
	// Make sure that context is zeroed before we do anything.
	// MFC and C++ apps call wglCreateContext() and wglDeleteContext() multiple times,
	// even though only one context is ever used by the app, so keep it clean. (DaveM)
	ZeroMemory(lpCtx, sizeof(DGL_ctx));
	lpCtx->bAllocated = TRUE;
	// Flag that buffers need creating on next wglMakeCurrent call.
	lpCtx->bHasBeenCurrent = FALSE;
	lpCtx->lpPF = (DGL_pixelFormat *)lpPF;	// cache pixel format
	lpCtx->bCanRender = FALSE;

	// Create all the internal resources here, not in dglMakeCurrent().
	// We do a re-size check in dglMakeCurrent in case of re-allocations. (DaveM)
	// We now try context allocations twice, first with video memory,
	// then again with system memory. This is similar to technique
	// used for dglWglResizeBuffers(). (DaveM)
	if (lpCtx->bHasBeenCurrent == FALSE) {
		if (!dglCreateContextBuffers(a, lpCtx, FALSE)) {
			if (glb.bMessageBoxWarnings && bWarnOnce && dwLogging) {
				bWarnOnce = FALSE;
                switch (nContextError) {
                   case GLDERR_DDRAW: strcpy(szMsg, szDDrawWarning); break;
                   case GLDERR_D3D: strcpy(szMsg, szD3DWarning); break;
                   case GLDERR_MEM: strcpy(szMsg, szResourceWarning); break;
                   case GLDERR_BPP: strcpy(szMsg, szBPPWarning); break;
                   default: strcpy(szMsg, "");
                }
                if (strlen(szMsg))
                    MessageBox(NULL, szMsg, "GLDirect", MB_OK | MB_ICONWARNING);
			}
            // Only need to try again if memory error
            if (nContextError == GLDERR_MEM) {
			    ddlogPrintf(DDLOG_WARN, "dglCreateContext failed 1st time with video memory");
            }
            else {
			    ddlogPrintf(DDLOG_ERROR, "dglCreateContext failed");
                return NULL;
            }
		}
	}

	// Now that we have a hWnd, we can intercept the WindowProc.
    hWnd = lpCtx->hWnd;
    if (hWnd) {
		// Only hook individual window handler once if not hooked before.
		lpfnWndProc = GetWindowLong(hWnd, GWL_WNDPROC);
		if (lpfnWndProc != (LONG)dglWndProc) {
			lpCtx->lpfnWndProc = lpfnWndProc;
			SetWindowLong(hWnd, GWL_WNDPROC, (LONG)dglWndProc);
			}
        // Find the parent window of the app too.
        if (glb.hWndActive == NULL) {
            while (hWnd != NULL) {
                glb.hWndActive = hWnd;
                hWnd = GetParent(hWnd);
            }
            // Hook the parent window too.
            lpfnWndProc = GetWindowLong(glb.hWndActive, GWL_WNDPROC);
            if (glb.hWndActive == lpCtx->hWnd)
                glb.lpfnWndProc = lpCtx->lpfnWndProc;
            else if (lpfnWndProc != (LONG)dglWndProc)
                glb.lpfnWndProc = lpfnWndProc;
            if (glb.lpfnWndProc)
                SetWindowLong(glb.hWndActive, GWL_WNDPROC, (LONG)dglWndProc);
        }
    }

	ddlogPrintf(DDLOG_SYSTEM, "dglCreateContext succeeded for HGLRC=%d", (int)hGLRC);

	return hGLRC;
}

// ***********************************************************************
// Make a DirectGL context current
// Used by wgl functions and dgl functions
BOOL dglMakeCurrent(
	HDC a,
	HGLRC b)
{
	int context;
	DGL_ctx* lpCtx;
	HWND hWnd;
	BOOL bNeedResize = FALSE;
	BOOL bWindowChanged, bContextChanged;
	LPDIRECTDRAWCLIPPER	lpddClipper;
	DWORD dwThreadId = GetCurrentThreadId();
	LONG lpfnWndProc;

	// Validate license
	if (!dglValidate())
		return FALSE;

	// Is context state ready ?
	if (!bContextReady)
		return FALSE;

	context = (int)b; // This is as a result of STRICT!
	ddlogPrintf(DDLOG_SYSTEM, "dglMakeCurrent: HDC=%X, HGLRC=%d, ThreadId=%X", a, context, dwThreadId);

	// If the HGLRC is NULL then make no context current;
	// Ditto if the HDC is NULL either. (DaveM)
	if (context == 0 || a == 0) {
		// Corresponding Mesa operation
#ifdef _USE_GLD3_WGL
		_mesa_make_current(NULL, NULL);
#else
		(*mesaFuncs.gl_make_current)(NULL, NULL);
#endif
		dglSetCurrentContext(0);
		return TRUE;
	}

	// Make sure the HGLRC is in range
	if ((context > DGL_MAX_CONTEXTS) || (context < 0)) {
		ddlogMessage(DDLOG_ERROR, "dglMakeCurrent: HGLRC out of range\n");
		return FALSE;
	}

	// Find address of context and make sure that it has been allocated
	lpCtx = dglGetContextAddress(b);
	if (!lpCtx->bAllocated) {
		ddlogMessage(DDLOG_ERROR, "dglMakeCurrent: Context not allocated\n");
//		return FALSE;
		return TRUE; // HACK: Shuts up "WebLab Viewer Pro". KeithH
	}

#ifdef GLD_THREADS
	// Serialize access to DirectDraw or DDS operations
	if (glb.bMultiThreaded)
		EnterCriticalSection(&CriticalSection);
#endif

	// Check if window has changed
	hWnd = (a != lpCtx->hDC) ? WindowFromDC(a) : lpCtx->hWnd;
	bWindowChanged = (hWnd != lpCtx->hWnd) ? TRUE : FALSE;
	bContextChanged = (b != dglGetCurrentContext()) ? TRUE : FALSE;

	// If the window has changed, make sure the clipper is updated. (DaveM)
	if (glb.bDirectDrawPersistant && !lpCtx->bFullscreen && (bWindowChanged || bContextChanged)) {
		lpCtx->hWnd = hWnd;
#ifndef _USE_GLD3_WGL
		IDirectDrawSurface4_GetClipper(lpCtx->lpFront4, &lpddClipper);
		IDirectDrawClipper_SetHWnd(lpddClipper, 0, lpCtx->hWnd);
		IDirectDrawClipper_Release(lpddClipper);
#endif // _USE_GLD3_WGL
	}

	// Make sure hDC and hWnd is current. (DaveM)
	// Obtain the dimensions of the rendering window
	lpCtx->hDC = a; // Cache DC
	lpCtx->hWnd = hWnd;
	hWndLastActive = hWnd;

	// Check for non-window DC = memory DC ?
	if (hWnd == NULL) {
		if (GetClipBox(a, &lpCtx->rcScreenRect) == ERROR) {
			ddlogMessage(DDLOG_WARN, "GetClipBox failed in dglMakeCurrent\n");
			SetRect(&lpCtx->rcScreenRect, 0, 0, 0, 0);
		}
	}
	else if (!GetClientRect(lpCtx->hWnd, &lpCtx->rcScreenRect)) {
		ddlogMessage(DDLOG_WARN, "GetClientRect failed in dglMakeCurrent\n");
		SetRect(&lpCtx->rcScreenRect, 0, 0, 0, 0);
	}
	// Check if buffers need to be re-sized;
	// If so, wait until Mesa GL stuff is setup before re-sizing;
	if (lpCtx->dwWidth != lpCtx->rcScreenRect.right - lpCtx->rcScreenRect.left ||
		lpCtx->dwHeight != lpCtx->rcScreenRect.bottom - lpCtx->rcScreenRect.top)
		bNeedResize = TRUE;

	// Now we can update our globals
	dglSetCurrentContext(b);

	// Corresponding Mesa operation
#ifdef _USE_GLD3_WGL
	_mesa_make_current(lpCtx->glCtx, lpCtx->glBuffer);
	lpCtx->glCtx->Driver.UpdateState(lpCtx->glCtx, _NEW_ALL);
	if (bNeedResize) {
		// Resize buffers (Note Mesa GL needs to be setup beforehand);
		// Resize Mesa internal buffer too via glViewport() command,
		// which subsequently calls dglWglResizeBuffers() too.
		lpCtx->glCtx->Driver.Viewport(lpCtx->glCtx, 0, 0, lpCtx->dwWidth, lpCtx->dwHeight);
		lpCtx->bHasBeenCurrent = TRUE;
	}
#else
	(*mesaFuncs.gl_make_current)(lpCtx->glCtx, lpCtx->glBuffer);

	dglSetupDDPointers(lpCtx->glCtx);

	// Insure DirectDraw surfaces fit current window DC
	if (bNeedResize) {
		// Resize buffers (Note Mesa GL needs to be setup beforehand);
		// Resize Mesa internal buffer too via glViewport() command,
		// which subsequently calls dglWglResizeBuffers() too.
		(*mesaFuncs.gl_Viewport)(lpCtx->glCtx, 0, 0, lpCtx->dwWidth, lpCtx->dwHeight);
		lpCtx->bHasBeenCurrent = TRUE;
	}
#endif // _USE_GLD3_WGL
	ddlogPrintf(DDLOG_SYSTEM, "dglMakeCurrent: width = %d, height = %d", lpCtx->dwWidth, lpCtx->dwHeight);

	// We have to clear D3D back buffer and render state if emulated front buffering
	// for different window (but not context) like in Solid Edge.
	if (glb.bDirectDrawPersistant && glb.bPersistantBuffers
		&& (bWindowChanged /* || bContextChanged */) && lpCtx->EmulateSingle) {
#ifdef _USE_GLD3_WGL
//		IDirect3DDevice8_EndScene(lpCtx->pDev);
//		lpCtx->bSceneStarted = FALSE;
		lpCtx->glCtx->Driver.Clear(lpCtx->glCtx, GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT,
			GL_TRUE, 0, 0, lpCtx->dwWidth, lpCtx->dwHeight);
#else
		IDirect3DDevice3_EndScene(lpCtx->lpDev3);
		lpCtx->bSceneStarted = FALSE;
		dglClearD3D(lpCtx->glCtx, GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT,
			GL_TRUE, 0, 0, lpCtx->dwWidth, lpCtx->dwHeight);
#endif // _USE_GLD3_WGL
	}

	// The first time we call MakeCurrent we set the initial viewport size
	if (lpCtx->bHasBeenCurrent == FALSE)
#ifdef _USE_GLD3_WGL
		lpCtx->glCtx->Driver.Viewport(lpCtx->glCtx, 0, 0, lpCtx->dwWidth, lpCtx->dwHeight);
#else
		(*mesaFuncs.gl_Viewport)(lpCtx->glCtx, 0, 0, lpCtx->dwWidth, lpCtx->dwHeight);
#endif // _USE_GLD3_WGL
	lpCtx->bHasBeenCurrent = TRUE;

#ifdef GLD_THREADS
	// Release serialized access
	if (glb.bMultiThreaded)
		LeaveCriticalSection(&CriticalSection);
#endif

	return TRUE;
}

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

BOOL dglDeleteContext(
	HGLRC a)
{
	DGL_ctx* lpCtx;
	DWORD dwThreadId = GetCurrentThreadId();
    char argstr[256];

#if 0	// We have enough trouble throwing exceptions as it is... (DaveM)
	// Validate license
	if (!dglValidate())
		return FALSE;
#endif

	// Is context state ready ?
	if (!bContextReady)
		return FALSE;

	ddlogPrintf(DDLOG_SYSTEM, "dglDeleteContext: Deleting context HGLRC=%d, ThreadId=%X", (int)a, dwThreadId);

	// Make sure the HGLRC is in range
	if (((int) a> DGL_MAX_CONTEXTS) || ((int)a < 0)) {
		ddlogMessage(DDLOG_ERROR, "dglDeleteCurrent: HGLRC out of range\n");
		return FALSE;
	}

	// Make sure context is valid
	lpCtx = dglGetContextAddress(a);
	if (!lpCtx->bAllocated) {
		ddlogPrintf(DDLOG_WARN, "Tried to delete unallocated context HGLRC=%d", (int)a);
//		return FALSE;
		return TRUE; // HACK: Shuts up "WebLab Viewer Pro". KeithH
	}

	// Make sure context is de-activated
	if (a == dglGetCurrentContext()) {
		ddlogPrintf(DDLOG_WARN, "dglDeleteContext: context HGLRC=%d still active", (int)a);
		dglMakeCurrent(NULL, NULL);
	}

#ifdef GLD_THREADS
	// Serialize access to DirectDraw or DDS operations
	if (glb.bMultiThreaded)
		EnterCriticalSection(&CriticalSection);
#endif

	// We are about to destroy all Direct3D objects.
	// Therefore we must disable rendering
	lpCtx->bCanRender = FALSE;

	// This exception handler was installed to catch some
	// particularly nasty apps. Console apps that call exit()
	// fall into this catagory (i.e. Win32 Glut).

    // VC cannot successfully implement multiple exception handlers
    // if more than one exception occurs. Therefore reverting back to
    // single exception handler as Keith originally had it. (DaveM)

#define WARN_MESSAGE(p) strcpy(argstr, (#p));
#define SAFE_RELEASE(p) WARN_MESSAGE(p); RELEASE(p);

__try {
#ifdef _USE_GLD3_WGL
    WARN_MESSAGE(gl_destroy_framebuffer);
	if (lpCtx->glBuffer)
		_mesa_destroy_framebuffer(lpCtx->glBuffer);
    WARN_MESSAGE(gl_destroy_context);
	if (lpCtx->glCtx)
		_mesa_destroy_context(lpCtx->glCtx);
    WARN_MESSAGE(gl_destroy_visual);
	if (lpCtx->glVis)
		_mesa_destroy_visual(lpCtx->glVis);

	_gldDriver.DestroyDrawable(lpCtx);
#else
	// Destroy the Mesa context
    WARN_MESSAGE(gl_destroy_framebuffer);
	if (lpCtx->glBuffer)
		(*mesaFuncs.gl_destroy_framebuffer)(lpCtx->glBuffer);
    WARN_MESSAGE(gl_destroy_context);
	if (lpCtx->glCtx)
		(*mesaFuncs.gl_destroy_context)(lpCtx->glCtx);
    WARN_MESSAGE(gl_destroy_visual);
	if (lpCtx->glVis)
		(*mesaFuncs.gl_destroy_visual)(lpCtx->glVis);

	SAFE_RELEASE(lpCtx->m_pvbuf); // release D3D vertex buffer
	SAFE_RELEASE(lpCtx->m_vbuf); // release D3D vertex buffer

	// Delete the global palette
	SAFE_RELEASE(lpCtx->lpGlobalPalette);

	// Clean up.
	if (lpCtx->lpViewport3) {
		if (lpCtx->lpDev3) IDirect3DDevice3_DeleteViewport(lpCtx->lpDev3, lpCtx->lpViewport3);
		SAFE_RELEASE(lpCtx->lpViewport3);
		lpCtx->lpViewport3 = NULL;
	}

	SAFE_RELEASE(lpCtx->lpDev3);
	if (lpCtx->lpDepth4) {
		if (lpCtx->lpBack4)
			IDirectDrawSurface4_DeleteAttachedSurface(lpCtx->lpBack4, 0L, lpCtx->lpDepth4);
		else
			IDirectDrawSurface4_DeleteAttachedSurface(lpCtx->lpFront4, 0L, lpCtx->lpDepth4);
		SAFE_RELEASE(lpCtx->lpDepth4);
		lpCtx->lpDepth4 = NULL;
	}
	SAFE_RELEASE(lpCtx->lpBack4);
	SAFE_RELEASE(lpCtx->lpFront4);
	if (lpCtx->bFullscreen) {
		IDirectDraw4_RestoreDisplayMode(lpCtx->lpDD4);
		IDirectDraw4_SetCooperativeLevel(lpCtx->lpDD4, NULL, DDSCL_NORMAL);
	}
	SAFE_RELEASE(lpCtx->lpD3D3);
	SAFE_RELEASE(lpCtx->lpDD4);
	SAFE_RELEASE(lpCtx->lpDD1);
#endif // _ULSE_GLD3_WGL

}
__except(EXCEPTION_EXECUTE_HANDLER) {
    ddlogPrintf(DDLOG_WARN, "Exception raised in dglDeleteContext: %s", argstr);
}

	// Restore the window message handler because this context may be used
	// again by another window with a *different* message handler. (DaveM)
	if (lpCtx->lpfnWndProc) {
		SetWindowLong(lpCtx->hWnd, GWL_WNDPROC, (LONG)lpCtx->lpfnWndProc);
		lpCtx->lpfnWndProc = (LONG)NULL;
		}

	lpCtx->bAllocated = FALSE; // This context is now free for use

#ifdef GLD_THREADS
	// Release serialized access
	if (glb.bMultiThreaded)
		LeaveCriticalSection(&CriticalSection);
#endif

	return TRUE;
}

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

BOOL dglSwapBuffers(
	HDC hDC)
{
	RECT		rSrcRect;	// Source rectangle
	RECT		rDstRect;	// Destination rectangle
	POINT		pt;
	HRESULT		hResult;

	DDBLTFX		bltFX;
	DWORD		dwBlitFlags;
	DDBLTFX		*lpBltFX;

//	DWORD		dwThreadId = GetCurrentThreadId();
	HGLRC		hGLRC = dglGetCurrentContext();
	DGL_ctx		*lpCtx = dglGetContextAddress(hGLRC);
	HWND		hWnd;

	HDC 		hDCAux;		// for memory DC
	int 		x,y,w,h;	// for memory DC BitBlt

#if 0	// Perhaps not a good idea. Called too often. KH
	// Validate license
	if (!dglValidate())
		return FALSE;
#endif

	if (!lpCtx) {
		return TRUE; //FALSE; // No current context
	}

	if (!lpCtx->bCanRender) {
		// Don't return false else some apps will bail.
		return TRUE;
	}

	hWnd = lpCtx->hWnd;
	if (hDC != lpCtx->hDC) {
		ddlogPrintf(DDLOG_WARN, "dglSwapBuffers: HDC=%X does not match HDC=%X for HGLRC=%d", hDC, lpCtx->hDC, hGLRC);
		hWnd = WindowFromDC(hDC);
	}

#ifndef _USE_GLD3_WGL
	// Ensure that the surfaces exist before we tell
	// the device to render to them.
	IDirectDraw4_RestoreAllSurfaces(lpCtx->lpDD4);

	// Make sure that the vertex caches have been emptied
//	dglStateChange(lpCtx);

	// Some OpenGL programs don't issue a glFinish - check for it here.
	if (lpCtx->bSceneStarted) {
		IDirect3DDevice3_EndScene(lpCtx->lpDev3);
		lpCtx->bSceneStarted = FALSE;
	}
#endif

#if 0
	// If the calling app is not active then we don't need to Blit/Flip.
	// We can therefore simply return TRUE.
	if (!glb.bAppActive)
		return TRUE;
	// Addendum: This is WRONG! We should bail if the app is *minimized*,
	//           not merely if the app is just plain 'not active'.
	//           KeithH, 27/May/2000.
#endif

	// Check for non-window DC = memory DC ?
	if (hWnd == NULL) {
		if (GetClipBox(hDC, &rSrcRect) == ERROR)
			return TRUE;
		// Use GDI BitBlt instead from compatible DirectDraw DC
		x = rSrcRect.left;
		y = rSrcRect.top;
		w = rSrcRect.right - rSrcRect.left;
		h = rSrcRect.bottom - rSrcRect.top;

		// Ack. DX8 does not have a GetDC() function...
                // TODO: Defer to DX7 or DX9 drivers... (DaveM)
		return TRUE;
	}

	// Bail if window client region is not drawable, like in Solid Edge
	if (!IsWindow(hWnd) /* || !IsWindowVisible(hWnd) */ || !GetClientRect(hWnd, &rSrcRect))
		return TRUE;

#ifdef GLD_THREADS
	// Serialize access to DirectDraw or DDS operations
	if (glb.bMultiThreaded)
		EnterCriticalSection(&CriticalSection);
#endif

#ifdef _USE_GLD3_WGL
	// Notify Mesa of impending swap, so Mesa can flush internal buffers.
	_mesa_notifySwapBuffers(lpCtx->glCtx);
	// Now perform driver buffer swap
	_gldDriver.SwapBuffers(lpCtx, hDC, hWnd);
#else
	if (lpCtx->bFullscreen) {
		// Sync with retrace if required
		if (glb.bWaitForRetrace) {
			IDirectDraw4_WaitForVerticalBlank(
				lpCtx->lpDD4,
				DDWAITVB_BLOCKBEGIN,
				0);
		}

		// Perform the fullscreen flip
		TRY(IDirectDrawSurface4_Flip(
			lpCtx->lpFront4,
			NULL,
			DDFLIP_WAIT),
			"dglSwapBuffers: Flip");
	} else {
		// Calculate current window position and size
		pt.x = pt.y = 0;
		ClientToScreen(hWnd, &pt);
		GetClientRect(hWnd, &rDstRect);
		if (rDstRect.right > lpCtx->dwModeWidth)
			rDstRect.right = lpCtx->dwModeWidth;
		if (rDstRect.bottom > lpCtx->dwModeHeight)
			rDstRect.bottom = lpCtx->dwModeHeight;
		OffsetRect(&rDstRect, pt.x, pt.y);
		rSrcRect.left = rSrcRect.top = 0;
		rSrcRect.right = lpCtx->dwWidth;
		rSrcRect.bottom = lpCtx->dwHeight;
		if (rSrcRect.right > lpCtx->dwModeWidth)
			rSrcRect.right = lpCtx->dwModeWidth;
		if (rSrcRect.bottom > lpCtx->dwModeHeight)
			rSrcRect.bottom = lpCtx->dwModeHeight;

		if (glb.bWaitForRetrace) {
			// Sync the blit to the vertical retrace
			ZeroMemory(&bltFX, sizeof(bltFX));
			bltFX.dwSize = sizeof(bltFX);
			bltFX.dwDDFX = DDBLTFX_NOTEARING;
			dwBlitFlags = DDBLT_WAIT | DDBLT_DDFX;
			lpBltFX = &bltFX;
		} else {
			dwBlitFlags = DDBLT_WAIT;
			lpBltFX = NULL;
		}

		// Perform the actual blit
		TRY(IDirectDrawSurface4_Blt(
			lpCtx->lpFront4,
			&rDstRect,
			lpCtx->lpBack4, // Blit source
			&rSrcRect,
			dwBlitFlags,
			lpBltFX),
			"dglSwapBuffers: Blt");
	}
#endif // _USE_GLD3_WGL

#ifdef GLD_THREADS
	// Release serialized access
	if (glb.bMultiThreaded)
		LeaveCriticalSection(&CriticalSection);
#endif

    // TODO: Re-instate rendering bitmap snapshot feature??? (DaveM)

	// Render frame is completed
	ValidateRect(hWnd, NULL);
	lpCtx->bFrameStarted = FALSE;

	return TRUE;
}

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