summaryrefslogtreecommitdiffstats
path: root/src/old/d3dapp.cpp
blob: 0614fc35b700be6c9fc5097b18e694e7d05eeca2 (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
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
// * This file is part of the COLOBOT source code
// * Copyright (C) 2001-2008, Daniel ROUX & EPSITEC SA, www.epsitec.ch
// *
// * This program is free software: you can redistribute it and/or modify
// * it under the terms of the GNU General Public License as published by
// * the Free Software Foundation, either version 3 of the License, or
// * (at your option) any later version.
// *
// * This program is distributed in the hope that it will be useful,
// * but WITHOUT ANY WARRANTY; without even the implied warranty of
// * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// * GNU General Public License for more details.
// *
// * You should have received a copy of the GNU General Public License
// * along with this program. If not, see  http://www.gnu.org/licenses/.


#include <windows.h>
#include <winuser.h>
#include <mmsystem.h>
#include <stdio.h>
#include <direct.h>
#include <tchar.h>
#include <zmouse.h>
#include <dinput.h>

#include "common/struct.h"
#include "old/d3dtextr.h"
#include "old/d3dengine.h"
#include "common/language.h"
#include "common/event.h"
#include "common/profile.h"
#include "common/iman.h"
#include "common/restext.h"
#include "old/math3d.h"
#include "old/joystick.h"
#include "object/robotmain.h"
#include "sound/sound.h"
#include "old/d3dapp.h"

// fix for "MSH_MOUSEWHEEL undefined" error
#ifdef UNICODE
#define MSH_MOUSEWHEEL L"MSWHEEL_ROLLMSG"
#else
#define MSH_MOUSEWHEEL "MSWHEEL_ROLLMSG"
#endif


const int AUDIO_TRACK = 13;		// total number of audio tracks on the CD
const float MAX_STEP = 0.2f;		// maximum time for a step

const int WINDOW_DX = (640+6);		// dimensions in windowed mode
const int WINDOW_DY = (480+25);

#define USE_THREAD		false		// true does not work!
const float TIME_THREAD = 0.02f;




// Limit the use of the controls keyboard & joystick.

float AxeLimit(float value)
{
	if ( value < -1.0f )  value = -1.0f;
	if ( value >  1.0f )  value =  1.0f;
	return value;
}


// Entry point to the program. Initializes everything, and goes into a
// message-processing loop. Idle time is used to render the scene.

INT WINAPI WinMain( HINSTANCE hInst, HINSTANCE, LPSTR strCmdLine, INT )
{
	Error	err;
	char	string[100];

	CD3DApplication d3dApp;  // single instance of the application

	err = d3dApp.CheckMistery(strCmdLine);
	if ( err != ERR_OK )
	{
		GetResource(RES_ERR, err, string);
#if _NEWLOOK
		MessageBox( NULL, string, _T("CeeBot"), MB_ICONERROR|MB_OK );
#else
		MessageBox( NULL, string, _T("COLOBOT"), MB_ICONERROR|MB_OK );
#endif
		return 0;
	}

	if ( FAILED(d3dApp.Create(hInst, strCmdLine)) )
	{
		return 0;
	}

	return d3dApp.Run();  // execution of all
}


// Internal variables and function prototypes.

enum APPMSGTYPE { MSG_NONE, MSGERR_APPMUSTEXIT, MSGWARN_SWITCHEDTOSOFTWARE };

static INT     CALLBACK AboutProc( HWND, UINT, WPARAM, LPARAM );
static LRESULT CALLBACK WndProc( HWND, UINT, WPARAM, LPARAM );

static CD3DApplication* g_pD3DApp;



// Constructor.

CD3DApplication::CD3DApplication()
{
	int		i;

	m_iMan = new(CInstanceManager);
	m_event = new CEvent(m_iMan);

	m_pD3DEngine = 0;
	m_pRobotMain = 0;
	m_pSound     = 0;
	m_pFramework = 0;
	m_instance   = 0;
	m_hWnd       = 0;
	m_pDD        = 0;
	m_pD3D       = 0;
	m_pD3DDevice = 0;

	m_CDpath[0] = 0;

	m_pddsRenderTarget = 0;
	m_pddsDepthBuffer  = 0;

	m_keyState = 0;
	m_axeKey = Math::Vector(0.0f, 0.0f, 0.0f);
	m_axeJoy = Math::Vector(0.0f, 0.0f, 0.0f);

	m_vidMemTotal  = 0;
	m_bActive      = false;
	m_bActivateApp = false;
	m_bReady       = false;
	m_bJoystick    = false;
	m_aTime        = 0.0f;

	for ( i=0 ; i<32 ; i++ )
	{
		m_bJoyButton[i] = false;
	}

#if _NEWLOOK
	m_strWindowTitle  = _T("CeeBot");
#else
	m_strWindowTitle  = _T("COLOBOT");
#endif
	m_bAppUseZBuffer  = true;
	m_bAppUseStereo   = true;
	m_bShowStats      = false;
	m_bDebugMode      = false;
	m_bAudioState     = true;
	m_bAudioTrack     = true;
	m_bNiceMouse      = false;
	m_bSetupMode      = true;
	m_fnConfirmDevice = 0;

	ResetKey();

	g_pD3DApp = this;

	// Request event sent by Logitech.
	m_mshMouseWheel = RegisterWindowMessage(MSH_MOUSEWHEEL); 

	_mkdir("files\\");
}


// Destructor.

CD3DApplication::~CD3DApplication()
{
	delete m_iMan;
}



// Returns the path of the CD.

char* CD3DApplication::RetCDpath()
{
	return m_CDpath;
}

// Reads the information in the registry.

Error CD3DApplication::RegQuery()
{
	FILE*	file = NULL;
	HKEY	key;
	LONG	i;
	DWORD	type, len;
	char	filename[100];

#if _NEWLOOK
 #if _TEEN
	i = RegOpenKeyEx(HKEY_LOCAL_MACHINE, "Software\\Epsitec\\CeeBot-Teen\\Setup",
 #else
	i = RegOpenKeyEx(HKEY_LOCAL_MACHINE, "Software\\Epsitec\\CeeBot-A\\Setup",
 #endif
#else
	i = RegOpenKeyEx(HKEY_LOCAL_MACHINE, "Software\\Epsitec\\Colobot\\Setup",
#endif
					 0, KEY_READ, &key);
	if ( i != ERROR_SUCCESS )  return ERR_INSTALL;

	type = REG_SZ;
	len  = sizeof(m_CDpath);
	i = RegQueryValueEx(key, "CDpath", NULL, &type, (LPBYTE)m_CDpath, &len);
	if ( i != ERROR_SUCCESS || type != REG_SZ )  return ERR_INSTALL;

	filename[0] = m_CDpath[0];
	filename[1] = ':';
	filename[2] = '\\';
	filename[3] = 0;
	i = GetDriveType(filename);
	if ( i != DRIVE_CDROM )  return ERR_NOCD;

	strcat(filename, "install.ini");
	file = fopen(filename, "rb");  // install.ini file exist?
	if ( file == NULL )  return ERR_NOCD;
	fclose(file);

	return ERR_OK;
}

// Checks for audio tracks on the CD.

Error CD3DApplication::AudioQuery()
{
	MCI_OPEN_PARMS		mciOpenParms;
	MCI_STATUS_PARMS	mciStatusParms;
	DWORD				dwReturn;
	UINT				deviceID;
	char				device[10];

	// Open the device by specifying the device and filename.
	// MCI will attempt to choose the MIDI mapper as the output port.
	memset(&mciOpenParms, 0, sizeof(MCI_OPEN_PARMS));
	mciOpenParms.lpstrDeviceType = (LPCTSTR)MCI_DEVTYPE_CD_AUDIO;
	if ( m_CDpath[0] == 0 )
	{
		dwReturn = mciSendCommand(NULL,
								  MCI_OPEN,
								  MCI_OPEN_TYPE|MCI_OPEN_TYPE_ID,
								  (DWORD)(LPVOID)&mciOpenParms);
	}
	else
	{
		device[0] = m_CDpath[0];
		device[1] = ':';
		device[2] = 0;
		mciOpenParms.lpstrElementName = device;
		dwReturn = mciSendCommand(NULL,
								  MCI_OPEN,
								  MCI_OPEN_TYPE|MCI_OPEN_TYPE_ID|MCI_OPEN_ELEMENT,
								  (DWORD)(LPVOID)&mciOpenParms);
	}
	if ( dwReturn != 0 )
	{
		return ERR_NOCD;
	}

	// The device opened successfully; get the device ID.
	deviceID = mciOpenParms.wDeviceID;

	memset(&mciStatusParms, 0, sizeof(MCI_STATUS_PARMS));
	mciStatusParms.dwItem = MCI_STATUS_NUMBER_OF_TRACKS;
	dwReturn = mciSendCommand(deviceID,
							  MCI_STATUS,
							  MCI_WAIT|MCI_STATUS_ITEM,
							  (DWORD)&mciStatusParms);
	if ( dwReturn != 0 )
	{
		mciSendCommand(deviceID, MCI_CLOSE, 0, NULL);
		return ERR_NOCD;
	}

	if ( mciStatusParms.dwReturn != AUDIO_TRACK )
	{
		mciSendCommand(deviceID, MCI_CLOSE, 0, NULL);
		return ERR_NOCD;
	}

	mciSendCommand(deviceID, MCI_CLOSE, 0, NULL);
	return ERR_OK;
}

// Checks for the key.

Error CD3DApplication::CheckMistery(char *strCmdLine)
{
	if ( strstr(strCmdLine, "-debug") != 0 )
	{
		m_bShowStats = true;
		SetDebugMode(true);
	}

	if ( strstr(strCmdLine, "-audiostate") != 0 )
	{
		m_bAudioState = false;
	}

	if ( strstr(strCmdLine, "-audiotrack") != 0 )
	{
		m_bAudioTrack = false;
	}

	m_CDpath[0] = 0;
#if _FULL
	if ( strstr(strCmdLine, "-nocd") == 0 && !m_bDebugMode )
	{
		Error	err;

		err = RegQuery();
		if ( err != ERR_OK )  return err;

		//?err = AudioQuery();
		//?if ( err != ERR_OK )  return err;
	}
#endif
#if _SCHOOL & _EDU
	if ( strstr(strCmdLine, "-nosetup") != 0 )
	{
		m_bSetupMode = false;
	}
	m_bAudioTrack = false;
#endif
#if _SCHOOL & _PERSO
	Error err = RegQuery();
	if ( err != ERR_OK )  return err;
	m_bAudioTrack = false;
#endif
#if _SCHOOL & _CEEBOTDEMO
	m_bAudioTrack = false;
#endif
#if _NET
	m_bAudioTrack = false;
#endif
#if _DEMO
	m_bAudioTrack = false;
#endif

	return ERR_OK;
}


// Returns the total amount of video memory for textures.

int CD3DApplication::GetVidMemTotal()
{
	return m_vidMemTotal;
}

bool CD3DApplication::IsVideo8MB()
{
	if ( m_vidMemTotal == 0 )  return false;
	return (m_vidMemTotal <= 8388608L);  // 8 Mb or less (2 ^ 23)?
}

bool CD3DApplication::IsVideo32MB()
{
	if ( m_vidMemTotal == 0 )  return false;
	return (m_vidMemTotal > 16777216L);  // more than 16 Mb (2 ^ 24)?
}


void CD3DApplication::SetShowStat(bool bShow)
{
	m_bShowStats = bShow;
}

bool CD3DApplication::RetShowStat()
{
	return m_bShowStats;
}


void CD3DApplication::SetDebugMode(bool bMode)
{
	m_bDebugMode = bMode;
	D3DTextr_SetDebugMode(m_bDebugMode);
}

bool CD3DApplication::RetDebugMode()
{
	return m_bDebugMode;
}

bool CD3DApplication::RetSetupMode()
{
	return m_bSetupMode;
}




// Son process of time management.

DWORD WINAPI ThreadRoutine(LPVOID)
{
	Event	event;
	float	time;
	int		ms, start, end, delay;

	ms = (int)(TIME_THREAD*1000.0f);
	time = 0.0f;
	while ( true )
	{
		start = timeGetTime();

		g_pD3DApp->m_pD3DEngine->FrameMove(TIME_THREAD);

		ZeroMemory(&event, sizeof(Event));
		event.event = EVENT_FRAME;
		event.rTime = TIME_THREAD;
		event.axeX = AxeLimit(g_pD3DApp->m_axeKey.x + g_pD3DApp->m_axeJoy.x);
		event.axeY = AxeLimit(g_pD3DApp->m_axeKey.y + g_pD3DApp->m_axeJoy.y);
		event.axeZ = AxeLimit(g_pD3DApp->m_axeKey.z + g_pD3DApp->m_axeJoy.z);
		event.keyState = g_pD3DApp->m_keyState;

		if ( g_pD3DApp->m_pRobotMain != 0 )
		{
			g_pD3DApp->m_pRobotMain->EventProcess(event);
		}

		end = timeGetTime();

		delay = ms-(end-start);
		if ( delay > 0 )
		{
			Sleep(delay);  // waiting 20ms-used
		}
		time += TIME_THREAD;
	}
	return 0;
}


// Called during device intialization, this code checks the device
// for some minimum set of capabilities.

HRESULT CD3DApplication::ConfirmDevice( DDCAPS* pddDriverCaps,
									    D3DDEVICEDESC7* pd3dDeviceDesc )
{
//?	if( pd3dDeviceDesc->wMaxVertexBlendMatrices < 2 )
//?		return E_FAIL;

    return S_OK;
}

// Create the application.

HRESULT CD3DApplication::Create( HINSTANCE hInst, TCHAR* strCmdLine )
{
	HRESULT hr;
	char	deviceName[100];
	char	modeName[100];
	int		iValue;
	DWORD	style;
	bool	bFull, b3D;

	m_instance = hInst;

	InitCurrentDirectory();

	// Enumerate available D3D devices. The callback is used so the app can
	// confirm/reject each enumerated device depending on its capabilities.
	if( FAILED( hr = D3DEnum_EnumerateDevices( m_fnConfirmDevice ) ) )
	{
		DisplayFrameworkError( hr, MSGERR_APPMUSTEXIT );
		return hr;
	}

	if( FAILED( hr = D3DEnum_SelectDefaultDevice( &m_pDeviceInfo ) ) )
	{
		DisplayFrameworkError( hr, MSGERR_APPMUSTEXIT );
		return hr;
	}

	if ( !m_bDebugMode )
	{
		m_pDeviceInfo->bWindowed = false;  // full screen
	}
	if ( GetProfileInt("Device", "FullScreen", bFull) )
	{
		m_pDeviceInfo->bWindowed = !bFull;
	}
	m_pDeviceInfo->bWindowed = true;

	// Create the 3D engine.
	if( (m_pD3DEngine = new CD3DEngine(m_iMan, this)) == NULL )
	{
		DisplayFrameworkError( D3DENUMERR_ENGINE, MSGERR_APPMUSTEXIT );
		return E_OUTOFMEMORY;
	}
	SetEngine(m_pD3DEngine);

	// Initialize the app's custom scene stuff
	if( FAILED( hr = m_pD3DEngine->OneTimeSceneInit() ) )
	{
		DisplayFrameworkError( hr, MSGERR_APPMUSTEXIT );
		return hr;
	}

	// Create a new CD3DFramework class. This class does all of our D3D
	// initialization and manages the common D3D objects.
	if( (m_pFramework = new CD3DFramework7()) == NULL )
	{
		DisplayFrameworkError( E_OUTOFMEMORY, MSGERR_APPMUSTEXIT );
		return E_OUTOFMEMORY;
	}

	// Create the sound instance.
	if( (m_pSound = new CSound(m_iMan)) == NULL )
	{
		DisplayFrameworkError( D3DENUMERR_SOUND, MSGERR_APPMUSTEXIT );
		return E_OUTOFMEMORY;
	}

	// Create the robot application.
	if( (m_pRobotMain = new CRobotMain(m_iMan)) == NULL )
	{
		DisplayFrameworkError( D3DENUMERR_ROBOT, MSGERR_APPMUSTEXIT );
		return E_OUTOFMEMORY;
	}

	// Register the window class
	WNDCLASS wndClass = { 0, WndProc, 0, 0, hInst,
						  LoadIcon( hInst, MAKEINTRESOURCE(IDI_MAIN_ICON) ),
						  LoadCursor( NULL, IDC_ARROW ), 
						  (HBRUSH)GetStockObject(WHITE_BRUSH),
						  NULL, _T("D3D Window") };
	RegisterClass( &wndClass );

	// Create the render window
	style = WS_CAPTION|WS_VISIBLE;
	if ( m_bDebugMode )  style |= WS_SYSMENU;  // close box
	m_hWnd = CreateWindow( _T("D3D Window"), m_strWindowTitle,
//?						   WS_OVERLAPPEDWINDOW|WS_VISIBLE,
						   style, CW_USEDEFAULT, CW_USEDEFAULT,
						   WINDOW_DX, WINDOW_DY, 0L,
//?						   LoadMenu( hInst, MAKEINTRESOURCE(IDR_MENU) ), 
						   NULL,
						   hInst, 0L );
	UpdateWindow( m_hWnd );

	if ( !GetProfileInt("Setup", "Sound3D", b3D) )
	{
		b3D = true;
	}
	m_pSound->SetDebugMode(m_bDebugMode);
	m_pSound->Create(m_hWnd, b3D);
	m_pSound->CacheAll();
	m_pSound->SetState(m_bAudioState);
	m_pSound->SetAudioTrack(m_bAudioTrack);
	m_pSound->SetCDpath(m_CDpath);

	// Initialize the 3D environment for the app
	if( FAILED( hr = Initialize3DEnvironment() ) )
	{
		DisplayFrameworkError( hr, MSGERR_APPMUSTEXIT );
		Cleanup3DEnvironment();
		return E_FAIL;
	}

	// Change the display device driver.
	GetProfileString("Device", "Name", deviceName, 100);
	GetProfileString("Device", "Mode", modeName, 100);
	GetProfileInt("Device", "FullScreen", bFull);
	if ( deviceName[0] != 0 && modeName[0] != 0 && bFull )
	{
		ChangeDevice(deviceName, modeName, bFull);
	}

	// First execution?
	if ( !GetProfileInt("Setup", "ObjectDirty", iValue) )
	{
		m_pD3DEngine->FirstExecuteAdapt(true);
	}

	// Creates the file colobot.ini at the first execution.
	m_pRobotMain->CreateIni();

#if _DEMO
	m_pRobotMain->ChangePhase(PHASE_NAME);
#else
#if _NET | _SCHOOL
	m_pRobotMain->ChangePhase(PHASE_WELCOME2);
#else
#if _FRENCH
	m_pRobotMain->ChangePhase(PHASE_WELCOME2);
#endif
#if _ENGLISH
	m_pRobotMain->ChangePhase(PHASE_WELCOME2);
#endif
#if _GERMAN
	m_pRobotMain->ChangePhase(PHASE_WELCOME2);
#endif
#if _WG
	m_pRobotMain->ChangePhase(PHASE_WELCOME1);
#endif
#if _POLISH
	m_pRobotMain->ChangePhase(PHASE_WELCOME1);
#endif
#endif
#endif
	m_pD3DEngine->TimeInit();

#if USE_THREAD
	m_thread = CreateThread(NULL, 0, ThreadRoutine, this, 0, &m_threadId);
	SetThreadPriority(m_thread, THREAD_PRIORITY_ABOVE_NORMAL);
#endif

	// The app is ready to go
	m_bReady = true;

	return S_OK;
}


// Message-processing loop. Idle time is used to render the scene.

INT CD3DApplication::Run()
{
	// Load keyboard accelerators
	HACCEL hAccel = LoadAccelerators( NULL, MAKEINTRESOURCE(IDR_MAIN_ACCEL) );

	// Now we're ready to recieve and process Windows messages.
	bool bGotMsg;
	MSG  msg;
	PeekMessage( &msg, NULL, 0U, 0U, PM_NOREMOVE );

	while( WM_QUIT != msg.message  )
	{
		// Use PeekMessage() if the app is active, so we can use idle time to
		// render the scene. Else, use GetMessage() to avoid eating CPU time.
		if( m_bActive )
			bGotMsg = PeekMessage( &msg, NULL, 0U, 0U, PM_REMOVE );
		else
			bGotMsg = GetMessage( &msg, NULL, 0U, 0U );

		if( bGotMsg )
		{
			// Translate and dispatch the message
			if( TranslateAccelerator( m_hWnd, hAccel, &msg ) == 0 )
			{
				TranslateMessage( &msg );
				DispatchMessage( &msg );
			}
		}
		else
		{
			// Render a frame during idle time (no messages are waiting)
			if( m_bActive && m_bReady )
			{
				Event	event;

				while ( m_event->GetEvent(event) )
				{
					if ( event.event == EVENT_QUIT )
					{
//? 					SendMessage( m_hWnd, WM_CLOSE, 0, 0 );
						m_pSound->StopMusic();
						Cleanup3DEnvironment();
						PostQuitMessage(0);
						return msg.wParam;
					}
					m_pRobotMain->EventProcess(event);
				}

				if ( !RetNiceMouse() )
				{
					SetMouseType(m_pD3DEngine->RetMouseType());
				}

				if( FAILED( Render3DEnvironment() ) )
					DestroyWindow( m_hWnd );
			}
		}
	}

	return msg.wParam;
}



// Conversion of the position of the mouse.
// x: 0=left, 1=right
// y: 0=down, 1=up

Math::Point CD3DApplication::ConvPosToInterface(HWND hWnd, LPARAM lParam)
{
	POINT	cpos;
	Math::Point	pos;
	float	px, py, w, h;

	cpos.x = (short)LOWORD(lParam);
	cpos.y = (short)HIWORD(lParam);

	if ( !m_pDeviceInfo->bWindowed )
	{
		ClientToScreen(hWnd, &cpos);
	}

	px = (float)cpos.x;
	py = (float)cpos.y;
	w  = (float)m_ddsdRenderTarget.dwWidth;
	h  = (float)m_ddsdRenderTarget.dwHeight;

	pos.x = px/w;
	pos.y = 1.0f-py/h;

	return pos;
}

// Physically moves the mouse.

void CD3DApplication::SetMousePos(Math::Point pos)
{
	POINT	p;

	pos.y = 1.0f-pos.y;

	pos.x *= m_ddsdRenderTarget.dwWidth;
	pos.y *= m_ddsdRenderTarget.dwHeight;

	p.x = (int)pos.x;
	p.y = (int)pos.y;
	ClientToScreen(m_hWnd, &p);
	
	SetCursorPos(p.x, p.y);
}

// Choosing the type of cursor for the mouse.

void CD3DApplication::SetMouseType(D3DMouse type)
{
	HCURSOR		hc;

	if ( type == D3DMOUSEHAND )
	{
		hc = LoadCursor(m_instance, MAKEINTRESOURCE(IDC_CURSORHAND));
	}
	else if ( type == D3DMOUSECROSS )
	{
		hc = LoadCursor(NULL, IDC_CROSS);
	}
	else if ( type == D3DMOUSEEDIT )
	{
		hc = LoadCursor(NULL, IDC_IBEAM);
	}
	else if ( type == D3DMOUSENO )
	{
		hc = LoadCursor(NULL, IDC_NO);
	}
	else if ( type == D3DMOUSEMOVE )
	{
		hc = LoadCursor(NULL, IDC_SIZEALL);
	}
	else if ( type == D3DMOUSEMOVEH )
	{
		hc = LoadCursor(NULL, IDC_SIZEWE);
	}
	else if ( type == D3DMOUSEMOVEV )
	{
		hc = LoadCursor(NULL, IDC_SIZENS);
	}
	else if ( type == D3DMOUSEMOVED )
	{
		hc = LoadCursor(NULL, IDC_SIZENESW);
	}
	else if ( type == D3DMOUSEMOVEI )
	{
		hc = LoadCursor(NULL, IDC_SIZENWSE);
	}
	else if ( type == D3DMOUSEWAIT )
	{
		hc = LoadCursor(NULL, IDC_WAIT);
	}
	else if ( type == D3DMOUSESCROLLL )
	{
		hc = LoadCursor(m_instance, MAKEINTRESOURCE(IDC_CURSORSCROLLL));
	}
	else if ( type == D3DMOUSESCROLLR )
	{
		hc = LoadCursor(m_instance, MAKEINTRESOURCE(IDC_CURSORSCROLLR));
	}
	else if ( type == D3DMOUSESCROLLU )
	{
		hc = LoadCursor(m_instance, MAKEINTRESOURCE(IDC_CURSORSCROLLU));
	}
	else if ( type == D3DMOUSESCROLLD )
	{
		hc = LoadCursor(m_instance, MAKEINTRESOURCE(IDC_CURSORSCROLLD));
	}
	else if ( type == D3DMOUSETARGET )
	{
		hc = LoadCursor(m_instance, MAKEINTRESOURCE(IDC_CURSORTARGET));
	}
	else
	{
		hc = LoadCursor(NULL, IDC_ARROW);
	}

	if ( hc != NULL )
	{
		SetCursor(hc);
	}
}

// Choice of mode for the mouse.

void CD3DApplication::SetNiceMouse(bool bNice)
{
	if ( bNice == m_bNiceMouse )  return;
	m_bNiceMouse = bNice;

	if ( m_bNiceMouse )
	{
		ShowCursor(false);  // hides the ugly windows mouse
		SetCursor(NULL);
	}
	else
	{
		ShowCursor(true);  // shows the ugly windows mouse
		SetCursor(LoadCursor(NULL, IDC_ARROW));
	}
}

// Whether to use the mouse pretty shaded.

bool CD3DApplication::RetNiceMouse()
{
	if (  m_pDeviceInfo->bWindowed )  return false;
	if ( !m_pDeviceInfo->bHardware )  return false;

	return m_bNiceMouse;
}

// Indicates whether it is possible to use the mouse pretty shaded.

bool CD3DApplication::RetNiceMouseCap()
{
	if (  m_pDeviceInfo->bWindowed )  return false;
	if ( !m_pDeviceInfo->bHardware )  return false;

	return true;
}


// Static msg handler which passes messages to the application class.

LRESULT CALLBACK WndProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam )
{
	if ( g_pD3DApp != 0 )
	{
		Event	event;
		short	move;

		ZeroMemory(&event, sizeof(Event));

#if 0
		if ( uMsg == WM_KEYDOWN ||
			 uMsg == WM_CHAR ||
			 uMsg == WM_XBUTTONDOWN ||
			 uMsg == WM_XBUTTONUP )
		{
			char s[100];
			sprintf(s, "event: %d %d %d\n", uMsg, wParam, lParam);
			OutputDebugString(s);
		}
#endif

		if ( uMsg == WM_LBUTTONDOWN )  event.event = EVENT_LBUTTONDOWN;
		if ( uMsg == WM_RBUTTONDOWN )  event.event = EVENT_RBUTTONDOWN;
		if ( uMsg == WM_LBUTTONUP   )  event.event = EVENT_LBUTTONUP;
		if ( uMsg == WM_RBUTTONUP   )  event.event = EVENT_RBUTTONUP;
		if ( uMsg == WM_MOUSEMOVE   )  event.event = EVENT_MOUSEMOVE;
		if ( uMsg == WM_KEYDOWN     )  event.event = EVENT_KEYDOWN;
		if ( uMsg == WM_KEYUP       )  event.event = EVENT_KEYUP;
		if ( uMsg == WM_CHAR        )  event.event = EVENT_CHAR;

		if ( uMsg == WM_XBUTTONUP )
		{
			if ( (wParam>>16) == XBUTTON1 )  event.event = EVENT_HYPER_PREV;
			if ( (wParam>>16) == XBUTTON2 )  event.event = EVENT_HYPER_NEXT;
		}

		event.param = wParam;
		event.axeX = AxeLimit(g_pD3DApp->m_axeKey.x + g_pD3DApp->m_axeJoy.x);
		event.axeY = AxeLimit(g_pD3DApp->m_axeKey.y + g_pD3DApp->m_axeJoy.y);
		event.axeZ = AxeLimit(g_pD3DApp->m_axeKey.z + g_pD3DApp->m_axeJoy.z);
		event.keyState = g_pD3DApp->m_keyState;

		if ( uMsg == WM_LBUTTONDOWN ||
			 uMsg == WM_RBUTTONDOWN ||
			 uMsg == WM_LBUTTONUP   ||
			 uMsg == WM_RBUTTONUP   ||
			 uMsg == WM_MOUSEMOVE   )  // mouse event?
		{
			event.pos = g_pD3DApp->ConvPosToInterface(hWnd, lParam);
			g_pD3DApp->m_mousePos = event.pos;
			g_pD3DApp->m_pD3DEngine->SetMousePos(event.pos);
		}

		if ( uMsg == WM_MOUSEWHEEL )  // mouse wheel?
		{
			event.event = EVENT_KEYDOWN;
			event.pos = g_pD3DApp->m_mousePos;
			move = HIWORD(wParam);
			if ( move/WHEEL_DELTA > 0 )  event.param = VK_WHEELUP;
			if ( move/WHEEL_DELTA < 0 )  event.param = VK_WHEELDOWN;
		}
		if ( g_pD3DApp->m_mshMouseWheel != 0 &&
			 uMsg == g_pD3DApp->m_mshMouseWheel )  // Logitech mouse wheel?
		{
			event.event = EVENT_KEYDOWN;
			event.pos = g_pD3DApp->m_mousePos;
			move = LOWORD(wParam);
			if ( move/WHEEL_DELTA > 0 )  event.param = VK_WHEELUP;
			if ( move/WHEEL_DELTA < 0 )  event.param = VK_WHEELDOWN;
		}

		if ( event.event == EVENT_KEYDOWN ||
			 event.event == EVENT_KEYUP   ||
			 event.event == EVENT_CHAR    )
		{
			if ( event.param == 0 )
			{
				event.event = EVENT_NULL;
			}
		}

		if ( g_pD3DApp->m_pRobotMain != 0 && event.event != 0 )
		{
			g_pD3DApp->m_pRobotMain->EventProcess(event);
//?			if ( !g_pD3DApp->RetNiceMouse() )
//?			{
//?				g_pD3DApp->SetMouseType(g_pD3DApp->m_pD3DEngine->RetMouseType());
//?			}
		}
		if ( g_pD3DApp->m_pD3DEngine != 0 )
		{
			g_pD3DApp->m_pD3DEngine->MsgProc( hWnd, uMsg, wParam, lParam );
		}
		return g_pD3DApp->MsgProc( hWnd, uMsg, wParam, lParam );
	}

	return DefWindowProc( hWnd, uMsg, wParam, lParam );
}


// Minimal message proc function for the about box.

BOOL CALLBACK AboutProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM )
{
    if( WM_COMMAND == uMsg )
        if( IDOK == LOWORD(wParam) || IDCANCEL == LOWORD(wParam) )
            EndDialog( hWnd, TRUE );

    return WM_INITDIALOG == uMsg ? TRUE : FALSE;
}



// Ignore keypresses.

void CD3DApplication::FlushPressKey()
{
	m_keyState = 0;
	m_axeKey = Math::Vector(0.0f, 0.0f, 0.0f);
	m_axeJoy = Math::Vector(0.0f, 0.0f, 0.0f);
}

// Resets the default keys.

void CD3DApplication::ResetKey()
{
	int		i;

	for ( i=0 ; i<50 ; i++ )
	{
		m_key[i][0] = 0;
		m_key[i][1] = 0;
	}
	m_key[KEYRANK_LEFT   ][0] = VK_LEFT;
	m_key[KEYRANK_RIGHT  ][0] = VK_RIGHT;
	m_key[KEYRANK_UP     ][0] = VK_UP;
	m_key[KEYRANK_DOWN   ][0] = VK_DOWN;
	m_key[KEYRANK_GUP    ][0] = VK_SHIFT;
	m_key[KEYRANK_GDOWN  ][0] = VK_CONTROL;
	m_key[KEYRANK_CAMERA ][0] = VK_SPACE;
	m_key[KEYRANK_CAMERA ][1] = VK_BUTTON2;
	m_key[KEYRANK_DESEL  ][0] = VK_NUMPAD0;
	m_key[KEYRANK_DESEL  ][1] = VK_BUTTON6;
	m_key[KEYRANK_ACTION ][0] = VK_RETURN;
	m_key[KEYRANK_ACTION ][1] = VK_BUTTON1;
	m_key[KEYRANK_NEAR   ][0] = VK_ADD;
	m_key[KEYRANK_NEAR   ][1] = VK_BUTTON5;
	m_key[KEYRANK_AWAY   ][0] = VK_SUBTRACT;
	m_key[KEYRANK_AWAY   ][1] = VK_BUTTON4;
	m_key[KEYRANK_NEXT   ][0] = VK_TAB;
	m_key[KEYRANK_NEXT   ][1] = VK_BUTTON3;
	m_key[KEYRANK_HUMAN  ][0] = VK_HOME;
	m_key[KEYRANK_HUMAN  ][1] = VK_BUTTON7;
	m_key[KEYRANK_QUIT   ][0] = VK_ESCAPE;
	m_key[KEYRANK_HELP   ][0] = VK_F1;
	m_key[KEYRANK_PROG   ][0] = VK_F2;
	m_key[KEYRANK_CBOT   ][0] = VK_F3;
	m_key[KEYRANK_VISIT  ][0] = VK_DECIMAL;
	m_key[KEYRANK_SPEED10][0] = VK_F4;
	m_key[KEYRANK_SPEED15][0] = VK_F5;
	m_key[KEYRANK_SPEED20][0] = VK_F6;
//	m_key[KEYRANK_SPEED30][0] = VK_F7;
}

// Modifies a button.

void CD3DApplication::SetKey(int keyRank, int option, int key)
{
	if ( keyRank <  0  ||
		 keyRank >= 50 )  return;

	if ( option <  0 ||
		 option >= 2 )  return;

	m_key[keyRank][option] = key;
}

// Gives a hint.

int CD3DApplication::RetKey(int keyRank, int option)
{
	if ( keyRank <  0  ||
		 keyRank >= 50 )  return 0;

	if ( option <  0 ||
		 option >= 2 )  return 0;

	return m_key[keyRank][option];
}



// Use the joystick or keyboard.

void CD3DApplication::SetJoystick(bool bEnable)
{
	m_bJoystick = bEnable;

	if ( m_bJoystick )  // joystick ?
	{
		if ( !InitDirectInput(m_instance, m_hWnd) )  // initialise joystick
		{
			m_bJoystick = false;
		}
		else
		{
			SetAcquire(true);
			SetTimer(m_hWnd, 0, 1000/30, NULL);
		}
	}
	else	// keyboard?
	{
        KillTimer(m_hWnd, 0);
		SetAcquire(false);
		FreeDirectInput();
	}
}

bool CD3DApplication::RetJoystick()
{
	return m_bJoystick;
}


// Message handling function.

LRESULT CD3DApplication::MsgProc( HWND hWnd, UINT uMsg, WPARAM wParam,
                                  LPARAM lParam )
{
    HRESULT		hr;
	DIJOYSTATE	js;
	int			i;

	// The F10 key sends another message to activate
	// menu in standard Windows applications!
	if ( uMsg == WM_SYSKEYDOWN && wParam == VK_F10 )
	{
		uMsg = WM_KEYDOWN;
	}
	if ( uMsg == WM_SYSKEYUP && wParam == VK_F10 )
	{
		uMsg = WM_KEYUP;
	}

	// Mange event "menu" sent by Alt or F10.
	if ( uMsg == WM_SYSCOMMAND && wParam == SC_KEYMENU )
	{
		return 0;
	}

	if ( uMsg == WM_KEYDOWN || uMsg == WM_KEYUP )
	{
		if ( GetKeyState(VK_SHIFT) & 0x8000 )
		{
			m_keyState |= KS_SHIFT;
		}
		else
		{
			m_keyState &= ~KS_SHIFT;
		}

		if ( GetKeyState(VK_CONTROL) & 0x8000 )
		{
			m_keyState |= KS_CONTROL;
		}
		else
		{
			m_keyState &= ~KS_CONTROL;
		}
	}

	switch( uMsg )
	{
		case WM_KEYDOWN:
			if ( wParam == m_key[KEYRANK_UP   ][0] )  m_axeKey.y =  1.0f;
			if ( wParam == m_key[KEYRANK_UP   ][1] )  m_axeKey.y =  1.0f;
			if ( wParam == m_key[KEYRANK_DOWN ][0] )  m_axeKey.y = -1.0f;
			if ( wParam == m_key[KEYRANK_DOWN ][1] )  m_axeKey.y = -1.0f;
			if ( wParam == m_key[KEYRANK_LEFT ][0] )  m_axeKey.x = -1.0f;
			if ( wParam == m_key[KEYRANK_LEFT ][1] )  m_axeKey.x = -1.0f;
			if ( wParam == m_key[KEYRANK_RIGHT][0] )  m_axeKey.x =  1.0f;
			if ( wParam == m_key[KEYRANK_RIGHT][1] )  m_axeKey.x =  1.0f;
			if ( wParam == m_key[KEYRANK_GUP  ][0] )  m_axeKey.z =  1.0f;
			if ( wParam == m_key[KEYRANK_GUP  ][1] )  m_axeKey.z =  1.0f;
			if ( wParam == m_key[KEYRANK_GDOWN][0] )  m_axeKey.z = -1.0f;
			if ( wParam == m_key[KEYRANK_GDOWN][1] )  m_axeKey.z = -1.0f;
			if ( wParam == m_key[KEYRANK_NEAR ][0] )  m_keyState |= KS_NUMPLUS;
			if ( wParam == m_key[KEYRANK_NEAR ][1] )  m_keyState |= KS_NUMPLUS;
			if ( wParam == m_key[KEYRANK_AWAY ][0] )  m_keyState |= KS_NUMMINUS;
			if ( wParam == m_key[KEYRANK_AWAY ][1] )  m_keyState |= KS_NUMMINUS;
			if ( wParam == VK_PRIOR                )  m_keyState |= KS_PAGEUP;
			if ( wParam == VK_NEXT                 )  m_keyState |= KS_PAGEDOWN;
//?			if ( wParam == VK_SHIFT                )  m_keyState |= KS_SHIFT;
//?			if ( wParam == VK_CONTROL              )  m_keyState |= KS_CONTROL;
			if ( wParam == VK_NUMPAD8              )  m_keyState |= KS_NUMUP;
			if ( wParam == VK_NUMPAD2              )  m_keyState |= KS_NUMDOWN;
			if ( wParam == VK_NUMPAD4              )  m_keyState |= KS_NUMLEFT;
			if ( wParam == VK_NUMPAD6              )  m_keyState |= KS_NUMRIGHT;
			break;

		case WM_KEYUP:
			if ( wParam == m_key[KEYRANK_UP   ][0] )  m_axeKey.y = 0.0f;
			if ( wParam == m_key[KEYRANK_UP   ][1] )  m_axeKey.y = 0.0f;
			if ( wParam == m_key[KEYRANK_DOWN ][0] )  m_axeKey.y = 0.0f;
			if ( wParam == m_key[KEYRANK_DOWN ][1] )  m_axeKey.y = 0.0f;
			if ( wParam == m_key[KEYRANK_LEFT ][0] )  m_axeKey.x = 0.0f;
			if ( wParam == m_key[KEYRANK_LEFT ][1] )  m_axeKey.x = 0.0f;
			if ( wParam == m_key[KEYRANK_RIGHT][0] )  m_axeKey.x = 0.0f;
			if ( wParam == m_key[KEYRANK_RIGHT][1] )  m_axeKey.x = 0.0f;
			if ( wParam == m_key[KEYRANK_GUP  ][0] )  m_axeKey.z = 0.0f;
			if ( wParam == m_key[KEYRANK_GUP  ][1] )  m_axeKey.z = 0.0f;
			if ( wParam == m_key[KEYRANK_GDOWN][0] )  m_axeKey.z = 0.0f;
			if ( wParam == m_key[KEYRANK_GDOWN][1] )  m_axeKey.z = 0.0f;
			if ( wParam == m_key[KEYRANK_NEAR ][0] )  m_keyState &= ~KS_NUMPLUS;
			if ( wParam == m_key[KEYRANK_NEAR ][1] )  m_keyState &= ~KS_NUMPLUS;
			if ( wParam == m_key[KEYRANK_AWAY ][0] )  m_keyState &= ~KS_NUMMINUS;
			if ( wParam == m_key[KEYRANK_AWAY ][1] )  m_keyState &= ~KS_NUMMINUS;
			if ( wParam == VK_PRIOR                )  m_keyState &= ~KS_PAGEUP;
			if ( wParam == VK_NEXT                 )  m_keyState &= ~KS_PAGEDOWN;
//?			if ( wParam == VK_SHIFT                )  m_keyState &= ~KS_SHIFT;
//?			if ( wParam == VK_CONTROL              )  m_keyState &= ~KS_CONTROL;
			if ( wParam == VK_NUMPAD8              )  m_keyState &= ~KS_NUMUP;
			if ( wParam == VK_NUMPAD2              )  m_keyState &= ~KS_NUMDOWN;
			if ( wParam == VK_NUMPAD4              )  m_keyState &= ~KS_NUMLEFT;
			if ( wParam == VK_NUMPAD6              )  m_keyState &= ~KS_NUMRIGHT;
			break;

		case WM_LBUTTONDOWN:
			m_keyState |= KS_MLEFT;
			break;

		case WM_RBUTTONDOWN:
			m_keyState |= KS_MRIGHT;
			break;

		case WM_LBUTTONUP:
			m_keyState &= ~KS_MLEFT;
			break;

		case WM_RBUTTONUP:
			m_keyState &= ~KS_MRIGHT;
			break;

        case WM_PAINT:
            // Handle paint messages when the app is not ready
            if( m_pFramework && !m_bReady )
            {
                if( m_pDeviceInfo->bWindowed )
                    m_pFramework->ShowFrame();
                else
                    m_pFramework->FlipToGDISurface( true );
            }
            break;

        case WM_MOVE:
            // If in windowed mode, move the Framework's window
            if( m_pFramework && m_bActive && m_bReady && m_pDeviceInfo->bWindowed )
                m_pFramework->Move( (SHORT)LOWORD(lParam), (SHORT)HIWORD(lParam) );
            break;

        case WM_SIZE:
            // Check to see if we are losing our window...
            if( SIZE_MAXHIDE==wParam || SIZE_MINIMIZED==wParam )
			{
                m_bActive = false;
			}
            else
			{
                m_bActive = true;
			}
//?			char s[100];
//?			sprintf(s, "WM_SIZE %d %d %d\n", m_bActive, m_bReady, m_pDeviceInfo->bWindowed);
//?			OutputDebugString(s);

            // A new window size will require a new backbuffer
            // size, so the 3D structures must be changed accordingly.
            if( m_bActive && m_bReady && m_pDeviceInfo->bWindowed )
            {
                m_bReady = false;

//?				OutputDebugString("WM_SIZE Change3DEnvironment\n");
                if( FAILED( hr = Change3DEnvironment() ) )
                    return 0;

                m_bReady = true;
            }
            break;

        case WM_TIMER:
			if ( m_bActivateApp && m_bJoystick )
			{
                if ( UpdateInputState(js) )
				{
					m_axeJoy.x =  js.lX/1000.0f+js.lRz/1000.0f;  // tourner
					m_axeJoy.y = -js.lY/1000.0f;  // avancer
					m_axeJoy.z = -js.rglSlider[0]/1000.0f;  // monter

					m_axeJoy.x = Math::Neutral(m_axeJoy.x, 0.2f);
					m_axeJoy.y = Math::Neutral(m_axeJoy.y, 0.2f);
					m_axeJoy.z = Math::Neutral(m_axeJoy.z, 0.2f);

//?					char s[100];
//?					sprintf(s, "x=%d y=%d z=%  x=%d y=%d z=%d\n", js.lX,js.lY,js.lZ,js.lRx,js.lRy,js.lRz);
//?					OutputDebugString(s);

					for ( i=0 ; i<32 ; i++ )
					{
						if ( js.rgbButtons[i] != 0 && !m_bJoyButton[i] )
						{
							m_bJoyButton[i] = true;
							PostMessage(m_hWnd, WM_KEYDOWN, VK_BUTTON1+i, 0);
						}
						if ( js.rgbButtons[i] == 0 && m_bJoyButton[i] )
						{
							m_bJoyButton[i] = false;
							PostMessage(m_hWnd, WM_KEYUP, VK_BUTTON1+i, 0);
						}
					}
				}
				else
				{
					OutputDebugString("UpdateInputState error\n");
				}
			}
			break;

        case WM_ACTIVATE:
            if( LOWORD(wParam) == WA_INACTIVE )
			{
				m_bActivateApp = false;
			}
            else
			{
				m_bActivateApp = true;
			}

			if ( m_bActivateApp && m_bJoystick )
			{
				SetAcquire(true);  // re-enables the joystick
			}
			break;

		case MM_MCINOTIFY:
			if ( wParam == MCI_NOTIFY_SUCCESSFUL )
			{
				OutputDebugString("Event MM_MCINOTIFY\n");
				m_pSound->SuspendMusic();
				m_pSound->RestartMusic();
			}
			break;

        case WM_SETCURSOR:
            // Prevent a cursor in fullscreen mode
            if( m_bActive && m_bReady && !m_pDeviceInfo->bWindowed )
            {
//?             SetCursor(NULL);
                return 1;
            }
            break;

        case WM_ENTERMENULOOP:
            // Pause the app when menus are displayed
            Pause(true);
            break;
        case WM_EXITMENULOOP:
            Pause(false);
            break;

        case WM_ENTERSIZEMOVE:
            // Halt frame movement while the app is sizing or moving
			m_pD3DEngine->TimeEnterGel();
            break;
        case WM_EXITSIZEMOVE:
			m_pD3DEngine->TimeExitGel();
            break;

        case WM_NCHITTEST:
            // Prevent the user from selecting the menu in fullscreen mode
            if( !m_pDeviceInfo->bWindowed )
                return HTCLIENT;

            break;

        case WM_POWERBROADCAST:
            switch( wParam )
            {
                case PBT_APMQUERYSUSPEND:
                    // At this point, the app should save any data for open
                    // network connections, files, etc.., and prepare to go into
                    // a suspended mode.
                    return OnQuerySuspend( (DWORD)lParam );

                case PBT_APMRESUMESUSPEND:
                    // At this point, the app should recover any data, network
                    // connections, files, etc.., and resume running from when
                    // the app was suspended.
                    return OnResumeSuspend( (DWORD)lParam );
            }
            break;

        case WM_SYSCOMMAND:
            // Prevent moving/sizing and power loss in fullscreen mode
            switch( wParam )
            {
                case SC_MOVE:
                case SC_SIZE:
                case SC_MAXIMIZE:
                case SC_MONITORPOWER:
                    if( false == m_pDeviceInfo->bWindowed )
                        return 1;
                    break;
            }
            break;

        case WM_COMMAND:
            switch( LOWORD(wParam) )
            {
                case IDM_CHANGEDEVICE:
                    // Display the device-selection dialog box.
                    if( m_bActive && m_bReady )
                    {
                        Pause(true);

                        if( SUCCEEDED( D3DEnum_UserChangeDevice( &m_pDeviceInfo ) ) )
                        {
                            if( FAILED( hr = Change3DEnvironment() ) )
                                return 0;
                        }
                        Pause(false);
                    }
                    return 0;

                case IDM_ABOUT:
                    // Display the About box
                    Pause(true);
                    DialogBox( (HINSTANCE)GetWindowLong( hWnd, GWL_HINSTANCE ),
                               MAKEINTRESOURCE(IDD_ABOUT), hWnd, AboutProc );
                    Pause(false);
                    return 0;

                case IDM_EXIT:
                    // Recieved key/menu command to exit app
                    SendMessage( hWnd, WM_CLOSE, 0, 0 );
                    return 0;
            }
            break;

        case WM_GETMINMAXINFO:
            ((MINMAXINFO*)lParam)->ptMinTrackSize.x = 100;
            ((MINMAXINFO*)lParam)->ptMinTrackSize.y = 100;
            break;

        case WM_CLOSE:
            DestroyWindow( hWnd );
            return 0;

        case WM_DESTROY:
            Cleanup3DEnvironment();
            PostQuitMessage(0);
            return 0;
	}

	return DefWindowProc( hWnd, uMsg, wParam, lParam );
}

            
// Enumeration function to report valid pixel formats for z-buffers.

HRESULT WINAPI EnumZBufferFormatsCallback(DDPIXELFORMAT* pddpf,
										  VOID* pContext)
{
    DDPIXELFORMAT* pddpfOut = (DDPIXELFORMAT*)pContext;

	char s[100];
	sprintf(s, "EnumZBufferFormatsCallback %d\n", pddpf->dwRGBBitCount);
	OutputDebugString(s);

    if( pddpfOut->dwRGBBitCount == pddpf->dwRGBBitCount )
    {
        (*pddpfOut) = (*pddpf);
        return D3DENUMRET_CANCEL;
    }

    return D3DENUMRET_OK;
}

// Internal function called by Create() to make and attach a zbuffer
// to the renderer.

HRESULT CD3DApplication::CreateZBuffer(GUID* pDeviceGUID)
{
    HRESULT hr;

    // Check if the device supports z-bufferless hidden surface removal. If so,
    // we don't really need a z-buffer
    D3DDEVICEDESC7 ddDesc;
    m_pD3DDevice->GetCaps( &ddDesc );
    if( ddDesc.dpcTriCaps.dwRasterCaps & D3DPRASTERCAPS_ZBUFFERLESSHSR )
        return S_OK;

    // Get z-buffer dimensions from the render target
    DDSURFACEDESC2 ddsd;
    ddsd.dwSize = sizeof(ddsd);
    m_pddsRenderTarget->GetSurfaceDesc( &ddsd );

    // Setup the surface desc for the z-buffer.
    ddsd.dwFlags        = DDSD_WIDTH | DDSD_HEIGHT | DDSD_CAPS | DDSD_PIXELFORMAT;
    ddsd.ddsCaps.dwCaps = DDSCAPS_ZBUFFER | DDSCAPS_VIDEOMEMORY;
    ddsd.ddpfPixelFormat.dwSize = 0;  // Tag the pixel format as unitialized

    // Get an appropiate pixel format from enumeration of the formats. On the
    // first pass, we look for a zbuffer dpeth which is equal to the frame
    // buffer depth (as some cards unfornately require this).
    m_pD3D->EnumZBufferFormats( *pDeviceGUID, EnumZBufferFormatsCallback,
                                (VOID*)&ddsd.ddpfPixelFormat );
    if( 0 == ddsd.ddpfPixelFormat.dwSize )
    {
        // Try again, just accepting any 16-bit zbuffer
        ddsd.ddpfPixelFormat.dwRGBBitCount = 16;
        m_pD3D->EnumZBufferFormats( *pDeviceGUID, EnumZBufferFormatsCallback,
                                    (VOID*)&ddsd.ddpfPixelFormat );
            
        if( 0 == ddsd.ddpfPixelFormat.dwSize )
        {
            DEBUG_MSG( _T("Device doesn't support requested zbuffer format") );
            return D3DFWERR_NOZBUFFER;
        }
    }

    // Create and attach a z-buffer
    if( FAILED( hr = m_pDD->CreateSurface( &ddsd, &m_pddsDepthBuffer, NULL ) ) )
    {
        DEBUG_MSG( _T("Error: Couldn't create a ZBuffer surface") );
        if( hr != DDERR_OUTOFVIDEOMEMORY )
            return D3DFWERR_NOZBUFFER;
        DEBUG_MSG( _T("Error: Out of video memory") );
        return DDERR_OUTOFVIDEOMEMORY;
    }

    if( FAILED( m_pddsRenderTarget->AddAttachedSurface( m_pddsDepthBuffer ) ) )
    {
        DEBUG_MSG( _T("Error: Couldn't attach zbuffer to render surface") );
        return D3DFWERR_NOZBUFFER;
    }

    // Finally, this call rebuilds internal structures
    if( FAILED( m_pD3DDevice->SetRenderTarget( m_pddsRenderTarget, 0L ) ) )
    {
        DEBUG_MSG( _T("Error: SetRenderTarget() failed after attaching zbuffer!") );
        return D3DFWERR_NOZBUFFER;
    }

    return S_OK;
}

// Initializes the sample framework, then calls the app-specific function
// to initialize device specific objects. This code is structured to
// handled any errors that may occur duing initialization.

HRESULT CD3DApplication::Initialize3DEnvironment()
{
    HRESULT		hr;
	DDSCAPS2	ddsCaps2; 
    DWORD		dwFrameworkFlags = 0L;
	DWORD		dwTotal; 
	DWORD		dwFree;

    dwFrameworkFlags |= ( !m_pDeviceInfo->bWindowed ? D3DFW_FULLSCREEN : 0L );
    dwFrameworkFlags |= (  m_pDeviceInfo->bStereo   ? D3DFW_STEREO     : 0L );
    dwFrameworkFlags |= (  m_bAppUseZBuffer         ? D3DFW_ZBUFFER    : 0L );

    // Initialize the D3D framework
    if( SUCCEEDED( hr = m_pFramework->Initialize( m_hWnd,
                     m_pDeviceInfo->pDriverGUID, m_pDeviceInfo->pDeviceGUID,
                     &m_pDeviceInfo->ddsdFullscreenMode, dwFrameworkFlags ) ) )
    {
        m_pDD        = m_pFramework->GetDirectDraw();
        m_pD3D       = m_pFramework->GetDirect3D();
        m_pD3DDevice = m_pFramework->GetD3DDevice();

		m_pD3DEngine->SetD3DDevice(m_pD3DDevice);

		m_pddsRenderTarget = m_pFramework->GetRenderSurface();

		m_ddsdRenderTarget.dwSize = sizeof(m_ddsdRenderTarget);
		m_pddsRenderTarget->GetSurfaceDesc( &m_ddsdRenderTarget );

		// Request the amount of video memory.
		ZeroMemory(&ddsCaps2, sizeof(ddsCaps2));
		ddsCaps2.dwCaps = DDSCAPS_TEXTURE; 
		dwTotal = 0;
		hr = m_pDD->GetAvailableVidMem(&ddsCaps2, &dwTotal, &dwFree); 
		m_vidMemTotal = dwTotal;

		// Let the app run its startup code which creates the 3d scene.
		if( SUCCEEDED( hr = m_pD3DEngine->InitDeviceObjects() ) )
		{
//? 		CreateZBuffer(m_pDeviceInfo->pDeviceGUID);
			return S_OK;
		}
		else
		{
			DeleteDeviceObjects();
			m_pFramework->DestroyObjects();
		}
	}

	// If we get here, the first initialization passed failed. If that was with a
	// hardware device, try again using a software rasterizer instead.
	if( m_pDeviceInfo->bHardware )
	{
		// Try again with a software rasterizer
		DisplayFrameworkError( hr, MSGWARN_SWITCHEDTOSOFTWARE );
		D3DEnum_SelectDefaultDevice( &m_pDeviceInfo, D3DENUM_SOFTWAREONLY );
		return Initialize3DEnvironment();
	}
 
	return hr;
}


// Handles driver, device, and/or mode changes for the app.

HRESULT CD3DApplication::Change3DEnvironment()
{
#if 0
	HRESULT hr;
	static bool  bOldWindowedState = true;
	static DWORD dwSavedStyle;
	static RECT  rcSaved;

	// Release all scene objects that will be re-created for the new device
	DeleteDeviceObjects();

	// Release framework objects, so a new device can be created
	if( FAILED( hr = m_pFramework->DestroyObjects() ) )
	{
		DisplayFrameworkError( hr, MSGERR_APPMUSTEXIT );
		SendMessage( m_hWnd, WM_CLOSE, 0, 0 );
		return hr;
	}

	// Check if going from fullscreen to windowed mode, or vice versa.
	if( bOldWindowedState != m_pDeviceInfo->bWindowed )
	{
		if( m_pDeviceInfo->bWindowed )
		{
			// Coming from fullscreen mode, so restore window properties
			SetWindowLong( m_hWnd, GWL_STYLE, dwSavedStyle );
			SetWindowPos( m_hWnd, HWND_NOTOPMOST, rcSaved.left, rcSaved.top,
						  ( rcSaved.right - rcSaved.left ), 
						  ( rcSaved.bottom - rcSaved.top ), SWP_SHOWWINDOW );
		}
		else
		{
			// Going to fullscreen mode, save/set window properties as needed
			dwSavedStyle = GetWindowLong( m_hWnd, GWL_STYLE );
			GetWindowRect( m_hWnd, &rcSaved );
			SetWindowLong( m_hWnd, GWL_STYLE, WS_POPUP|WS_SYSMENU|WS_VISIBLE );
		}

		bOldWindowedState = m_pDeviceInfo->bWindowed;
	}

	// Inform the framework class of the driver change. It will internally
	// re-create valid surfaces, a d3ddevice, etc.
	if( FAILED( hr = Initialize3DEnvironment() ) )
	{
		DisplayFrameworkError( hr, MSGERR_APPMUSTEXIT );
		SendMessage( m_hWnd, WM_CLOSE, 0, 0 );
		return hr;
	}

	return S_OK;
#else
	HRESULT hr;

	// Release all scene objects that will be re-created for the new device
	DeleteDeviceObjects();

	// Release framework objects, so a new device can be created
	if( FAILED( hr = m_pFramework->DestroyObjects() ) )
	{
		DisplayFrameworkError( hr, MSGERR_APPMUSTEXIT );
		SendMessage( m_hWnd, WM_CLOSE, 0, 0 );
		return hr;
	}

	if( m_pDeviceInfo->bWindowed )
	{
		SetWindowPos(m_hWnd, HWND_NOTOPMOST, 10, 10, WINDOW_DX, WINDOW_DY, SWP_SHOWWINDOW);
	}

	// Inform the framework class of the driver change. It will internally
	// re-create valid surfaces, a d3ddevice, etc.
	if( FAILED( hr = Initialize3DEnvironment() ) )
	{
		DisplayFrameworkError( hr, MSGERR_APPMUSTEXIT );
		SendMessage( m_hWnd, WM_CLOSE, 0, 0 );
		return hr;
	}

	m_pD3DEngine->ChangeLOD();

	if( m_pDeviceInfo->bWindowed )
	{
		SetNiceMouse(false);  // hides the ugly windows mouse
	}

	return S_OK;
#endif
}



// Evolved throughout the game

void CD3DApplication::StepSimul(float rTime)
{
	Event	event;

	if ( m_pRobotMain == 0 )  return;

	ZeroMemory(&event, sizeof(Event));
	event.event = EVENT_FRAME;  // funny bug release "Maximize speed"!
	event.rTime = rTime;
	event.axeX = AxeLimit(m_axeKey.x + m_axeJoy.x);
	event.axeY = AxeLimit(m_axeKey.y + m_axeJoy.y);
	event.axeZ = AxeLimit(m_axeKey.z + m_axeJoy.z);
	event.keyState = m_keyState;

//?char s[100];
//?sprintf(s, "StepSimul %.3f\n", event.rTime);
//?OutputDebugString(s);
	m_pRobotMain->EventProcess(event);
}


// Draws the scene.

HRESULT CD3DApplication::Render3DEnvironment()
{
    HRESULT hr;
	float	rTime;

    // Check the cooperative level before rendering
    if( FAILED( hr = m_pDD->TestCooperativeLevel() ) )
    {
        switch( hr )
        {
            case DDERR_EXCLUSIVEMODEALREADYSET:
            case DDERR_NOEXCLUSIVEMODE:
				OutputDebugString("DDERR_EXCLUSIVEMODEALREADYSET\n");
                // Do nothing because some other app has exclusive mode
                return S_OK;

            case DDERR_WRONGMODE:
				OutputDebugString("DDERR_WRONGMODE\n");
                // The display mode changed on us. Resize accordingly
                if( m_pDeviceInfo->bWindowed )
                    return Change3DEnvironment();
                break;
        }
        return hr;
    }

	// Get the relative time, in seconds
	rTime = m_pD3DEngine->TimeGet();
	if ( rTime > MAX_STEP )  rTime = MAX_STEP;  // never more than 0.5s!
	m_aTime += rTime;

#if !USE_THREAD
    if( FAILED( hr = m_pD3DEngine->FrameMove(rTime) ) )
        return hr;

    // FrameMove (animate) the scene
	StepSimul(rTime);
#endif

	// Render the scene.
	if( FAILED( hr = m_pD3DEngine->Render() ) )
		return hr;

	DrawSuppl();

    // Show the frame rate, etc.
    if( m_bShowStats )
        ShowStats();

    // Show the frame on the primary surface.
    if( FAILED( hr = m_pFramework->ShowFrame() ) )
    {
        if( DDERR_SURFACELOST != hr )
            return hr;

        m_pFramework->RestoreSurfaces();
        m_pD3DEngine->RestoreSurfaces();
    }

    return S_OK;
}


// Cleanup scene objects

VOID CD3DApplication::Cleanup3DEnvironment()
{
    m_bActive = false;
    m_bReady  = false;

    if( m_pFramework )
    {
        DeleteDeviceObjects();
        SAFE_DELETE( m_pFramework );

        m_pD3DEngine->FinalCleanup();
    }

    D3DEnum_FreeResources();
//?	FreeDirectInput();
}

// Called when the app is exitting, or the device is being changed,
// this function deletes any device dependant objects.

VOID CD3DApplication::DeleteDeviceObjects()
{
    if( m_pFramework )
    {
        m_pD3DEngine->DeleteDeviceObjects();
	    SAFE_RELEASE( m_pddsDepthBuffer );
    }
}



// Called in to toggle the pause state of the app. This function
// brings the GDI surface to the front of the display, so drawing
// output like message boxes and menus may be displayed.

VOID CD3DApplication::Pause( bool bPause )
{
    static DWORD dwAppPausedCount = 0L;

    dwAppPausedCount += ( bPause ? +1 : -1 );
    m_bReady          = ( dwAppPausedCount ? false : true );

    // Handle the first pause request (of many, nestable pause requests)
    if( bPause && ( 1 == dwAppPausedCount ) )
    {
        // Get a surface for the GDI
        if( m_pFramework )
            m_pFramework->FlipToGDISurface( true );

        // Stop the scene from animating
		m_pD3DEngine->TimeEnterGel();
    }

    if( 0 == dwAppPausedCount )
    {
        // Restart the scene
		m_pD3DEngine->TimeExitGel();
    }
}


// Called when the app receives a PBT_APMQUERYSUSPEND message, meaning
// the computer is about to be suspended. At this point, the app should
// save any data for open network connections, files, etc.., and prepare
// to go into a suspended mode.

LRESULT CD3DApplication::OnQuerySuspend( DWORD dwFlags )
{
	OutputDebugString("OnQuerySuspend\n");
    Pause(true);
    return true;
}


// Called when the app receives a PBT_APMRESUMESUSPEND message, meaning
// the computer has just resumed from a suspended state. At this point, 
// the app should recover any data, network connections, files, etc..,
// and resume running from when the app was suspended.

LRESULT CD3DApplication::OnResumeSuspend( DWORD dwData )
{
	OutputDebugString("OnResumeSuspend\n");
    Pause(false);
    return true;
}


// Draw all the additional graphic elements.

void CD3DApplication::DrawSuppl()
{
	HDC			hDC;
	Math::Point		p1, p2;
	POINT		list[3];
	RECT		rect;
	HPEN		hPen;
	HGDIOBJ		old;
	Math::Point		pos;
	float		d;
	int			nbOut;

	if ( FAILED(m_pddsRenderTarget->GetDC(&hDC)) )  return;

	// Displays the selection rectangle.
	if ( m_pD3DEngine->GetHilite(p1, p2) )
	{
		nbOut = 0;
		if ( p1.x < 0.0f || p1.x > 1.0f )  nbOut ++;
		if ( p1.y < 0.0f || p1.y > 1.0f )  nbOut ++;
		if ( p2.x < 0.0f || p2.x > 1.0f )  nbOut ++;
		if ( p2.y < 0.0f || p2.y > 1.0f )  nbOut ++;
		if ( nbOut <= 2 )
		{
#if 0
			time = Math::Mod(m_aTime, 0.5f);
			if ( time < 0.25f )  d = time*4.0f;
			else                 d = (2.0f-time*4.0f);
#endif
#if 0
			time = Math::Mod(m_aTime, 0.5f);
			if ( time < 0.4f )  d = time/0.4f;
			else                d = 1.0f-(time-0.4f)/0.1f;
#endif
#if 1
			d = 0.5f+sinf(m_aTime*6.0f)*0.5f;
#endif
			d *= (p2.x-p1.x)*0.1f;
			p1.x += d;
			p1.y += d;
			p2.x -= d;
			p2.y -= d;

			hPen = CreatePen(PS_SOLID, 1, RGB(255,255,0));  // yellow
			old = SelectObject(hDC, hPen);

			rect.left   = (int)(p1.x*m_ddsdRenderTarget.dwWidth);
			rect.right  = (int)(p2.x*m_ddsdRenderTarget.dwWidth);
			rect.top    = (int)((1.0f-p2.y)*m_ddsdRenderTarget.dwHeight);
			rect.bottom = (int)((1.0f-p1.y)*m_ddsdRenderTarget.dwHeight);

			list[0].x = rect.left;
			list[0].y = rect.top+(rect.bottom-rect.top)/5;
			list[1].x = rect.left;
			list[1].y = rect.top;
			list[2].x = rect.left+(rect.right-rect.left)/5;
			list[2].y = rect.top;
			Polyline(hDC, list, 3);

			list[0].x = rect.right;
			list[0].y = rect.top+(rect.bottom-rect.top)/5;
			list[1].x = rect.right;
			list[1].y = rect.top;
			list[2].x = rect.right+(rect.left-rect.right)/5;
			list[2].y = rect.top;
			Polyline(hDC, list, 3);

			list[0].x = rect.left;
			list[0].y = rect.bottom+(rect.top-rect.bottom)/5;
			list[1].x = rect.left;
			list[1].y = rect.bottom;
			list[2].x = rect.left+(rect.right-rect.left)/5;
			list[2].y = rect.bottom;
			Polyline(hDC, list, 3);

			list[0].x = rect.right;
			list[0].y = rect.bottom+(rect.top-rect.bottom)/5;
			list[1].x = rect.right;
			list[1].y = rect.bottom;
			list[2].x = rect.right+(rect.left-rect.right)/5;
			list[2].y = rect.bottom;
			Polyline(hDC, list, 3);

			if ( old != 0 )  SelectObject(hDC, old);
			DeleteObject(hPen);
		}
	}

	m_pddsRenderTarget->ReleaseDC(hDC);
}

// Shows frame rate and dimensions of the rendering device.

VOID CD3DApplication::ShowStats()
{
    static FLOAT fFPS      = 0.0f;
    static FLOAT fLastTime = 0.0f;
    static DWORD dwFrames  = 0L;

    // Keep track of the time lapse and frame count
    FLOAT fTime = timeGetTime() * 0.001f; // Get current time in seconds
    ++dwFrames;

    // Update the frame rate once per second
    if( fTime - fLastTime > 1.0f )
    {
        fFPS      = dwFrames / (fTime - fLastTime);
        fLastTime = fTime;
        dwFrames  = 0L;
    }

	int t = m_pD3DEngine->RetStatisticTriangle();

    // Setup the text buffer to write out dimensions
    TCHAR buffer[100];
    sprintf( buffer, _T("%7.02f fps T=%d (%dx%dx%d)"), fFPS, t,
             m_ddsdRenderTarget.dwWidth, m_ddsdRenderTarget.dwHeight, 
             m_ddsdRenderTarget.ddpfPixelFormat.dwRGBBitCount );
    OutputText( 400, 2, buffer );

	int	x, y, i;
	if ( m_pD3DEngine->GetSpriteCoord(x, y) )
	{
	    OutputText( x, y, "+" );
	}

	for ( i=0 ; i<10 ; i++ )
	{
		char* info = m_pD3DEngine->RetInfoText(i);
		x = 50;
		y = m_ddsdRenderTarget.dwHeight-20-i*20;
		OutputText( x, y, info );
	}
}


// Draws text on the window.

VOID CD3DApplication::OutputText( DWORD x, DWORD y, TCHAR* str )
{
    HDC hDC;

    // Get a DC for the surface. Then, write out the buffer
    if( m_pddsRenderTarget )
    {
        if( SUCCEEDED( m_pddsRenderTarget->GetDC(&hDC) ) )
        {
            SetTextColor( hDC, RGB(255,255,0) );
            SetBkMode( hDC, TRANSPARENT );
            ExtTextOut( hDC, x, y, 0, NULL, str, lstrlen(str), NULL );
            m_pddsRenderTarget->ReleaseDC(hDC);
        }
    }
}




// Defines a function that allocates memory for and initializes
// members within a BITMAPINFOHEADER structure

PBITMAPINFO CD3DApplication::CreateBitmapInfoStruct(HBITMAP hBmp)
{ 
	BITMAP		bmp;
	PBITMAPINFO	pbmi;
	WORD		cClrBits;
 
	// Retrieve the bitmap's color format, width, and height.
	if ( !GetObject(hBmp, sizeof(BITMAP), (LPSTR)&bmp) )
		return 0;
  
	// Convert the color format to a count of bits.
	cClrBits = (WORD)(bmp.bmPlanes * bmp.bmBitsPixel);
 
	     if ( cClrBits ==  1 )  cClrBits =  1;
	else if ( cClrBits <=  4 )  cClrBits =  4;
	else if ( cClrBits <=  8 )  cClrBits =  8;
	else if ( cClrBits <= 16 )  cClrBits = 16;
	else if ( cClrBits <= 24 )  cClrBits = 24;
	else                        cClrBits = 32;
 
	// Allocate memory for the BITMAPINFO structure. (This structure 
	// contains a BITMAPINFOHEADER structure and an array of RGBQUAD data 
	// structures.) 
	if ( cClrBits != 24 )
	{
		 pbmi = (PBITMAPINFO)LocalAlloc(LPTR,
					sizeof(BITMAPINFOHEADER) +
					sizeof(RGBQUAD) * (2^cClrBits));
	}
	// There is no RGBQUAD array for the 24-bit-per-pixel format.
	else
	{
		 pbmi = (PBITMAPINFO)LocalAlloc(LPTR,
					sizeof(BITMAPINFOHEADER));
	}
 
	// Initialize the fields in the BITMAPINFO structure.
	pbmi->bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
	pbmi->bmiHeader.biWidth = bmp.bmWidth;
	pbmi->bmiHeader.biHeight = bmp.bmHeight;
	pbmi->bmiHeader.biPlanes = bmp.bmPlanes;
	pbmi->bmiHeader.biBitCount = bmp.bmBitsPixel;
	if ( cClrBits < 24 )
		pbmi->bmiHeader.biClrUsed = 2^cClrBits;
  
	// If the bitmap is not compressed, set the BI_RGB flag.
 	pbmi->bmiHeader.biCompression = BI_RGB;
 
	// Compute the number of bytes in the array of color
	// indices and store the result in biSizeImage.
	pbmi->bmiHeader.biSizeImage = (pbmi->bmiHeader.biWidth + 7) /8
								  * pbmi->bmiHeader.biHeight
								  * cClrBits;
 
	// Set biClrImportant to 0, indicating that all of the
	// device colors are important.
	pbmi->bmiHeader.biClrImportant = 0;

	return pbmi;
} 
 
// Defines a function that initializes the remaining structures,
// retrieves the array of palette indices, opens the file, copies
// the data, and closes the file. 

bool CD3DApplication::CreateBMPFile(LPTSTR pszFile, PBITMAPINFO pbi, HBITMAP hBMP, HDC hDC)
{ 
	FILE*				file;		// file handle
	BITMAPFILEHEADER	hdr;		// bitmap file-header
	PBITMAPINFOHEADER	pbih;		// bitmap info-header
	LPBYTE				lpBits;		// memory pointer
	DWORD				dwTotal;	// total count of bytes
 
	pbih = (PBITMAPINFOHEADER)pbi;
	lpBits = (LPBYTE)GlobalAlloc(GMEM_FIXED, pbih->biSizeImage);
	if ( !lpBits )  return false;
 
	// Retrieve the color table (RGBQUAD array) and the bits
	// (array of palette indices) from the DIB.
	if ( !GetDIBits(hDC, hBMP, 0, (WORD)pbih->biHeight,
					lpBits, pbi, DIB_RGB_COLORS) )
		return false;
 
	// Create the .BMP file.
	file = fopen(pszFile, "wb");
	if ( file == NULL )  return false;
 
	hdr.bfType = 0x4d42; // 0x42 = "B" 0x4d = "M"
 
	// Compute the size of the entire file.
	hdr.bfSize = (DWORD)(sizeof(BITMAPFILEHEADER) +
						 pbih->biSize + pbih->biClrUsed
						 * sizeof(RGBQUAD) + pbih->biSizeImage);
 
	hdr.bfReserved1 = 0;
	hdr.bfReserved2 = 0;
 
	// Compute the offset to the array of color indices.
	hdr.bfOffBits = (DWORD)sizeof(BITMAPFILEHEADER) +
					pbih->biSize + pbih->biClrUsed
					* sizeof (RGBQUAD);
 
	// Copy the BITMAPFILEHEADER into the .BMP file.
	fwrite(&hdr, sizeof(BITMAPFILEHEADER), 1, file);
 
	// Copy the BITMAPINFOHEADER and RGBQUAD array into the file.
	fwrite(pbih, sizeof(BITMAPINFOHEADER)+pbih->biClrUsed*sizeof(RGBQUAD), 1, file);
 
	// Copy the array of color indices into the .BMP file.
	dwTotal = pbih->biSizeImage;
	fwrite(lpBits, dwTotal, 1, file);
 
	// Close the .BMP file.
	fclose(file);
 
	// Free memory.
	GlobalFree((HGLOBAL)lpBits);
	return true;
}

// Write a file. BMP screenshot.

bool CD3DApplication::WriteScreenShot(char *filename, int width, int height)
{
	D3DVIEWPORT7	vp;
	HDC				hDC;
	HDC				hDCImage;
	HBITMAP			hb;
	PBITMAPINFO		info;
	int				dx, dy;

	m_pD3DDevice->GetViewport(&vp);
	dx = vp.dwWidth;
	dy = vp.dwHeight;

	if ( FAILED(m_pddsRenderTarget->GetDC(&hDC)) )  return false;

	hDCImage = CreateCompatibleDC(hDC);
	if ( hDCImage == 0 )
	{
		m_pddsRenderTarget->ReleaseDC(hDC);
		return false;
	}

	hb = CreateCompatibleBitmap(hDC, width, height);
	if ( hb == 0 )
	{
		DeleteDC(hDCImage);
		m_pddsRenderTarget->ReleaseDC(hDC);
		return false;
	}

	SelectObject(hDCImage, hb);
	StretchBlt(hDCImage, 0, 0, width, height, hDC, 0, 0, dx, dy, SRCCOPY);

	info = CreateBitmapInfoStruct(hb);
	if ( info == 0 )
	{
		DeleteObject(hb);
		DeleteDC(hDCImage);
		m_pddsRenderTarget->ReleaseDC(hDC);
		return false;
	}

	CreateBMPFile(filename, info, hb, hDCImage);

	DeleteObject(hb);
    DeleteDC(hDCImage);
	m_pddsRenderTarget->ReleaseDC(hDC);
	return true;
}


// Initializes an hDC on the rendering surface.

bool CD3DApplication::GetRenderDC(HDC &hDC)
{
	if ( FAILED(m_pddsRenderTarget->GetDC(&hDC)) )  return false;
	return true;
}

// Frees the hDC of the rendering surface.

bool CD3DApplication::ReleaseRenderDC(HDC &hDC)
{
	m_pddsRenderTarget->ReleaseDC(hDC);
	return true;
}




// Perform the list of all graphics devices available.
// For the device selected, lists the full screen modes
// possible.
// buf* --> nom1<0> nom2<0> <0>

bool CD3DApplication::EnumDevices(char *bufDevices,  int lenDevices,
								  char *bufModes,    int lenModes,
								  int &totalDevices, int &selectDevices,
								  int &totalModes,   int &selectModes)
{
	D3DEnum_DeviceInfo*	pDeviceList;
	D3DEnum_DeviceInfo*	pDevice;
	DDSURFACEDESC2*		pddsdMode;
	DWORD				numDevices, device, mode;
	int					len;
	char				text[100];

	D3DEnum_GetDevices(&pDeviceList, &numDevices);

	selectDevices = -1;
	selectModes = -1;
	totalModes = 0;
	for( device=0 ; device<numDevices ; device++ )
	{
		pDevice = &pDeviceList[device];

		len = strlen(pDevice->strDesc)+1;
		if ( len >= lenDevices )  break;  // bufDevices full!
		strcpy(bufDevices, pDevice->strDesc);
		bufDevices += len;
		lenDevices -= len;

		if ( pDevice == m_pDeviceInfo )  // select device ?
		{
			selectDevices = device;

			for( mode=0 ; mode<pDevice->dwNumModes ; mode++ )
			{
				pddsdMode = &pDevice->pddsdModes[mode];

				sprintf(text, "%ld x %ld x %ld",
								pddsdMode->dwWidth,
								pddsdMode->dwHeight,
								pddsdMode->ddpfPixelFormat.dwRGBBitCount);

				len = strlen(text)+1;
				if ( len >= lenModes )  break;  // bufModes full !
				strcpy(bufModes, text);
				bufModes += len;
				lenModes -= len;

				if ( mode == m_pDeviceInfo->dwCurrentMode )  // select mode ?
				{
					selectModes = mode;
				}
			}
			bufModes[0] = 0;
			totalModes = pDevice->dwNumModes;
		}
	}
	bufDevices[0] = 0;
	totalDevices = numDevices;

	return true;
}

// Indicates whether it is in full screen mode.

bool CD3DApplication::RetFullScreen()
{
	return !m_pDeviceInfo->bWindowed;
}

// Change the graphics mode.

bool CD3DApplication::ChangeDevice(char *deviceName, char *modeName,
								   bool bFull)
{
	D3DEnum_DeviceInfo*	pDeviceList;
	D3DEnum_DeviceInfo*	pDevice;
	DDSURFACEDESC2*		pddsdMode;
	DWORD				numDevices, device, mode;
	HRESULT				hr;
	char				text[100];

	D3DEnum_GetDevices(&pDeviceList, &numDevices);

	for( device=0 ; device<numDevices ; device++ )
	{
		pDevice = &pDeviceList[device];

		if ( strcmp(pDevice->strDesc, deviceName) == 0 )  // device found ?
		{
			for( mode=0 ; mode<pDevice->dwNumModes ; mode++ )
			{
				pddsdMode = &pDevice->pddsdModes[mode];

				sprintf(text, "%ld x %ld x %ld",
								pddsdMode->dwWidth,
								pddsdMode->dwHeight,
								pddsdMode->ddpfPixelFormat.dwRGBBitCount);

				if ( strcmp(text, modeName) == 0 )  // mode found ?
				{
					m_pDeviceInfo               = pDevice;
					pDevice->bWindowed          = !bFull;
					pDevice->dwCurrentMode      = mode;
					pDevice->ddsdFullscreenMode = pDevice->pddsdModes[mode];

					m_bReady = false;

					if ( FAILED( hr = Change3DEnvironment() ) )
					{
						return false;
					}

					SetProfileString("Device", "Name", deviceName);
					SetProfileString("Device", "Mode", modeName);
					SetProfileInt("Device", "FullScreen", bFull);
					m_bReady = true;
					return true;
				}
			}
		}
	}

	return false;
}



// Displays error messages in a message box.

VOID CD3DApplication::DisplayFrameworkError( HRESULT hr, DWORD dwType )
{
    TCHAR strMsg[512];

    switch( hr )
    {
        case D3DENUMERR_ENGINE:
            lstrcpy( strMsg, _T("Could not create 3D Engine application!") );
            break;
        case D3DENUMERR_ROBOT:
            lstrcpy( strMsg, _T("Could not create Robot application!") );
            break;
        case D3DENUMERR_NODIRECTDRAW:
            lstrcpy( strMsg, _T("Could not create DirectDraw!") );
            break;
        case D3DENUMERR_NOCOMPATIBLEDEVICES:
            lstrcpy( strMsg, _T("Could not find any compatible Direct3D\n"
                     "devices.") );
            break;
        case D3DENUMERR_SUGGESTREFRAST:
            lstrcpy( strMsg, _T("Could not find any compatible devices.\n\n"
                     "Try enabling the reference rasterizer using\n"
                     "EnableRefRast.reg.") );
            break;
        case D3DENUMERR_ENUMERATIONFAILED:
            lstrcpy( strMsg, _T("Enumeration failed. Your system may be in an\n"
                     "unstable state and need to be rebooted") );
            break;
        case D3DFWERR_INITIALIZATIONFAILED:
            lstrcpy( strMsg, _T("Generic initialization error.\n\nEnable "
                     "debug output for detailed information.") );
            break;
        case D3DFWERR_NODIRECTDRAW:
            lstrcpy( strMsg, _T("No DirectDraw") );
            break;
        case D3DFWERR_NODIRECT3D:
            lstrcpy( strMsg, _T("No Direct3D") );
            break;
        case D3DFWERR_INVALIDMODE:
            lstrcpy( strMsg, _T("COLOBOT requires a 16-bit (or higher) "
                                "display mode\nto run in a window.\n\nPlease "
                                "switch your desktop settings accordingly.") );
            break;
        case D3DFWERR_COULDNTSETCOOPLEVEL:
            lstrcpy( strMsg, _T("Could not set Cooperative Level") );
            break;
        case D3DFWERR_NO3DDEVICE:
            lstrcpy( strMsg, _T("Could not create the Direct3DDevice object.") );
            
            if( MSGWARN_SWITCHEDTOSOFTWARE == dwType )
                lstrcat( strMsg, _T("\nThe 3D hardware chipset may not support"
                                    "\nrendering in the current display mode.") );
            break;
        case D3DFWERR_NOZBUFFER:
            lstrcpy( strMsg, _T("No ZBuffer") );
            break;
        case D3DFWERR_INVALIDZBUFFERDEPTH:
            lstrcpy( strMsg, _T("Invalid Z-buffer depth. Try switching modes\n"
                     "from 16- to 32-bit (or vice versa)") );
            break;
        case D3DFWERR_NOVIEWPORT:
            lstrcpy( strMsg, _T("No Viewport") );
            break;
        case D3DFWERR_NOPRIMARY:
            lstrcpy( strMsg, _T("No primary") );
            break;
        case D3DFWERR_NOCLIPPER:
            lstrcpy( strMsg, _T("No Clipper") );
            break;
        case D3DFWERR_BADDISPLAYMODE:
            lstrcpy( strMsg, _T("Bad display mode") );
            break;
        case D3DFWERR_NOBACKBUFFER:
            lstrcpy( strMsg, _T("No backbuffer") );
            break;
        case D3DFWERR_NONZEROREFCOUNT:
            lstrcpy( strMsg, _T("A DDraw object has a non-zero reference\n"
                     "count (meaning it was not properly cleaned up)." ) );
            break;
        case D3DFWERR_NORENDERTARGET:
            lstrcpy( strMsg, _T("No render target") );
            break;
        case E_OUTOFMEMORY:
            lstrcpy( strMsg, _T("Not enough memory!") );
            break;
        case DDERR_OUTOFVIDEOMEMORY:
            lstrcpy( strMsg, _T("There was insufficient video memory "
                     "to use the\nhardware device.") );
            break;
        default:
            lstrcpy( strMsg, _T("Generic application error.\n\nEnable "
                     "debug output for detailed information.") );
    }

    if( MSGERR_APPMUSTEXIT == dwType )
    {
        lstrcat( strMsg, _T("\n\nCOLOBOT will now exit.") );
        MessageBox( NULL, strMsg, m_strWindowTitle, MB_ICONERROR|MB_OK );
    }
    else
    {
        if( MSGWARN_SWITCHEDTOSOFTWARE == dwType )
            lstrcat( strMsg, _T("\n\nSwitching to software rasterizer.") );
        MessageBox( NULL, strMsg, m_strWindowTitle, MB_ICONWARNING|MB_OK );
    }
}