]> git.xonotic.org Git - xonotic/darkplaces.git/blob - vid_wgl.c
use both .items2 and serverflags in items stat, to finally fix the runes
[xonotic/darkplaces.git] / vid_wgl.c
1 /*
2 Copyright (C) 1996-1997 Id Software, Inc.
3
4 This program is free software; you can redistribute it and/or
5 modify it under the terms of the GNU General Public License
6 as published by the Free Software Foundation; either version 2
7 of the License, or (at your option) any later version.
8
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
12
13 See the GNU General Public License for more details.
14
15 You should have received a copy of the GNU General Public License
16 along with this program; if not, write to the Free Software
17 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
18
19 */
20 // vid_wgl.c -- NT GL vid component
21
22 #ifdef _MSC_VER
23 #pragma comment(lib, "comctl32.lib")
24 #endif
25
26 #ifdef SUPPORTDIRECTX
27 // Include DX libs
28 #ifdef _MSC_VER
29 #pragma comment(lib, "dinput8.lib")
30 #pragma comment(lib, "dxguid.lib")
31 #endif
32 #ifndef DIRECTINPUT_VERSION
33 #       define DIRECTINPUT_VERSION 0x0500  /* Version 5.0 */
34 #endif
35 #endif
36
37 #include "quakedef.h"
38 #include <windows.h>
39 #include <mmsystem.h>
40 #ifdef SUPPORTDIRECTX
41 #include <dsound.h>
42 #endif
43 #include "resource.h"
44 #include <commctrl.h>
45 #ifdef SUPPORTDIRECTX
46 #include <dinput.h>
47 #endif
48 #include "dpsoftrast.h"
49
50 #ifdef SUPPORTD3D
51 #include <d3d9.h>
52
53 cvar_t vid_dx9 = {CVAR_SAVE, "vid_dx9", "0", "use Microsoft Direct3D9(r) for rendering"};
54 cvar_t vid_dx9_hal = {CVAR_SAVE, "vid_dx9_hal", "1", "enables hardware rendering (1), otherwise software reference rasterizer (0 - very slow), note that 0 is necessary when using NVPerfHUD (which renders in hardware but requires this option to enable it)"};
55 cvar_t vid_dx9_softvertex = {CVAR_SAVE, "vid_dx9_softvertex", "0", "enables software vertex processing (for compatibility testing?  or if you have a very fast CPU), usually you want this off"};
56 cvar_t vid_dx9_triplebuffer = {CVAR_SAVE, "vid_dx9_triplebuffer", "0", "enables triple buffering when using vid_vsync in fullscreen, this options adds some latency and only helps when framerate is below 60 so you usually don't want it"};
57 //cvar_t vid_dx10 = {CVAR_SAVE, "vid_dx10", "1", "use Microsoft Direct3D10(r) for rendering"};
58 //cvar_t vid_dx11 = {CVAR_SAVE, "vid_dx11", "1", "use Microsoft Direct3D11(r) for rendering"};
59
60 D3DPRESENT_PARAMETERS vid_d3dpresentparameters;
61
62 // we declare this in vid_shared.c because it is required by dedicated server and all clients when SUPPORTD3D is defined
63 extern LPDIRECT3DDEVICE9 vid_d3d9dev;
64
65 LPDIRECT3D9 vid_d3d9;
66 D3DCAPS9 vid_d3d9caps;
67 qboolean vid_d3ddevicelost;
68 #endif
69
70 extern HINSTANCE global_hInstance;
71
72 static HINSTANCE gldll;
73
74 #ifndef WM_MOUSEWHEEL
75 #define WM_MOUSEWHEEL                   0x020A
76 #endif
77
78 // Tell startup code that we have a client
79 int cl_available = true;
80
81 qboolean vid_supportrefreshrate = true;
82
83 static int (WINAPI *qwglChoosePixelFormat)(HDC, CONST PIXELFORMATDESCRIPTOR *);
84 static int (WINAPI *qwglDescribePixelFormat)(HDC, int, UINT, LPPIXELFORMATDESCRIPTOR);
85 //static int (WINAPI *qwglGetPixelFormat)(HDC);
86 static BOOL (WINAPI *qwglSetPixelFormat)(HDC, int, CONST PIXELFORMATDESCRIPTOR *);
87 static BOOL (WINAPI *qwglSwapBuffers)(HDC);
88 static HGLRC (WINAPI *qwglCreateContext)(HDC);
89 static BOOL (WINAPI *qwglDeleteContext)(HGLRC);
90 static HGLRC (WINAPI *qwglGetCurrentContext)(VOID);
91 static HDC (WINAPI *qwglGetCurrentDC)(VOID);
92 static PROC (WINAPI *qwglGetProcAddress)(LPCSTR);
93 static BOOL (WINAPI *qwglMakeCurrent)(HDC, HGLRC);
94 static BOOL (WINAPI *qwglSwapIntervalEXT)(int interval);
95 static const char *(WINAPI *qwglGetExtensionsStringARB)(HDC hdc);
96 static BOOL (WINAPI *qwglChoosePixelFormatARB)(HDC hdc, const int *piAttribIList, const FLOAT *pfAttribFList, UINT nMaxFormats, int *piFormats, UINT *nNumFormats);
97 static BOOL (WINAPI *qwglGetPixelFormatAttribivARB)(HDC hdc, int iPixelFormat, int iLayerPlane, UINT nAttributes, const int *piAttributes, int *piValues);
98
99 static dllfunction_t wglfuncs[] =
100 {
101         {"wglChoosePixelFormat", (void **) &qwglChoosePixelFormat},
102         {"wglDescribePixelFormat", (void **) &qwglDescribePixelFormat},
103 //      {"wglGetPixelFormat", (void **) &qwglGetPixelFormat},
104         {"wglSetPixelFormat", (void **) &qwglSetPixelFormat},
105         {"wglSwapBuffers", (void **) &qwglSwapBuffers},
106         {"wglCreateContext", (void **) &qwglCreateContext},
107         {"wglDeleteContext", (void **) &qwglDeleteContext},
108         {"wglGetProcAddress", (void **) &qwglGetProcAddress},
109         {"wglMakeCurrent", (void **) &qwglMakeCurrent},
110         {"wglGetCurrentContext", (void **) &qwglGetCurrentContext},
111         {"wglGetCurrentDC", (void **) &qwglGetCurrentDC},
112         {NULL, NULL}
113 };
114
115 static dllfunction_t wglswapintervalfuncs[] =
116 {
117         {"wglSwapIntervalEXT", (void **) &qwglSwapIntervalEXT},
118         {NULL, NULL}
119 };
120
121 static dllfunction_t wglpixelformatfuncs[] =
122 {
123         {"wglChoosePixelFormatARB", (void **) &qwglChoosePixelFormatARB},
124         {"wglGetPixelFormatAttribivARB", (void **) &qwglGetPixelFormatAttribivARB},
125         {NULL, NULL}
126 };
127
128 static DEVMODE gdevmode, initialdevmode;
129 static qboolean vid_initialized = false;
130 static qboolean vid_wassuspended = false;
131 static qboolean vid_usingmouse = false;
132 static qboolean vid_usinghidecursor = false;
133 static qboolean vid_usingvsync = false;
134 static qboolean vid_usevsync = false;
135 static HICON hIcon;
136
137 // used by cd_win.c and snd_win.c
138 HWND mainwindow;
139
140 static HDC       baseDC;
141 static HGLRC baseRC;
142
143 static HDC vid_softhdc;
144 static HGDIOBJ vid_softhdc_backup;
145 static BITMAPINFO vid_softbmi;
146 static HBITMAP vid_softdibhandle;
147
148 //HWND WINAPI InitializeWindow (HINSTANCE hInstance, int nCmdShow);
149
150 static qboolean vid_isfullscreen;
151
152 //void VID_MenuDraw (void);
153 //void VID_MenuKey (int key);
154
155 //LONG WINAPI MainWndProc (HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
156 //void AppActivate(BOOL fActive, BOOL minimize);
157 //void ClearAllStates (void);
158 //void VID_UpdateWindowStatus (void);
159
160 //====================================
161
162 static int window_x, window_y;
163
164 static qboolean mouseinitialized;
165
166 #ifdef SUPPORTDIRECTX
167 static qboolean dinput;
168 #define DINPUT_BUFFERSIZE           16
169 #define iDirectInputCreate(a,b,c,d)     pDirectInputCreate(a,b,c,d)
170
171 static HRESULT (WINAPI *pDirectInputCreate)(HINSTANCE hinst, DWORD dwVersion, LPDIRECTINPUT * lplpDirectInput, LPUNKNOWN punkOuter);
172 #endif
173
174 // LordHavoc: thanks to backslash for this support for mouse buttons 4 and 5
175 /* backslash :: imouse explorer buttons */
176 /* These are #ifdefed out for non-Win2K in the February 2001 version of
177    MS's platform SDK, but we need them for compilation. . . */
178 #ifndef WM_XBUTTONDOWN
179    #define WM_XBUTTONDOWN      0x020B
180    #define WM_XBUTTONUP      0x020C
181 #endif
182 #ifndef MK_XBUTTON1
183    #define MK_XBUTTON1         0x0020
184    #define MK_XBUTTON2         0x0040
185 #endif
186 #ifndef MK_XBUTTON3
187 // LordHavoc: lets hope this allows more buttons in the future...
188    #define MK_XBUTTON3         0x0080
189    #define MK_XBUTTON4         0x0100
190    #define MK_XBUTTON5         0x0200
191    #define MK_XBUTTON6         0x0400
192    #define MK_XBUTTON7         0x0800
193 #endif
194 /* :: backslash */
195
196 // mouse variables
197 static int                      mouse_buttons;
198 static int                      mouse_oldbuttonstate;
199
200 static unsigned int uiWheelMessage;
201 #ifdef SUPPORTDIRECTX
202 static qboolean dinput_acquired;
203
204 static unsigned int             mstate_di;
205 #endif
206
207 static cvar_t vid_forcerefreshrate = {0, "vid_forcerefreshrate", "0", "try to set the given vid_refreshrate even if Windows doesn't list it as valid video mode"};
208
209 #ifdef SUPPORTDIRECTX
210 static LPDIRECTINPUT            g_pdi;
211 static LPDIRECTINPUTDEVICE      g_pMouse;
212 static HINSTANCE hInstDI;
213 #endif
214
215 // forward-referenced functions
216 static void IN_StartupMouse (void);
217
218
219 //====================================
220
221 qboolean vid_reallyhidden = true;
222 #ifdef SUPPORTD3D
223 qboolean vid_begunscene = false;
224 #endif
225 void VID_Finish (void)
226 {
227 #ifdef SUPPORTD3D
228         HRESULT hr;
229 #endif
230         vid_hidden = vid_reallyhidden;
231
232         vid_usevsync = vid_vsync.integer && !cls.timedemo && qwglSwapIntervalEXT;
233
234         if (!vid_hidden)
235         {
236                 switch(vid.renderpath)
237                 {
238                 case RENDERPATH_GL11:
239                 case RENDERPATH_GL13:
240                 case RENDERPATH_GL20:
241                 case RENDERPATH_GLES1:
242                 case RENDERPATH_GLES2:
243                         if (vid_usingvsync != vid_usevsync)
244                         {
245                                 vid_usingvsync = vid_usevsync;
246                                 qwglSwapIntervalEXT (vid_usevsync);
247                         }
248                         if (r_speeds.integer == 2 || gl_finish.integer)
249                                 GL_Finish();
250                         SwapBuffers(baseDC);
251                         break;
252                 case RENDERPATH_D3D9:
253 #ifdef SUPPORTD3D
254                         if (vid_begunscene)
255                         {
256                                 IDirect3DDevice9_EndScene(vid_d3d9dev);
257                                 vid_begunscene = false;
258                         }
259                         if (!vid_reallyhidden)
260                         {
261                                 if (!vid_d3ddevicelost)
262                                 {
263                                         vid_hidden = vid_reallyhidden;
264                                         hr = IDirect3DDevice9_Present(vid_d3d9dev, NULL, NULL, NULL, NULL);
265                                         if (hr == D3DERR_DEVICELOST)
266                                         {
267                                                 vid_d3ddevicelost = true;
268                                                 vid_hidden = true;
269                                                 Sleep(100);
270                                         }
271                                 }
272                                 else
273                                 {
274                                         hr = IDirect3DDevice9_TestCooperativeLevel(vid_d3d9dev);
275                                         switch(hr)
276                                         {
277                                         case D3DERR_DEVICELOST:
278                                                 vid_d3ddevicelost = true;
279                                                 vid_hidden = true;
280                                                 Sleep(100);
281                                                 break;
282                                         case D3DERR_DEVICENOTRESET:
283                                                 vid_d3ddevicelost = false;
284                                                 vid_hidden = vid_reallyhidden;
285                                                 R_Modules_DeviceLost();
286                                                 IDirect3DDevice9_Reset(vid_d3d9dev, &vid_d3dpresentparameters);
287                                                 R_Modules_DeviceRestored();
288                                                 break;
289                                         case D3D_OK:
290                                                 vid_hidden = vid_reallyhidden;
291                                                 IDirect3DDevice9_Present(vid_d3d9dev, NULL, NULL, NULL, NULL);
292                                                 break;
293                                         }
294                                 }
295                                 if (!vid_begunscene && !vid_hidden)
296                                 {
297                                         IDirect3DDevice9_BeginScene(vid_d3d9dev);
298                                         vid_begunscene = true;
299                                 }
300                         }
301 #endif
302                         break;
303                 case RENDERPATH_D3D10:
304                         break;
305                 case RENDERPATH_D3D11:
306                         break;
307                 case RENDERPATH_SOFT:
308                         DPSOFTRAST_Finish();
309 //                      baseDC = GetDC(mainwindow);
310                         BitBlt(baseDC, 0, 0, vid.width, vid.height, vid_softhdc, 0, 0, SRCCOPY);
311 //                      ReleaseDC(mainwindow, baseDC);
312 //                      baseDC = NULL;
313                         break;
314                 }
315         }
316
317         // make sure a context switch can happen every frame - Logitech drivers
318         // input drivers sometimes eat cpu time every 3 seconds or lag badly
319         // without this help
320         Sleep(0);
321
322         VID_UpdateGamma(false, 256);
323 }
324
325 //==========================================================================
326
327
328
329
330 static unsigned char scantokey[128] =
331 {
332 //  0           1       2    3     4     5       6       7      8         9      A          B           C       D           E           F
333         0          ,27    ,'1'  ,'2'  ,'3'  ,'4'    ,'5'    ,'6'   ,'7'      ,'8'   ,'9'       ,'0'        ,'-'   ,'='         ,K_BACKSPACE,9    ,//0
334         'q'        ,'w'   ,'e'  ,'r'  ,'t'  ,'y'    ,'u'    ,'i'   ,'o'      ,'p'   ,'['       ,']'        ,13    ,K_CTRL      ,'a'        ,'s'  ,//1
335         'd'        ,'f'   ,'g'  ,'h'  ,'j'  ,'k'    ,'l'    ,';'   ,'\''     ,'`'   ,K_SHIFT   ,'\\'       ,'z'   ,'x'         ,'c'        ,'v'  ,//2
336         'b'        ,'n'   ,'m'  ,','  ,'.'  ,'/'    ,K_SHIFT,'*'   ,K_ALT    ,' '   ,0         ,K_F1       ,K_F2  ,K_F3        ,K_F4       ,K_F5 ,//3
337         K_F6       ,K_F7  ,K_F8 ,K_F9 ,K_F10,K_PAUSE,0      ,K_HOME,K_UPARROW,K_PGUP,K_KP_MINUS,K_LEFTARROW,K_KP_5,K_RIGHTARROW,K_KP_PLUS  ,K_END,//4
338         K_DOWNARROW,K_PGDN,K_INS,K_DEL,0    ,0      ,0      ,K_F11 ,K_F12    ,0     ,0         ,0          ,0     ,0           ,0          ,0    ,//5
339         0          ,0     ,0    ,0    ,0    ,0      ,0      ,0     ,0        ,0     ,0         ,0          ,0     ,0           ,0          ,0    ,//6
340         0          ,0     ,0    ,0    ,0    ,0      ,0      ,0     ,0        ,0     ,0         ,0          ,0     ,0           ,0          ,0     //7
341 };
342
343
344 /*
345 =======
346 MapKey
347
348 Map from windows to quake keynums
349 =======
350 */
351 static int MapKey (int key, int virtualkey)
352 {
353         int result;
354         int modified = (key >> 16) & 255;
355         qboolean is_extended = false;
356
357         if (modified < 128 && scantokey[modified])
358                 result = scantokey[modified];
359         else
360         {
361                 result = 0;
362                 Con_DPrintf("key 0x%02x (0x%8x, 0x%8x) has no translation\n", modified, key, virtualkey);
363         }
364
365         if (key & (1 << 24))
366                 is_extended = true;
367
368         if ( !is_extended )
369         {
370                 switch ( result )
371                 {
372                 case K_HOME:
373                         return K_KP_HOME;
374                 case K_UPARROW:
375                         return K_KP_UPARROW;
376                 case K_PGUP:
377                         return K_KP_PGUP;
378                 case K_LEFTARROW:
379                         return K_KP_LEFTARROW;
380                 case K_RIGHTARROW:
381                         return K_KP_RIGHTARROW;
382                 case K_END:
383                         return K_KP_END;
384                 case K_DOWNARROW:
385                         return K_KP_DOWNARROW;
386                 case K_PGDN:
387                         return K_KP_PGDN;
388                 case K_INS:
389                         return K_KP_INS;
390                 case K_DEL:
391                         return K_KP_DEL;
392                 default:
393                         return result;
394                 }
395         }
396         else
397         {
398                 switch ( result )
399                 {
400                 case 0x0D:
401                         return K_KP_ENTER;
402                 case 0x2F:
403                         return K_KP_SLASH;
404                 case 0xAF:
405                         return K_KP_PLUS;
406                 }
407                 return result;
408         }
409 }
410
411 /*
412 ===================================================================
413
414 MAIN WINDOW
415
416 ===================================================================
417 */
418
419 /*
420 ================
421 ClearAllStates
422 ================
423 */
424 static void ClearAllStates (void)
425 {
426         Key_ClearStates ();
427         if (vid_usingmouse)
428                 mouse_oldbuttonstate = 0;
429 }
430
431 void AppActivate(BOOL fActive, BOOL minimize)
432 /****************************************************************************
433 *
434 * Function:     AppActivate
435 * Parameters:   fActive - True if app is activating
436 *
437 * Description:  If the application is activating, then swap the system
438 *               into SYSPAL_NOSTATIC mode so that our palettes will display
439 *               correctly.
440 *
441 ****************************************************************************/
442 {
443         static qboolean sound_active = false;  // initially blocked by Sys_InitConsole()
444
445         vid_activewindow = fActive != FALSE;
446         vid_reallyhidden = minimize != FALSE;
447
448         // enable/disable sound on focus gain/loss
449         if ((!vid_reallyhidden && vid_activewindow) || !snd_mutewhenidle.integer)
450         {
451                 if (!sound_active)
452                 {
453                         S_UnblockSound ();
454                         sound_active = true;
455                 }
456         }
457         else
458         {
459                 if (sound_active)
460                 {
461                         S_BlockSound ();
462                         sound_active = false;
463                 }
464         }
465
466         if (fActive)
467         {
468                 if (vid_isfullscreen)
469                 {
470                         if (vid_wassuspended)
471                         {
472                                 vid_wassuspended = false;
473                                 if (gldll)
474                                 {
475                                         ChangeDisplaySettings (&gdevmode, CDS_FULLSCREEN);
476                                         ShowWindow(mainwindow, SW_SHOWNORMAL);
477                                 }
478                         }
479
480                         // LordHavoc: from dabb, fix for alt-tab bug in NVidia drivers
481                         if (gldll)
482                                 MoveWindow(mainwindow,0,0,gdevmode.dmPelsWidth,gdevmode.dmPelsHeight,false);
483                 }
484         }
485
486         if (!fActive)
487         {
488                 VID_SetMouse(false, false, false);
489                 if (vid_isfullscreen)
490                 {
491                         if (gldll)
492                                 ChangeDisplaySettings (NULL, 0);
493                         vid_wassuspended = true;
494                 }
495                 VID_RestoreSystemGamma();
496         }
497 }
498
499 //TODO: move it around in vid_wgl.c since I dont think this is the right position
500 void Sys_SendKeyEvents (void)
501 {
502         MSG msg;
503
504         while (PeekMessage (&msg, NULL, 0, 0, PM_NOREMOVE))
505         {
506                 if (!GetMessage (&msg, NULL, 0, 0))
507                         Sys_Quit (1);
508
509                 TranslateMessage (&msg);
510                 DispatchMessage (&msg);
511         }
512 }
513
514 LONG CDAudio_MessageHandler(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
515
516 static keynum_t buttonremap[16] =
517 {
518         K_MOUSE1,
519         K_MOUSE2,
520         K_MOUSE3,
521         K_MOUSE4,
522         K_MOUSE5,
523         K_MOUSE6,
524         K_MOUSE7,
525         K_MOUSE8,
526         K_MOUSE9,
527         K_MOUSE10,
528         K_MOUSE11,
529         K_MOUSE12,
530         K_MOUSE13,
531         K_MOUSE14,
532         K_MOUSE15,
533         K_MOUSE16,
534 };
535
536 /* main window procedure */
537 LONG WINAPI MainWndProc (HWND hWnd, UINT uMsg, WPARAM  wParam, LPARAM lParam)
538 {
539         LONG    lRet = 1;
540         int             fActive, fMinimized, temp;
541         unsigned char state[256];
542         unsigned char asciichar[4];
543         int             vkey;
544         int             charlength;
545         qboolean down = false;
546
547         if ( uMsg == uiWheelMessage )
548                 uMsg = WM_MOUSEWHEEL;
549
550         switch (uMsg)
551         {
552                 case WM_KILLFOCUS:
553                         if (vid_isfullscreen)
554                                 ShowWindow(mainwindow, SW_SHOWMINNOACTIVE);
555                         break;
556
557                 case WM_CREATE:
558                         break;
559
560                 case WM_MOVE:
561                         window_x = (int) LOWORD(lParam);
562                         window_y = (int) HIWORD(lParam);
563                         VID_SetMouse(false, false, false);
564                         break;
565
566                 case WM_KEYDOWN:
567                 case WM_SYSKEYDOWN:
568                         down = true;
569                 case WM_KEYUP:
570                 case WM_SYSKEYUP:
571                         vkey = MapKey(lParam, wParam);
572                         GetKeyboardState (state);
573                         // alt/ctrl/shift tend to produce funky ToAscii values,
574                         // and if it's not a single character we don't know care about it
575                         charlength = ToAscii (wParam, lParam >> 16, state, (LPWORD)asciichar, 0);
576                         if (vkey == K_ALT || vkey == K_CTRL || vkey == K_SHIFT || charlength == 0)
577                                 asciichar[0] = 0;
578                         else if( charlength == 2 ) {
579                                 asciichar[0] = asciichar[1];
580                         }
581                         if (!VID_JoyBlockEmulatedKeys(vkey))
582                                 Key_Event (vkey, asciichar[0], down);
583                         break;
584
585                 case WM_SYSCHAR:
586                 // keep Alt-Space from happening
587                         break;
588
589                 case WM_SYSCOMMAND:
590                         // prevent screensaver from occuring while the active window
591                         // note: password-locked screensavers on Vista still work
592                         if (vid_activewindow && ((wParam & 0xFFF0) == SC_SCREENSAVE || (wParam & 0xFFF0) == SC_MONITORPOWER))
593                                 lRet = 0;
594                         else
595                                 lRet = DefWindowProc (hWnd, uMsg, wParam, lParam);
596                         break;
597
598         // this is complicated because Win32 seems to pack multiple mouse events into
599         // one update sometimes, so we always check all states and look for events
600                 case WM_LBUTTONDOWN:
601                 case WM_LBUTTONUP:
602                 case WM_RBUTTONDOWN:
603                 case WM_RBUTTONUP:
604                 case WM_MBUTTONDOWN:
605                 case WM_MBUTTONUP:
606                 case WM_XBUTTONDOWN:   // backslash :: imouse explorer buttons
607                 case WM_XBUTTONUP:      // backslash :: imouse explorer buttons
608                 case WM_MOUSEMOVE:
609                         temp = 0;
610
611                         if (wParam & MK_LBUTTON)
612                                 temp |= 1;
613
614                         if (wParam & MK_RBUTTON)
615                                 temp |= 2;
616
617                         if (wParam & MK_MBUTTON)
618                                 temp |= 4;
619
620                         /* backslash :: imouse explorer buttons */
621                         if (wParam & MK_XBUTTON1)
622                                 temp |= 8;
623
624                         if (wParam & MK_XBUTTON2)
625                                 temp |= 16;
626                         /* :: backslash */
627
628                         // LordHavoc: lets hope this allows more buttons in the future...
629                         if (wParam & MK_XBUTTON3)
630                                 temp |= 32;
631                         if (wParam & MK_XBUTTON4)
632                                 temp |= 64;
633                         if (wParam & MK_XBUTTON5)
634                                 temp |= 128;
635                         if (wParam & MK_XBUTTON6)
636                                 temp |= 256;
637                         if (wParam & MK_XBUTTON7)
638                                 temp |= 512;
639
640 #ifdef SUPPORTDIRECTX
641                         if (!dinput_acquired)
642 #endif
643                         {
644                                 // perform button actions
645                                 int i;
646                                 for (i=0 ; i<mouse_buttons && i < 16 ; i++)
647                                         if ((temp ^ mouse_oldbuttonstate) & (1<<i))
648                                                 Key_Event (buttonremap[i], 0, (temp & (1<<i)) != 0);
649                                 mouse_oldbuttonstate = temp;
650                         }
651
652                         break;
653
654                 // JACK: This is the mouse wheel with the Intellimouse
655                 // Its delta is either positive or neg, and we generate the proper
656                 // Event.
657                 case WM_MOUSEWHEEL:
658                         if ((short) HIWORD(wParam) > 0) {
659                                 Key_Event(K_MWHEELUP, 0, true);
660                                 Key_Event(K_MWHEELUP, 0, false);
661                         } else {
662                                 Key_Event(K_MWHEELDOWN, 0, true);
663                                 Key_Event(K_MWHEELDOWN, 0, false);
664                         }
665                         break;
666
667                 case WM_SIZE:
668                         break;
669
670                 case WM_CLOSE:
671                         if (MessageBox (mainwindow, "Are you sure you want to quit?", "Confirm Exit", MB_YESNO | MB_SETFOREGROUND | MB_ICONQUESTION) == IDYES)
672                                 Sys_Quit (0);
673
674                         break;
675
676                 case WM_ACTIVATE:
677                         fActive = LOWORD(wParam);
678                         fMinimized = (BOOL) HIWORD(wParam);
679                         AppActivate(!(fActive == WA_INACTIVE), fMinimized);
680
681                 // fix the leftover Alt from any Alt-Tab or the like that switched us away
682                         ClearAllStates ();
683
684                         break;
685
686                 //case WM_DESTROY:
687                 //      PostQuitMessage (0);
688                 //      break;
689
690                 case MM_MCINOTIFY:
691                         lRet = CDAudio_MessageHandler (hWnd, uMsg, wParam, lParam);
692                         break;
693
694                 default:
695                         /* pass all unhandled messages to DefWindowProc */
696                         lRet = DefWindowProc (hWnd, uMsg, wParam, lParam);
697                 break;
698         }
699
700         /* return 1 if handled message, 0 if not */
701         return lRet;
702 }
703
704 int VID_SetGamma(unsigned short *ramps, int rampsize)
705 {
706         if (qwglMakeCurrent)
707         {
708                 HDC hdc = GetDC (NULL);
709                 int i = SetDeviceGammaRamp(hdc, ramps);
710                 ReleaseDC (NULL, hdc);
711                 return i; // return success or failure
712         }
713         else
714                 return 0;
715 }
716
717 int VID_GetGamma(unsigned short *ramps, int rampsize)
718 {
719         if (qwglMakeCurrent)
720         {
721                 HDC hdc = GetDC (NULL);
722                 int i = GetDeviceGammaRamp(hdc, ramps);
723                 ReleaseDC (NULL, hdc);
724                 return i; // return success or failure
725         }
726         else
727                 return 0;
728 }
729
730 static void GL_CloseLibrary(void)
731 {
732         if (gldll)
733         {
734                 FreeLibrary(gldll);
735                 gldll = 0;
736                 gl_driver[0] = 0;
737                 qwglGetProcAddress = NULL;
738                 gl_extensions = "";
739                 gl_platform = "";
740                 gl_platformextensions = "";
741         }
742 }
743
744 static int GL_OpenLibrary(const char *name)
745 {
746         Con_Printf("Loading OpenGL driver %s\n", name);
747         GL_CloseLibrary();
748         if (!(gldll = LoadLibrary(name)))
749         {
750                 Con_Printf("Unable to LoadLibrary %s\n", name);
751                 return false;
752         }
753         strlcpy(gl_driver, name, sizeof(gl_driver));
754         return true;
755 }
756
757 void *GL_GetProcAddress(const char *name)
758 {
759         if (gldll)
760         {
761                 void *p = NULL;
762                 if (qwglGetProcAddress != NULL)
763                         p = (void *) qwglGetProcAddress(name);
764                 if (p == NULL)
765                         p = (void *) GetProcAddress(gldll, name);
766                 return p;
767         }
768         else
769                 return NULL;
770 }
771
772 #ifndef WGL_ARB_pixel_format
773 #define WGL_NUMBER_PIXEL_FORMATS_ARB   0x2000
774 #define WGL_DRAW_TO_WINDOW_ARB         0x2001
775 #define WGL_DRAW_TO_BITMAP_ARB         0x2002
776 #define WGL_ACCELERATION_ARB           0x2003
777 #define WGL_NEED_PALETTE_ARB           0x2004
778 #define WGL_NEED_SYSTEM_PALETTE_ARB    0x2005
779 #define WGL_SWAP_LAYER_BUFFERS_ARB     0x2006
780 #define WGL_SWAP_METHOD_ARB            0x2007
781 #define WGL_NUMBER_OVERLAYS_ARB        0x2008
782 #define WGL_NUMBER_UNDERLAYS_ARB       0x2009
783 #define WGL_TRANSPARENT_ARB            0x200A
784 #define WGL_TRANSPARENT_RED_VALUE_ARB  0x2037
785 #define WGL_TRANSPARENT_GREEN_VALUE_ARB 0x2038
786 #define WGL_TRANSPARENT_BLUE_VALUE_ARB 0x2039
787 #define WGL_TRANSPARENT_ALPHA_VALUE_ARB 0x203A
788 #define WGL_TRANSPARENT_INDEX_VALUE_ARB 0x203B
789 #define WGL_SHARE_DEPTH_ARB            0x200C
790 #define WGL_SHARE_STENCIL_ARB          0x200D
791 #define WGL_SHARE_ACCUM_ARB            0x200E
792 #define WGL_SUPPORT_GDI_ARB            0x200F
793 #define WGL_SUPPORT_OPENGL_ARB         0x2010
794 #define WGL_DOUBLE_BUFFER_ARB          0x2011
795 #define WGL_STEREO_ARB                 0x2012
796 #define WGL_PIXEL_TYPE_ARB             0x2013
797 #define WGL_COLOR_BITS_ARB             0x2014
798 #define WGL_RED_BITS_ARB               0x2015
799 #define WGL_RED_SHIFT_ARB              0x2016
800 #define WGL_GREEN_BITS_ARB             0x2017
801 #define WGL_GREEN_SHIFT_ARB            0x2018
802 #define WGL_BLUE_BITS_ARB              0x2019
803 #define WGL_BLUE_SHIFT_ARB             0x201A
804 #define WGL_ALPHA_BITS_ARB             0x201B
805 #define WGL_ALPHA_SHIFT_ARB            0x201C
806 #define WGL_ACCUM_BITS_ARB             0x201D
807 #define WGL_ACCUM_RED_BITS_ARB         0x201E
808 #define WGL_ACCUM_GREEN_BITS_ARB       0x201F
809 #define WGL_ACCUM_BLUE_BITS_ARB        0x2020
810 #define WGL_ACCUM_ALPHA_BITS_ARB       0x2021
811 #define WGL_DEPTH_BITS_ARB             0x2022
812 #define WGL_STENCIL_BITS_ARB           0x2023
813 #define WGL_AUX_BUFFERS_ARB            0x2024
814 #define WGL_NO_ACCELERATION_ARB        0x2025
815 #define WGL_GENERIC_ACCELERATION_ARB   0x2026
816 #define WGL_FULL_ACCELERATION_ARB      0x2027
817 #define WGL_SWAP_EXCHANGE_ARB          0x2028
818 #define WGL_SWAP_COPY_ARB              0x2029
819 #define WGL_SWAP_UNDEFINED_ARB         0x202A
820 #define WGL_TYPE_RGBA_ARB              0x202B
821 #define WGL_TYPE_COLORINDEX_ARB        0x202C
822 #endif
823
824 #ifndef WGL_ARB_multisample
825 #define WGL_SAMPLE_BUFFERS_ARB         0x2041
826 #define WGL_SAMPLES_ARB                0x2042
827 #endif
828
829
830 static void IN_Init(void);
831 void VID_Init(void)
832 {
833         WNDCLASS wc;
834
835 #ifdef SUPPORTD3D
836         Cvar_RegisterVariable(&vid_dx9);
837         Cvar_RegisterVariable(&vid_dx9_hal);
838         Cvar_RegisterVariable(&vid_dx9_softvertex);
839         Cvar_RegisterVariable(&vid_dx9_triplebuffer);
840 //      Cvar_RegisterVariable(&vid_dx10);
841 //      Cvar_RegisterVariable(&vid_dx11);
842 #endif
843
844         InitCommonControls();
845         hIcon = LoadIcon (global_hInstance, MAKEINTRESOURCE (IDI_ICON1));
846
847         // Register the frame class
848         wc.style         = 0;
849         wc.lpfnWndProc   = (WNDPROC)MainWndProc;
850         wc.cbClsExtra    = 0;
851         wc.cbWndExtra    = 0;
852         wc.hInstance     = global_hInstance;
853         wc.hIcon         = hIcon;
854         wc.hCursor       = LoadCursor (NULL,IDC_ARROW);
855         wc.hbrBackground = NULL;
856         wc.lpszMenuName  = 0;
857         wc.lpszClassName = "DarkPlacesWindowClass";
858
859         if (!RegisterClass (&wc))
860                 Con_Printf ("Couldn't register window class\n");
861
862         memset(&initialdevmode, 0, sizeof(initialdevmode));
863         EnumDisplaySettings(NULL, ENUM_CURRENT_SETTINGS, &initialdevmode);
864
865         IN_Init();
866 }
867
868 qboolean VID_InitModeGL(viddef_mode_t *mode)
869 {
870         int i;
871         HDC hdc;
872         RECT rect;
873         MSG msg;
874         PIXELFORMATDESCRIPTOR pfd =
875         {
876                 sizeof(PIXELFORMATDESCRIPTOR),  // size of this pfd
877                 1,                              // version number
878                 PFD_DRAW_TO_WINDOW              // support window
879                 |  PFD_SUPPORT_OPENGL   // support OpenGL
880                 |  PFD_DOUBLEBUFFER ,   // double buffered
881                 PFD_TYPE_RGBA,                  // RGBA type
882                 24,                             // 24-bit color depth
883                 0, 0, 0, 0, 0, 0,               // color bits ignored
884                 0,                              // no alpha buffer
885                 0,                              // shift bit ignored
886                 0,                              // no accumulation buffer
887                 0, 0, 0, 0,                     // accum bits ignored
888                 32,                             // 32-bit z-buffer
889                 0,                              // no stencil buffer
890                 0,                              // no auxiliary buffer
891                 PFD_MAIN_PLANE,                 // main layer
892                 0,                              // reserved
893                 0, 0, 0                         // layer masks ignored
894         };
895         int windowpass;
896         int pixelformat, newpixelformat;
897         UINT numpixelformats;
898         DWORD WindowStyle, ExWindowStyle;
899         int CenterX, CenterY;
900         const char *gldrivername;
901         int depth;
902         DEVMODE thismode;
903         qboolean foundmode, foundgoodmode;
904         int *a;
905         float *af;
906         int attribs[128];
907         float attribsf[16];
908         int bpp = mode->bitsperpixel;
909         int width = mode->width;
910         int height = mode->height;
911         int refreshrate = (int)floor(mode->refreshrate+0.5);
912         int stereobuffer = mode->stereobuffer;
913         int samples = mode->samples;
914         int fullscreen = mode->fullscreen;
915
916         if (vid_initialized)
917                 Sys_Error("VID_InitMode called when video is already initialised");
918
919         // if stencil is enabled, ask for alpha too
920         if (bpp >= 32)
921         {
922                 pfd.cRedBits = 8;
923                 pfd.cGreenBits = 8;
924                 pfd.cBlueBits = 8;
925                 pfd.cAlphaBits = 8;
926                 pfd.cDepthBits = 24;
927                 pfd.cStencilBits = 8;
928         }
929         else
930         {
931                 pfd.cRedBits = 5;
932                 pfd.cGreenBits = 5;
933                 pfd.cBlueBits = 5;
934                 pfd.cAlphaBits = 0;
935                 pfd.cDepthBits = 16;
936                 pfd.cStencilBits = 0;
937         }
938
939         if (stereobuffer)
940                 pfd.dwFlags |= PFD_STEREO;
941
942         a = attribs;
943         af = attribsf;
944         *a++ = WGL_DRAW_TO_WINDOW_ARB;
945         *a++ = GL_TRUE;
946         *a++ = WGL_ACCELERATION_ARB;
947         *a++ = WGL_FULL_ACCELERATION_ARB;
948         *a++ = WGL_DOUBLE_BUFFER_ARB;
949         *a++ = true;
950
951         if (bpp >= 32)
952         {
953                 *a++ = WGL_RED_BITS_ARB;
954                 *a++ = 8;
955                 *a++ = WGL_GREEN_BITS_ARB;
956                 *a++ = 8;
957                 *a++ = WGL_BLUE_BITS_ARB;
958                 *a++ = 8;
959                 *a++ = WGL_ALPHA_BITS_ARB;
960                 *a++ = 8;
961                 *a++ = WGL_DEPTH_BITS_ARB;
962                 *a++ = 24;
963                 *a++ = WGL_STENCIL_BITS_ARB;
964                 *a++ = 8;
965         }
966         else
967         {
968                 *a++ = WGL_RED_BITS_ARB;
969                 *a++ = 1;
970                 *a++ = WGL_GREEN_BITS_ARB;
971                 *a++ = 1;
972                 *a++ = WGL_BLUE_BITS_ARB;
973                 *a++ = 1;
974                 *a++ = WGL_DEPTH_BITS_ARB;
975                 *a++ = 16;
976         }
977
978         if (stereobuffer)
979         {
980                 *a++ = WGL_STEREO_ARB;
981                 *a++ = GL_TRUE;
982         }
983
984         if (samples > 1)
985         {
986                 *a++ = WGL_SAMPLE_BUFFERS_ARB;
987                 *a++ = 1;
988                 *a++ = WGL_SAMPLES_ARB;
989                 *a++ = samples;
990         }
991
992         *a = 0;
993         *af = 0;
994
995         gldrivername = "opengl32.dll";
996 // COMMANDLINEOPTION: Windows WGL: -gl_driver <drivername> selects a GL driver library, default is opengl32.dll, useful only for 3dfxogl.dll or 3dfxvgl.dll, if you don't know what this is for, you don't need it
997         i = COM_CheckParm("-gl_driver");
998         if (i && i < com_argc - 1)
999                 gldrivername = com_argv[i + 1];
1000         if (!GL_OpenLibrary(gldrivername))
1001         {
1002                 Con_Printf("Unable to load GL driver %s\n", gldrivername);
1003                 return false;
1004         }
1005
1006         memset(&gdevmode, 0, sizeof(gdevmode));
1007
1008         vid_isfullscreen = false;
1009         if (fullscreen)
1010         {
1011                 if(vid_forcerefreshrate.integer)
1012                 {
1013                         foundmode = true;
1014                         gdevmode.dmFields = DM_BITSPERPEL | DM_PELSWIDTH | DM_PELSHEIGHT;
1015                         gdevmode.dmBitsPerPel = bpp;
1016                         gdevmode.dmPelsWidth = width;
1017                         gdevmode.dmPelsHeight = height;
1018                         gdevmode.dmSize = sizeof (gdevmode);
1019                         if(refreshrate)
1020                         {
1021                                 gdevmode.dmFields |= DM_DISPLAYFREQUENCY;
1022                                 gdevmode.dmDisplayFrequency = refreshrate;
1023                         }
1024                 }
1025                 else
1026                 {
1027                         if(refreshrate == 0)
1028                                 refreshrate = initialdevmode.dmDisplayFrequency; // default vid_refreshrate to the rate of the desktop
1029
1030                         foundmode = false;
1031                         foundgoodmode = false;
1032
1033                         thismode.dmSize = sizeof(thismode);
1034                         thismode.dmDriverExtra = 0;
1035                         for(i = 0; EnumDisplaySettings(NULL, i, &thismode); ++i)
1036                         {
1037                                 if(~thismode.dmFields & (DM_BITSPERPEL | DM_PELSWIDTH | DM_PELSHEIGHT | DM_DISPLAYFREQUENCY))
1038                                 {
1039                                         Con_DPrintf("enumerating modes yielded a bogus item... please debug this\n");
1040                                         continue;
1041                                 }
1042                                 if(developer_extra.integer)
1043                                         Con_DPrintf("Found mode %dx%dx%dbpp %dHz... ", (int)thismode.dmPelsWidth, (int)thismode.dmPelsHeight, (int)thismode.dmBitsPerPel, (int)thismode.dmDisplayFrequency);
1044                                 if(thismode.dmBitsPerPel != (DWORD)bpp)
1045                                 {
1046                                         if(developer_extra.integer)
1047                                                 Con_DPrintf("wrong bpp\n");
1048                                         continue;
1049                                 }
1050                                 if(thismode.dmPelsWidth != (DWORD)width)
1051                                 {
1052                                         if(developer_extra.integer)
1053                                                 Con_DPrintf("wrong width\n");
1054                                         continue;
1055                                 }
1056                                 if(thismode.dmPelsHeight != (DWORD)height)
1057                                 {
1058                                         if(developer_extra.integer)
1059                                                 Con_DPrintf("wrong height\n");
1060                                         continue;
1061                                 }
1062
1063                                 if(foundgoodmode)
1064                                 {
1065                                         // if we have a good mode, make sure this mode is better than the previous one, and allowed by the refreshrate
1066                                         if(thismode.dmDisplayFrequency > (DWORD)refreshrate)
1067                                         {
1068                                                 if(developer_extra.integer)
1069                                                         Con_DPrintf("too high refresh rate\n");
1070                                                 continue;
1071                                         }
1072                                         else if(thismode.dmDisplayFrequency <= gdevmode.dmDisplayFrequency)
1073                                         {
1074                                                 if(developer_extra.integer)
1075                                                         Con_DPrintf("doesn't beat previous best match (too low)\n");
1076                                                 continue;
1077                                         }
1078                                 }
1079                                 else if(foundmode)
1080                                 {
1081                                         // we do have one, but it isn't good... make sure it has a lower frequency than the previous one
1082                                         if(thismode.dmDisplayFrequency >= gdevmode.dmDisplayFrequency)
1083                                         {
1084                                                 if(developer_extra.integer)
1085                                                         Con_DPrintf("doesn't beat previous best match (too high)\n");
1086                                                 continue;
1087                                         }
1088                                 }
1089                                 // otherwise, take anything
1090
1091                                 memcpy(&gdevmode, &thismode, sizeof(gdevmode));
1092                                 if(thismode.dmDisplayFrequency <= (DWORD)refreshrate)
1093                                         foundgoodmode = true;
1094                                 else
1095                                 {
1096                                         if(developer_extra.integer)
1097                                                 Con_DPrintf("(out of range)\n");
1098                                 }
1099                                 foundmode = true;
1100                                 if(developer_extra.integer)
1101                                         Con_DPrintf("accepted\n");
1102                         }
1103                 }
1104
1105                 if (!foundmode)
1106                 {
1107                         VID_Shutdown();
1108                         Con_Printf("Unable to find the requested mode %dx%dx%dbpp\n", width, height, bpp);
1109                         return false;
1110                 }
1111                 else if(ChangeDisplaySettings (&gdevmode, CDS_FULLSCREEN) != DISP_CHANGE_SUCCESSFUL)
1112                 {
1113                         VID_Shutdown();
1114                         Con_Printf("Unable to change to requested mode %dx%dx%dbpp\n", width, height, bpp);
1115                         return false;
1116                 }
1117
1118                 vid_isfullscreen = true;
1119                 WindowStyle = WS_POPUP;
1120                 ExWindowStyle = WS_EX_TOPMOST;
1121         }
1122         else
1123         {
1124                 hdc = GetDC (NULL);
1125                 i = GetDeviceCaps(hdc, RASTERCAPS);
1126                 depth = GetDeviceCaps(hdc, PLANES) * GetDeviceCaps(hdc, BITSPIXEL);
1127                 ReleaseDC (NULL, hdc);
1128                 if (i & RC_PALETTE)
1129                 {
1130                         VID_Shutdown();
1131                         Con_Print("Can't run in non-RGB mode\n");
1132                         return false;
1133                 }
1134                 if (bpp > depth)
1135                 {
1136                         VID_Shutdown();
1137                         Con_Print("A higher desktop depth is required to run this video mode\n");
1138                         return false;
1139                 }
1140
1141                 WindowStyle = WS_OVERLAPPED | WS_BORDER | WS_CAPTION | WS_SYSMENU | WS_MINIMIZEBOX;
1142                 ExWindowStyle = 0;
1143         }
1144
1145         rect.top = 0;
1146         rect.left = 0;
1147         rect.right = width;
1148         rect.bottom = height;
1149         AdjustWindowRectEx(&rect, WindowStyle, false, 0);
1150
1151         if (fullscreen)
1152         {
1153                 CenterX = 0;
1154                 CenterY = 0;
1155         }
1156         else
1157         {
1158                 CenterX = (GetSystemMetrics(SM_CXSCREEN) - (rect.right - rect.left)) / 2;
1159                 CenterY = (GetSystemMetrics(SM_CYSCREEN) - (rect.bottom - rect.top)) / 2;
1160         }
1161         CenterX = max(0, CenterX);
1162         CenterY = max(0, CenterY);
1163
1164         // x and y may be changed by WM_MOVE messages
1165         window_x = CenterX;
1166         window_y = CenterY;
1167         rect.left += CenterX;
1168         rect.right += CenterX;
1169         rect.top += CenterY;
1170         rect.bottom += CenterY;
1171
1172         pixelformat = 0;
1173         newpixelformat = 0;
1174         // start out at the final windowpass if samples is 1 as it's the only feature we need extended pixel formats for
1175         for (windowpass = samples == 1;windowpass < 2;windowpass++)
1176         {
1177                 gl_extensions = "";
1178                 gl_platformextensions = "";
1179
1180                 mainwindow = CreateWindowEx (ExWindowStyle, "DarkPlacesWindowClass", gamename, WindowStyle, rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top, NULL, NULL, global_hInstance, NULL);
1181                 if (!mainwindow)
1182                 {
1183                         Con_Printf("CreateWindowEx(%d, %s, %s, %d, %d, %d, %d, %d, %p, %p, %p, %p) failed\n", (int)ExWindowStyle, "DarkPlacesWindowClass", gamename, (int)WindowStyle, (int)(rect.left), (int)(rect.top), (int)(rect.right - rect.left), (int)(rect.bottom - rect.top), (void *)NULL, (void *)NULL, (void *)global_hInstance, (void *)NULL);
1184                         VID_Shutdown();
1185                         return false;
1186                 }
1187
1188                 baseDC = GetDC(mainwindow);
1189
1190                 if (!newpixelformat)
1191                         newpixelformat = ChoosePixelFormat(baseDC, &pfd);
1192                 pixelformat = newpixelformat;
1193                 if (!pixelformat)
1194                 {
1195                         VID_Shutdown();
1196                         Con_Printf("ChoosePixelFormat(%p, %p) failed\n", (void *)baseDC, (void *)&pfd);
1197                         return false;
1198                 }
1199
1200                 if (SetPixelFormat(baseDC, pixelformat, &pfd) == false)
1201                 {
1202                         VID_Shutdown();
1203                         Con_Printf("SetPixelFormat(%p, %d, %p) failed\n", (void *)baseDC, pixelformat, (void *)&pfd);
1204                         return false;
1205                 }
1206
1207                 if (!GL_CheckExtension("wgl", wglfuncs, NULL, false))
1208                 {
1209                         VID_Shutdown();
1210                         Con_Print("wgl functions not found\n");
1211                         return false;
1212                 }
1213
1214                 baseRC = qwglCreateContext(baseDC);
1215                 if (!baseRC)
1216                 {
1217                         VID_Shutdown();
1218                         Con_Print("Could not initialize GL (wglCreateContext failed).\n\nMake sure you are in 65536 color mode, and try running -window.\n");
1219                         return false;
1220                 }
1221                 if (!qwglMakeCurrent(baseDC, baseRC))
1222                 {
1223                         VID_Shutdown();
1224                         Con_Printf("wglMakeCurrent(%p, %p) failed\n", (void *)baseDC, (void *)baseRC);
1225                         return false;
1226                 }
1227
1228                 if ((qglGetString = (const GLubyte* (GLAPIENTRY *)(GLenum name))GL_GetProcAddress("glGetString")) == NULL)
1229                 {
1230                         VID_Shutdown();
1231                         Con_Print("glGetString not found\n");
1232                         return false;
1233                 }
1234                 if ((qwglGetExtensionsStringARB = (const char *(WINAPI *)(HDC hdc))GL_GetProcAddress("wglGetExtensionsStringARB")) == NULL)
1235                         Con_Print("wglGetExtensionsStringARB not found\n");
1236
1237                 gl_extensions = (const char *)qglGetString(GL_EXTENSIONS);
1238                 gl_platform = "WGL";
1239                 gl_platformextensions = "";
1240
1241                 if (qwglGetExtensionsStringARB)
1242                         gl_platformextensions = (const char *)qwglGetExtensionsStringARB(baseDC);
1243
1244                 if (!gl_extensions)
1245                         gl_extensions = "";
1246                 if (!gl_platformextensions)
1247                         gl_platformextensions = "";
1248
1249                 // now some nice Windows pain:
1250                 // we have created a window, we needed one to find out if there are
1251                 // any multisample pixel formats available, the problem is that to
1252                 // actually use one of those multisample formats we now have to
1253                 // recreate the window (yes Microsoft OpenGL really is that bad)
1254
1255                 if (windowpass == 0)
1256                 {
1257                         if (!GL_CheckExtension("WGL_ARB_pixel_format", wglpixelformatfuncs, "-noarbpixelformat", false) || !qwglChoosePixelFormatARB(baseDC, attribs, attribsf, 1, &newpixelformat, &numpixelformats) || !newpixelformat)
1258                                 break;
1259                         // ok we got one - do it all over again with newpixelformat
1260                         qwglMakeCurrent(NULL, NULL);
1261                         qwglDeleteContext(baseRC);baseRC = 0;
1262                         ReleaseDC(mainwindow, baseDC);baseDC = 0;
1263                         // eat up any messages waiting for us
1264                         while (PeekMessage (&msg, NULL, 0, 0, PM_REMOVE))
1265                         {
1266                                 TranslateMessage (&msg);
1267                                 DispatchMessage (&msg);
1268                         }
1269                 }
1270         }
1271
1272         /*
1273         if (!fullscreen)
1274                 SetWindowPos (mainwindow, NULL, CenterX, CenterY, 0, 0,SWP_NOSIZE | SWP_NOZORDER | SWP_SHOWWINDOW | SWP_DRAWFRAME);
1275         */
1276
1277         ShowWindow (mainwindow, SW_SHOWDEFAULT);
1278         UpdateWindow (mainwindow);
1279
1280         // now we try to make sure we get the focus on the mode switch, because
1281         // sometimes in some systems we don't.  We grab the foreground, then
1282         // finish setting up, pump all our messages, and sleep for a little while
1283         // to let messages finish bouncing around the system, then we put
1284         // ourselves at the top of the z order, then grab the foreground again,
1285         // Who knows if it helps, but it probably doesn't hurt
1286         SetForegroundWindow (mainwindow);
1287
1288         while (PeekMessage (&msg, NULL, 0, 0, PM_REMOVE))
1289         {
1290                 TranslateMessage (&msg);
1291                 DispatchMessage (&msg);
1292         }
1293
1294         Sleep (100);
1295
1296         SetWindowPos (mainwindow, HWND_TOP, 0, 0, 0, 0, SWP_DRAWFRAME | SWP_NOMOVE | SWP_NOSIZE | SWP_SHOWWINDOW | SWP_NOCOPYBITS);
1297
1298         SetForegroundWindow (mainwindow);
1299
1300         // fix the leftover Alt from any Alt-Tab or the like that switched us away
1301         ClearAllStates ();
1302
1303 // COMMANDLINEOPTION: Windows WGL: -novideosync disables WGL_EXT_swap_control
1304         GL_CheckExtension("WGL_EXT_swap_control", wglswapintervalfuncs, "-novideosync", false);
1305
1306         GL_Init ();
1307
1308         //vid_menudrawfn = VID_MenuDraw;
1309         //vid_menukeyfn = VID_MenuKey;
1310         vid_usingmouse = false;
1311         vid_usinghidecursor = false;
1312         vid_usingvsync = false;
1313         vid_reallyhidden = vid_hidden = false;
1314         vid_initialized = true;
1315
1316         IN_StartupMouse ();
1317
1318         if (qwglSwapIntervalEXT)
1319         {
1320                 vid_usevsync = vid_vsync.integer != 0;
1321                 vid_usingvsync = vid_vsync.integer != 0;
1322                 qwglSwapIntervalEXT (vid_usevsync);
1323         }
1324
1325         return true;
1326 }
1327
1328 #ifdef SUPPORTD3D
1329 static D3DADAPTER_IDENTIFIER9 d3d9adapteridentifier;
1330
1331 extern cvar_t gl_info_extensions;
1332 extern cvar_t gl_info_vendor;
1333 extern cvar_t gl_info_renderer;
1334 extern cvar_t gl_info_version;
1335 extern cvar_t gl_info_platform;
1336 extern cvar_t gl_info_driver;
1337 qboolean VID_InitModeDX(viddef_mode_t *mode, int version)
1338 {
1339         int deviceindex;
1340         RECT rect;
1341         MSG msg;
1342         DWORD WindowStyle, ExWindowStyle;
1343         int CenterX, CenterY;
1344         int bpp = mode->bitsperpixel;
1345         int width = mode->width;
1346         int height = mode->height;
1347         int refreshrate = (int)floor(mode->refreshrate+0.5);
1348 //      int stereobuffer = mode->stereobuffer;
1349         int samples = mode->samples;
1350         int fullscreen = mode->fullscreen;
1351         int numdevices;
1352
1353         if (vid_initialized)
1354                 Sys_Error("VID_InitMode called when video is already initialised");
1355
1356         vid_isfullscreen = fullscreen != 0;
1357         if (fullscreen)
1358         {
1359                 WindowStyle = WS_POPUP;
1360                 ExWindowStyle = WS_EX_TOPMOST;
1361         }
1362         else
1363         {
1364                 WindowStyle = WS_OVERLAPPED | WS_BORDER | WS_CAPTION | WS_SYSMENU | WS_MINIMIZEBOX;
1365                 ExWindowStyle = 0;
1366         }
1367
1368         rect.top = 0;
1369         rect.left = 0;
1370         rect.right = width;
1371         rect.bottom = height;
1372         AdjustWindowRectEx(&rect, WindowStyle, false, 0);
1373
1374         if (fullscreen)
1375         {
1376                 CenterX = 0;
1377                 CenterY = 0;
1378         }
1379         else
1380         {
1381                 CenterX = (GetSystemMetrics(SM_CXSCREEN) - (rect.right - rect.left)) / 2;
1382                 CenterY = (GetSystemMetrics(SM_CYSCREEN) - (rect.bottom - rect.top)) / 2;
1383         }
1384         CenterX = max(0, CenterX);
1385         CenterY = max(0, CenterY);
1386
1387         // x and y may be changed by WM_MOVE messages
1388         window_x = CenterX;
1389         window_y = CenterY;
1390         rect.left += CenterX;
1391         rect.right += CenterX;
1392         rect.top += CenterY;
1393         rect.bottom += CenterY;
1394
1395         gl_extensions = "";
1396         gl_platformextensions = "";
1397
1398         mainwindow = CreateWindowEx (ExWindowStyle, "DarkPlacesWindowClass", gamename, WindowStyle, rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top, NULL, NULL, global_hInstance, NULL);
1399         if (!mainwindow)
1400         {
1401                 Con_Printf("CreateWindowEx(%d, %s, %s, %d, %d, %d, %d, %d, %p, %p, %p, %p) failed\n", (int)ExWindowStyle, "DarkPlacesWindowClass", gamename, (int)WindowStyle, (int)(rect.left), (int)(rect.top), (int)(rect.right - rect.left), (int)(rect.bottom - rect.top), (void *)NULL, (void *)NULL, global_hInstance, (void *)NULL);
1402                 VID_Shutdown();
1403                 return false;
1404         }
1405
1406         baseDC = GetDC(mainwindow);
1407
1408         vid_d3d9 = Direct3DCreate9(D3D_SDK_VERSION);
1409         if (!vid_d3d9)
1410                 Sys_Error("VID_InitMode: Direct3DCreate9 failed");
1411
1412         numdevices = IDirect3D9_GetAdapterCount(vid_d3d9);
1413         vid_d3d9dev = NULL;
1414         memset(&d3d9adapteridentifier, 0, sizeof(d3d9adapteridentifier));
1415         for (deviceindex = 0;deviceindex < numdevices && !vid_d3d9dev;deviceindex++)
1416         {
1417                 memset(&vid_d3dpresentparameters, 0, sizeof(vid_d3dpresentparameters));
1418 //              vid_d3dpresentparameters.Flags = D3DPRESENTFLAG_DISCARD_DEPTHSTENCIL;
1419                 vid_d3dpresentparameters.Flags = 0;
1420                 vid_d3dpresentparameters.SwapEffect = D3DSWAPEFFECT_DISCARD;
1421                 vid_d3dpresentparameters.hDeviceWindow = mainwindow;
1422                 vid_d3dpresentparameters.BackBufferWidth = width;
1423                 vid_d3dpresentparameters.BackBufferHeight = height;
1424                 vid_d3dpresentparameters.MultiSampleType = samples > 1 ? (D3DMULTISAMPLE_TYPE)samples : D3DMULTISAMPLE_NONE;
1425                 vid_d3dpresentparameters.BackBufferCount = fullscreen ? (vid_dx9_triplebuffer.integer ? 3 : 2) : 1;
1426                 vid_d3dpresentparameters.FullScreen_RefreshRateInHz = fullscreen ? refreshrate : 0;
1427                 vid_d3dpresentparameters.Windowed = !fullscreen;
1428                 vid_d3dpresentparameters.EnableAutoDepthStencil = true;
1429                 vid_d3dpresentparameters.AutoDepthStencilFormat = bpp > 16 ? D3DFMT_D24S8 : D3DFMT_D16;
1430                 vid_d3dpresentparameters.BackBufferFormat = fullscreen?D3DFMT_X8R8G8B8:D3DFMT_UNKNOWN;
1431                 vid_d3dpresentparameters.PresentationInterval = vid_vsync.integer ? D3DPRESENT_INTERVAL_ONE : D3DPRESENT_INTERVAL_IMMEDIATE;
1432
1433                 memset(&d3d9adapteridentifier, 0, sizeof(d3d9adapteridentifier));
1434                 IDirect3D9_GetAdapterIdentifier(vid_d3d9, deviceindex, 0, &d3d9adapteridentifier);
1435
1436                 IDirect3D9_CreateDevice(vid_d3d9, deviceindex, vid_dx9_hal.integer ? D3DDEVTYPE_HAL : D3DDEVTYPE_REF, mainwindow, vid_dx9_softvertex.integer ? D3DCREATE_SOFTWARE_VERTEXPROCESSING : D3DCREATE_HARDWARE_VERTEXPROCESSING, &vid_d3dpresentparameters, &vid_d3d9dev);
1437         }
1438
1439         if (!vid_d3d9dev)
1440         {
1441                 VID_Shutdown();
1442                 return false;
1443         }
1444
1445         IDirect3DDevice9_GetDeviceCaps(vid_d3d9dev, &vid_d3d9caps);
1446
1447         Con_Printf("Using D3D9 device: %s\n", d3d9adapteridentifier.Description);
1448         gl_extensions = "";
1449         gl_platform = "D3D9";
1450         gl_platformextensions = "";
1451
1452         ShowWindow (mainwindow, SW_SHOWDEFAULT);
1453         UpdateWindow (mainwindow);
1454
1455         // now we try to make sure we get the focus on the mode switch, because
1456         // sometimes in some systems we don't.  We grab the foreground, then
1457         // finish setting up, pump all our messages, and sleep for a little while
1458         // to let messages finish bouncing around the system, then we put
1459         // ourselves at the top of the z order, then grab the foreground again,
1460         // Who knows if it helps, but it probably doesn't hurt
1461         SetForegroundWindow (mainwindow);
1462
1463         while (PeekMessage (&msg, NULL, 0, 0, PM_REMOVE))
1464         {
1465                 TranslateMessage (&msg);
1466                 DispatchMessage (&msg);
1467         }
1468
1469         Sleep (100);
1470
1471         SetWindowPos (mainwindow, HWND_TOP, 0, 0, 0, 0, SWP_DRAWFRAME | SWP_NOMOVE | SWP_NOSIZE | SWP_SHOWWINDOW | SWP_NOCOPYBITS);
1472
1473         SetForegroundWindow (mainwindow);
1474
1475         // fix the leftover Alt from any Alt-Tab or the like that switched us away
1476         ClearAllStates ();
1477
1478         gl_renderer = d3d9adapteridentifier.Description;
1479         gl_vendor = d3d9adapteridentifier.Driver;
1480         gl_version = "";
1481         gl_extensions = "";
1482
1483         Con_Printf("D3D9 adapter info:\n");
1484         Con_Printf("Description: %s\n", d3d9adapteridentifier.Description);
1485         Con_Printf("DeviceId: %x\n", (unsigned int)d3d9adapteridentifier.DeviceId);
1486         Con_Printf("DeviceName: %p\n", d3d9adapteridentifier.DeviceName);
1487         Con_Printf("Driver: %s\n", d3d9adapteridentifier.Driver);
1488         Con_Printf("DriverVersion: %08x%08x\n", (unsigned int)d3d9adapteridentifier.DriverVersion.u.HighPart, (unsigned int)d3d9adapteridentifier.DriverVersion.u.LowPart);
1489         Con_DPrintf("GL_EXTENSIONS: %s\n", gl_extensions);
1490         Con_DPrintf("%s_EXTENSIONS: %s\n", gl_platform, gl_platformextensions);
1491
1492         // clear the extension flags
1493         memset(&vid.support, 0, sizeof(vid.support));
1494         Cvar_SetQuick(&gl_info_extensions, "");
1495
1496         // D3D9 requires BGRA
1497         vid.forcetextype = TEXTYPE_BGRA;
1498
1499         vid.forcevbo = false;
1500         vid.support.arb_depth_texture = true;
1501         vid.support.arb_draw_buffers = vid_d3d9caps.NumSimultaneousRTs > 1;
1502         vid.support.arb_occlusion_query = true; // can't find a cap for this
1503         vid.support.arb_shadow = true;
1504         vid.support.arb_texture_compression = true;
1505         vid.support.arb_texture_cube_map = true;
1506         vid.support.arb_texture_non_power_of_two = (vid_d3d9caps.TextureCaps & D3DPTEXTURECAPS_POW2) == 0;
1507         vid.support.arb_vertex_buffer_object = true;
1508         vid.support.ext_blend_subtract = true;
1509         vid.support.ext_draw_range_elements = true;
1510         vid.support.ext_framebuffer_object = true;
1511
1512         // FIXME remove this workaround once FBO + npot texture mapping is fixed
1513         if(!vid.support.arb_texture_non_power_of_two)
1514         {
1515                 vid.support.arb_framebuffer_object = false;
1516                 vid.support.ext_framebuffer_object = false;
1517         }
1518
1519         vid.support.ext_texture_3d = true;
1520         vid.support.ext_texture_compression_s3tc = true;
1521         vid.support.ext_texture_filter_anisotropic = true;
1522         vid.support.ati_separate_stencil = (vid_d3d9caps.StencilCaps & D3DSTENCILCAPS_TWOSIDED) != 0;
1523         vid.support.ext_texture_srgb = false; // FIXME use D3DSAMP_SRGBTEXTURE if CheckDeviceFormat agrees
1524
1525         vid.maxtexturesize_2d = min(vid_d3d9caps.MaxTextureWidth, vid_d3d9caps.MaxTextureHeight);
1526         vid.maxtexturesize_3d = vid_d3d9caps.MaxVolumeExtent;
1527         vid.maxtexturesize_cubemap = vid.maxtexturesize_2d;
1528         vid.texunits = 4;
1529         vid.teximageunits = vid_d3d9caps.MaxSimultaneousTextures;
1530         vid.texarrayunits = 8; // can't find a caps field for this?
1531         vid.max_anisotropy = vid_d3d9caps.MaxAnisotropy;
1532         vid.maxdrawbuffers = vid_d3d9caps.NumSimultaneousRTs;
1533
1534         vid.texunits = bound(4, vid.texunits, MAX_TEXTUREUNITS);
1535         vid.teximageunits = bound(16, vid.teximageunits, MAX_TEXTUREUNITS);
1536         vid.texarrayunits = bound(8, vid.texarrayunits, MAX_TEXTUREUNITS);
1537         Con_DPrintf("Using D3D9.0 rendering path - %i texture matrix, %i texture images, %i texcoords, shadowmapping supported%s\n", vid.texunits, vid.teximageunits, vid.texarrayunits, vid.maxdrawbuffers > 1 ? ", MRT detected (allows prepass deferred lighting)" : "");
1538         vid.renderpath = RENDERPATH_D3D9;
1539         vid.sRGBcapable2D = false;
1540         vid.sRGBcapable3D = true;
1541         vid.useinterleavedarrays = true;
1542
1543         Cvar_SetQuick(&gl_info_vendor, gl_vendor);
1544         Cvar_SetQuick(&gl_info_renderer, gl_renderer);
1545         Cvar_SetQuick(&gl_info_version, gl_version);
1546         Cvar_SetQuick(&gl_info_platform, gl_platform ? gl_platform : "");
1547         Cvar_SetQuick(&gl_info_driver, gl_driver);
1548
1549         // LordHavoc: report supported extensions
1550         Con_DPrintf("\nQuakeC extensions for server and client: %s\nQuakeC extensions for menu: %s\n", vm_sv_extensions, vm_m_extensions );
1551
1552         // clear to black (loading plaque will be seen over this)
1553         IDirect3DDevice9_Clear(vid_d3d9dev, 0, NULL, D3DCLEAR_TARGET, D3DCOLOR_XRGB(0, 0, 0), 1.0f, 0);
1554         IDirect3DDevice9_BeginScene(vid_d3d9dev);
1555         IDirect3DDevice9_EndScene(vid_d3d9dev);
1556         IDirect3DDevice9_Present(vid_d3d9dev, NULL, NULL, NULL, NULL);
1557         // because the only time we end/begin scene is in VID_Finish, we'd better start a scene now...
1558         IDirect3DDevice9_BeginScene(vid_d3d9dev);
1559         vid_begunscene = true;
1560
1561         //vid_menudrawfn = VID_MenuDraw;
1562         //vid_menukeyfn = VID_MenuKey;
1563         vid_usingmouse = false;
1564         vid_usinghidecursor = false;
1565         vid_usingvsync = false;
1566         vid_hidden = vid_reallyhidden = false;
1567         vid_initialized = true;
1568
1569         IN_StartupMouse ();
1570
1571         return true;
1572 }
1573 #endif
1574
1575 qboolean VID_InitModeSOFT(viddef_mode_t *mode)
1576 {
1577         int i;
1578         HDC hdc;
1579         RECT rect;
1580         MSG msg;
1581         int pixelformat, newpixelformat;
1582         DWORD WindowStyle, ExWindowStyle;
1583         int CenterX, CenterY;
1584         int depth;
1585         DEVMODE thismode;
1586         qboolean foundmode, foundgoodmode;
1587         int bpp = mode->bitsperpixel;
1588         int width = mode->width;
1589         int height = mode->height;
1590         int refreshrate = (int)floor(mode->refreshrate+0.5);
1591         int fullscreen = mode->fullscreen;
1592
1593         if (vid_initialized)
1594                 Sys_Error("VID_InitMode called when video is already initialised");
1595
1596         memset(&gdevmode, 0, sizeof(gdevmode));
1597
1598         vid_isfullscreen = false;
1599         if (fullscreen)
1600         {
1601                 if(vid_forcerefreshrate.integer)
1602                 {
1603                         foundmode = true;
1604                         gdevmode.dmFields = DM_BITSPERPEL | DM_PELSWIDTH | DM_PELSHEIGHT;
1605                         gdevmode.dmBitsPerPel = bpp;
1606                         gdevmode.dmPelsWidth = width;
1607                         gdevmode.dmPelsHeight = height;
1608                         gdevmode.dmSize = sizeof (gdevmode);
1609                         if(refreshrate)
1610                         {
1611                                 gdevmode.dmFields |= DM_DISPLAYFREQUENCY;
1612                                 gdevmode.dmDisplayFrequency = refreshrate;
1613                         }
1614                 }
1615                 else
1616                 {
1617                         if(refreshrate == 0)
1618                                 refreshrate = initialdevmode.dmDisplayFrequency; // default vid_refreshrate to the rate of the desktop
1619
1620                         foundmode = false;
1621                         foundgoodmode = false;
1622
1623                         thismode.dmSize = sizeof(thismode);
1624                         thismode.dmDriverExtra = 0;
1625                         for(i = 0; EnumDisplaySettings(NULL, i, &thismode); ++i)
1626                         {
1627                                 if(~thismode.dmFields & (DM_BITSPERPEL | DM_PELSWIDTH | DM_PELSHEIGHT | DM_DISPLAYFREQUENCY))
1628                                 {
1629                                         Con_DPrintf("enumerating modes yielded a bogus item... please debug this\n");
1630                                         continue;
1631                                 }
1632                                 if(developer_extra.integer)
1633                                         Con_DPrintf("Found mode %dx%dx%dbpp %dHz... ", (int)thismode.dmPelsWidth, (int)thismode.dmPelsHeight, (int)thismode.dmBitsPerPel, (int)thismode.dmDisplayFrequency);
1634                                 if(thismode.dmBitsPerPel != (DWORD)bpp)
1635                                 {
1636                                         if(developer_extra.integer)
1637                                                 Con_DPrintf("wrong bpp\n");
1638                                         continue;
1639                                 }
1640                                 if(thismode.dmPelsWidth != (DWORD)width)
1641                                 {
1642                                         if(developer_extra.integer)
1643                                                 Con_DPrintf("wrong width\n");
1644                                         continue;
1645                                 }
1646                                 if(thismode.dmPelsHeight != (DWORD)height)
1647                                 {
1648                                         if(developer_extra.integer)
1649                                                 Con_DPrintf("wrong height\n");
1650                                         continue;
1651                                 }
1652
1653                                 if(foundgoodmode)
1654                                 {
1655                                         // if we have a good mode, make sure this mode is better than the previous one, and allowed by the refreshrate
1656                                         if(thismode.dmDisplayFrequency > (DWORD)refreshrate)
1657                                         {
1658                                                 if(developer_extra.integer)
1659                                                         Con_DPrintf("too high refresh rate\n");
1660                                                 continue;
1661                                         }
1662                                         else if(thismode.dmDisplayFrequency <= gdevmode.dmDisplayFrequency)
1663                                         {
1664                                                 if(developer_extra.integer)
1665                                                         Con_DPrintf("doesn't beat previous best match (too low)\n");
1666                                                 continue;
1667                                         }
1668                                 }
1669                                 else if(foundmode)
1670                                 {
1671                                         // we do have one, but it isn't good... make sure it has a lower frequency than the previous one
1672                                         if(thismode.dmDisplayFrequency >= gdevmode.dmDisplayFrequency)
1673                                         {
1674                                                 if(developer_extra.integer)
1675                                                         Con_DPrintf("doesn't beat previous best match (too high)\n");
1676                                                 continue;
1677                                         }
1678                                 }
1679                                 // otherwise, take anything
1680
1681                                 memcpy(&gdevmode, &thismode, sizeof(gdevmode));
1682                                 if(thismode.dmDisplayFrequency <= (DWORD)refreshrate)
1683                                         foundgoodmode = true;
1684                                 else
1685                                 {
1686                                         if(developer_extra.integer)
1687                                                 Con_DPrintf("(out of range)\n");
1688                                 }
1689                                 foundmode = true;
1690                                 if(developer_extra.integer)
1691                                         Con_DPrintf("accepted\n");
1692                         }
1693                 }
1694
1695                 if (!foundmode)
1696                 {
1697                         VID_Shutdown();
1698                         Con_Printf("Unable to find the requested mode %dx%dx%dbpp\n", width, height, bpp);
1699                         return false;
1700                 }
1701                 else if(ChangeDisplaySettings (&gdevmode, CDS_FULLSCREEN) != DISP_CHANGE_SUCCESSFUL)
1702                 {
1703                         VID_Shutdown();
1704                         Con_Printf("Unable to change to requested mode %dx%dx%dbpp\n", width, height, bpp);
1705                         return false;
1706                 }
1707
1708                 vid_isfullscreen = true;
1709                 WindowStyle = WS_POPUP;
1710                 ExWindowStyle = WS_EX_TOPMOST;
1711         }
1712         else
1713         {
1714                 hdc = GetDC (NULL);
1715                 i = GetDeviceCaps(hdc, RASTERCAPS);
1716                 depth = GetDeviceCaps(hdc, PLANES) * GetDeviceCaps(hdc, BITSPIXEL);
1717                 ReleaseDC (NULL, hdc);
1718                 if (i & RC_PALETTE)
1719                 {
1720                         VID_Shutdown();
1721                         Con_Print("Can't run in non-RGB mode\n");
1722                         return false;
1723                 }
1724                 if (bpp > depth)
1725                 {
1726                         VID_Shutdown();
1727                         Con_Print("A higher desktop depth is required to run this video mode\n");
1728                         return false;
1729                 }
1730
1731                 WindowStyle = WS_OVERLAPPED | WS_BORDER | WS_CAPTION | WS_SYSMENU | WS_MINIMIZEBOX;
1732                 ExWindowStyle = 0;
1733         }
1734
1735         rect.top = 0;
1736         rect.left = 0;
1737         rect.right = width;
1738         rect.bottom = height;
1739         AdjustWindowRectEx(&rect, WindowStyle, false, 0);
1740
1741         if (fullscreen)
1742         {
1743                 CenterX = 0;
1744                 CenterY = 0;
1745         }
1746         else
1747         {
1748                 CenterX = (GetSystemMetrics(SM_CXSCREEN) - (rect.right - rect.left)) / 2;
1749                 CenterY = (GetSystemMetrics(SM_CYSCREEN) - (rect.bottom - rect.top)) / 2;
1750         }
1751         CenterX = max(0, CenterX);
1752         CenterY = max(0, CenterY);
1753
1754         // x and y may be changed by WM_MOVE messages
1755         window_x = CenterX;
1756         window_y = CenterY;
1757         rect.left += CenterX;
1758         rect.right += CenterX;
1759         rect.top += CenterY;
1760         rect.bottom += CenterY;
1761
1762         pixelformat = 0;
1763         newpixelformat = 0;
1764         gl_extensions = "";
1765         gl_platformextensions = "";
1766
1767         mainwindow = CreateWindowEx (ExWindowStyle, "DarkPlacesWindowClass", gamename, WindowStyle, rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top, NULL, NULL, global_hInstance, NULL);
1768         if (!mainwindow)
1769         {
1770                 Con_Printf("CreateWindowEx(%d, %s, %s, %d, %d, %d, %d, %d, %p, %p, %p, %p) failed\n", (int)ExWindowStyle, "DarkPlacesWindowClass", gamename, (int)WindowStyle, (int)(rect.left), (int)(rect.top), (int)(rect.right - rect.left), (int)(rect.bottom - rect.top), (void *)NULL, (void *)NULL, (void *)global_hInstance, (void *)NULL);
1771                 VID_Shutdown();
1772                 return false;
1773         }
1774
1775         baseDC = GetDC(mainwindow);
1776         vid.softpixels = NULL;
1777         memset(&vid_softbmi, 0, sizeof(vid_softbmi));
1778         vid_softbmi.bmiHeader.biSize = sizeof(vid_softbmi.bmiHeader);
1779         vid_softbmi.bmiHeader.biWidth = width;
1780         vid_softbmi.bmiHeader.biHeight = -height; // negative to make a top-down bitmap
1781         vid_softbmi.bmiHeader.biPlanes = 1;
1782         vid_softbmi.bmiHeader.biBitCount = 32;
1783         vid_softbmi.bmiHeader.biCompression = BI_RGB;
1784         vid_softbmi.bmiHeader.biSizeImage = width*height*4;
1785         vid_softbmi.bmiHeader.biClrUsed = 256;
1786         vid_softbmi.bmiHeader.biClrImportant = 256;
1787         vid_softdibhandle = CreateDIBSection(baseDC, &vid_softbmi, DIB_RGB_COLORS, (void **)&vid.softpixels, NULL, 0);
1788         if (!vid_softdibhandle)
1789         {
1790                 Con_Printf("CreateDIBSection failed\n");
1791                 VID_Shutdown();
1792                 return false;
1793         }
1794
1795         vid_softhdc = CreateCompatibleDC(baseDC);
1796         vid_softhdc_backup = SelectObject(vid_softhdc, vid_softdibhandle);
1797         if (!vid_softhdc_backup)
1798         {
1799                 Con_Printf("SelectObject failed\n");
1800                 VID_Shutdown();
1801                 return false;
1802         }
1803 //      ReleaseDC(mainwindow, baseDC);
1804 //      baseDC = NULL;
1805
1806         vid.softdepthpixels = (unsigned int *)calloc(1, mode->width * mode->height * 4);
1807         if (DPSOFTRAST_Init(mode->width, mode->height, vid_soft_threads.integer, vid_soft_interlace.integer, (unsigned int *)vid.softpixels, (unsigned int *)vid.softdepthpixels) < 0)
1808         {
1809                 Con_Printf("Failed to initialize software rasterizer\n");
1810                 VID_Shutdown();
1811                 return false;
1812         }
1813
1814         VID_Soft_SharedSetup();
1815
1816         ShowWindow (mainwindow, SW_SHOWDEFAULT);
1817         UpdateWindow (mainwindow);
1818
1819         // now we try to make sure we get the focus on the mode switch, because
1820         // sometimes in some systems we don't.  We grab the foreground, then
1821         // finish setting up, pump all our messages, and sleep for a little while
1822         // to let messages finish bouncing around the system, then we put
1823         // ourselves at the top of the z order, then grab the foreground again,
1824         // Who knows if it helps, but it probably doesn't hurt
1825         SetForegroundWindow (mainwindow);
1826
1827         while (PeekMessage (&msg, NULL, 0, 0, PM_REMOVE))
1828         {
1829                 TranslateMessage (&msg);
1830                 DispatchMessage (&msg);
1831         }
1832
1833         Sleep (100);
1834
1835         SetWindowPos (mainwindow, HWND_TOP, 0, 0, 0, 0, SWP_DRAWFRAME | SWP_NOMOVE | SWP_NOSIZE | SWP_SHOWWINDOW | SWP_NOCOPYBITS);
1836
1837         SetForegroundWindow (mainwindow);
1838
1839         // fix the leftover Alt from any Alt-Tab or the like that switched us away
1840         ClearAllStates ();
1841
1842         //vid_menudrawfn = VID_MenuDraw;
1843         //vid_menukeyfn = VID_MenuKey;
1844         vid_usingmouse = false;
1845         vid_usinghidecursor = false;
1846         vid_usingvsync = false;
1847         vid_reallyhidden = vid_hidden = false;
1848         vid_initialized = true;
1849
1850         IN_StartupMouse ();
1851
1852         return true;
1853 }
1854
1855 qboolean VID_InitMode(viddef_mode_t *mode)
1856 {
1857 #ifdef SSE_POSSIBLE
1858         if (vid_soft.integer)
1859                 return VID_InitModeSOFT(mode);
1860 #endif
1861 #ifdef SUPPORTD3D
1862 //      if (vid_dx11.integer)
1863 //              return VID_InitModeDX(mode, 11);
1864 //      if (vid_dx10.integer)
1865 //              return VID_InitModeDX(mode, 10);
1866         if (vid_dx9.integer)
1867                 return VID_InitModeDX(mode, 9);
1868 #endif
1869         return VID_InitModeGL(mode);
1870 }
1871
1872
1873 static void IN_Shutdown(void);
1874 void VID_Shutdown (void)
1875 {
1876         qboolean isgl;
1877         if(vid_initialized == false)
1878                 return;
1879
1880         VID_EnableJoystick(false);
1881         VID_SetMouse(false, false, false);
1882         VID_RestoreSystemGamma();
1883
1884         vid_initialized = false;
1885         isgl = gldll != NULL;
1886         IN_Shutdown();
1887         gl_driver[0] = 0;
1888         gl_extensions = "";
1889         gl_platform = "";
1890         gl_platformextensions = "";
1891         if (vid_softhdc)
1892         {
1893                 SelectObject(vid_softhdc, vid_softhdc_backup);
1894                 ReleaseDC(mainwindow, vid_softhdc);
1895         }
1896         vid_softhdc = NULL;
1897         vid_softhdc_backup = NULL;
1898         if (vid_softdibhandle)
1899                 DeleteObject(vid_softdibhandle);
1900         vid_softdibhandle = NULL;
1901         vid.softpixels = NULL;
1902         if (vid.softdepthpixels)
1903                 free(vid.softdepthpixels);
1904         vid.softdepthpixels = NULL;
1905 #ifdef SUPPORTD3D
1906         if (vid_d3d9dev)
1907         {
1908                 if (vid_begunscene)
1909                         IDirect3DDevice9_EndScene(vid_d3d9dev);
1910                 vid_begunscene = false;
1911 //              Cmd_ExecuteString("r_texturestats", src_command, true);
1912 //              Cmd_ExecuteString("memlist", src_command, true);
1913                 IDirect3DDevice9_Release(vid_d3d9dev);
1914         }
1915         vid_d3d9dev = NULL;
1916         if (vid_d3d9)
1917                 IDirect3D9_Release(vid_d3d9);
1918         vid_d3d9 = NULL;
1919 #endif
1920         if (qwglMakeCurrent)
1921                 qwglMakeCurrent(NULL, NULL);
1922         qwglMakeCurrent = NULL;
1923         if (baseRC && qwglDeleteContext)
1924                 qwglDeleteContext(baseRC);
1925         qwglDeleteContext = NULL;
1926         // close the library before we get rid of the window
1927         GL_CloseLibrary();
1928         if (baseDC && mainwindow)
1929                 ReleaseDC(mainwindow, baseDC);
1930         baseDC = NULL;
1931         AppActivate(false, false);
1932         if (mainwindow)
1933                 DestroyWindow(mainwindow);
1934         mainwindow = 0;
1935         if (vid_isfullscreen && isgl)
1936                 ChangeDisplaySettings (NULL, 0);
1937         vid_isfullscreen = false;
1938 }
1939
1940 void VID_SetMouse(qboolean fullscreengrab, qboolean relative, qboolean hidecursor)
1941 {
1942         static qboolean restore_spi;
1943         static int originalmouseparms[3];
1944
1945         if (!mouseinitialized)
1946                 return;
1947
1948         if (relative)
1949         {
1950                 if (!vid_usingmouse)
1951                 {
1952                         vid_usingmouse = true;
1953                         cl_ignoremousemoves = 2;
1954 #ifdef SUPPORTDIRECTX
1955                         if (dinput && g_pMouse)
1956                         {
1957                                 IDirectInputDevice_Acquire(g_pMouse);
1958                                 dinput_acquired = true;
1959                         }
1960                         else
1961 #endif
1962                         {
1963                                 RECT window_rect;
1964                                 window_rect.left = window_x;
1965                                 window_rect.top = window_y;
1966                                 window_rect.right = window_x + vid.width;
1967                                 window_rect.bottom = window_y + vid.height;
1968
1969                                 // change mouse settings to turn off acceleration
1970 // COMMANDLINEOPTION: Windows GDI Input: -noforcemparms disables setting of mouse parameters (not used with -dinput, windows only)
1971                                 if (!COM_CheckParm ("-noforcemparms") && SystemParametersInfo (SPI_GETMOUSE, 0, originalmouseparms, 0))
1972                                 {
1973                                         int newmouseparms[3];
1974                                         newmouseparms[0] = 0; // threshold to double movement (only if accel level is >= 1)
1975                                         newmouseparms[1] = 0; // threshold to quadruple movement (only if accel level is >= 2)
1976                                         newmouseparms[2] = 0; // maximum level of acceleration (0 = off)
1977                                         restore_spi = SystemParametersInfo (SPI_SETMOUSE, 0, newmouseparms, 0) != FALSE;
1978                                 }
1979                                 else
1980                                         restore_spi = false;
1981                                 SetCursorPos ((window_x + vid.width / 2), (window_y + vid.height / 2));
1982
1983                                 SetCapture (mainwindow);
1984                                 ClipCursor (&window_rect);
1985                         }
1986                 }
1987         }
1988         else
1989         {
1990                 if (vid_usingmouse)
1991                 {
1992                         vid_usingmouse = false;
1993                         cl_ignoremousemoves = 2;
1994 #ifdef SUPPORTDIRECTX
1995                         if (dinput_acquired)
1996                         {
1997                                 IDirectInputDevice_Unacquire(g_pMouse);
1998                                 dinput_acquired = false;
1999                         }
2000                         else
2001 #endif
2002                         {
2003                                 // restore system mouseparms if we changed them
2004                                 if (restore_spi)
2005                                         SystemParametersInfo (SPI_SETMOUSE, 0, originalmouseparms, 0);
2006                                 restore_spi = false;
2007                                 ClipCursor (NULL);
2008                                 ReleaseCapture ();
2009                         }
2010                 }
2011         }
2012
2013         if (vid_usinghidecursor != hidecursor)
2014         {
2015                 vid_usinghidecursor = hidecursor;
2016                 ShowCursor (!hidecursor);
2017         }
2018 }
2019
2020 void VID_BuildJoyState(vid_joystate_t *joystate)
2021 {
2022         VID_Shared_BuildJoyState_Begin(joystate);
2023         VID_Shared_BuildJoyState_Finish(joystate);
2024 }
2025
2026 void VID_EnableJoystick(qboolean enable)
2027 {
2028         int index = joy_enable.integer > 0 ? joy_index.integer : -1;
2029         qboolean success = false;
2030         int sharedcount = 0;
2031         sharedcount = VID_Shared_SetJoystick(index);
2032         if (index >= 0 && index < sharedcount)
2033                 success = true;
2034
2035         // update cvar containing count of XInput joysticks
2036         if (joy_detected.integer != sharedcount)
2037                 Cvar_SetValueQuick(&joy_detected, sharedcount);
2038
2039         if (joy_active.integer != (success ? 1 : 0))
2040                 Cvar_SetValueQuick(&joy_active, success ? 1 : 0);
2041 }
2042
2043 #ifdef SUPPORTDIRECTX
2044 /*
2045 ===========
2046 IN_InitDInput
2047 ===========
2048 */
2049 static qboolean IN_InitDInput (void)
2050 {
2051     HRESULT             hr;
2052         DIPROPDWORD     dipdw = {
2053                 {
2054                         sizeof(DIPROPDWORD),        // diph.dwSize
2055                         sizeof(DIPROPHEADER),       // diph.dwHeaderSize
2056                         0,                          // diph.dwObj
2057                         DIPH_DEVICE,                // diph.dwHow
2058                 },
2059                 DINPUT_BUFFERSIZE,              // dwData
2060         };
2061
2062         if (!hInstDI)
2063         {
2064                 hInstDI = LoadLibrary("dinput.dll");
2065
2066                 if (hInstDI == NULL)
2067                 {
2068                         Con_Print("Couldn't load dinput.dll\n");
2069                         return false;
2070                 }
2071         }
2072
2073         if (!pDirectInputCreate)
2074         {
2075                 pDirectInputCreate = (HRESULT (__stdcall *)(HINSTANCE,DWORD,LPDIRECTINPUT *,LPUNKNOWN))GetProcAddress(hInstDI,"DirectInputCreateA");
2076
2077                 if (!pDirectInputCreate)
2078                 {
2079                         Con_Print("Couldn't get DI proc addr\n");
2080                         return false;
2081                 }
2082         }
2083
2084 // register with DirectInput and get an IDirectInput to play with.
2085         hr = iDirectInputCreate(global_hInstance, DIRECTINPUT_VERSION, &g_pdi, NULL);
2086
2087         if (FAILED(hr))
2088         {
2089                 return false;
2090         }
2091
2092 // obtain an interface to the system mouse device.
2093 #ifdef __cplusplus
2094         hr = IDirectInput_CreateDevice(g_pdi, GUID_SysMouse, &g_pMouse, NULL);
2095 #else
2096         hr = IDirectInput_CreateDevice(g_pdi, &GUID_SysMouse, &g_pMouse, NULL);
2097 #endif
2098
2099         if (FAILED(hr))
2100         {
2101                 Con_Print("Couldn't open DI mouse device\n");
2102                 return false;
2103         }
2104
2105 // set the data format to "mouse format".
2106         hr = IDirectInputDevice_SetDataFormat(g_pMouse, &c_dfDIMouse);
2107
2108         if (FAILED(hr))
2109         {
2110                 Con_Print("Couldn't set DI mouse format\n");
2111                 return false;
2112         }
2113
2114 // set the cooperativity level.
2115         hr = IDirectInputDevice_SetCooperativeLevel(g_pMouse, mainwindow,
2116                         DISCL_EXCLUSIVE | DISCL_FOREGROUND);
2117
2118         if (FAILED(hr))
2119         {
2120                 Con_Print("Couldn't set DI coop level\n");
2121                 return false;
2122         }
2123
2124
2125 // set the buffer size to DINPUT_BUFFERSIZE elements.
2126 // the buffer size is a DWORD property associated with the device
2127         hr = IDirectInputDevice_SetProperty(g_pMouse, DIPROP_BUFFERSIZE, &dipdw.diph);
2128
2129         if (FAILED(hr))
2130         {
2131                 Con_Print("Couldn't set DI buffersize\n");
2132                 return false;
2133         }
2134
2135         return true;
2136 }
2137 #endif
2138
2139
2140 /*
2141 ===========
2142 IN_StartupMouse
2143 ===========
2144 */
2145 static void IN_StartupMouse (void)
2146 {
2147         if (COM_CheckParm ("-nomouse"))
2148                 return;
2149
2150         mouseinitialized = true;
2151
2152 #ifdef SUPPORTDIRECTX
2153 // COMMANDLINEOPTION: Windows Input: -dinput enables DirectInput for mouse input
2154         if (COM_CheckParm ("-dinput"))
2155                 dinput = IN_InitDInput ();
2156
2157         if (dinput)
2158                 Con_Print("DirectInput initialized\n");
2159         else
2160                 Con_Print("DirectInput not initialized\n");
2161 #endif
2162
2163         mouse_buttons = 10;
2164 }
2165
2166
2167 /*
2168 ===========
2169 IN_MouseMove
2170 ===========
2171 */
2172 static void IN_MouseMove (void)
2173 {
2174         POINT current_pos;
2175
2176         GetCursorPos (&current_pos);
2177         in_windowmouse_x = current_pos.x - window_x;
2178         in_windowmouse_y = current_pos.y - window_y;
2179
2180         if (!vid_usingmouse)
2181                 return;
2182
2183 #ifdef SUPPORTDIRECTX
2184         if (dinput_acquired)
2185         {
2186                 int i;
2187                 DIDEVICEOBJECTDATA      od;
2188                 DWORD                           dwElements;
2189                 HRESULT                         hr;
2190
2191                 for (;;)
2192                 {
2193                         dwElements = 1;
2194
2195                         hr = IDirectInputDevice_GetDeviceData(g_pMouse,
2196                                         sizeof(DIDEVICEOBJECTDATA), &od, &dwElements, 0);
2197
2198                         if ((hr == DIERR_INPUTLOST) || (hr == DIERR_NOTACQUIRED))
2199                         {
2200                                 IDirectInputDevice_Acquire(g_pMouse);
2201                                 break;
2202                         }
2203
2204                         /* Unable to read data or no data available */
2205                         if (FAILED(hr) || dwElements == 0)
2206                                 break;
2207
2208                         /* Look at the element to see what happened */
2209
2210                         if ((int)od.dwOfs == DIMOFS_X)
2211                                 in_mouse_x += (LONG) od.dwData;
2212                         if ((int)od.dwOfs == DIMOFS_Y)
2213                                 in_mouse_y += (LONG) od.dwData;
2214                         if ((int)od.dwOfs == DIMOFS_Z)
2215                         {
2216                                 if((LONG)od.dwData < 0)
2217                                 {
2218                                         Key_Event(K_MWHEELDOWN, 0, true);
2219                                         Key_Event(K_MWHEELDOWN, 0, false);
2220                                 }
2221                                 else if((LONG)od.dwData > 0)
2222                                 {
2223                                         Key_Event(K_MWHEELUP, 0, true);
2224                                         Key_Event(K_MWHEELUP, 0, false);
2225                                 }
2226                         }
2227                         if ((int)od.dwOfs == DIMOFS_BUTTON0)
2228                                 mstate_di = (mstate_di & ~1) | ((od.dwData & 0x80) >> 7);
2229                         if ((int)od.dwOfs == DIMOFS_BUTTON1)
2230                                 mstate_di = (mstate_di & ~2) | ((od.dwData & 0x80) >> 6);
2231                         if ((int)od.dwOfs == DIMOFS_BUTTON2)
2232                                 mstate_di = (mstate_di & ~4) | ((od.dwData & 0x80) >> 5);
2233                         if ((int)od.dwOfs == DIMOFS_BUTTON3)
2234                                 mstate_di = (mstate_di & ~8) | ((od.dwData & 0x80) >> 4);
2235                 }
2236
2237                 // perform button actions
2238                 for (i=0 ; i<mouse_buttons && i < 16 ; i++)
2239                         if ((mstate_di ^ mouse_oldbuttonstate) & (1<<i))
2240                                 Key_Event (buttonremap[i], 0, (mstate_di & (1<<i)) != 0);
2241                 mouse_oldbuttonstate = mstate_di;
2242         }
2243         else
2244 #endif
2245         {
2246                 in_mouse_x += in_windowmouse_x - (int)(vid.width / 2);
2247                 in_mouse_y += in_windowmouse_y - (int)(vid.height / 2);
2248
2249                 // if the mouse has moved, force it to the center, so there's room to move
2250                 if (in_mouse_x || in_mouse_y)
2251                         SetCursorPos ((window_x + vid.width / 2), (window_y + vid.height / 2));
2252         }
2253 }
2254
2255
2256 /*
2257 ===========
2258 IN_Move
2259 ===========
2260 */
2261 void IN_Move (void)
2262 {
2263         vid_joystate_t joystate;
2264         if (vid_activewindow && !vid_reallyhidden)
2265                 IN_MouseMove ();
2266         VID_EnableJoystick(true);
2267         VID_BuildJoyState(&joystate);
2268         VID_ApplyJoyState(&joystate);
2269 }
2270
2271
2272 static void IN_Init(void)
2273 {
2274         uiWheelMessage = RegisterWindowMessage ( "MSWHEEL_ROLLMSG" );
2275         Cvar_RegisterVariable (&vid_forcerefreshrate);
2276 }
2277
2278 static void IN_Shutdown(void)
2279 {
2280 #ifdef SUPPORTDIRECTX
2281         if (g_pMouse)
2282                 IDirectInputDevice_Release(g_pMouse);
2283         g_pMouse = NULL;
2284
2285         if (g_pdi)
2286                 IDirectInput_Release(g_pdi);
2287         g_pdi = NULL;
2288 #endif
2289 }
2290
2291 size_t VID_ListModes(vid_mode_t *modes, size_t maxcount)
2292 {
2293         int i;
2294         size_t k;
2295         DEVMODE thismode;
2296
2297         thismode.dmSize = sizeof(thismode);
2298         thismode.dmDriverExtra = 0;
2299         k = 0;
2300         for(i = 0; EnumDisplaySettings(NULL, i, &thismode); ++i)
2301         {
2302                 if(~thismode.dmFields & (DM_BITSPERPEL | DM_PELSWIDTH | DM_PELSHEIGHT | DM_DISPLAYFREQUENCY))
2303                 {
2304                         Con_DPrintf("enumerating modes yielded a bogus item... please debug this\n");
2305                         continue;
2306                 }
2307                 if(k >= maxcount)
2308                         break;
2309                 modes[k].width = thismode.dmPelsWidth;
2310                 modes[k].height = thismode.dmPelsHeight;
2311                 modes[k].bpp = thismode.dmBitsPerPel;
2312                 modes[k].refreshrate = thismode.dmDisplayFrequency;
2313                 modes[k].pixelheight_num = 1;
2314                 modes[k].pixelheight_denom = 1; // Win32 apparently does not provide this (FIXME)
2315                 ++k;
2316         }
2317         return k;
2318 }