]> icculus.org git repositories - divverent/darkplaces.git/blob - vid_wgl.c
split and overhauled R_Upload into two functions:
[divverent/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
49 #ifdef SUPPORTD3D
50 #include <d3d9.h>
51
52 cvar_t vid_dx9 = {CVAR_SAVE, "vid_dx9", "0", "use Microsoft Direct3D9(r) for rendering"};
53 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)"};
54 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"};
55 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"};
56 //cvar_t vid_dx10 = {CVAR_SAVE, "vid_dx10", "1", "use Microsoft Direct3D10(r) for rendering"};
57 //cvar_t vid_dx11 = {CVAR_SAVE, "vid_dx11", "1", "use Microsoft Direct3D11(r) for rendering"};
58
59 D3DPRESENT_PARAMETERS vid_d3dpresentparameters;
60
61 // we declare this in vid_shared.c because it is required by dedicated server and all clients when SUPPORTD3D is defined
62 extern LPDIRECT3DDEVICE9 vid_d3d9dev;
63
64 LPDIRECT3D9 vid_d3d9;
65 D3DCAPS9 vid_d3d9caps;
66 qboolean vid_d3ddevicelost;
67 #endif
68
69 extern HINSTANCE global_hInstance;
70
71 static HINSTANCE gldll;
72
73 #ifndef WM_MOUSEWHEEL
74 #define WM_MOUSEWHEEL                   0x020A
75 #endif
76
77 // Tell startup code that we have a client
78 int cl_available = true;
79
80 qboolean vid_supportrefreshrate = true;
81
82 static int (WINAPI *qwglChoosePixelFormat)(HDC, CONST PIXELFORMATDESCRIPTOR *);
83 static int (WINAPI *qwglDescribePixelFormat)(HDC, int, UINT, LPPIXELFORMATDESCRIPTOR);
84 //static int (WINAPI *qwglGetPixelFormat)(HDC);
85 static BOOL (WINAPI *qwglSetPixelFormat)(HDC, int, CONST PIXELFORMATDESCRIPTOR *);
86 static BOOL (WINAPI *qwglSwapBuffers)(HDC);
87 static HGLRC (WINAPI *qwglCreateContext)(HDC);
88 static BOOL (WINAPI *qwglDeleteContext)(HGLRC);
89 static HGLRC (WINAPI *qwglGetCurrentContext)(VOID);
90 static HDC (WINAPI *qwglGetCurrentDC)(VOID);
91 static PROC (WINAPI *qwglGetProcAddress)(LPCSTR);
92 static BOOL (WINAPI *qwglMakeCurrent)(HDC, HGLRC);
93 static BOOL (WINAPI *qwglSwapIntervalEXT)(int interval);
94 static const char *(WINAPI *qwglGetExtensionsStringARB)(HDC hdc);
95 static BOOL (WINAPI *qwglChoosePixelFormatARB)(HDC hdc, const int *piAttribIList, const FLOAT *pfAttribFList, UINT nMaxFormats, int *piFormats, UINT *nNumFormats);
96 static BOOL (WINAPI *qwglGetPixelFormatAttribivARB)(HDC hdc, int iPixelFormat, int iLayerPlane, UINT nAttributes, const int *piAttributes, int *piValues);
97
98 static dllfunction_t wglfuncs[] =
99 {
100         {"wglChoosePixelFormat", (void **) &qwglChoosePixelFormat},
101         {"wglDescribePixelFormat", (void **) &qwglDescribePixelFormat},
102 //      {"wglGetPixelFormat", (void **) &qwglGetPixelFormat},
103         {"wglSetPixelFormat", (void **) &qwglSetPixelFormat},
104         {"wglSwapBuffers", (void **) &qwglSwapBuffers},
105         {"wglCreateContext", (void **) &qwglCreateContext},
106         {"wglDeleteContext", (void **) &qwglDeleteContext},
107         {"wglGetProcAddress", (void **) &qwglGetProcAddress},
108         {"wglMakeCurrent", (void **) &qwglMakeCurrent},
109         {"wglGetCurrentContext", (void **) &qwglGetCurrentContext},
110         {"wglGetCurrentDC", (void **) &qwglGetCurrentDC},
111         {NULL, NULL}
112 };
113
114 static dllfunction_t wglswapintervalfuncs[] =
115 {
116         {"wglSwapIntervalEXT", (void **) &qwglSwapIntervalEXT},
117         {NULL, NULL}
118 };
119
120 static dllfunction_t wglpixelformatfuncs[] =
121 {
122         {"wglChoosePixelFormatARB", (void **) &qwglChoosePixelFormatARB},
123         {"wglGetPixelFormatAttribivARB", (void **) &qwglGetPixelFormatAttribivARB},
124         {NULL, NULL}
125 };
126
127 static DEVMODE gdevmode, initialdevmode;
128 static qboolean vid_initialized = false;
129 static qboolean vid_wassuspended = false;
130 static qboolean vid_usingmouse = false;
131 static qboolean vid_usinghidecursor = false;
132 static qboolean vid_usingvsync = false;
133 static qboolean vid_usevsync = false;
134 static HICON hIcon;
135
136 // used by cd_win.c and snd_win.c
137 HWND mainwindow;
138
139 static HDC       baseDC;
140 static HGLRC baseRC;
141
142 //HWND WINAPI InitializeWindow (HINSTANCE hInstance, int nCmdShow);
143
144 static qboolean vid_isfullscreen;
145
146 //void VID_MenuDraw (void);
147 //void VID_MenuKey (int key);
148
149 //LONG WINAPI MainWndProc (HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
150 //void AppActivate(BOOL fActive, BOOL minimize);
151 //void ClearAllStates (void);
152 //void VID_UpdateWindowStatus (void);
153
154 //====================================
155
156 static int window_x, window_y;
157
158 static qboolean mouseinitialized;
159
160 #ifdef SUPPORTDIRECTX
161 static qboolean dinput;
162 #define DINPUT_BUFFERSIZE           16
163 #define iDirectInputCreate(a,b,c,d)     pDirectInputCreate(a,b,c,d)
164
165 static HRESULT (WINAPI *pDirectInputCreate)(HINSTANCE hinst, DWORD dwVersion, LPDIRECTINPUT * lplpDirectInput, LPUNKNOWN punkOuter);
166 #endif
167
168 // LordHavoc: thanks to backslash for this support for mouse buttons 4 and 5
169 /* backslash :: imouse explorer buttons */
170 /* These are #ifdefed out for non-Win2K in the February 2001 version of
171    MS's platform SDK, but we need them for compilation. . . */
172 #ifndef WM_XBUTTONDOWN
173    #define WM_XBUTTONDOWN      0x020B
174    #define WM_XBUTTONUP      0x020C
175 #endif
176 #ifndef MK_XBUTTON1
177    #define MK_XBUTTON1         0x0020
178    #define MK_XBUTTON2         0x0040
179 #endif
180 #ifndef MK_XBUTTON3
181 // LordHavoc: lets hope this allows more buttons in the future...
182    #define MK_XBUTTON3         0x0080
183    #define MK_XBUTTON4         0x0100
184    #define MK_XBUTTON5         0x0200
185    #define MK_XBUTTON6         0x0400
186    #define MK_XBUTTON7         0x0800
187 #endif
188 /* :: backslash */
189
190 // mouse variables
191 static int                      mouse_buttons;
192 static int                      mouse_oldbuttonstate;
193
194 static unsigned int uiWheelMessage;
195 #ifdef SUPPORTDIRECTX
196 static qboolean dinput_acquired;
197
198 static unsigned int             mstate_di;
199 #endif
200
201 // joystick defines and variables
202 // where should defines be moved?
203 #define JOY_ABSOLUTE_AXIS       0x00000000              // control like a joystick
204 #define JOY_RELATIVE_AXIS       0x00000010              // control like a mouse, spinner, trackball
205 #define JOY_MAX_AXES            6                               // X, Y, Z, R, U, V
206 #define JOY_AXIS_X                      0
207 #define JOY_AXIS_Y                      1
208 #define JOY_AXIS_Z                      2
209 #define JOY_AXIS_R                      3
210 #define JOY_AXIS_U                      4
211 #define JOY_AXIS_V                      5
212
213 enum _ControlList
214 {
215         AxisNada = 0, AxisForward, AxisLook, AxisSide, AxisTurn
216 };
217
218 static DWORD    dwAxisFlags[JOY_MAX_AXES] =
219 {
220         JOY_RETURNX, JOY_RETURNY, JOY_RETURNZ, JOY_RETURNR, JOY_RETURNU, JOY_RETURNV
221 };
222
223 static DWORD    dwAxisMap[JOY_MAX_AXES];
224 static DWORD    dwControlMap[JOY_MAX_AXES];
225 static PDWORD   pdwRawValue[JOY_MAX_AXES];
226
227 // none of these cvars are saved over a session
228 // this means that advanced controller configuration needs to be executed
229 // each time.  this avoids any problems with getting back to a default usage
230 // or when changing from one controller to another.  this way at least something
231 // works.
232 static cvar_t in_joystick = {CVAR_SAVE, "joystick","0", "enables joysticks"};
233 static cvar_t joy_name = {0, "joyname", "joystick", "name of joystick to use (informational only, used only by joyadvanced 1 mode)"};
234 static cvar_t joy_advanced = {0, "joyadvanced", "0", "use more than 2 axis joysticks (configuring this is very technical)"};
235 static cvar_t joy_advaxisx = {0, "joyadvaxisx", "0", "axis mapping for joyadvanced 1 mode"};
236 static cvar_t joy_advaxisy = {0, "joyadvaxisy", "0", "axis mapping for joyadvanced 1 mode"};
237 static cvar_t joy_advaxisz = {0, "joyadvaxisz", "0", "axis mapping for joyadvanced 1 mode"};
238 static cvar_t joy_advaxisr = {0, "joyadvaxisr", "0", "axis mapping for joyadvanced 1 mode"};
239 static cvar_t joy_advaxisu = {0, "joyadvaxisu", "0", "axis mapping for joyadvanced 1 mode"};
240 static cvar_t joy_advaxisv = {0, "joyadvaxisv", "0", "axis mapping for joyadvanced 1 mode"};
241 static cvar_t joy_forwardthreshold = {0, "joyforwardthreshold", "0.15", "minimum joystick movement necessary to move forward"};
242 static cvar_t joy_sidethreshold = {0, "joysidethreshold", "0.15", "minimum joystick movement necessary to move sideways (strafing)"};
243 static cvar_t joy_pitchthreshold = {0, "joypitchthreshold", "0.15", "minimum joystick movement necessary to look up/down"};
244 static cvar_t joy_yawthreshold = {0, "joyyawthreshold", "0.15", "minimum joystick movement necessary to turn left/right"};
245 static cvar_t joy_forwardsensitivity = {0, "joyforwardsensitivity", "-1.0", "how fast the joystick moves forward"};
246 static cvar_t joy_sidesensitivity = {0, "joysidesensitivity", "-1.0", "how fast the joystick moves sideways (strafing)"};
247 static cvar_t joy_pitchsensitivity = {0, "joypitchsensitivity", "1.0", "how fast the joystick looks up/down"};
248 static cvar_t joy_yawsensitivity = {0, "joyyawsensitivity", "-1.0", "how fast the joystick turns left/right"};
249 static cvar_t joy_wwhack1 = {0, "joywwhack1", "0.0", "special hack for wingman warrior"};
250 static cvar_t joy_wwhack2 = {0, "joywwhack2", "0.0", "special hack for wingman warrior"};
251
252 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"};
253
254 static qboolean joy_avail, joy_advancedinit, joy_haspov;
255 static DWORD            joy_oldbuttonstate, joy_oldpovstate;
256
257 static int                      joy_id;
258 static DWORD            joy_flags;
259 static DWORD            joy_numbuttons;
260
261 #ifdef SUPPORTDIRECTX
262 static LPDIRECTINPUT            g_pdi;
263 static LPDIRECTINPUTDEVICE      g_pMouse;
264 static HINSTANCE hInstDI;
265 #endif
266
267 static JOYINFOEX        ji;
268
269 // forward-referenced functions
270 static void IN_StartupJoystick (void);
271 static void Joy_AdvancedUpdate_f (void);
272 static void IN_JoyMove (void);
273 static void IN_StartupMouse (void);
274
275
276 //====================================
277
278 qboolean vid_reallyhidden = true;
279 #ifdef SUPPORTD3D
280 qboolean vid_begunscene = false;
281 #endif
282 void VID_Finish (void)
283 {
284 #ifdef SUPPORTD3D
285         if (vid_d3d9dev)
286         {
287                 DWORD d;
288                 if (vid_begunscene)
289                 {
290                         IDirect3DDevice9_EndScene(vid_d3d9dev);
291                         vid_begunscene = false;
292                 }
293                 if (vid_reallyhidden)
294                         return;
295                 d = IDirect3DDevice9_TestCooperativeLevel(vid_d3d9dev);
296                 switch(d)
297                 {
298                 case D3DERR_DEVICELOST:
299                         vid_d3ddevicelost = true;
300                         vid_hidden = true;
301                         Sleep(100);
302                         break;
303                 case D3DERR_DEVICENOTRESET:
304                         vid_d3ddevicelost = false;
305                         vid_hidden = vid_reallyhidden;
306                         R_Modules_DeviceLost();
307                         IDirect3DDevice9_Reset(vid_d3d9dev, &vid_d3dpresentparameters);
308                         R_Modules_DeviceRestored();
309                         break;
310                 case D3D_OK:
311                         vid_hidden = vid_reallyhidden;
312                         IDirect3DDevice9_Present(vid_d3d9dev, NULL, NULL, NULL, NULL);
313                         break;
314                 }
315                 if (!vid_begunscene && !vid_hidden)
316                 {
317                         IDirect3DDevice9_BeginScene(vid_d3d9dev);
318                         vid_begunscene = true;
319                 }
320                 return;
321         }
322 #endif
323
324         vid_hidden = vid_reallyhidden;
325
326         vid_usevsync = vid_vsync.integer && !cls.timedemo && qwglSwapIntervalEXT;
327         if (vid_usingvsync != vid_usevsync)
328         {
329                 vid_usingvsync = vid_usevsync;
330                 qwglSwapIntervalEXT (vid_usevsync);
331         }
332
333         if (!vid_hidden)
334         {
335                 CHECKGLERROR
336                 if (r_speeds.integer == 2 || gl_finish.integer)
337                 {
338                         qglFinish();CHECKGLERROR
339                 }
340                 SwapBuffers(baseDC);
341         }
342
343         // make sure a context switch can happen every frame - Logitech drivers
344         // input drivers sometimes eat cpu time every 3 seconds or lag badly
345         // without this help
346         Sleep(0);
347
348         VID_UpdateGamma(false, 256);
349 }
350
351 //==========================================================================
352
353
354
355
356 static unsigned char scantokey[128] =
357 {
358 //  0           1       2    3     4     5       6       7      8         9      A          B           C       D           E           F
359         0          ,27    ,'1'  ,'2'  ,'3'  ,'4'    ,'5'    ,'6'   ,'7'      ,'8'   ,'9'       ,'0'        ,'-'   ,'='         ,K_BACKSPACE,9    ,//0
360         'q'        ,'w'   ,'e'  ,'r'  ,'t'  ,'y'    ,'u'    ,'i'   ,'o'      ,'p'   ,'['       ,']'        ,13    ,K_CTRL      ,'a'        ,'s'  ,//1
361         'd'        ,'f'   ,'g'  ,'h'  ,'j'  ,'k'    ,'l'    ,';'   ,'\''     ,'`'   ,K_SHIFT   ,'\\'       ,'z'   ,'x'         ,'c'        ,'v'  ,//2
362         'b'        ,'n'   ,'m'  ,','  ,'.'  ,'/'    ,K_SHIFT,'*'   ,K_ALT    ,' '   ,0         ,K_F1       ,K_F2  ,K_F3        ,K_F4       ,K_F5 ,//3
363         K_F6       ,K_F7  ,K_F8 ,K_F9 ,K_F10,K_PAUSE,0      ,K_HOME,K_UPARROW,K_PGUP,K_KP_MINUS,K_LEFTARROW,K_KP_5,K_RIGHTARROW,K_KP_PLUS  ,K_END,//4
364         K_DOWNARROW,K_PGDN,K_INS,K_DEL,0    ,0      ,0      ,K_F11 ,K_F12    ,0     ,0         ,0          ,0     ,0           ,0          ,0    ,//5
365         0          ,0     ,0    ,0    ,0    ,0      ,0      ,0     ,0        ,0     ,0         ,0          ,0     ,0           ,0          ,0    ,//6
366         0          ,0     ,0    ,0    ,0    ,0      ,0      ,0     ,0        ,0     ,0         ,0          ,0     ,0           ,0          ,0     //7
367 };
368
369
370 /*
371 =======
372 MapKey
373
374 Map from windows to quake keynums
375 =======
376 */
377 static int MapKey (int key, int virtualkey)
378 {
379         int result;
380         int modified = (key >> 16) & 255;
381         qboolean is_extended = false;
382
383         if (modified < 128 && scantokey[modified])
384                 result = scantokey[modified];
385         else
386         {
387                 result = 0;
388                 Con_DPrintf("key 0x%02x (0x%8x, 0x%8x) has no translation\n", modified, key, virtualkey);
389         }
390
391         if (key & (1 << 24))
392                 is_extended = true;
393
394         if ( !is_extended )
395         {
396                 switch ( result )
397                 {
398                 case K_HOME:
399                         return K_KP_HOME;
400                 case K_UPARROW:
401                         return K_KP_UPARROW;
402                 case K_PGUP:
403                         return K_KP_PGUP;
404                 case K_LEFTARROW:
405                         return K_KP_LEFTARROW;
406                 case K_RIGHTARROW:
407                         return K_KP_RIGHTARROW;
408                 case K_END:
409                         return K_KP_END;
410                 case K_DOWNARROW:
411                         return K_KP_DOWNARROW;
412                 case K_PGDN:
413                         return K_KP_PGDN;
414                 case K_INS:
415                         return K_KP_INS;
416                 case K_DEL:
417                         return K_KP_DEL;
418                 default:
419                         return result;
420                 }
421         }
422         else
423         {
424                 switch ( result )
425                 {
426                 case 0x0D:
427                         return K_KP_ENTER;
428                 case 0x2F:
429                         return K_KP_SLASH;
430                 case 0xAF:
431                         return K_KP_PLUS;
432                 }
433                 return result;
434         }
435 }
436
437 /*
438 ===================================================================
439
440 MAIN WINDOW
441
442 ===================================================================
443 */
444
445 /*
446 ================
447 ClearAllStates
448 ================
449 */
450 static void ClearAllStates (void)
451 {
452         Key_ClearStates ();
453         if (vid_usingmouse)
454                 mouse_oldbuttonstate = 0;
455 }
456
457 void AppActivate(BOOL fActive, BOOL minimize)
458 /****************************************************************************
459 *
460 * Function:     AppActivate
461 * Parameters:   fActive - True if app is activating
462 *
463 * Description:  If the application is activating, then swap the system
464 *               into SYSPAL_NOSTATIC mode so that our palettes will display
465 *               correctly.
466 *
467 ****************************************************************************/
468 {
469         static qboolean sound_active = false;  // initially blocked by Sys_InitConsole()
470
471         vid_activewindow = fActive != FALSE;
472         vid_reallyhidden = minimize != FALSE;
473
474         // enable/disable sound on focus gain/loss
475         if ((!vid_reallyhidden && vid_activewindow) || !snd_mutewhenidle.integer)
476         {
477                 if (!sound_active)
478                 {
479                         S_UnblockSound ();
480                         sound_active = true;
481                 }
482         }
483         else
484         {
485                 if (sound_active)
486                 {
487                         S_BlockSound ();
488                         sound_active = false;
489                 }
490         }
491
492         if (fActive)
493         {
494                 if (vid_isfullscreen)
495                 {
496                         if (vid_wassuspended)
497                         {
498                                 vid_wassuspended = false;
499                                 if (gldll)
500                                 {
501                                         ChangeDisplaySettings (&gdevmode, CDS_FULLSCREEN);
502                                         ShowWindow(mainwindow, SW_SHOWNORMAL);
503                                 }
504                         }
505
506                         // LordHavoc: from dabb, fix for alt-tab bug in NVidia drivers
507                         if (gldll)
508                                 MoveWindow(mainwindow,0,0,gdevmode.dmPelsWidth,gdevmode.dmPelsHeight,false);
509                 }
510         }
511
512         if (!fActive)
513         {
514                 VID_SetMouse(false, false, false);
515                 if (vid_isfullscreen)
516                 {
517                         if (gldll)
518                                 ChangeDisplaySettings (NULL, 0);
519                         vid_wassuspended = true;
520                 }
521                 VID_RestoreSystemGamma();
522         }
523 }
524
525 //TODO: move it around in vid_wgl.c since I dont think this is the right position
526 void Sys_SendKeyEvents (void)
527 {
528         MSG msg;
529
530         while (PeekMessage (&msg, NULL, 0, 0, PM_NOREMOVE))
531         {
532                 if (!GetMessage (&msg, NULL, 0, 0))
533                         Sys_Quit (1);
534
535                 TranslateMessage (&msg);
536                 DispatchMessage (&msg);
537         }
538 }
539
540 LONG CDAudio_MessageHandler(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
541
542 static keynum_t buttonremap[16] =
543 {
544         K_MOUSE1,
545         K_MOUSE2,
546         K_MOUSE3,
547         K_MOUSE4,
548         K_MOUSE5,
549         K_MOUSE6,
550         K_MOUSE7,
551         K_MOUSE8,
552         K_MOUSE9,
553         K_MOUSE10,
554         K_MOUSE11,
555         K_MOUSE12,
556         K_MOUSE13,
557         K_MOUSE14,
558         K_MOUSE15,
559         K_MOUSE16,
560 };
561
562 /* main window procedure */
563 LONG WINAPI MainWndProc (HWND hWnd, UINT uMsg, WPARAM  wParam, LPARAM lParam)
564 {
565         LONG    lRet = 1;
566         int             fActive, fMinimized, temp;
567         unsigned char state[256];
568         unsigned char asciichar[4];
569         int             vkey;
570         int             charlength;
571         qboolean down = false;
572
573         if ( uMsg == uiWheelMessage )
574                 uMsg = WM_MOUSEWHEEL;
575
576         switch (uMsg)
577         {
578                 case WM_KILLFOCUS:
579                         if (vid_isfullscreen)
580                                 ShowWindow(mainwindow, SW_SHOWMINNOACTIVE);
581                         break;
582
583                 case WM_CREATE:
584                         break;
585
586                 case WM_MOVE:
587                         window_x = (int) LOWORD(lParam);
588                         window_y = (int) HIWORD(lParam);
589                         VID_SetMouse(false, false, false);
590                         break;
591
592                 case WM_KEYDOWN:
593                 case WM_SYSKEYDOWN:
594                         down = true;
595                 case WM_KEYUP:
596                 case WM_SYSKEYUP:
597                         vkey = MapKey(lParam, wParam);
598                         GetKeyboardState (state);
599                         // alt/ctrl/shift tend to produce funky ToAscii values,
600                         // and if it's not a single character we don't know care about it
601                         charlength = ToAscii (wParam, lParam >> 16, state, (LPWORD)asciichar, 0);
602                         if (vkey == K_ALT || vkey == K_CTRL || vkey == K_SHIFT || charlength == 0)
603                                 asciichar[0] = 0;
604                         else if( charlength == 2 ) {
605                                 asciichar[0] = asciichar[1];
606                         }
607                         Key_Event (vkey, asciichar[0], down);
608                         break;
609
610                 case WM_SYSCHAR:
611                 // keep Alt-Space from happening
612                         break;
613
614                 case WM_SYSCOMMAND:
615                         // prevent screensaver from occuring while the active window
616                         // note: password-locked screensavers on Vista still work
617                         if (vid_activewindow && ((wParam & 0xFFF0) == SC_SCREENSAVE || (wParam & 0xFFF0) == SC_MONITORPOWER))
618                                 lRet = 0;
619                         else
620                                 lRet = DefWindowProc (hWnd, uMsg, wParam, lParam);
621                         break;
622
623         // this is complicated because Win32 seems to pack multiple mouse events into
624         // one update sometimes, so we always check all states and look for events
625                 case WM_LBUTTONDOWN:
626                 case WM_LBUTTONUP:
627                 case WM_RBUTTONDOWN:
628                 case WM_RBUTTONUP:
629                 case WM_MBUTTONDOWN:
630                 case WM_MBUTTONUP:
631                 case WM_XBUTTONDOWN:   // backslash :: imouse explorer buttons
632                 case WM_XBUTTONUP:      // backslash :: imouse explorer buttons
633                 case WM_MOUSEMOVE:
634                         temp = 0;
635
636                         if (wParam & MK_LBUTTON)
637                                 temp |= 1;
638
639                         if (wParam & MK_RBUTTON)
640                                 temp |= 2;
641
642                         if (wParam & MK_MBUTTON)
643                                 temp |= 4;
644
645                         /* backslash :: imouse explorer buttons */
646                         if (wParam & MK_XBUTTON1)
647                                 temp |= 8;
648
649                         if (wParam & MK_XBUTTON2)
650                                 temp |= 16;
651                         /* :: backslash */
652
653                         // LordHavoc: lets hope this allows more buttons in the future...
654                         if (wParam & MK_XBUTTON3)
655                                 temp |= 32;
656                         if (wParam & MK_XBUTTON4)
657                                 temp |= 64;
658                         if (wParam & MK_XBUTTON5)
659                                 temp |= 128;
660                         if (wParam & MK_XBUTTON6)
661                                 temp |= 256;
662                         if (wParam & MK_XBUTTON7)
663                                 temp |= 512;
664
665 #ifdef SUPPORTDIRECTX
666                         if (!dinput_acquired)
667 #endif
668                         {
669                                 // perform button actions
670                                 int i;
671                                 for (i=0 ; i<mouse_buttons && i < 16 ; i++)
672                                         if ((temp ^ mouse_oldbuttonstate) & (1<<i))
673                                                 Key_Event (buttonremap[i], 0, (temp & (1<<i)) != 0);
674                                 mouse_oldbuttonstate = temp;
675                         }
676
677                         break;
678
679                 // JACK: This is the mouse wheel with the Intellimouse
680                 // Its delta is either positive or neg, and we generate the proper
681                 // Event.
682                 case WM_MOUSEWHEEL:
683                         if ((short) HIWORD(wParam) > 0) {
684                                 Key_Event(K_MWHEELUP, 0, true);
685                                 Key_Event(K_MWHEELUP, 0, false);
686                         } else {
687                                 Key_Event(K_MWHEELDOWN, 0, true);
688                                 Key_Event(K_MWHEELDOWN, 0, false);
689                         }
690                         break;
691
692                 case WM_SIZE:
693                         break;
694
695                 case WM_CLOSE:
696                         if (MessageBox (mainwindow, "Are you sure you want to quit?", "Confirm Exit", MB_YESNO | MB_SETFOREGROUND | MB_ICONQUESTION) == IDYES)
697                                 Sys_Quit (0);
698
699                         break;
700
701                 case WM_ACTIVATE:
702                         fActive = LOWORD(wParam);
703                         fMinimized = (BOOL) HIWORD(wParam);
704                         AppActivate(!(fActive == WA_INACTIVE), fMinimized);
705
706                 // fix the leftover Alt from any Alt-Tab or the like that switched us away
707                         ClearAllStates ();
708
709                         break;
710
711                 //case WM_DESTROY:
712                 //      PostQuitMessage (0);
713                 //      break;
714
715                 case MM_MCINOTIFY:
716                         lRet = CDAudio_MessageHandler (hWnd, uMsg, wParam, lParam);
717                         break;
718
719                 default:
720                         /* pass all unhandled messages to DefWindowProc */
721                         lRet = DefWindowProc (hWnd, uMsg, wParam, lParam);
722                 break;
723         }
724
725         /* return 1 if handled message, 0 if not */
726         return lRet;
727 }
728
729 int VID_SetGamma(unsigned short *ramps, int rampsize)
730 {
731         if (qwglMakeCurrent)
732         {
733                 HDC hdc = GetDC (NULL);
734                 int i = SetDeviceGammaRamp(hdc, ramps);
735                 ReleaseDC (NULL, hdc);
736                 return i; // return success or failure
737         }
738         else
739                 return 0;
740 }
741
742 int VID_GetGamma(unsigned short *ramps, int rampsize)
743 {
744         if (qwglMakeCurrent)
745         {
746                 HDC hdc = GetDC (NULL);
747                 int i = GetDeviceGammaRamp(hdc, ramps);
748                 ReleaseDC (NULL, hdc);
749                 return i; // return success or failure
750         }
751         else
752                 return 0;
753 }
754
755 static void GL_CloseLibrary(void)
756 {
757         if (gldll)
758         {
759                 FreeLibrary(gldll);
760                 gldll = 0;
761                 gl_driver[0] = 0;
762                 qwglGetProcAddress = NULL;
763                 gl_extensions = "";
764                 gl_platform = "";
765                 gl_platformextensions = "";
766         }
767 }
768
769 static int GL_OpenLibrary(const char *name)
770 {
771         Con_Printf("Loading OpenGL driver %s\n", name);
772         GL_CloseLibrary();
773         if (!(gldll = LoadLibrary(name)))
774         {
775                 Con_Printf("Unable to LoadLibrary %s\n", name);
776                 return false;
777         }
778         strlcpy(gl_driver, name, sizeof(gl_driver));
779         return true;
780 }
781
782 void *GL_GetProcAddress(const char *name)
783 {
784         if (gldll)
785         {
786                 void *p = NULL;
787                 if (qwglGetProcAddress != NULL)
788                         p = (void *) qwglGetProcAddress(name);
789                 if (p == NULL)
790                         p = (void *) GetProcAddress(gldll, name);
791                 return p;
792         }
793         else
794                 return NULL;
795 }
796
797 #ifndef WGL_ARB_pixel_format
798 #define WGL_NUMBER_PIXEL_FORMATS_ARB   0x2000
799 #define WGL_DRAW_TO_WINDOW_ARB         0x2001
800 #define WGL_DRAW_TO_BITMAP_ARB         0x2002
801 #define WGL_ACCELERATION_ARB           0x2003
802 #define WGL_NEED_PALETTE_ARB           0x2004
803 #define WGL_NEED_SYSTEM_PALETTE_ARB    0x2005
804 #define WGL_SWAP_LAYER_BUFFERS_ARB     0x2006
805 #define WGL_SWAP_METHOD_ARB            0x2007
806 #define WGL_NUMBER_OVERLAYS_ARB        0x2008
807 #define WGL_NUMBER_UNDERLAYS_ARB       0x2009
808 #define WGL_TRANSPARENT_ARB            0x200A
809 #define WGL_TRANSPARENT_RED_VALUE_ARB  0x2037
810 #define WGL_TRANSPARENT_GREEN_VALUE_ARB 0x2038
811 #define WGL_TRANSPARENT_BLUE_VALUE_ARB 0x2039
812 #define WGL_TRANSPARENT_ALPHA_VALUE_ARB 0x203A
813 #define WGL_TRANSPARENT_INDEX_VALUE_ARB 0x203B
814 #define WGL_SHARE_DEPTH_ARB            0x200C
815 #define WGL_SHARE_STENCIL_ARB          0x200D
816 #define WGL_SHARE_ACCUM_ARB            0x200E
817 #define WGL_SUPPORT_GDI_ARB            0x200F
818 #define WGL_SUPPORT_OPENGL_ARB         0x2010
819 #define WGL_DOUBLE_BUFFER_ARB          0x2011
820 #define WGL_STEREO_ARB                 0x2012
821 #define WGL_PIXEL_TYPE_ARB             0x2013
822 #define WGL_COLOR_BITS_ARB             0x2014
823 #define WGL_RED_BITS_ARB               0x2015
824 #define WGL_RED_SHIFT_ARB              0x2016
825 #define WGL_GREEN_BITS_ARB             0x2017
826 #define WGL_GREEN_SHIFT_ARB            0x2018
827 #define WGL_BLUE_BITS_ARB              0x2019
828 #define WGL_BLUE_SHIFT_ARB             0x201A
829 #define WGL_ALPHA_BITS_ARB             0x201B
830 #define WGL_ALPHA_SHIFT_ARB            0x201C
831 #define WGL_ACCUM_BITS_ARB             0x201D
832 #define WGL_ACCUM_RED_BITS_ARB         0x201E
833 #define WGL_ACCUM_GREEN_BITS_ARB       0x201F
834 #define WGL_ACCUM_BLUE_BITS_ARB        0x2020
835 #define WGL_ACCUM_ALPHA_BITS_ARB       0x2021
836 #define WGL_DEPTH_BITS_ARB             0x2022
837 #define WGL_STENCIL_BITS_ARB           0x2023
838 #define WGL_AUX_BUFFERS_ARB            0x2024
839 #define WGL_NO_ACCELERATION_ARB        0x2025
840 #define WGL_GENERIC_ACCELERATION_ARB   0x2026
841 #define WGL_FULL_ACCELERATION_ARB      0x2027
842 #define WGL_SWAP_EXCHANGE_ARB          0x2028
843 #define WGL_SWAP_COPY_ARB              0x2029
844 #define WGL_SWAP_UNDEFINED_ARB         0x202A
845 #define WGL_TYPE_RGBA_ARB              0x202B
846 #define WGL_TYPE_COLORINDEX_ARB        0x202C
847 #endif
848
849 #ifndef WGL_ARB_multisample
850 #define WGL_SAMPLE_BUFFERS_ARB         0x2041
851 #define WGL_SAMPLES_ARB                0x2042
852 #endif
853
854
855 static void IN_Init(void);
856 void VID_Init(void)
857 {
858         WNDCLASS wc;
859
860 #ifdef SUPPORTD3D
861         Cvar_RegisterVariable(&vid_dx9);
862         Cvar_RegisterVariable(&vid_dx9_hal);
863         Cvar_RegisterVariable(&vid_dx9_softvertex);
864         Cvar_RegisterVariable(&vid_dx9_triplebuffer);
865 //      Cvar_RegisterVariable(&vid_dx10);
866 //      Cvar_RegisterVariable(&vid_dx11);
867 #endif
868
869         InitCommonControls();
870         hIcon = LoadIcon (global_hInstance, MAKEINTRESOURCE (IDI_ICON1));
871
872         // Register the frame class
873         wc.style         = 0;
874         wc.lpfnWndProc   = (WNDPROC)MainWndProc;
875         wc.cbClsExtra    = 0;
876         wc.cbWndExtra    = 0;
877         wc.hInstance     = global_hInstance;
878         wc.hIcon         = hIcon;
879         wc.hCursor       = LoadCursor (NULL,IDC_ARROW);
880         wc.hbrBackground = NULL;
881         wc.lpszMenuName  = 0;
882         wc.lpszClassName = "DarkPlacesWindowClass";
883
884         if (!RegisterClass (&wc))
885                 Con_Printf ("Couldn't register window class\n");
886
887         memset(&initialdevmode, 0, sizeof(initialdevmode));
888         EnumDisplaySettings(NULL, ENUM_CURRENT_SETTINGS, &initialdevmode);
889
890         IN_Init();
891 }
892
893 qboolean VID_InitModeGL(viddef_mode_t *mode)
894 {
895         int i;
896         HDC hdc;
897         RECT rect;
898         MSG msg;
899         PIXELFORMATDESCRIPTOR pfd =
900         {
901                 sizeof(PIXELFORMATDESCRIPTOR),  // size of this pfd
902                 1,                              // version number
903                 PFD_DRAW_TO_WINDOW              // support window
904                 |  PFD_SUPPORT_OPENGL   // support OpenGL
905                 |  PFD_DOUBLEBUFFER ,   // double buffered
906                 PFD_TYPE_RGBA,                  // RGBA type
907                 24,                             // 24-bit color depth
908                 0, 0, 0, 0, 0, 0,               // color bits ignored
909                 0,                              // no alpha buffer
910                 0,                              // shift bit ignored
911                 0,                              // no accumulation buffer
912                 0, 0, 0, 0,                     // accum bits ignored
913                 32,                             // 32-bit z-buffer
914                 0,                              // no stencil buffer
915                 0,                              // no auxiliary buffer
916                 PFD_MAIN_PLANE,                 // main layer
917                 0,                              // reserved
918                 0, 0, 0                         // layer masks ignored
919         };
920         int windowpass;
921         int pixelformat, newpixelformat;
922         UINT numpixelformats;
923         DWORD WindowStyle, ExWindowStyle;
924         int CenterX, CenterY;
925         const char *gldrivername;
926         int depth;
927         DEVMODE thismode;
928         qboolean foundmode, foundgoodmode;
929         int *a;
930         float *af;
931         int attribs[128];
932         float attribsf[16];
933         int bpp = mode->bitsperpixel;
934         int width = mode->width;
935         int height = mode->height;
936         int refreshrate = (int)floor(mode->refreshrate+0.5);
937         int stereobuffer = mode->stereobuffer;
938         int samples = mode->samples;
939         int fullscreen = mode->fullscreen;
940
941         if (vid_initialized)
942                 Sys_Error("VID_InitMode called when video is already initialised");
943
944         // if stencil is enabled, ask for alpha too
945         if (bpp >= 32)
946         {
947                 pfd.cRedBits = 8;
948                 pfd.cGreenBits = 8;
949                 pfd.cBlueBits = 8;
950                 pfd.cAlphaBits = 8;
951                 pfd.cDepthBits = 24;
952                 pfd.cStencilBits = 8;
953         }
954         else
955         {
956                 pfd.cRedBits = 5;
957                 pfd.cGreenBits = 5;
958                 pfd.cBlueBits = 5;
959                 pfd.cAlphaBits = 0;
960                 pfd.cDepthBits = 16;
961                 pfd.cStencilBits = 0;
962         }
963
964         if (stereobuffer)
965                 pfd.dwFlags |= PFD_STEREO;
966
967         a = attribs;
968         af = attribsf;
969         *a++ = WGL_DRAW_TO_WINDOW_ARB;
970         *a++ = GL_TRUE;
971         *a++ = WGL_ACCELERATION_ARB;
972         *a++ = WGL_FULL_ACCELERATION_ARB;
973         *a++ = WGL_DOUBLE_BUFFER_ARB;
974         *a++ = true;
975
976         if (bpp >= 32)
977         {
978                 *a++ = WGL_RED_BITS_ARB;
979                 *a++ = 8;
980                 *a++ = WGL_GREEN_BITS_ARB;
981                 *a++ = 8;
982                 *a++ = WGL_BLUE_BITS_ARB;
983                 *a++ = 8;
984                 *a++ = WGL_ALPHA_BITS_ARB;
985                 *a++ = 8;
986                 *a++ = WGL_DEPTH_BITS_ARB;
987                 *a++ = 24;
988                 *a++ = WGL_STENCIL_BITS_ARB;
989                 *a++ = 8;
990         }
991         else
992         {
993                 *a++ = WGL_RED_BITS_ARB;
994                 *a++ = 1;
995                 *a++ = WGL_GREEN_BITS_ARB;
996                 *a++ = 1;
997                 *a++ = WGL_BLUE_BITS_ARB;
998                 *a++ = 1;
999                 *a++ = WGL_DEPTH_BITS_ARB;
1000                 *a++ = 16;
1001         }
1002
1003         if (stereobuffer)
1004         {
1005                 *a++ = WGL_STEREO_ARB;
1006                 *a++ = GL_TRUE;
1007         }
1008
1009         if (samples > 1)
1010         {
1011                 *a++ = WGL_SAMPLE_BUFFERS_ARB;
1012                 *a++ = 1;
1013                 *a++ = WGL_SAMPLES_ARB;
1014                 *a++ = samples;
1015         }
1016
1017         *a = 0;
1018         *af = 0;
1019
1020         gldrivername = "opengl32.dll";
1021 // 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
1022         i = COM_CheckParm("-gl_driver");
1023         if (i && i < com_argc - 1)
1024                 gldrivername = com_argv[i + 1];
1025         if (!GL_OpenLibrary(gldrivername))
1026         {
1027                 Con_Printf("Unable to load GL driver %s\n", gldrivername);
1028                 return false;
1029         }
1030
1031         memset(&gdevmode, 0, sizeof(gdevmode));
1032
1033         vid_isfullscreen = false;
1034         if (fullscreen)
1035         {
1036                 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         IN_StartupJoystick ();
1343
1344         if (qwglSwapIntervalEXT)
1345         {
1346                 vid_usevsync = vid_vsync.integer != 0;
1347                 vid_usingvsync = vid_vsync.integer != 0;
1348                 qwglSwapIntervalEXT (vid_usevsync);
1349         }
1350
1351         return true;
1352 }
1353
1354 #ifdef SUPPORTD3D
1355 static D3DADAPTER_IDENTIFIER9 d3d9adapteridentifier;
1356
1357 extern cvar_t gl_info_extensions;
1358 extern cvar_t gl_info_vendor;
1359 extern cvar_t gl_info_renderer;
1360 extern cvar_t gl_info_version;
1361 extern cvar_t gl_info_platform;
1362 extern cvar_t gl_info_driver;
1363 qboolean VID_InitModeDX(viddef_mode_t *mode, int version)
1364 {
1365         int deviceindex;
1366         RECT rect;
1367         MSG msg;
1368         int pixelformat, newpixelformat;
1369         DWORD WindowStyle, ExWindowStyle;
1370         int CenterX, CenterY;
1371         int bpp = mode->bitsperpixel;
1372         int width = mode->width;
1373         int height = mode->height;
1374         int refreshrate = (int)floor(mode->refreshrate+0.5);
1375 //      int stereobuffer = mode->stereobuffer;
1376         int samples = mode->samples;
1377         int fullscreen = mode->fullscreen;
1378         int numdevices;
1379
1380         if (vid_initialized)
1381                 Sys_Error("VID_InitMode called when video is already initialised");
1382
1383         vid_isfullscreen = fullscreen != 0;
1384         if (fullscreen)
1385         {
1386                 WindowStyle = WS_POPUP;
1387                 ExWindowStyle = WS_EX_TOPMOST;
1388         }
1389         else
1390         {
1391                 WindowStyle = WS_OVERLAPPED | WS_BORDER | WS_CAPTION | WS_SYSMENU | WS_MINIMIZEBOX;
1392                 ExWindowStyle = 0;
1393         }
1394
1395         rect.top = 0;
1396         rect.left = 0;
1397         rect.right = width;
1398         rect.bottom = height;
1399         AdjustWindowRectEx(&rect, WindowStyle, false, 0);
1400
1401         if (fullscreen)
1402         {
1403                 CenterX = 0;
1404                 CenterY = 0;
1405         }
1406         else
1407         {
1408                 CenterX = (GetSystemMetrics(SM_CXSCREEN) - (rect.right - rect.left)) / 2;
1409                 CenterY = (GetSystemMetrics(SM_CYSCREEN) - (rect.bottom - rect.top)) / 2;
1410         }
1411         CenterX = max(0, CenterX);
1412         CenterY = max(0, CenterY);
1413
1414         // x and y may be changed by WM_MOVE messages
1415         window_x = CenterX;
1416         window_y = CenterY;
1417         rect.left += CenterX;
1418         rect.right += CenterX;
1419         rect.top += CenterY;
1420         rect.bottom += CenterY;
1421
1422         pixelformat = 0;
1423         newpixelformat = 0;
1424         gl_extensions = "";
1425         gl_platformextensions = "";
1426
1427         mainwindow = CreateWindowEx (ExWindowStyle, "DarkPlacesWindowClass", gamename, WindowStyle, rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top, NULL, NULL, global_hInstance, NULL);
1428         if (!mainwindow)
1429         {
1430                 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);
1431                 VID_Shutdown();
1432                 return false;
1433         }
1434
1435         baseDC = GetDC(mainwindow);
1436
1437         vid_d3d9 = Direct3DCreate9(D3D_SDK_VERSION);
1438         if (!vid_d3d9)
1439                 Sys_Error("VID_InitMode: Direct3DCreate9 failed");
1440
1441         numdevices = IDirect3D9_GetAdapterCount(vid_d3d9);
1442         vid_d3d9dev = NULL;
1443         memset(&d3d9adapteridentifier, 0, sizeof(d3d9adapteridentifier));
1444         for (deviceindex = 0;deviceindex < numdevices && !vid_d3d9dev;deviceindex++)
1445         {
1446                 memset(&vid_d3dpresentparameters, 0, sizeof(vid_d3dpresentparameters));
1447                 vid_d3dpresentparameters.Flags = D3DPRESENTFLAG_DISCARD_DEPTHSTENCIL;
1448                 vid_d3dpresentparameters.SwapEffect = D3DSWAPEFFECT_DISCARD;
1449                 vid_d3dpresentparameters.hDeviceWindow = mainwindow;
1450                 vid_d3dpresentparameters.BackBufferWidth = width;
1451                 vid_d3dpresentparameters.BackBufferHeight = height;
1452                 vid_d3dpresentparameters.MultiSampleType = samples > 1 ? (D3DMULTISAMPLE_TYPE)samples : D3DMULTISAMPLE_NONE;
1453                 vid_d3dpresentparameters.BackBufferCount = fullscreen ? (vid_dx9_triplebuffer.integer ? 3 : 2) : 1;
1454                 vid_d3dpresentparameters.FullScreen_RefreshRateInHz = fullscreen ? refreshrate : 0;
1455                 vid_d3dpresentparameters.Windowed = !fullscreen;
1456                 vid_d3dpresentparameters.EnableAutoDepthStencil = true;
1457                 vid_d3dpresentparameters.AutoDepthStencilFormat = bpp > 16 ? D3DFMT_D24S8 : D3DFMT_D16;
1458                 vid_d3dpresentparameters.BackBufferFormat = fullscreen?D3DFMT_X8R8G8B8:D3DFMT_UNKNOWN;
1459                 vid_d3dpresentparameters.PresentationInterval = vid_vsync.integer ? D3DPRESENT_INTERVAL_ONE : D3DPRESENT_INTERVAL_IMMEDIATE;
1460
1461                 memset(&d3d9adapteridentifier, 0, sizeof(d3d9adapteridentifier));
1462                 IDirect3D9_GetAdapterIdentifier(vid_d3d9, deviceindex, 0, &d3d9adapteridentifier);
1463
1464                 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);
1465         }
1466
1467         if (!vid_d3d9dev)
1468         {
1469                 VID_Shutdown();
1470                 return false;
1471         }
1472
1473         IDirect3DDevice9_GetDeviceCaps(vid_d3d9dev, &vid_d3d9caps);
1474
1475         Con_Printf("Using D3D9 device: %s\n", d3d9adapteridentifier.Description);
1476         gl_extensions = "";
1477         gl_platform = "D3D9";
1478         gl_platformextensions = "";
1479
1480         ShowWindow (mainwindow, SW_SHOWDEFAULT);
1481         UpdateWindow (mainwindow);
1482
1483         // now we try to make sure we get the focus on the mode switch, because
1484         // sometimes in some systems we don't.  We grab the foreground, then
1485         // finish setting up, pump all our messages, and sleep for a little while
1486         // to let messages finish bouncing around the system, then we put
1487         // ourselves at the top of the z order, then grab the foreground again,
1488         // Who knows if it helps, but it probably doesn't hurt
1489         SetForegroundWindow (mainwindow);
1490
1491         while (PeekMessage (&msg, NULL, 0, 0, PM_REMOVE))
1492         {
1493                 TranslateMessage (&msg);
1494                 DispatchMessage (&msg);
1495         }
1496
1497         Sleep (100);
1498
1499         SetWindowPos (mainwindow, HWND_TOP, 0, 0, 0, 0, SWP_DRAWFRAME | SWP_NOMOVE | SWP_NOSIZE | SWP_SHOWWINDOW | SWP_NOCOPYBITS);
1500
1501         SetForegroundWindow (mainwindow);
1502
1503         // fix the leftover Alt from any Alt-Tab or the like that switched us away
1504         ClearAllStates ();
1505
1506         gl_renderer = d3d9adapteridentifier.Description;
1507         gl_vendor = d3d9adapteridentifier.Driver;
1508         gl_version = "";
1509         gl_extensions = "";
1510
1511         Con_Printf("D3D9 adapter info:\n");
1512         Con_Printf("Description: %s\n", d3d9adapteridentifier.Description);
1513         Con_Printf("DeviceId: %x\n", (unsigned int)d3d9adapteridentifier.DeviceId);
1514         Con_Printf("DeviceName: %p\n", d3d9adapteridentifier.DeviceName);
1515         Con_Printf("Driver: %s\n", d3d9adapteridentifier.Driver);
1516         Con_Printf("DriverVersion: %08x%08x\n", (unsigned int)d3d9adapteridentifier.DriverVersion.u.HighPart, (unsigned int)d3d9adapteridentifier.DriverVersion.u.LowPart);
1517         Con_DPrintf("GL_EXTENSIONS: %s\n", gl_extensions);
1518         Con_DPrintf("%s_EXTENSIONS: %s\n", gl_platform, gl_platformextensions);
1519
1520         // clear the extension flags
1521         memset(&vid.support, 0, sizeof(vid.support));
1522         Cvar_SetQuick(&gl_info_extensions, "");
1523
1524         CHECKGLERROR
1525
1526         vid.forcevbo = true;
1527         vid.support.arb_depth_texture = true;
1528         vid.support.arb_draw_buffers = vid_d3d9caps.NumSimultaneousRTs > 1;
1529         vid.support.arb_occlusion_query = true; // can't find a cap for this
1530         vid.support.arb_shadow = true;
1531         vid.support.arb_texture_compression = true;
1532         vid.support.arb_texture_cube_map = true;
1533         vid.support.arb_texture_non_power_of_two = (vid_d3d9caps.TextureCaps & D3DPTEXTURECAPS_POW2) == 0;
1534         vid.support.arb_vertex_buffer_object = true;
1535         vid.support.ext_blend_subtract = true;
1536         vid.support.ext_draw_range_elements = true;
1537         vid.support.ext_framebuffer_object = true;
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
1543         vid.maxtexturesize_2d = min(vid_d3d9caps.MaxTextureWidth, vid_d3d9caps.MaxTextureHeight);
1544         vid.maxtexturesize_3d = vid_d3d9caps.MaxVolumeExtent;
1545         vid.maxtexturesize_cubemap = vid.maxtexturesize_2d;
1546         vid.texunits = 4;
1547         vid.teximageunits = vid_d3d9caps.MaxSimultaneousTextures;
1548         vid.texarrayunits = 8; // can't find a caps field for this?
1549         vid.max_anisotropy = vid_d3d9caps.MaxAnisotropy;
1550         vid.maxdrawbuffers = vid_d3d9caps.NumSimultaneousRTs;
1551
1552         vid.texunits = bound(4, vid.texunits, MAX_TEXTUREUNITS);
1553         vid.teximageunits = bound(16, vid.teximageunits, MAX_TEXTUREUNITS);
1554         vid.texarrayunits = bound(8, vid.texarrayunits, MAX_TEXTUREUNITS);
1555         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)" : "");
1556         vid.renderpath = RENDERPATH_D3D9;
1557
1558         Cvar_SetQuick(&gl_info_vendor, gl_vendor);
1559         Cvar_SetQuick(&gl_info_renderer, gl_renderer);
1560         Cvar_SetQuick(&gl_info_version, gl_version);
1561         Cvar_SetQuick(&gl_info_platform, gl_platform ? gl_platform : "");
1562         Cvar_SetQuick(&gl_info_driver, gl_driver);
1563
1564         // LordHavoc: report supported extensions
1565         Con_DPrintf("\nQuakeC extensions for server and client: %s\nQuakeC extensions for menu: %s\n", vm_sv_extensions, vm_m_extensions );
1566
1567         // clear to black (loading plaque will be seen over this)
1568         IDirect3DDevice9_Clear(vid_d3d9dev, 0, NULL, D3DCLEAR_TARGET, D3DCOLOR_XRGB(0, 0, 0), 1.0f, 0);
1569         IDirect3DDevice9_BeginScene(vid_d3d9dev);
1570         IDirect3DDevice9_EndScene(vid_d3d9dev);
1571         IDirect3DDevice9_Present(vid_d3d9dev, NULL, NULL, NULL, NULL);
1572         // because the only time we end/begin scene is in VID_Finish, we'd better start a scene now...
1573         IDirect3DDevice9_BeginScene(vid_d3d9dev);
1574         vid_begunscene = true;
1575
1576         //vid_menudrawfn = VID_MenuDraw;
1577         //vid_menukeyfn = VID_MenuKey;
1578         vid_usingmouse = false;
1579         vid_usinghidecursor = false;
1580         vid_usingvsync = false;
1581         vid_hidden = vid_reallyhidden = false;
1582         vid_initialized = true;
1583
1584         IN_StartupMouse ();
1585         IN_StartupJoystick ();
1586
1587         return true;
1588 }
1589 #endif
1590
1591 qboolean VID_InitMode(viddef_mode_t *mode)
1592 {
1593 #ifdef SUPPORTD3D
1594 //      if (vid_dx11.integer)
1595 //              return VID_InitModeDX(mode, 11);
1596 //      if (vid_dx10.integer)
1597 //              return VID_InitModeDX(mode, 10);
1598         if (vid_dx9.integer)
1599                 return VID_InitModeDX(mode, 9);
1600 #endif
1601         return VID_InitModeGL(mode);
1602 }
1603
1604
1605 static void IN_Shutdown(void);
1606 void VID_Shutdown (void)
1607 {
1608         qboolean isgl;
1609         if(vid_initialized == false)
1610                 return;
1611
1612         VID_SetMouse(false, false, false);
1613         VID_RestoreSystemGamma();
1614
1615         vid_initialized = false;
1616         isgl = gldll != NULL;
1617         IN_Shutdown();
1618         gl_driver[0] = 0;
1619         gl_extensions = "";
1620         gl_platform = "";
1621         gl_platformextensions = "";
1622 #ifdef SUPPORTD3D
1623         if (vid_d3d9dev)
1624         {
1625                 if (vid_begunscene)
1626                         IDirect3DDevice9_EndScene(vid_d3d9dev);
1627                 vid_begunscene = false;
1628 //              Cmd_ExecuteString("r_texturestats", src_command);
1629 //              Cmd_ExecuteString("memlist", src_command);
1630                 IDirect3DDevice9_Release(vid_d3d9dev);
1631         }
1632         vid_d3d9dev = NULL;
1633         if (vid_d3d9)
1634                 IDirect3D9_Release(vid_d3d9);
1635         vid_d3d9 = NULL;
1636 #endif
1637         if (qwglMakeCurrent)
1638                 qwglMakeCurrent(NULL, NULL);
1639         qwglMakeCurrent = NULL;
1640         if (baseRC && qwglDeleteContext)
1641                 qwglDeleteContext(baseRC);
1642         qwglDeleteContext = NULL;
1643         // close the library before we get rid of the window
1644         GL_CloseLibrary();
1645         if (baseDC && mainwindow)
1646                 ReleaseDC(mainwindow, baseDC);
1647         AppActivate(false, false);
1648         if (mainwindow)
1649                 DestroyWindow(mainwindow);
1650         mainwindow = 0;
1651         if (vid_isfullscreen && isgl)
1652                 ChangeDisplaySettings (NULL, 0);
1653         vid_isfullscreen = false;
1654 }
1655
1656 void VID_SetMouse(qboolean fullscreengrab, qboolean relative, qboolean hidecursor)
1657 {
1658         static qboolean restore_spi;
1659         static int originalmouseparms[3];
1660
1661         if (!mouseinitialized)
1662                 return;
1663
1664         if (relative)
1665         {
1666                 if (!vid_usingmouse)
1667                 {
1668                         vid_usingmouse = true;
1669                         cl_ignoremousemoves = 2;
1670 #ifdef SUPPORTDIRECTX
1671                         if (dinput && g_pMouse)
1672                         {
1673                                 IDirectInputDevice_Acquire(g_pMouse);
1674                                 dinput_acquired = true;
1675                         }
1676                         else
1677 #endif
1678                         {
1679                                 RECT window_rect;
1680                                 window_rect.left = window_x;
1681                                 window_rect.top = window_y;
1682                                 window_rect.right = window_x + vid.width;
1683                                 window_rect.bottom = window_y + vid.height;
1684
1685                                 // change mouse settings to turn off acceleration
1686 // COMMANDLINEOPTION: Windows GDI Input: -noforcemparms disables setting of mouse parameters (not used with -dinput, windows only)
1687                                 if (!COM_CheckParm ("-noforcemparms") && SystemParametersInfo (SPI_GETMOUSE, 0, originalmouseparms, 0))
1688                                 {
1689                                         int newmouseparms[3];
1690                                         newmouseparms[0] = 0; // threshold to double movement (only if accel level is >= 1)
1691                                         newmouseparms[1] = 0; // threshold to quadruple movement (only if accel level is >= 2)
1692                                         newmouseparms[2] = 0; // maximum level of acceleration (0 = off)
1693                                         restore_spi = SystemParametersInfo (SPI_SETMOUSE, 0, newmouseparms, 0) != FALSE;
1694                                 }
1695                                 else
1696                                         restore_spi = false;
1697                                 SetCursorPos ((window_x + vid.width / 2), (window_y + vid.height / 2));
1698
1699                                 SetCapture (mainwindow);
1700                                 ClipCursor (&window_rect);
1701                         }
1702                 }
1703         }
1704         else
1705         {
1706                 if (vid_usingmouse)
1707                 {
1708                         vid_usingmouse = false;
1709                         cl_ignoremousemoves = 2;
1710 #ifdef SUPPORTDIRECTX
1711                         if (dinput_acquired)
1712                         {
1713                                 IDirectInputDevice_Unacquire(g_pMouse);
1714                                 dinput_acquired = false;
1715                         }
1716                         else
1717 #endif
1718                         {
1719                                 // restore system mouseparms if we changed them
1720                                 if (restore_spi)
1721                                         SystemParametersInfo (SPI_SETMOUSE, 0, originalmouseparms, 0);
1722                                 restore_spi = false;
1723                                 ClipCursor (NULL);
1724                                 ReleaseCapture ();
1725                         }
1726                 }
1727         }
1728
1729         if (vid_usinghidecursor != hidecursor)
1730         {
1731                 vid_usinghidecursor = hidecursor;
1732                 ShowCursor (!hidecursor);
1733         }
1734 }
1735
1736
1737 #ifdef SUPPORTDIRECTX
1738 /*
1739 ===========
1740 IN_InitDInput
1741 ===========
1742 */
1743 static qboolean IN_InitDInput (void)
1744 {
1745     HRESULT             hr;
1746         DIPROPDWORD     dipdw = {
1747                 {
1748                         sizeof(DIPROPDWORD),        // diph.dwSize
1749                         sizeof(DIPROPHEADER),       // diph.dwHeaderSize
1750                         0,                          // diph.dwObj
1751                         DIPH_DEVICE,                // diph.dwHow
1752                 },
1753                 DINPUT_BUFFERSIZE,              // dwData
1754         };
1755
1756         if (!hInstDI)
1757         {
1758                 hInstDI = LoadLibrary("dinput.dll");
1759
1760                 if (hInstDI == NULL)
1761                 {
1762                         Con_Print("Couldn't load dinput.dll\n");
1763                         return false;
1764                 }
1765         }
1766
1767         if (!pDirectInputCreate)
1768         {
1769                 pDirectInputCreate = (HRESULT (__stdcall *)(HINSTANCE,DWORD,LPDIRECTINPUT *,LPUNKNOWN))GetProcAddress(hInstDI,"DirectInputCreateA");
1770
1771                 if (!pDirectInputCreate)
1772                 {
1773                         Con_Print("Couldn't get DI proc addr\n");
1774                         return false;
1775                 }
1776         }
1777
1778 // register with DirectInput and get an IDirectInput to play with.
1779         hr = iDirectInputCreate(global_hInstance, DIRECTINPUT_VERSION, &g_pdi, NULL);
1780
1781         if (FAILED(hr))
1782         {
1783                 return false;
1784         }
1785
1786 // obtain an interface to the system mouse device.
1787 #ifdef __cplusplus
1788         hr = IDirectInput_CreateDevice(g_pdi, GUID_SysMouse, &g_pMouse, NULL);
1789 #else
1790         hr = IDirectInput_CreateDevice(g_pdi, &GUID_SysMouse, &g_pMouse, NULL);
1791 #endif
1792
1793         if (FAILED(hr))
1794         {
1795                 Con_Print("Couldn't open DI mouse device\n");
1796                 return false;
1797         }
1798
1799 // set the data format to "mouse format".
1800         hr = IDirectInputDevice_SetDataFormat(g_pMouse, &c_dfDIMouse);
1801
1802         if (FAILED(hr))
1803         {
1804                 Con_Print("Couldn't set DI mouse format\n");
1805                 return false;
1806         }
1807
1808 // set the cooperativity level.
1809         hr = IDirectInputDevice_SetCooperativeLevel(g_pMouse, mainwindow,
1810                         DISCL_EXCLUSIVE | DISCL_FOREGROUND);
1811
1812         if (FAILED(hr))
1813         {
1814                 Con_Print("Couldn't set DI coop level\n");
1815                 return false;
1816         }
1817
1818
1819 // set the buffer size to DINPUT_BUFFERSIZE elements.
1820 // the buffer size is a DWORD property associated with the device
1821         hr = IDirectInputDevice_SetProperty(g_pMouse, DIPROP_BUFFERSIZE, &dipdw.diph);
1822
1823         if (FAILED(hr))
1824         {
1825                 Con_Print("Couldn't set DI buffersize\n");
1826                 return false;
1827         }
1828
1829         return true;
1830 }
1831 #endif
1832
1833
1834 /*
1835 ===========
1836 IN_StartupMouse
1837 ===========
1838 */
1839 static void IN_StartupMouse (void)
1840 {
1841         if (COM_CheckParm ("-nomouse"))
1842                 return;
1843
1844         mouseinitialized = true;
1845
1846 #ifdef SUPPORTDIRECTX
1847 // COMMANDLINEOPTION: Windows Input: -dinput enables DirectInput for mouse/joystick input
1848         if (COM_CheckParm ("-dinput"))
1849                 dinput = IN_InitDInput ();
1850
1851         if (dinput)
1852                 Con_Print("DirectInput initialized\n");
1853         else
1854                 Con_Print("DirectInput not initialized\n");
1855 #endif
1856
1857         mouse_buttons = 10;
1858 }
1859
1860
1861 /*
1862 ===========
1863 IN_MouseMove
1864 ===========
1865 */
1866 static void IN_MouseMove (void)
1867 {
1868         POINT current_pos;
1869
1870         GetCursorPos (&current_pos);
1871         in_windowmouse_x = current_pos.x - window_x;
1872         in_windowmouse_y = current_pos.y - window_y;
1873
1874         if (!vid_usingmouse)
1875                 return;
1876
1877 #ifdef SUPPORTDIRECTX
1878         if (dinput_acquired)
1879         {
1880                 int i;
1881                 DIDEVICEOBJECTDATA      od;
1882                 DWORD                           dwElements;
1883                 HRESULT                         hr;
1884
1885                 for (;;)
1886                 {
1887                         dwElements = 1;
1888
1889                         hr = IDirectInputDevice_GetDeviceData(g_pMouse,
1890                                         sizeof(DIDEVICEOBJECTDATA), &od, &dwElements, 0);
1891
1892                         if ((hr == DIERR_INPUTLOST) || (hr == DIERR_NOTACQUIRED))
1893                         {
1894                                 IDirectInputDevice_Acquire(g_pMouse);
1895                                 break;
1896                         }
1897
1898                         /* Unable to read data or no data available */
1899                         if (FAILED(hr) || dwElements == 0)
1900                                 break;
1901
1902                         /* Look at the element to see what happened */
1903
1904                         if ((int)od.dwOfs == DIMOFS_X)
1905                                 in_mouse_x += (LONG) od.dwData;
1906                         if ((int)od.dwOfs == DIMOFS_Y)
1907                                 in_mouse_y += (LONG) od.dwData;
1908                         if ((int)od.dwOfs == DIMOFS_Z)
1909                         {
1910                                 if((LONG)od.dwData < 0)
1911                                 {
1912                                         Key_Event(K_MWHEELDOWN, 0, true);
1913                                         Key_Event(K_MWHEELDOWN, 0, false);
1914                                 }
1915                                 else if((LONG)od.dwData > 0)
1916                                 {
1917                                         Key_Event(K_MWHEELUP, 0, true);
1918                                         Key_Event(K_MWHEELUP, 0, false);
1919                                 }
1920                         }
1921                         if ((int)od.dwOfs == DIMOFS_BUTTON0)
1922                                 mstate_di = (mstate_di & ~1) | ((od.dwData & 0x80) >> 7);
1923                         if ((int)od.dwOfs == DIMOFS_BUTTON1)
1924                                 mstate_di = (mstate_di & ~2) | ((od.dwData & 0x80) >> 6);
1925                         if ((int)od.dwOfs == DIMOFS_BUTTON2)
1926                                 mstate_di = (mstate_di & ~4) | ((od.dwData & 0x80) >> 5);
1927                         if ((int)od.dwOfs == DIMOFS_BUTTON3)
1928                                 mstate_di = (mstate_di & ~8) | ((od.dwData & 0x80) >> 4);
1929                 }
1930
1931                 // perform button actions
1932                 for (i=0 ; i<mouse_buttons && i < 16 ; i++)
1933                         if ((mstate_di ^ mouse_oldbuttonstate) & (1<<i))
1934                                 Key_Event (buttonremap[i], 0, (mstate_di & (1<<i)) != 0);
1935                 mouse_oldbuttonstate = mstate_di;
1936         }
1937         else
1938 #endif
1939         {
1940                 in_mouse_x += in_windowmouse_x - (int)(vid.width / 2);
1941                 in_mouse_y += in_windowmouse_y - (int)(vid.height / 2);
1942
1943                 // if the mouse has moved, force it to the center, so there's room to move
1944                 if (in_mouse_x || in_mouse_y)
1945                         SetCursorPos ((window_x + vid.width / 2), (window_y + vid.height / 2));
1946         }
1947 }
1948
1949
1950 /*
1951 ===========
1952 IN_Move
1953 ===========
1954 */
1955 void IN_Move (void)
1956 {
1957         if (vid_activewindow && !vid_reallyhidden)
1958         {
1959                 IN_MouseMove ();
1960                 IN_JoyMove ();
1961         }
1962 }
1963
1964
1965 /*
1966 ===============
1967 IN_StartupJoystick
1968 ===============
1969 */
1970 static void IN_StartupJoystick (void)
1971 {
1972         int                     numdevs;
1973         JOYCAPS         jc;
1974         MMRESULT        mmr;
1975         mmr = 0;
1976
1977         // assume no joystick
1978         joy_avail = false;
1979
1980         // abort startup if user requests no joystick
1981 // COMMANDLINEOPTION: Windows Input: -nojoy disables joystick support, may be a small speed increase
1982         if (COM_CheckParm ("-nojoy"))
1983                 return;
1984
1985         // verify joystick driver is present
1986         if ((numdevs = joyGetNumDevs ()) == 0)
1987         {
1988                 Con_Print("\njoystick not found -- driver not present\n\n");
1989                 return;
1990         }
1991
1992         // cycle through the joystick ids for the first valid one
1993         for (joy_id=0 ; joy_id<numdevs ; joy_id++)
1994         {
1995                 memset (&ji, 0, sizeof(ji));
1996                 ji.dwSize = sizeof(ji);
1997                 ji.dwFlags = JOY_RETURNCENTERED;
1998
1999                 if ((mmr = joyGetPosEx (joy_id, &ji)) == JOYERR_NOERROR)
2000                         break;
2001         }
2002
2003         // abort startup if we didn't find a valid joystick
2004         if (mmr != JOYERR_NOERROR)
2005         {
2006                 Con_Printf("\njoystick not found -- no valid joysticks (%x)\n\n", mmr);
2007                 return;
2008         }
2009
2010         // get the capabilities of the selected joystick
2011         // abort startup if command fails
2012         memset (&jc, 0, sizeof(jc));
2013         if ((mmr = joyGetDevCaps (joy_id, &jc, sizeof(jc))) != JOYERR_NOERROR)
2014         {
2015                 Con_Printf("\njoystick not found -- invalid joystick capabilities (%x)\n\n", mmr);
2016                 return;
2017         }
2018
2019         // save the joystick's number of buttons and POV status
2020         joy_numbuttons = jc.wNumButtons;
2021         joy_haspov = (jc.wCaps & JOYCAPS_HASPOV) != 0;
2022
2023         // old button and POV states default to no buttons pressed
2024         joy_oldbuttonstate = joy_oldpovstate = 0;
2025
2026         // mark the joystick as available and advanced initialization not completed
2027         // this is needed as cvars are not available during initialization
2028
2029         joy_avail = true;
2030         joy_advancedinit = false;
2031
2032         Con_Print("\njoystick detected\n\n");
2033 }
2034
2035
2036 /*
2037 ===========
2038 RawValuePointer
2039 ===========
2040 */
2041 static PDWORD RawValuePointer (int axis)
2042 {
2043         switch (axis)
2044         {
2045         case JOY_AXIS_X:
2046                 return &ji.dwXpos;
2047         case JOY_AXIS_Y:
2048                 return &ji.dwYpos;
2049         case JOY_AXIS_Z:
2050                 return &ji.dwZpos;
2051         case JOY_AXIS_R:
2052                 return &ji.dwRpos;
2053         case JOY_AXIS_U:
2054                 return &ji.dwUpos;
2055         case JOY_AXIS_V:
2056                 return &ji.dwVpos;
2057         }
2058         return NULL; // LordHavoc: hush compiler warning
2059 }
2060
2061
2062 /*
2063 ===========
2064 Joy_AdvancedUpdate_f
2065 ===========
2066 */
2067 static void Joy_AdvancedUpdate_f (void)
2068 {
2069
2070         // called once by IN_ReadJoystick and by user whenever an update is needed
2071         // cvars are now available
2072         int     i;
2073         DWORD dwTemp;
2074
2075         // initialize all the maps
2076         for (i = 0; i < JOY_MAX_AXES; i++)
2077         {
2078                 dwAxisMap[i] = AxisNada;
2079                 dwControlMap[i] = JOY_ABSOLUTE_AXIS;
2080                 pdwRawValue[i] = RawValuePointer(i);
2081         }
2082
2083         if( joy_advanced.integer == 0)
2084         {
2085                 // default joystick initialization
2086                 // 2 axes only with joystick control
2087                 dwAxisMap[JOY_AXIS_X] = AxisTurn;
2088                 // dwControlMap[JOY_AXIS_X] = JOY_ABSOLUTE_AXIS;
2089                 dwAxisMap[JOY_AXIS_Y] = AxisForward;
2090                 // dwControlMap[JOY_AXIS_Y] = JOY_ABSOLUTE_AXIS;
2091         }
2092         else
2093         {
2094                 if (strcmp (joy_name.string, "joystick") != 0)
2095                 {
2096                         // notify user of advanced controller
2097                         Con_Printf("\n%s configured\n\n", joy_name.string);
2098                 }
2099
2100                 // advanced initialization here
2101                 // data supplied by user via joy_axisn cvars
2102                 dwTemp = (DWORD) joy_advaxisx.value;
2103                 dwAxisMap[JOY_AXIS_X] = dwTemp & 0x0000000f;
2104                 dwControlMap[JOY_AXIS_X] = dwTemp & JOY_RELATIVE_AXIS;
2105                 dwTemp = (DWORD) joy_advaxisy.value;
2106                 dwAxisMap[JOY_AXIS_Y] = dwTemp & 0x0000000f;
2107                 dwControlMap[JOY_AXIS_Y] = dwTemp & JOY_RELATIVE_AXIS;
2108                 dwTemp = (DWORD) joy_advaxisz.value;
2109                 dwAxisMap[JOY_AXIS_Z] = dwTemp & 0x0000000f;
2110                 dwControlMap[JOY_AXIS_Z] = dwTemp & JOY_RELATIVE_AXIS;
2111                 dwTemp = (DWORD) joy_advaxisr.value;
2112                 dwAxisMap[JOY_AXIS_R] = dwTemp & 0x0000000f;
2113                 dwControlMap[JOY_AXIS_R] = dwTemp & JOY_RELATIVE_AXIS;
2114                 dwTemp = (DWORD) joy_advaxisu.value;
2115                 dwAxisMap[JOY_AXIS_U] = dwTemp & 0x0000000f;
2116                 dwControlMap[JOY_AXIS_U] = dwTemp & JOY_RELATIVE_AXIS;
2117                 dwTemp = (DWORD) joy_advaxisv.value;
2118                 dwAxisMap[JOY_AXIS_V] = dwTemp & 0x0000000f;
2119                 dwControlMap[JOY_AXIS_V] = dwTemp & JOY_RELATIVE_AXIS;
2120         }
2121
2122         // compute the axes to collect from DirectInput
2123         joy_flags = JOY_RETURNCENTERED | JOY_RETURNBUTTONS | JOY_RETURNPOV;
2124         for (i = 0; i < JOY_MAX_AXES; i++)
2125         {
2126                 if (dwAxisMap[i] != AxisNada)
2127                 {
2128                         joy_flags |= dwAxisFlags[i];
2129                 }
2130         }
2131 }
2132
2133 /*
2134 ===============
2135 IN_ReadJoystick
2136 ===============
2137 */
2138 static qboolean IN_ReadJoystick (void)
2139 {
2140
2141         memset (&ji, 0, sizeof(ji));
2142         ji.dwSize = sizeof(ji);
2143         ji.dwFlags = joy_flags;
2144
2145         if (joyGetPosEx (joy_id, &ji) == JOYERR_NOERROR)
2146         {
2147                 // this is a hack -- there is a bug in the Logitech WingMan Warrior DirectInput Driver
2148                 // rather than having 32768 be the zero point, they have the zero point at 32668
2149                 // go figure -- anyway, now we get the full resolution out of the device
2150                 if (joy_wwhack1.integer != 0.0)
2151                 {
2152                         ji.dwUpos += 100;
2153                 }
2154                 return true;
2155         }
2156         else
2157         {
2158                 // read error occurred
2159                 // turning off the joystick seems too harsh for 1 read error,
2160                 // but what should be done?
2161                 return false;
2162         }
2163 }
2164
2165
2166 /*
2167 ===========
2168 IN_JoyMove
2169 ===========
2170 */
2171 static void IN_JoyMove (void)
2172 {
2173         float   speed, aspeed;
2174         float   fAxisValue, fTemp;
2175         int             i, mouselook = (in_mlook.state & 1) || freelook.integer;
2176
2177         // complete initialization if first time in
2178         // this is needed as cvars are not available at initialization time
2179         if( joy_advancedinit != true )
2180         {
2181                 Joy_AdvancedUpdate_f();
2182                 joy_advancedinit = true;
2183         }
2184
2185         if (joy_avail)
2186         {
2187                 int             i, key_index;
2188                 DWORD   buttonstate, povstate;
2189
2190                 // loop through the joystick buttons
2191                 // key a joystick event or auxillary event for higher number buttons for each state change
2192                 buttonstate = ji.dwButtons;
2193                 for (i=0 ; i < (int) joy_numbuttons ; i++)
2194                 {
2195                         if ( (buttonstate & (1<<i)) && !(joy_oldbuttonstate & (1<<i)) )
2196                         {
2197                                 key_index = (i < 16) ? K_JOY1 : K_AUX1;
2198                                 Key_Event (key_index + i, 0, true);
2199                         }
2200
2201                         if ( !(buttonstate & (1<<i)) && (joy_oldbuttonstate & (1<<i)) )
2202                         {
2203                                 key_index = (i < 16) ? K_JOY1 : K_AUX1;
2204                                 Key_Event (key_index + i, 0, false);
2205                         }
2206                 }
2207                 joy_oldbuttonstate = buttonstate;
2208
2209                 if (joy_haspov)
2210                 {
2211                         // convert POV information into 4 bits of state information
2212                         // this avoids any potential problems related to moving from one
2213                         // direction to another without going through the center position
2214                         povstate = 0;
2215                         if(ji.dwPOV != JOY_POVCENTERED)
2216                         {
2217                                 if (ji.dwPOV == JOY_POVFORWARD)
2218                                         povstate |= 0x01;
2219                                 if (ji.dwPOV == JOY_POVRIGHT)
2220                                         povstate |= 0x02;
2221                                 if (ji.dwPOV == JOY_POVBACKWARD)
2222                                         povstate |= 0x04;
2223                                 if (ji.dwPOV == JOY_POVLEFT)
2224                                         povstate |= 0x08;
2225                         }
2226                         // determine which bits have changed and key an auxillary event for each change
2227                         for (i=0 ; i < 4 ; i++)
2228                         {
2229                                 if ( (povstate & (1<<i)) && !(joy_oldpovstate & (1<<i)) )
2230                                 {
2231                                         Key_Event (K_AUX29 + i, 0, true);
2232                                 }
2233
2234                                 if ( !(povstate & (1<<i)) && (joy_oldpovstate & (1<<i)) )
2235                                 {
2236                                         Key_Event (K_AUX29 + i, 0, false);
2237                                 }
2238                         }
2239                         joy_oldpovstate = povstate;
2240                 }
2241         }
2242
2243         // verify joystick is available and that the user wants to use it
2244         if (!joy_avail || !in_joystick.integer)
2245         {
2246                 return;
2247         }
2248
2249         // collect the joystick data, if possible
2250         if (IN_ReadJoystick () != true)
2251         {
2252                 return;
2253         }
2254
2255         if (in_speed.state & 1)
2256                 speed = cl_movespeedkey.value;
2257         else
2258                 speed = 1;
2259         // LordHavoc: viewzoom affects sensitivity for sniping
2260         aspeed = speed * cl.realframetime * cl.viewzoom;
2261
2262         // loop through the axes
2263         for (i = 0; i < JOY_MAX_AXES; i++)
2264         {
2265                 // get the floating point zero-centered, potentially-inverted data for the current axis
2266                 fAxisValue = (float) *pdwRawValue[i];
2267                 // move centerpoint to zero
2268                 fAxisValue -= 32768.0;
2269
2270                 if (joy_wwhack2.integer != 0.0)
2271                 {
2272                         if (dwAxisMap[i] == AxisTurn)
2273                         {
2274                                 // this is a special formula for the Logitech WingMan Warrior
2275                                 // y=ax^b; where a = 300 and b = 1.3
2276                                 // also x values are in increments of 800 (so this is factored out)
2277                                 // then bounds check result to level out excessively high spin rates
2278                                 fTemp = 300.0 * pow(abs(fAxisValue) / 800.0, 1.3);
2279                                 if (fTemp > 14000.0)
2280                                         fTemp = 14000.0;
2281                                 // restore direction information
2282                                 fAxisValue = (fAxisValue > 0.0) ? fTemp : -fTemp;
2283                         }
2284                 }
2285
2286                 // convert range from -32768..32767 to -1..1
2287                 fAxisValue /= 32768.0;
2288
2289                 switch (dwAxisMap[i])
2290                 {
2291                 case AxisForward:
2292                         if ((joy_advanced.integer == 0) && mouselook)
2293                         {
2294                                 // user wants forward control to become look control
2295                                 if (fabs(fAxisValue) > joy_pitchthreshold.value)
2296                                 {
2297                                         // if mouse invert is on, invert the joystick pitch value
2298                                         // only absolute control support here (joy_advanced is false)
2299                                         if (m_pitch.value < 0.0)
2300                                         {
2301                                                 cl.viewangles[PITCH] -= (fAxisValue * joy_pitchsensitivity.value) * aspeed * cl_pitchspeed.value;
2302                                         }
2303                                         else
2304                                         {
2305                                                 cl.viewangles[PITCH] += (fAxisValue * joy_pitchsensitivity.value) * aspeed * cl_pitchspeed.value;
2306                                         }
2307                                         V_StopPitchDrift();
2308                                 }
2309                                 else
2310                                 {
2311                                         // no pitch movement
2312                                         // disable pitch return-to-center unless requested by user
2313                                         // *** this code can be removed when the lookspring bug is fixed
2314                                         // *** the bug always has the lookspring feature on
2315                                         if(lookspring.value == 0.0)
2316                                                 V_StopPitchDrift();
2317                                 }
2318                         }
2319                         else
2320                         {
2321                                 // user wants forward control to be forward control
2322                                 if (fabs(fAxisValue) > joy_forwardthreshold.value)
2323                                 {
2324                                         cl.cmd.forwardmove += (fAxisValue * joy_forwardsensitivity.value) * speed * cl_forwardspeed.value;
2325                                 }
2326                         }
2327                         break;
2328
2329                 case AxisSide:
2330                         if (fabs(fAxisValue) > joy_sidethreshold.value)
2331                         {
2332                                 cl.cmd.sidemove += (fAxisValue * joy_sidesensitivity.value) * speed * cl_sidespeed.value;
2333                         }
2334                         break;
2335
2336                 case AxisTurn:
2337                         if ((in_strafe.state & 1) || (lookstrafe.integer && mouselook))
2338                         {
2339                                 // user wants turn control to become side control
2340                                 if (fabs(fAxisValue) > joy_sidethreshold.value)
2341                                 {
2342                                         cl.cmd.sidemove -= (fAxisValue * joy_sidesensitivity.value) * speed * cl_sidespeed.value;
2343                                 }
2344                         }
2345                         else
2346                         {
2347                                 // user wants turn control to be turn control
2348                                 if (fabs(fAxisValue) > joy_yawthreshold.value)
2349                                 {
2350                                         if(dwControlMap[i] == JOY_ABSOLUTE_AXIS)
2351                                         {
2352                                                 cl.viewangles[YAW] += (fAxisValue * joy_yawsensitivity.value) * aspeed * cl_yawspeed.value;
2353                                         }
2354                                         else
2355                                         {
2356                                                 cl.viewangles[YAW] += (fAxisValue * joy_yawsensitivity.value) * speed * 180.0;
2357                                         }
2358
2359                                 }
2360                         }
2361                         break;
2362
2363                 case AxisLook:
2364                         if (mouselook)
2365                         {
2366                                 if (fabs(fAxisValue) > joy_pitchthreshold.value)
2367                                 {
2368                                         // pitch movement detected and pitch movement desired by user
2369                                         if(dwControlMap[i] == JOY_ABSOLUTE_AXIS)
2370                                         {
2371                                                 cl.viewangles[PITCH] += (fAxisValue * joy_pitchsensitivity.value) * aspeed * cl_pitchspeed.value;
2372                                         }
2373                                         else
2374                                         {
2375                                                 cl.viewangles[PITCH] += (fAxisValue * joy_pitchsensitivity.value) * speed * 180.0;
2376                                         }
2377                                         V_StopPitchDrift();
2378                                 }
2379                                 else
2380                                 {
2381                                         // no pitch movement
2382                                         // disable pitch return-to-center unless requested by user
2383                                         // *** this code can be removed when the lookspring bug is fixed
2384                                         // *** the bug always has the lookspring feature on
2385                                         if(lookspring.integer == 0)
2386                                                 V_StopPitchDrift();
2387                                 }
2388                         }
2389                         break;
2390
2391                 default:
2392                         break;
2393                 }
2394         }
2395 }
2396
2397 static void IN_Init(void)
2398 {
2399         uiWheelMessage = RegisterWindowMessage ( "MSWHEEL_ROLLMSG" );
2400
2401         // joystick variables
2402         Cvar_RegisterVariable (&in_joystick);
2403         Cvar_RegisterVariable (&joy_name);
2404         Cvar_RegisterVariable (&joy_advanced);
2405         Cvar_RegisterVariable (&joy_advaxisx);
2406         Cvar_RegisterVariable (&joy_advaxisy);
2407         Cvar_RegisterVariable (&joy_advaxisz);
2408         Cvar_RegisterVariable (&joy_advaxisr);
2409         Cvar_RegisterVariable (&joy_advaxisu);
2410         Cvar_RegisterVariable (&joy_advaxisv);
2411         Cvar_RegisterVariable (&joy_forwardthreshold);
2412         Cvar_RegisterVariable (&joy_sidethreshold);
2413         Cvar_RegisterVariable (&joy_pitchthreshold);
2414         Cvar_RegisterVariable (&joy_yawthreshold);
2415         Cvar_RegisterVariable (&joy_forwardsensitivity);
2416         Cvar_RegisterVariable (&joy_sidesensitivity);
2417         Cvar_RegisterVariable (&joy_pitchsensitivity);
2418         Cvar_RegisterVariable (&joy_yawsensitivity);
2419         Cvar_RegisterVariable (&joy_wwhack1);
2420         Cvar_RegisterVariable (&joy_wwhack2);
2421         Cvar_RegisterVariable (&vid_forcerefreshrate);
2422         Cmd_AddCommand ("joyadvancedupdate", Joy_AdvancedUpdate_f, "applies current joyadv* cvar settings to the joystick driver");
2423 }
2424
2425 static void IN_Shutdown(void)
2426 {
2427 #ifdef SUPPORTDIRECTX
2428         if (g_pMouse)
2429                 IDirectInputDevice_Release(g_pMouse);
2430         g_pMouse = NULL;
2431
2432         if (g_pdi)
2433                 IDirectInput_Release(g_pdi);
2434         g_pdi = NULL;
2435 #endif
2436 }
2437
2438 size_t VID_ListModes(vid_mode_t *modes, size_t maxcount)
2439 {
2440         int i;
2441         size_t k;
2442         DEVMODE thismode;
2443
2444         thismode.dmSize = sizeof(thismode);
2445         thismode.dmDriverExtra = 0;
2446         k = 0;
2447         for(i = 0; EnumDisplaySettings(NULL, i, &thismode); ++i)
2448         {
2449                 if(~thismode.dmFields & (DM_BITSPERPEL | DM_PELSWIDTH | DM_PELSHEIGHT | DM_DISPLAYFREQUENCY))
2450                 {
2451                         Con_DPrintf("enumerating modes yielded a bogus item... please debug this\n");
2452                         continue;
2453                 }
2454                 if(k >= maxcount)
2455                         break;
2456                 modes[k].width = thismode.dmPelsWidth;
2457                 modes[k].height = thismode.dmPelsHeight;
2458                 modes[k].bpp = thismode.dmBitsPerPel;
2459                 modes[k].refreshrate = thismode.dmDisplayFrequency;
2460                 modes[k].pixelheight_num = 1;
2461                 modes[k].pixelheight_denom = 1; // Win32 apparently does not provide this (FIXME)
2462                 ++k;
2463         }
2464         return k;
2465 }