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