snd_mutewhenidle 0: do NOT still mute when app is hidden (e.g. virtual desktop change)
[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 // gl_vidnt.c -- NT GL vid component
21
22 // we don't need a very new dinput
23 #define DIRECTINPUT_VERSION 0x0300
24
25 #include "quakedef.h"
26 #include <windows.h>
27 #include <mmsystem.h>
28 #ifdef SUPPORTDIRECTX
29 #include <dsound.h>
30 #endif
31 #include "resource.h"
32 #include <commctrl.h>
33 #ifdef SUPPORTDIRECTX
34 #include <dinput.h>
35 #endif
36
37 extern HINSTANCE global_hInstance;
38
39
40 #ifndef WM_MOUSEWHEEL
41 #define WM_MOUSEWHEEL                   0x020A
42 #endif
43
44 // Tell startup code that we have a client
45 int cl_available = true;
46
47 qboolean vid_supportrefreshrate = true;
48
49 static int (WINAPI *qwglChoosePixelFormat)(HDC, CONST PIXELFORMATDESCRIPTOR *);
50 static int (WINAPI *qwglDescribePixelFormat)(HDC, int, UINT, LPPIXELFORMATDESCRIPTOR);
51 //static int (WINAPI *qwglGetPixelFormat)(HDC);
52 static BOOL (WINAPI *qwglSetPixelFormat)(HDC, int, CONST PIXELFORMATDESCRIPTOR *);
53 static BOOL (WINAPI *qwglSwapBuffers)(HDC);
54 static HGLRC (WINAPI *qwglCreateContext)(HDC);
55 static BOOL (WINAPI *qwglDeleteContext)(HGLRC);
56 static HGLRC (WINAPI *qwglGetCurrentContext)(VOID);
57 static HDC (WINAPI *qwglGetCurrentDC)(VOID);
58 static PROC (WINAPI *qwglGetProcAddress)(LPCSTR);
59 static BOOL (WINAPI *qwglMakeCurrent)(HDC, HGLRC);
60 static BOOL (WINAPI *qwglSwapIntervalEXT)(int interval);
61 static const char *(WINAPI *qwglGetExtensionsStringARB)(HDC hdc);
62 static BOOL (WINAPI *qwglChoosePixelFormatARB)(HDC hdc, const int *piAttribIList, const FLOAT *pfAttribFList, UINT nMaxFormats, int *piFormats, UINT *nNumFormats);
63 static BOOL (WINAPI *qwglGetPixelFormatAttribivARB)(HDC hdc, int iPixelFormat, int iLayerPlane, UINT nAttributes, const int *piAttributes, int *piValues);
64
65 static dllfunction_t wglfuncs[] =
66 {
67         {"wglChoosePixelFormat", (void **) &qwglChoosePixelFormat},
68         {"wglDescribePixelFormat", (void **) &qwglDescribePixelFormat},
69 //      {"wglGetPixelFormat", (void **) &qwglGetPixelFormat},
70         {"wglSetPixelFormat", (void **) &qwglSetPixelFormat},
71         {"wglSwapBuffers", (void **) &qwglSwapBuffers},
72         {"wglCreateContext", (void **) &qwglCreateContext},
73         {"wglDeleteContext", (void **) &qwglDeleteContext},
74         {"wglGetProcAddress", (void **) &qwglGetProcAddress},
75         {"wglMakeCurrent", (void **) &qwglMakeCurrent},
76         {"wglGetCurrentContext", (void **) &qwglGetCurrentContext},
77         {"wglGetCurrentDC", (void **) &qwglGetCurrentDC},
78         {NULL, NULL}
79 };
80
81 static dllfunction_t wglswapintervalfuncs[] =
82 {
83         {"wglSwapIntervalEXT", (void **) &qwglSwapIntervalEXT},
84         {NULL, NULL}
85 };
86
87 static dllfunction_t wglpixelformatfuncs[] =
88 {
89         {"wglChoosePixelFormatARB", (void **) &qwglChoosePixelFormatARB},
90         {"wglGetPixelFormatAttribivARB", (void **) &qwglGetPixelFormatAttribivARB},
91         {NULL, NULL}
92 };
93
94 static DEVMODE gdevmode, initialdevmode;
95 static qboolean vid_initialized = false;
96 static qboolean vid_wassuspended = false;
97 static qboolean vid_usingmouse = false;
98 static qboolean vid_usinghidecursor = false;
99 static qboolean vid_usingvsync = false;
100 static qboolean vid_usevsync = false;
101 static HICON hIcon;
102
103 // used by cd_win.c and snd_win.c
104 HWND mainwindow;
105
106 static HDC       baseDC;
107 static HGLRC baseRC;
108
109 //HWND WINAPI InitializeWindow (HINSTANCE hInstance, int nCmdShow);
110
111 static qboolean vid_isfullscreen;
112
113 //void VID_MenuDraw (void);
114 //void VID_MenuKey (int key);
115
116 //LONG WINAPI MainWndProc (HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
117 //void AppActivate(BOOL fActive, BOOL minimize);
118 //void ClearAllStates (void);
119 //void VID_UpdateWindowStatus (void);
120
121 //====================================
122
123 static int window_x, window_y;
124
125 static qboolean mouseinitialized;
126
127 #ifdef SUPPORTDIRECTX
128 static qboolean dinput;
129 #define DINPUT_BUFFERSIZE           16
130 #define iDirectInputCreate(a,b,c,d)     pDirectInputCreate(a,b,c,d)
131
132 static HRESULT (WINAPI *pDirectInputCreate)(HINSTANCE hinst, DWORD dwVersion, LPDIRECTINPUT * lplpDirectInput, LPUNKNOWN punkOuter);
133 #endif
134
135 // LordHavoc: thanks to backslash for this support for mouse buttons 4 and 5
136 /* backslash :: imouse explorer buttons */
137 /* These are #ifdefed out for non-Win2K in the February 2001 version of
138    MS's platform SDK, but we need them for compilation. . . */
139 #ifndef WM_XBUTTONDOWN
140    #define WM_XBUTTONDOWN      0x020B
141    #define WM_XBUTTONUP      0x020C
142 #endif
143 #ifndef MK_XBUTTON1
144    #define MK_XBUTTON1         0x0020
145    #define MK_XBUTTON2         0x0040
146 #endif
147 #ifndef MK_XBUTTON3
148 // LordHavoc: lets hope this allows more buttons in the future...
149    #define MK_XBUTTON3         0x0080
150    #define MK_XBUTTON4         0x0100
151    #define MK_XBUTTON5         0x0200
152    #define MK_XBUTTON6         0x0400
153    #define MK_XBUTTON7         0x0800
154 #endif
155 /* :: backslash */
156
157 // mouse variables
158 static int                      mouse_buttons;
159 static int                      mouse_oldbuttonstate;
160
161 static unsigned int uiWheelMessage;
162 #ifdef SUPPORTDIRECTX
163 static qboolean dinput_acquired;
164
165 static unsigned int             mstate_di;
166 #endif
167
168 // joystick defines and variables
169 // where should defines be moved?
170 #define JOY_ABSOLUTE_AXIS       0x00000000              // control like a joystick
171 #define JOY_RELATIVE_AXIS       0x00000010              // control like a mouse, spinner, trackball
172 #define JOY_MAX_AXES            6                               // X, Y, Z, R, U, V
173 #define JOY_AXIS_X                      0
174 #define JOY_AXIS_Y                      1
175 #define JOY_AXIS_Z                      2
176 #define JOY_AXIS_R                      3
177 #define JOY_AXIS_U                      4
178 #define JOY_AXIS_V                      5
179
180 enum _ControlList
181 {
182         AxisNada = 0, AxisForward, AxisLook, AxisSide, AxisTurn
183 };
184
185 static DWORD    dwAxisFlags[JOY_MAX_AXES] =
186 {
187         JOY_RETURNX, JOY_RETURNY, JOY_RETURNZ, JOY_RETURNR, JOY_RETURNU, JOY_RETURNV
188 };
189
190 static DWORD    dwAxisMap[JOY_MAX_AXES];
191 static DWORD    dwControlMap[JOY_MAX_AXES];
192 static PDWORD   pdwRawValue[JOY_MAX_AXES];
193
194 // none of these cvars are saved over a session
195 // this means that advanced controller configuration needs to be executed
196 // each time.  this avoids any problems with getting back to a default usage
197 // or when changing from one controller to another.  this way at least something
198 // works.
199 static cvar_t in_joystick = {CVAR_SAVE, "joystick","0", "enables joysticks"};
200 static cvar_t joy_name = {0, "joyname", "joystick", "name of joystick to use (informational only, used only by joyadvanced 1 mode)"};
201 static cvar_t joy_advanced = {0, "joyadvanced", "0", "use more than 2 axis joysticks (configuring this is very technical)"};
202 static cvar_t joy_advaxisx = {0, "joyadvaxisx", "0", "axis mapping for joyadvanced 1 mode"};
203 static cvar_t joy_advaxisy = {0, "joyadvaxisy", "0", "axis mapping for joyadvanced 1 mode"};
204 static cvar_t joy_advaxisz = {0, "joyadvaxisz", "0", "axis mapping for joyadvanced 1 mode"};
205 static cvar_t joy_advaxisr = {0, "joyadvaxisr", "0", "axis mapping for joyadvanced 1 mode"};
206 static cvar_t joy_advaxisu = {0, "joyadvaxisu", "0", "axis mapping for joyadvanced 1 mode"};
207 static cvar_t joy_advaxisv = {0, "joyadvaxisv", "0", "axis mapping for joyadvanced 1 mode"};
208 static cvar_t joy_forwardthreshold = {0, "joyforwardthreshold", "0.15", "minimum joystick movement necessary to move forward"};
209 static cvar_t joy_sidethreshold = {0, "joysidethreshold", "0.15", "minimum joystick movement necessary to move sideways (strafing)"};
210 static cvar_t joy_pitchthreshold = {0, "joypitchthreshold", "0.15", "minimum joystick movement necessary to look up/down"};
211 static cvar_t joy_yawthreshold = {0, "joyyawthreshold", "0.15", "minimum joystick movement necessary to turn left/right"};
212 static cvar_t joy_forwardsensitivity = {0, "joyforwardsensitivity", "-1.0", "how fast the joystick moves forward"};
213 static cvar_t joy_sidesensitivity = {0, "joysidesensitivity", "-1.0", "how fast the joystick moves sideways (strafing)"};
214 static cvar_t joy_pitchsensitivity = {0, "joypitchsensitivity", "1.0", "how fast the joystick looks up/down"};
215 static cvar_t joy_yawsensitivity = {0, "joyyawsensitivity", "-1.0", "how fast the joystick turns left/right"};
216 static cvar_t joy_wwhack1 = {0, "joywwhack1", "0.0", "special hack for wingman warrior"};
217 static cvar_t joy_wwhack2 = {0, "joywwhack2", "0.0", "special hack for wingman warrior"};
218
219 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"};
220
221 static qboolean joy_avail, joy_advancedinit, joy_haspov;
222 static DWORD            joy_oldbuttonstate, joy_oldpovstate;
223
224 static int                      joy_id;
225 static DWORD            joy_flags;
226 static DWORD            joy_numbuttons;
227
228 #ifdef SUPPORTDIRECTX
229 static LPDIRECTINPUT            g_pdi;
230 static LPDIRECTINPUTDEVICE      g_pMouse;
231 static HINSTANCE hInstDI;
232 #endif
233
234 static JOYINFOEX        ji;
235
236 // forward-referenced functions
237 static void IN_StartupJoystick (void);
238 static void Joy_AdvancedUpdate_f (void);
239 static void IN_JoyMove (void);
240 static void IN_StartupMouse (void);
241
242
243 //====================================
244
245 void VID_Finish (void)
246 {
247         vid_usevsync = vid_vsync.integer && !cls.timedemo && gl_videosyncavailable;
248         if (vid_usingvsync != vid_usevsync && gl_videosyncavailable)
249         {
250                 vid_usingvsync = vid_usevsync;
251                 qwglSwapIntervalEXT (vid_usevsync);
252         }
253
254         if (r_render.integer && !vid_hidden)
255         {
256                 CHECKGLERROR
257                 if (r_speeds.integer == 2 || gl_finish.integer)
258                 {
259                         qglFinish();CHECKGLERROR
260                 }
261                 SwapBuffers(baseDC);
262         }
263
264         // make sure a context switch can happen every frame - Logitech drivers
265         // input drivers sometimes eat cpu time every 3 seconds or lag badly
266         // without this help
267         Sleep(0);
268
269         VID_UpdateGamma(false, 256);
270 }
271
272 //==========================================================================
273
274
275
276
277 static unsigned char scantokey[128] =
278 {
279 //  0           1       2    3     4     5       6       7      8         9      A          B           C       D           E           F
280         0          ,27    ,'1'  ,'2'  ,'3'  ,'4'    ,'5'    ,'6'   ,'7'      ,'8'   ,'9'       ,'0'        ,'-'   ,'='         ,K_BACKSPACE,9    ,//0
281         'q'        ,'w'   ,'e'  ,'r'  ,'t'  ,'y'    ,'u'    ,'i'   ,'o'      ,'p'   ,'['       ,']'        ,13    ,K_CTRL      ,'a'        ,'s'  ,//1
282         'd'        ,'f'   ,'g'  ,'h'  ,'j'  ,'k'    ,'l'    ,';'   ,'\''     ,'`'   ,K_SHIFT   ,'\\'       ,'z'   ,'x'         ,'c'        ,'v'  ,//2
283         'b'        ,'n'   ,'m'  ,','  ,'.'  ,'/'    ,K_SHIFT,'*'   ,K_ALT    ,' '   ,0         ,K_F1       ,K_F2  ,K_F3        ,K_F4       ,K_F5 ,//3
284         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
285         K_DOWNARROW,K_PGDN,K_INS,K_DEL,0    ,0      ,0      ,K_F11 ,K_F12    ,0     ,0         ,0          ,0     ,0           ,0          ,0    ,//5
286         0          ,0     ,0    ,0    ,0    ,0      ,0      ,0     ,0        ,0     ,0         ,0          ,0     ,0           ,0          ,0    ,//6
287         0          ,0     ,0    ,0    ,0    ,0      ,0      ,0     ,0        ,0     ,0         ,0          ,0     ,0           ,0          ,0     //7
288 };
289
290
291 /*
292 =======
293 MapKey
294
295 Map from windows to quake keynums
296 =======
297 */
298 static int MapKey (int key, int virtualkey)
299 {
300         int result;
301         int modified = (key >> 16) & 255;
302         qboolean is_extended = false;
303
304         if (modified < 128 && scantokey[modified])
305                 result = scantokey[modified];
306         else
307         {
308                 result = 0;
309                 Con_DPrintf("key 0x%02x (0x%8x, 0x%8x) has no translation\n", modified, key, virtualkey);
310         }
311
312         if (key & (1 << 24))
313                 is_extended = true;
314
315         if ( !is_extended )
316         {
317                 switch ( result )
318                 {
319                 case K_HOME:
320                         return K_KP_HOME;
321                 case K_UPARROW:
322                         return K_KP_UPARROW;
323                 case K_PGUP:
324                         return K_KP_PGUP;
325                 case K_LEFTARROW:
326                         return K_KP_LEFTARROW;
327                 case K_RIGHTARROW:
328                         return K_KP_RIGHTARROW;
329                 case K_END:
330                         return K_KP_END;
331                 case K_DOWNARROW:
332                         return K_KP_DOWNARROW;
333                 case K_PGDN:
334                         return K_KP_PGDN;
335                 case K_INS:
336                         return K_KP_INS;
337                 case K_DEL:
338                         return K_KP_DEL;
339                 default:
340                         return result;
341                 }
342         }
343         else
344         {
345                 switch ( result )
346                 {
347                 case 0x0D:
348                         return K_KP_ENTER;
349                 case 0x2F:
350                         return K_KP_SLASH;
351                 case 0xAF:
352                         return K_KP_PLUS;
353                 }
354                 return result;
355         }
356 }
357
358 /*
359 ===================================================================
360
361 MAIN WINDOW
362
363 ===================================================================
364 */
365
366 /*
367 ================
368 ClearAllStates
369 ================
370 */
371 static void ClearAllStates (void)
372 {
373         Key_ClearStates ();
374         if (vid_usingmouse)
375                 mouse_oldbuttonstate = 0;
376 }
377
378 void AppActivate(BOOL fActive, BOOL minimize)
379 /****************************************************************************
380 *
381 * Function:     AppActivate
382 * Parameters:   fActive - True if app is activating
383 *
384 * Description:  If the application is activating, then swap the system
385 *               into SYSPAL_NOSTATIC mode so that our palettes will display
386 *               correctly.
387 *
388 ****************************************************************************/
389 {
390         static qboolean sound_active = false;  // initially blocked by Sys_InitConsole()
391
392         vid_activewindow = fActive;
393         vid_hidden = minimize;
394
395         // enable/disable sound on focus gain/loss
396         if ((!vid_hidden && vid_activewindow) || !snd_mutewhenidle.integer)
397         {
398                 if (!sound_active)
399                 {
400                         S_UnblockSound ();
401                         sound_active = true;
402                 }
403         }
404         else
405         {
406                 if (sound_active)
407                 {
408                         S_BlockSound ();
409                         sound_active = false;
410                 }
411         }
412
413         if (fActive)
414         {
415                 if (vid_isfullscreen)
416                 {
417                         if (vid_wassuspended)
418                         {
419                                 vid_wassuspended = false;
420                                 ChangeDisplaySettings (&gdevmode, CDS_FULLSCREEN);
421                                 ShowWindow(mainwindow, SW_SHOWNORMAL);
422                         }
423
424                         // LordHavoc: from dabb, fix for alt-tab bug in NVidia drivers
425                         MoveWindow(mainwindow,0,0,gdevmode.dmPelsWidth,gdevmode.dmPelsHeight,false);
426                 }
427         }
428
429         if (!fActive)
430         {
431                 VID_SetMouse(false, false, false);
432                 if (vid_isfullscreen)
433                 {
434                         ChangeDisplaySettings (NULL, 0);
435                         vid_wassuspended = true;
436                 }
437                 VID_RestoreSystemGamma();
438         }
439 }
440
441 //TODO: move it around in vid_wgl.c since I dont think this is the right position
442 void Sys_SendKeyEvents (void)
443 {
444         MSG msg;
445
446         while (PeekMessage (&msg, NULL, 0, 0, PM_NOREMOVE))
447         {
448                 if (!GetMessage (&msg, NULL, 0, 0))
449                         Sys_Quit (1);
450
451                 TranslateMessage (&msg);
452                 DispatchMessage (&msg);
453         }
454 }
455
456 LONG CDAudio_MessageHandler(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
457
458 static keynum_t buttonremap[16] =
459 {
460         K_MOUSE1,
461         K_MOUSE2,
462         K_MOUSE3,
463         K_MOUSE4,
464         K_MOUSE5,
465         K_MOUSE6,
466         K_MOUSE7,
467         K_MOUSE8,
468         K_MOUSE9,
469         K_MOUSE10,
470         K_MOUSE11,
471         K_MOUSE12,
472         K_MOUSE13,
473         K_MOUSE14,
474         K_MOUSE15,
475         K_MOUSE16,
476 };
477
478 /* main window procedure */
479 LONG WINAPI MainWndProc (HWND hWnd, UINT uMsg, WPARAM  wParam, LPARAM lParam)
480 {
481         LONG    lRet = 1;
482         int             fActive, fMinimized, temp;
483         unsigned char state[256];
484         unsigned char asciichar[4];
485         int             vkey;
486         int             charlength;
487         qboolean down = false;
488
489         if ( uMsg == uiWheelMessage )
490                 uMsg = WM_MOUSEWHEEL;
491
492         switch (uMsg)
493         {
494                 case WM_KILLFOCUS:
495                         if (vid_isfullscreen)
496                                 ShowWindow(mainwindow, SW_SHOWMINNOACTIVE);
497                         break;
498
499                 case WM_CREATE:
500                         break;
501
502                 case WM_MOVE:
503                         window_x = (int) LOWORD(lParam);
504                         window_y = (int) HIWORD(lParam);
505                         VID_SetMouse(false, false, false);
506                         break;
507
508                 case WM_KEYDOWN:
509                 case WM_SYSKEYDOWN:
510                         down = true;
511                 case WM_KEYUP:
512                 case WM_SYSKEYUP:
513                         vkey = MapKey(lParam, wParam);
514                         GetKeyboardState (state);
515                         // alt/ctrl/shift tend to produce funky ToAscii values,
516                         // and if it's not a single character we don't know care about it
517                         charlength = ToAscii (wParam, lParam >> 16, state, (LPWORD)asciichar, 0);
518                         if (vkey == K_ALT || vkey == K_CTRL || vkey == K_SHIFT || charlength == 0)
519                                 asciichar[0] = 0;
520                         else if( charlength == 2 ) {
521                                 asciichar[0] = asciichar[1];
522                         }
523                         Key_Event (vkey, asciichar[0], down);
524                         break;
525
526                 case WM_SYSCHAR:
527                 // keep Alt-Space from happening
528                         break;
529
530                 case WM_SYSCOMMAND:
531                         // prevent screensaver from occuring while the active window
532                         // note: password-locked screensavers on Vista still work
533                         if (vid_activewindow && ((wParam & 0xFFF0) == SC_SCREENSAVE || (wParam & 0xFFF0) == SC_MONITORPOWER))
534                                 lRet = 0;
535                         else
536                                 lRet = DefWindowProc (hWnd, uMsg, wParam, lParam);
537                         break;
538
539         // this is complicated because Win32 seems to pack multiple mouse events into
540         // one update sometimes, so we always check all states and look for events
541                 case WM_LBUTTONDOWN:
542                 case WM_LBUTTONUP:
543                 case WM_RBUTTONDOWN:
544                 case WM_RBUTTONUP:
545                 case WM_MBUTTONDOWN:
546                 case WM_MBUTTONUP:
547                 case WM_XBUTTONDOWN:   // backslash :: imouse explorer buttons
548                 case WM_XBUTTONUP:      // backslash :: imouse explorer buttons
549                 case WM_MOUSEMOVE:
550                         temp = 0;
551
552                         if (wParam & MK_LBUTTON)
553                                 temp |= 1;
554
555                         if (wParam & MK_RBUTTON)
556                                 temp |= 2;
557
558                         if (wParam & MK_MBUTTON)
559                                 temp |= 4;
560
561                         /* backslash :: imouse explorer buttons */
562                         if (wParam & MK_XBUTTON1)
563                                 temp |= 8;
564
565                         if (wParam & MK_XBUTTON2)
566                                 temp |= 16;
567                         /* :: backslash */
568
569                         // LordHavoc: lets hope this allows more buttons in the future...
570                         if (wParam & MK_XBUTTON3)
571                                 temp |= 32;
572                         if (wParam & MK_XBUTTON4)
573                                 temp |= 64;
574                         if (wParam & MK_XBUTTON5)
575                                 temp |= 128;
576                         if (wParam & MK_XBUTTON6)
577                                 temp |= 256;
578                         if (wParam & MK_XBUTTON7)
579                                 temp |= 512;
580
581 #ifdef SUPPORTDIRECTX
582                         if (!dinput_acquired)
583 #endif
584                         {
585                                 // perform button actions
586                                 int i;
587                                 for (i=0 ; i<mouse_buttons && i < 16 ; i++)
588                                         if ((temp ^ mouse_oldbuttonstate) & (1<<i))
589                                                 Key_Event (buttonremap[i], 0, (temp & (1<<i)) != 0);
590                                 mouse_oldbuttonstate = temp;
591                         }
592
593                         break;
594
595                 // JACK: This is the mouse wheel with the Intellimouse
596                 // Its delta is either positive or neg, and we generate the proper
597                 // Event.
598                 case WM_MOUSEWHEEL:
599                         if ((short) HIWORD(wParam) > 0) {
600                                 Key_Event(K_MWHEELUP, 0, true);
601                                 Key_Event(K_MWHEELUP, 0, false);
602                         } else {
603                                 Key_Event(K_MWHEELDOWN, 0, true);
604                                 Key_Event(K_MWHEELDOWN, 0, false);
605                         }
606                         break;
607
608                 case WM_SIZE:
609                         break;
610
611                 case WM_CLOSE:
612                         if (MessageBox (mainwindow, "Are you sure you want to quit?", "Confirm Exit", MB_YESNO | MB_SETFOREGROUND | MB_ICONQUESTION) == IDYES)
613                                 Sys_Quit (0);
614
615                         break;
616
617                 case WM_ACTIVATE:
618                         fActive = LOWORD(wParam);
619                         fMinimized = (BOOL) HIWORD(wParam);
620                         AppActivate(!(fActive == WA_INACTIVE), fMinimized);
621
622                 // fix the leftover Alt from any Alt-Tab or the like that switched us away
623                         ClearAllStates ();
624
625                         break;
626
627                 //case WM_DESTROY:
628                 //      PostQuitMessage (0);
629                 //      break;
630
631                 case MM_MCINOTIFY:
632                         lRet = CDAudio_MessageHandler (hWnd, uMsg, wParam, lParam);
633                         break;
634
635                 default:
636                         /* pass all unhandled messages to DefWindowProc */
637                         lRet = DefWindowProc (hWnd, uMsg, wParam, lParam);
638                 break;
639         }
640
641         /* return 1 if handled message, 0 if not */
642         return lRet;
643 }
644
645 int VID_SetGamma(unsigned short *ramps, int rampsize)
646 {
647         HDC hdc = GetDC (NULL);
648         int i = SetDeviceGammaRamp(hdc, ramps);
649         ReleaseDC (NULL, hdc);
650         return i; // return success or failure
651 }
652
653 int VID_GetGamma(unsigned short *ramps, int rampsize)
654 {
655         HDC hdc = GetDC (NULL);
656         int i = GetDeviceGammaRamp(hdc, ramps);
657         ReleaseDC (NULL, hdc);
658         return i; // return success or failure
659 }
660
661 static HINSTANCE gldll;
662
663 static void GL_CloseLibrary(void)
664 {
665         FreeLibrary(gldll);
666         gldll = 0;
667         gl_driver[0] = 0;
668         qwglGetProcAddress = NULL;
669         gl_extensions = "";
670         gl_platform = "";
671         gl_platformextensions = "";
672 }
673
674 static int GL_OpenLibrary(const char *name)
675 {
676         Con_Printf("Loading OpenGL driver %s\n", name);
677         GL_CloseLibrary();
678         if (!(gldll = LoadLibrary(name)))
679         {
680                 Con_Printf("Unable to LoadLibrary %s\n", name);
681                 return false;
682         }
683         strlcpy(gl_driver, name, sizeof(gl_driver));
684         return true;
685 }
686
687 void *GL_GetProcAddress(const char *name)
688 {
689         void *p = NULL;
690         if (qwglGetProcAddress != NULL)
691                 p = (void *) qwglGetProcAddress(name);
692         if (p == NULL)
693                 p = (void *) GetProcAddress(gldll, name);
694         return p;
695 }
696
697 #ifndef WGL_ARB_pixel_format
698 #define WGL_NUMBER_PIXEL_FORMATS_ARB   0x2000
699 #define WGL_DRAW_TO_WINDOW_ARB         0x2001
700 #define WGL_DRAW_TO_BITMAP_ARB         0x2002
701 #define WGL_ACCELERATION_ARB           0x2003
702 #define WGL_NEED_PALETTE_ARB           0x2004
703 #define WGL_NEED_SYSTEM_PALETTE_ARB    0x2005
704 #define WGL_SWAP_LAYER_BUFFERS_ARB     0x2006
705 #define WGL_SWAP_METHOD_ARB            0x2007
706 #define WGL_NUMBER_OVERLAYS_ARB        0x2008
707 #define WGL_NUMBER_UNDERLAYS_ARB       0x2009
708 #define WGL_TRANSPARENT_ARB            0x200A
709 #define WGL_TRANSPARENT_RED_VALUE_ARB  0x2037
710 #define WGL_TRANSPARENT_GREEN_VALUE_ARB 0x2038
711 #define WGL_TRANSPARENT_BLUE_VALUE_ARB 0x2039
712 #define WGL_TRANSPARENT_ALPHA_VALUE_ARB 0x203A
713 #define WGL_TRANSPARENT_INDEX_VALUE_ARB 0x203B
714 #define WGL_SHARE_DEPTH_ARB            0x200C
715 #define WGL_SHARE_STENCIL_ARB          0x200D
716 #define WGL_SHARE_ACCUM_ARB            0x200E
717 #define WGL_SUPPORT_GDI_ARB            0x200F
718 #define WGL_SUPPORT_OPENGL_ARB         0x2010
719 #define WGL_DOUBLE_BUFFER_ARB          0x2011
720 #define WGL_STEREO_ARB                 0x2012
721 #define WGL_PIXEL_TYPE_ARB             0x2013
722 #define WGL_COLOR_BITS_ARB             0x2014
723 #define WGL_RED_BITS_ARB               0x2015
724 #define WGL_RED_SHIFT_ARB              0x2016
725 #define WGL_GREEN_BITS_ARB             0x2017
726 #define WGL_GREEN_SHIFT_ARB            0x2018
727 #define WGL_BLUE_BITS_ARB              0x2019
728 #define WGL_BLUE_SHIFT_ARB             0x201A
729 #define WGL_ALPHA_BITS_ARB             0x201B
730 #define WGL_ALPHA_SHIFT_ARB            0x201C
731 #define WGL_ACCUM_BITS_ARB             0x201D
732 #define WGL_ACCUM_RED_BITS_ARB         0x201E
733 #define WGL_ACCUM_GREEN_BITS_ARB       0x201F
734 #define WGL_ACCUM_BLUE_BITS_ARB        0x2020
735 #define WGL_ACCUM_ALPHA_BITS_ARB       0x2021
736 #define WGL_DEPTH_BITS_ARB             0x2022
737 #define WGL_STENCIL_BITS_ARB           0x2023
738 #define WGL_AUX_BUFFERS_ARB            0x2024
739 #define WGL_NO_ACCELERATION_ARB        0x2025
740 #define WGL_GENERIC_ACCELERATION_ARB   0x2026
741 #define WGL_FULL_ACCELERATION_ARB      0x2027
742 #define WGL_SWAP_EXCHANGE_ARB          0x2028
743 #define WGL_SWAP_COPY_ARB              0x2029
744 #define WGL_SWAP_UNDEFINED_ARB         0x202A
745 #define WGL_TYPE_RGBA_ARB              0x202B
746 #define WGL_TYPE_COLORINDEX_ARB        0x202C
747 #endif
748
749 #ifndef WGL_ARB_multisample
750 #define WGL_SAMPLE_BUFFERS_ARB         0x2041
751 #define WGL_SAMPLES_ARB                0x2042
752 #endif
753
754
755 static void IN_Init(void);
756 void VID_Init(void)
757 {
758         WNDCLASS wc;
759
760         InitCommonControls();
761         hIcon = LoadIcon (global_hInstance, MAKEINTRESOURCE (IDI_ICON1));
762
763         // Register the frame class
764         wc.style         = 0;
765         wc.lpfnWndProc   = (WNDPROC)MainWndProc;
766         wc.cbClsExtra    = 0;
767         wc.cbWndExtra    = 0;
768         wc.hInstance     = global_hInstance;
769         wc.hIcon         = hIcon;
770         wc.hCursor       = LoadCursor (NULL,IDC_ARROW);
771         wc.hbrBackground = NULL;
772         wc.lpszMenuName  = 0;
773         wc.lpszClassName = "DarkPlacesWindowClass";
774
775         if (!RegisterClass (&wc))
776                 Con_Printf ("Couldn't register window class\n");
777
778         memset(&initialdevmode, 0, sizeof(initialdevmode));
779         EnumDisplaySettings(NULL, ENUM_CURRENT_SETTINGS, &initialdevmode);
780
781         IN_Init();
782 }
783
784 int VID_InitMode (int fullscreen, int *width, int *height, int bpp, int refreshrate, int stereobuffer, int samples)
785 {
786         int i;
787         HDC hdc;
788         RECT rect;
789         MSG msg;
790         PIXELFORMATDESCRIPTOR pfd =
791         {
792                 sizeof(PIXELFORMATDESCRIPTOR),  // size of this pfd
793                 1,                              // version number
794                 PFD_DRAW_TO_WINDOW              // support window
795                 |  PFD_SUPPORT_OPENGL   // support OpenGL
796                 |  PFD_DOUBLEBUFFER ,   // double buffered
797                 PFD_TYPE_RGBA,                  // RGBA type
798                 24,                             // 24-bit color depth
799                 0, 0, 0, 0, 0, 0,               // color bits ignored
800                 0,                              // no alpha buffer
801                 0,                              // shift bit ignored
802                 0,                              // no accumulation buffer
803                 0, 0, 0, 0,                     // accum bits ignored
804                 32,                             // 32-bit z-buffer
805                 0,                              // no stencil buffer
806                 0,                              // no auxiliary buffer
807                 PFD_MAIN_PLANE,                 // main layer
808                 0,                              // reserved
809                 0, 0, 0                         // layer masks ignored
810         };
811         int windowpass;
812         int pixelformat, newpixelformat;
813         UINT numpixelformats;
814         DWORD WindowStyle, ExWindowStyle;
815         int CenterX, CenterY;
816         const char *gldrivername;
817         int depth;
818         DEVMODE thismode;
819         qboolean foundmode, foundgoodmode;
820         int *a;
821         float *af;
822         int attribs[128];
823         float attribsf[16];
824
825         if (vid_initialized)
826                 Sys_Error("VID_InitMode called when video is already initialised");
827
828         // if stencil is enabled, ask for alpha too
829         if (bpp >= 32)
830         {
831                 pfd.cRedBits = 8;
832                 pfd.cGreenBits = 8;
833                 pfd.cBlueBits = 8;
834                 pfd.cAlphaBits = 8;
835                 pfd.cDepthBits = 24;
836                 pfd.cStencilBits = 8;
837         }
838         else
839         {
840                 pfd.cRedBits = 5;
841                 pfd.cGreenBits = 5;
842                 pfd.cBlueBits = 5;
843                 pfd.cAlphaBits = 0;
844                 pfd.cDepthBits = 16;
845                 pfd.cStencilBits = 0;
846         }
847
848         if (stereobuffer)
849                 pfd.dwFlags |= PFD_STEREO;
850
851         a = attribs;
852         af = attribsf;
853         *a++ = WGL_DRAW_TO_WINDOW_ARB;
854         *a++ = GL_TRUE;
855         *a++ = WGL_ACCELERATION_ARB;
856         *a++ = WGL_FULL_ACCELERATION_ARB;
857         *a++ = WGL_DOUBLE_BUFFER_ARB;
858         *a++ = true;
859
860         if (bpp >= 32)
861         {
862                 *a++ = WGL_RED_BITS_ARB;
863                 *a++ = 8;
864                 *a++ = WGL_GREEN_BITS_ARB;
865                 *a++ = 8;
866                 *a++ = WGL_BLUE_BITS_ARB;
867                 *a++ = 8;
868                 *a++ = WGL_ALPHA_BITS_ARB;
869                 *a++ = 8;
870                 *a++ = WGL_DEPTH_BITS_ARB;
871                 *a++ = 24;
872                 *a++ = WGL_STENCIL_BITS_ARB;
873                 *a++ = 8;
874         }
875         else
876         {
877                 *a++ = WGL_RED_BITS_ARB;
878                 *a++ = 1;
879                 *a++ = WGL_GREEN_BITS_ARB;
880                 *a++ = 1;
881                 *a++ = WGL_BLUE_BITS_ARB;
882                 *a++ = 1;
883                 *a++ = WGL_DEPTH_BITS_ARB;
884                 *a++ = 16;
885         }
886
887         if (stereobuffer)
888         {
889                 *a++ = WGL_STEREO_ARB;
890                 *a++ = GL_TRUE;
891         }
892
893         if (samples > 1)
894         {
895                 *a++ = WGL_SAMPLE_BUFFERS_ARB;
896                 *a++ = 1;
897                 *a++ = WGL_SAMPLES_ARB;
898                 *a++ = samples;
899         }
900
901         *a = 0;
902         *af = 0;
903
904         gldrivername = "opengl32.dll";
905 // 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
906         i = COM_CheckParm("-gl_driver");
907         if (i && i < com_argc - 1)
908                 gldrivername = com_argv[i + 1];
909         if (!GL_OpenLibrary(gldrivername))
910         {
911                 Con_Printf("Unable to load GL driver %s\n", gldrivername);
912                 return false;
913         }
914
915         memset(&gdevmode, 0, sizeof(gdevmode));
916
917         vid_isfullscreen = false;
918         if (fullscreen)
919         {
920                 if(vid_forcerefreshrate.integer)
921                 {
922                         foundmode = true;
923                         gdevmode.dmFields = DM_BITSPERPEL | DM_PELSWIDTH | DM_PELSHEIGHT;
924                         gdevmode.dmBitsPerPel = bpp;
925                         gdevmode.dmPelsWidth = *width;
926                         gdevmode.dmPelsHeight = *height;
927                         gdevmode.dmSize = sizeof (gdevmode);
928                         if(refreshrate)
929                         {
930                                 gdevmode.dmFields |= DM_DISPLAYFREQUENCY;
931                                 gdevmode.dmDisplayFrequency = refreshrate;
932                         }
933                 }
934                 else
935                 {
936                         if(refreshrate == 0)
937                                 refreshrate = initialdevmode.dmDisplayFrequency; // default vid_refreshrate to the rate of the desktop
938
939                         foundmode = false;
940                         foundgoodmode = false;
941
942                         thismode.dmSize = sizeof(thismode);
943                         thismode.dmDriverExtra = 0;
944                         for(i = 0; EnumDisplaySettings(NULL, i, &thismode); ++i)
945                         {
946                                 if(~thismode.dmFields & (DM_BITSPERPEL | DM_PELSWIDTH | DM_PELSHEIGHT | DM_DISPLAYFREQUENCY))
947                                 {
948                                         Con_DPrintf("enumerating modes yielded a bogus item... please debug this\n");
949                                         continue;
950                                 }
951                                 if(developer.integer >= 100)
952                                         Con_Printf("Found mode %dx%dx%dbpp %dHz... ", (int)thismode.dmPelsWidth, (int)thismode.dmPelsHeight, (int)thismode.dmBitsPerPel, (int)thismode.dmDisplayFrequency);
953                                 if(thismode.dmBitsPerPel != (DWORD)bpp)
954                                 {
955                                         if(developer.integer >= 100)
956                                                 Con_Printf("wrong bpp\n");
957                                         continue;
958                                 }
959                                 if(thismode.dmPelsWidth != (DWORD)*width)
960                                 {
961                                         if(developer.integer >= 100)
962                                                 Con_Printf("wrong width\n");
963                                         continue;
964                                 }
965                                 if(thismode.dmPelsHeight != (DWORD)*height)
966                                 {
967                                         if(developer.integer >= 100)
968                                                 Con_Printf("wrong height\n");
969                                         continue;
970                                 }
971
972                                 if(foundgoodmode)
973                                 {
974                                         // if we have a good mode, make sure this mode is better than the previous one, and allowed by the refreshrate
975                                         if(thismode.dmDisplayFrequency > (DWORD)refreshrate)
976                                         {
977                                                 if(developer.integer >= 100)
978                                                         Con_Printf("too high refresh rate\n");
979                                                 continue;
980                                         }
981                                         else if(thismode.dmDisplayFrequency <= gdevmode.dmDisplayFrequency)
982                                         {
983                                                 if(developer.integer >= 100)
984                                                         Con_Printf("doesn't beat previous best match (too low)\n");
985                                                 continue;
986                                         }
987                                 }
988                                 else if(foundmode)
989                                 {
990                                         // we do have one, but it isn't good... make sure it has a lower frequency than the previous one
991                                         if(thismode.dmDisplayFrequency >= gdevmode.dmDisplayFrequency)
992                                         {
993                                                 if(developer.integer >= 100)
994                                                         Con_Printf("doesn't beat previous best match (too high)\n");
995                                                 continue;
996                                         }
997                                 }
998                                 // otherwise, take anything
999
1000                                 memcpy(&gdevmode, &thismode, sizeof(gdevmode));
1001                                 if(thismode.dmDisplayFrequency <= (DWORD)refreshrate)
1002                                         foundgoodmode = true;
1003                                 else
1004                                 {
1005                                         if(developer.integer >= 100)
1006                                                 Con_Printf("(out of range)\n");
1007                                 }
1008                                 foundmode = true;
1009                                 if(developer.integer >= 100)
1010                                         Con_Printf("accepted\n");
1011                         }
1012                 }
1013
1014                 if (!foundmode)
1015                 {
1016                         VID_Shutdown();
1017                         Con_Printf("Unable to find the requested mode %dx%dx%dbpp\n", *width, *height, bpp);
1018                         return false;
1019                 }
1020                 else if(ChangeDisplaySettings (&gdevmode, CDS_FULLSCREEN) != DISP_CHANGE_SUCCESSFUL)
1021                 {
1022                         VID_Shutdown();
1023                         Con_Printf("Unable to change to requested mode %dx%dx%dbpp\n", *width, *height, bpp);
1024                         return false;
1025                 }
1026
1027                 vid_isfullscreen = true;
1028                 WindowStyle = WS_POPUP;
1029                 ExWindowStyle = WS_EX_TOPMOST;
1030         }
1031         else
1032         {
1033                 hdc = GetDC (NULL);
1034                 i = GetDeviceCaps(hdc, RASTERCAPS);
1035                 depth = GetDeviceCaps(hdc, PLANES) * GetDeviceCaps(hdc, BITSPIXEL);
1036                 ReleaseDC (NULL, hdc);
1037                 if (i & RC_PALETTE)
1038                 {
1039                         VID_Shutdown();
1040                         Con_Print("Can't run in non-RGB mode\n");
1041                         return false;
1042                 }
1043                 if (bpp > depth)
1044                 {
1045                         VID_Shutdown();
1046                         Con_Print("A higher desktop depth is required to run this video mode\n");
1047                         return false;
1048                 }
1049
1050                 WindowStyle = WS_OVERLAPPED | WS_BORDER | WS_CAPTION | WS_SYSMENU | WS_MINIMIZEBOX;
1051                 ExWindowStyle = 0;
1052         }
1053
1054         rect.top = 0;
1055         rect.left = 0;
1056         rect.right = *width;
1057         rect.bottom = *height;
1058         AdjustWindowRectEx(&rect, WindowStyle, false, 0);
1059
1060         if (fullscreen)
1061         {
1062                 CenterX = 0;
1063                 CenterY = 0;
1064         }
1065         else
1066         {
1067                 CenterX = (GetSystemMetrics(SM_CXSCREEN) - (rect.right - rect.left)) / 2;
1068                 CenterY = (GetSystemMetrics(SM_CYSCREEN) - (rect.bottom - rect.top)) / 2;
1069         }
1070         CenterX = max(0, CenterX);
1071         CenterY = max(0, CenterY);
1072
1073         // x and y may be changed by WM_MOVE messages
1074         window_x = CenterX;
1075         window_y = CenterY;
1076         rect.left += CenterX;
1077         rect.right += CenterX;
1078         rect.top += CenterY;
1079         rect.bottom += CenterY;
1080
1081         pixelformat = 0;
1082         newpixelformat = 0;
1083         // start out at the final windowpass if samples is 1 as it's the only feature we need extended pixel formats for
1084         for (windowpass = samples == 1;windowpass < 2;windowpass++)
1085         {
1086                 gl_extensions = "";
1087                 gl_platformextensions = "";
1088
1089                 mainwindow = CreateWindowEx (ExWindowStyle, "DarkPlacesWindowClass", gamename, WindowStyle, rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top, NULL, NULL, global_hInstance, NULL);
1090                 if (!mainwindow)
1091                 {
1092                         Con_Printf("CreateWindowEx(%d, %s, %s, %d, %d, %d, %d, %d, %p, %p, %d, %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), NULL, NULL, (int)global_hInstance, NULL);
1093                         VID_Shutdown();
1094                         return false;
1095                 }
1096
1097                 baseDC = GetDC(mainwindow);
1098
1099                 if (!newpixelformat)
1100                         newpixelformat = ChoosePixelFormat(baseDC, &pfd);
1101                 pixelformat = newpixelformat;
1102                 if (!pixelformat)
1103                 {
1104                         VID_Shutdown();
1105                         Con_Printf("ChoosePixelFormat(%d, %p) failed\n", (int)baseDC, &pfd);
1106                         return false;
1107                 }
1108
1109                 if (SetPixelFormat(baseDC, pixelformat, &pfd) == false)
1110                 {
1111                         VID_Shutdown();
1112                         Con_Printf("SetPixelFormat(%d, %d, %p) failed\n", (int)baseDC, pixelformat, &pfd);
1113                         return false;
1114                 }
1115
1116                 if (!GL_CheckExtension("wgl", wglfuncs, NULL, false))
1117                 {
1118                         VID_Shutdown();
1119                         Con_Print("wgl functions not found\n");
1120                         return false;
1121                 }
1122
1123                 baseRC = qwglCreateContext(baseDC);
1124                 if (!baseRC)
1125                 {
1126                         VID_Shutdown();
1127                         Con_Print("Could not initialize GL (wglCreateContext failed).\n\nMake sure you are in 65536 color mode, and try running -window.\n");
1128                         return false;
1129                 }
1130                 if (!qwglMakeCurrent(baseDC, baseRC))
1131                 {
1132                         VID_Shutdown();
1133                         Con_Printf("wglMakeCurrent(%d, %d) failed\n", (int)baseDC, (int)baseRC);
1134                         return false;
1135                 }
1136
1137                 if ((qglGetString = (const GLubyte* (GLAPIENTRY *)(GLenum name))GL_GetProcAddress("glGetString")) == NULL)
1138                 {
1139                         VID_Shutdown();
1140                         Con_Print("glGetString not found\n");
1141                         return false;
1142                 }
1143                 if ((qwglGetExtensionsStringARB = (const char *(WINAPI *)(HDC hdc))GL_GetProcAddress("wglGetExtensionsStringARB")) == NULL)
1144                         Con_Print("wglGetExtensionsStringARB not found\n");
1145
1146                 gl_extensions = (const char *)qglGetString(GL_EXTENSIONS);
1147                 gl_platform = "WGL";
1148                 gl_platformextensions = "";
1149
1150                 if (qwglGetExtensionsStringARB)
1151                         gl_platformextensions = (const char *)qwglGetExtensionsStringARB(baseDC);
1152
1153                 if (!gl_extensions)
1154                         gl_extensions = "";
1155                 if (!gl_platformextensions)
1156                         gl_platformextensions = "";
1157
1158                 // now some nice Windows pain:
1159                 // we have created a window, we needed one to find out if there are
1160                 // any multisample pixel formats available, the problem is that to
1161                 // actually use one of those multisample formats we now have to
1162                 // recreate the window (yes Microsoft OpenGL really is that bad)
1163
1164                 if (windowpass == 0)
1165                 {
1166                         if (!GL_CheckExtension("WGL_ARB_pixel_format", wglpixelformatfuncs, "-noarbpixelformat", false) || !qwglChoosePixelFormatARB(baseDC, attribs, attribsf, 1, &newpixelformat, &numpixelformats) || !newpixelformat)
1167                                 break;
1168                         // ok we got one - do it all over again with newpixelformat
1169                         qwglMakeCurrent(NULL, NULL);
1170                         qwglDeleteContext(baseRC);baseRC = 0;
1171                         ReleaseDC(mainwindow, baseDC);baseDC = 0;
1172                         // eat up any messages waiting for us
1173                         while (PeekMessage (&msg, NULL, 0, 0, PM_REMOVE))
1174                         {
1175                                 TranslateMessage (&msg);
1176                                 DispatchMessage (&msg);
1177                         }
1178                 }
1179         }
1180
1181         /*
1182         if (!fullscreen)
1183                 SetWindowPos (mainwindow, NULL, CenterX, CenterY, 0, 0,SWP_NOSIZE | SWP_NOZORDER | SWP_SHOWWINDOW | SWP_DRAWFRAME);
1184         */
1185
1186         ShowWindow (mainwindow, SW_SHOWDEFAULT);
1187         UpdateWindow (mainwindow);
1188
1189         // now we try to make sure we get the focus on the mode switch, because
1190         // sometimes in some systems we don't.  We grab the foreground, then
1191         // finish setting up, pump all our messages, and sleep for a little while
1192         // to let messages finish bouncing around the system, then we put
1193         // ourselves at the top of the z order, then grab the foreground again,
1194         // Who knows if it helps, but it probably doesn't hurt
1195         SetForegroundWindow (mainwindow);
1196
1197         while (PeekMessage (&msg, NULL, 0, 0, PM_REMOVE))
1198         {
1199                 TranslateMessage (&msg);
1200                 DispatchMessage (&msg);
1201         }
1202
1203         Sleep (100);
1204
1205         SetWindowPos (mainwindow, HWND_TOP, 0, 0, 0, 0, SWP_DRAWFRAME | SWP_NOMOVE | SWP_NOSIZE | SWP_SHOWWINDOW | SWP_NOCOPYBITS);
1206
1207         SetForegroundWindow (mainwindow);
1208
1209         // fix the leftover Alt from any Alt-Tab or the like that switched us away
1210         ClearAllStates ();
1211
1212         gl_videosyncavailable = false;
1213
1214 // COMMANDLINEOPTION: Windows WGL: -novideosync disables WGL_EXT_swap_control
1215         gl_videosyncavailable = GL_CheckExtension("WGL_EXT_swap_control", wglswapintervalfuncs, "-novideosync", false);
1216
1217         GL_Init ();
1218
1219         //vid_menudrawfn = VID_MenuDraw;
1220         //vid_menukeyfn = VID_MenuKey;
1221         vid_usingmouse = false;
1222         vid_usinghidecursor = false;
1223         vid_usingvsync = false;
1224         vid_hidden = false;
1225         vid_initialized = true;
1226
1227         IN_StartupMouse ();
1228         IN_StartupJoystick ();
1229
1230         if (gl_videosyncavailable)
1231         {
1232                 vid_usevsync = vid_vsync.integer;
1233                 vid_usingvsync = vid_vsync.integer;
1234                 qwglSwapIntervalEXT (vid_usevsync);
1235         }
1236
1237         return true;
1238 }
1239
1240 static void IN_Shutdown(void);
1241 void VID_Shutdown (void)
1242 {
1243         if(vid_initialized == false)
1244                 return;
1245
1246         VID_SetMouse(false, false, false);
1247         VID_RestoreSystemGamma();
1248
1249         vid_initialized = false;
1250         IN_Shutdown();
1251         if (qwglMakeCurrent)
1252                 qwglMakeCurrent(NULL, NULL);
1253         if (baseRC && qwglDeleteContext)
1254                 qwglDeleteContext(baseRC);
1255         // close the library before we get rid of the window
1256         GL_CloseLibrary();
1257         if (baseDC && mainwindow)
1258                 ReleaseDC(mainwindow, baseDC);
1259         AppActivate(false, false);
1260         if (mainwindow)
1261                 DestroyWindow(mainwindow);
1262         mainwindow = 0;
1263         if (vid_isfullscreen)
1264                 ChangeDisplaySettings (NULL, 0);
1265         vid_isfullscreen = false;
1266 }
1267
1268 void VID_SetMouse(qboolean fullscreengrab, qboolean relative, qboolean hidecursor)
1269 {
1270         static qboolean restore_spi;
1271         static int originalmouseparms[3];
1272
1273         if (!mouseinitialized)
1274                 return;
1275
1276         if (relative)
1277         {
1278                 if (!vid_usingmouse)
1279                 {
1280                         vid_usingmouse = true;
1281                         cl_ignoremousemoves = 2;
1282 #ifdef SUPPORTDIRECTX
1283                         if (dinput && g_pMouse)
1284                         {
1285                                 IDirectInputDevice_Acquire(g_pMouse);
1286                                 dinput_acquired = true;
1287                         }
1288                         else
1289 #endif
1290                         {
1291                                 RECT window_rect;
1292                                 window_rect.left = window_x;
1293                                 window_rect.top = window_y;
1294                                 window_rect.right = window_x + vid.width;
1295                                 window_rect.bottom = window_y + vid.height;
1296
1297                                 // change mouse settings to turn off acceleration
1298 // COMMANDLINEOPTION: Windows GDI Input: -noforcemparms disables setting of mouse parameters (not used with -dinput, windows only)
1299                                 if (!COM_CheckParm ("-noforcemparms") && SystemParametersInfo (SPI_GETMOUSE, 0, originalmouseparms, 0))
1300                                 {
1301                                         int newmouseparms[3];
1302                                         newmouseparms[0] = 0; // threshold to double movement (only if accel level is >= 1)
1303                                         newmouseparms[1] = 0; // threshold to quadruple movement (only if accel level is >= 2)
1304                                         newmouseparms[2] = 0; // maximum level of acceleration (0 = off)
1305                                         restore_spi = SystemParametersInfo (SPI_SETMOUSE, 0, newmouseparms, 0);
1306                                 }
1307                                 else
1308                                         restore_spi = false;
1309                                 SetCursorPos ((window_x + vid.width / 2), (window_y + vid.height / 2));
1310
1311                                 SetCapture (mainwindow);
1312                                 ClipCursor (&window_rect);
1313                         }
1314                 }
1315         }
1316         else
1317         {
1318                 if (vid_usingmouse)
1319                 {
1320                         vid_usingmouse = false;
1321                         cl_ignoremousemoves = 2;
1322 #ifdef SUPPORTDIRECTX
1323                         if (dinput_acquired)
1324                         {
1325                                 IDirectInputDevice_Unacquire(g_pMouse);
1326                                 dinput_acquired = false;
1327                         }
1328                         else
1329 #endif
1330                         {
1331                                 // restore system mouseparms if we changed them
1332                                 if (restore_spi)
1333                                         SystemParametersInfo (SPI_SETMOUSE, 0, originalmouseparms, 0);
1334                                 restore_spi = false;
1335                                 ClipCursor (NULL);
1336                                 ReleaseCapture ();
1337                         }
1338                 }
1339         }
1340
1341         if (vid_usinghidecursor != hidecursor)
1342         {
1343                 vid_usinghidecursor = hidecursor;
1344                 ShowCursor (!hidecursor);
1345         }
1346 }
1347
1348
1349 #ifdef SUPPORTDIRECTX
1350 /*
1351 ===========
1352 IN_InitDInput
1353 ===========
1354 */
1355 static qboolean IN_InitDInput (void)
1356 {
1357     HRESULT             hr;
1358         DIPROPDWORD     dipdw = {
1359                 {
1360                         sizeof(DIPROPDWORD),        // diph.dwSize
1361                         sizeof(DIPROPHEADER),       // diph.dwHeaderSize
1362                         0,                          // diph.dwObj
1363                         DIPH_DEVICE,                // diph.dwHow
1364                 },
1365                 DINPUT_BUFFERSIZE,              // dwData
1366         };
1367
1368         if (!hInstDI)
1369         {
1370                 hInstDI = LoadLibrary("dinput.dll");
1371
1372                 if (hInstDI == NULL)
1373                 {
1374                         Con_Print("Couldn't load dinput.dll\n");
1375                         return false;
1376                 }
1377         }
1378
1379         if (!pDirectInputCreate)
1380         {
1381                 pDirectInputCreate = (void *)GetProcAddress(hInstDI,"DirectInputCreateA");
1382
1383                 if (!pDirectInputCreate)
1384                 {
1385                         Con_Print("Couldn't get DI proc addr\n");
1386                         return false;
1387                 }
1388         }
1389
1390 // register with DirectInput and get an IDirectInput to play with.
1391         hr = iDirectInputCreate(global_hInstance, DIRECTINPUT_VERSION, &g_pdi, NULL);
1392
1393         if (FAILED(hr))
1394         {
1395                 return false;
1396         }
1397
1398 // obtain an interface to the system mouse device.
1399         hr = IDirectInput_CreateDevice(g_pdi, &GUID_SysMouse, &g_pMouse, NULL);
1400
1401         if (FAILED(hr))
1402         {
1403                 Con_Print("Couldn't open DI mouse device\n");
1404                 return false;
1405         }
1406
1407 // set the data format to "mouse format".
1408         hr = IDirectInputDevice_SetDataFormat(g_pMouse, &c_dfDIMouse);
1409
1410         if (FAILED(hr))
1411         {
1412                 Con_Print("Couldn't set DI mouse format\n");
1413                 return false;
1414         }
1415
1416 // set the cooperativity level.
1417         hr = IDirectInputDevice_SetCooperativeLevel(g_pMouse, mainwindow,
1418                         DISCL_EXCLUSIVE | DISCL_FOREGROUND);
1419
1420         if (FAILED(hr))
1421         {
1422                 Con_Print("Couldn't set DI coop level\n");
1423                 return false;
1424         }
1425
1426
1427 // set the buffer size to DINPUT_BUFFERSIZE elements.
1428 // the buffer size is a DWORD property associated with the device
1429         hr = IDirectInputDevice_SetProperty(g_pMouse, DIPROP_BUFFERSIZE, &dipdw.diph);
1430
1431         if (FAILED(hr))
1432         {
1433                 Con_Print("Couldn't set DI buffersize\n");
1434                 return false;
1435         }
1436
1437         return true;
1438 }
1439 #endif
1440
1441
1442 /*
1443 ===========
1444 IN_StartupMouse
1445 ===========
1446 */
1447 static void IN_StartupMouse (void)
1448 {
1449         if (COM_CheckParm ("-nomouse"))
1450                 return;
1451
1452         mouseinitialized = true;
1453
1454 #ifdef SUPPORTDIRECTX
1455 // COMMANDLINEOPTION: Windows Input: -dinput enables DirectInput for mouse/joystick input
1456         if (COM_CheckParm ("-dinput"))
1457                 dinput = IN_InitDInput ();
1458
1459         if (dinput)
1460                 Con_Print("DirectInput initialized\n");
1461         else
1462                 Con_Print("DirectInput not initialized\n");
1463 #endif
1464
1465         mouse_buttons = 10;
1466 }
1467
1468
1469 /*
1470 ===========
1471 IN_MouseMove
1472 ===========
1473 */
1474 static void IN_MouseMove (void)
1475 {
1476         POINT current_pos;
1477
1478         GetCursorPos (&current_pos);
1479         in_windowmouse_x = current_pos.x - window_x;
1480         in_windowmouse_y = current_pos.y - window_y;
1481
1482         if (!vid_usingmouse)
1483                 return;
1484
1485 #ifdef SUPPORTDIRECTX
1486         if (dinput_acquired)
1487         {
1488                 int i;
1489                 DIDEVICEOBJECTDATA      od;
1490                 DWORD                           dwElements;
1491                 HRESULT                         hr;
1492
1493                 for (;;)
1494                 {
1495                         dwElements = 1;
1496
1497                         hr = IDirectInputDevice_GetDeviceData(g_pMouse,
1498                                         sizeof(DIDEVICEOBJECTDATA), &od, &dwElements, 0);
1499
1500                         if ((hr == DIERR_INPUTLOST) || (hr == DIERR_NOTACQUIRED))
1501                         {
1502                                 IDirectInputDevice_Acquire(g_pMouse);
1503                                 break;
1504                         }
1505
1506                         /* Unable to read data or no data available */
1507                         if (FAILED(hr) || dwElements == 0)
1508                                 break;
1509
1510                         /* Look at the element to see what happened */
1511
1512                         switch (od.dwOfs)
1513                         {
1514                                 case DIMOFS_X:
1515                                         in_mouse_x += (LONG) od.dwData;
1516                                         break;
1517
1518                                 case DIMOFS_Y:
1519                                         in_mouse_y += (LONG) od.dwData;
1520                                         break;
1521
1522                                 case DIMOFS_Z:
1523                                         if((LONG) od.dwData < 0)
1524                                         {
1525                                                 Key_Event (K_MWHEELDOWN, 0, true);
1526                                                 Key_Event (K_MWHEELDOWN, 0, false);
1527                                         }
1528                                         else if((LONG) od.dwData > 0)
1529                                         {
1530                                                 Key_Event (K_MWHEELUP, 0, true);
1531                                                 Key_Event (K_MWHEELUP, 0, false);
1532                                         }
1533                                         break;
1534
1535                                 case DIMOFS_BUTTON0:
1536                                         if (od.dwData & 0x80)
1537                                                 mstate_di |= 1;
1538                                         else
1539                                                 mstate_di &= ~1;
1540                                         break;
1541
1542                                 case DIMOFS_BUTTON1:
1543                                         if (od.dwData & 0x80)
1544                                                 mstate_di |= (1<<1);
1545                                         else
1546                                                 mstate_di &= ~(1<<1);
1547                                         break;
1548
1549                                 case DIMOFS_BUTTON2:
1550                                         if (od.dwData & 0x80)
1551                                                 mstate_di |= (1<<2);
1552                                         else
1553                                                 mstate_di &= ~(1<<2);
1554                                         break;
1555
1556                                 case DIMOFS_BUTTON3:
1557                                         if (od.dwData & 0x80)
1558                                                 mstate_di |= (1<<3);
1559                                         else
1560                                                 mstate_di &= ~(1<<3);
1561                                         break;
1562                         }
1563                 }
1564
1565                 // perform button actions
1566                 for (i=0 ; i<mouse_buttons && i < 16 ; i++)
1567                         if ((mstate_di ^ mouse_oldbuttonstate) & (1<<i))
1568                                 Key_Event (buttonremap[i], 0, (mstate_di & (1<<i)) != 0);
1569                 mouse_oldbuttonstate = mstate_di;
1570         }
1571         else
1572 #endif
1573         {
1574                 in_mouse_x += in_windowmouse_x - (int)(vid.width / 2);
1575                 in_mouse_y += in_windowmouse_y - (int)(vid.height / 2);
1576
1577                 // if the mouse has moved, force it to the center, so there's room to move
1578                 if (in_mouse_x || in_mouse_y)
1579                         SetCursorPos ((window_x + vid.width / 2), (window_y + vid.height / 2));
1580         }
1581 }
1582
1583
1584 /*
1585 ===========
1586 IN_Move
1587 ===========
1588 */
1589 void IN_Move (void)
1590 {
1591         if (vid_activewindow && !vid_hidden)
1592         {
1593                 IN_MouseMove ();
1594                 IN_JoyMove ();
1595         }
1596 }
1597
1598
1599 /*
1600 ===============
1601 IN_StartupJoystick
1602 ===============
1603 */
1604 static void IN_StartupJoystick (void)
1605 {
1606         int                     numdevs;
1607         JOYCAPS         jc;
1608         MMRESULT        mmr;
1609         mmr = 0;
1610
1611         // assume no joystick
1612         joy_avail = false;
1613
1614         // abort startup if user requests no joystick
1615 // COMMANDLINEOPTION: Windows Input: -nojoy disables joystick support, may be a small speed increase
1616         if (COM_CheckParm ("-nojoy"))
1617                 return;
1618
1619         // verify joystick driver is present
1620         if ((numdevs = joyGetNumDevs ()) == 0)
1621         {
1622                 Con_Print("\njoystick not found -- driver not present\n\n");
1623                 return;
1624         }
1625
1626         // cycle through the joystick ids for the first valid one
1627         for (joy_id=0 ; joy_id<numdevs ; joy_id++)
1628         {
1629                 memset (&ji, 0, sizeof(ji));
1630                 ji.dwSize = sizeof(ji);
1631                 ji.dwFlags = JOY_RETURNCENTERED;
1632
1633                 if ((mmr = joyGetPosEx (joy_id, &ji)) == JOYERR_NOERROR)
1634                         break;
1635         }
1636
1637         // abort startup if we didn't find a valid joystick
1638         if (mmr != JOYERR_NOERROR)
1639         {
1640                 Con_Printf("\njoystick not found -- no valid joysticks (%x)\n\n", mmr);
1641                 return;
1642         }
1643
1644         // get the capabilities of the selected joystick
1645         // abort startup if command fails
1646         memset (&jc, 0, sizeof(jc));
1647         if ((mmr = joyGetDevCaps (joy_id, &jc, sizeof(jc))) != JOYERR_NOERROR)
1648         {
1649                 Con_Printf("\njoystick not found -- invalid joystick capabilities (%x)\n\n", mmr);
1650                 return;
1651         }
1652
1653         // save the joystick's number of buttons and POV status
1654         joy_numbuttons = jc.wNumButtons;
1655         joy_haspov = jc.wCaps & JOYCAPS_HASPOV;
1656
1657         // old button and POV states default to no buttons pressed
1658         joy_oldbuttonstate = joy_oldpovstate = 0;
1659
1660         // mark the joystick as available and advanced initialization not completed
1661         // this is needed as cvars are not available during initialization
1662
1663         joy_avail = true;
1664         joy_advancedinit = false;
1665
1666         Con_Print("\njoystick detected\n\n");
1667 }
1668
1669
1670 /*
1671 ===========
1672 RawValuePointer
1673 ===========
1674 */
1675 static PDWORD RawValuePointer (int axis)
1676 {
1677         switch (axis)
1678         {
1679         case JOY_AXIS_X:
1680                 return &ji.dwXpos;
1681         case JOY_AXIS_Y:
1682                 return &ji.dwYpos;
1683         case JOY_AXIS_Z:
1684                 return &ji.dwZpos;
1685         case JOY_AXIS_R:
1686                 return &ji.dwRpos;
1687         case JOY_AXIS_U:
1688                 return &ji.dwUpos;
1689         case JOY_AXIS_V:
1690                 return &ji.dwVpos;
1691         }
1692         return NULL; // LordHavoc: hush compiler warning
1693 }
1694
1695
1696 /*
1697 ===========
1698 Joy_AdvancedUpdate_f
1699 ===========
1700 */
1701 static void Joy_AdvancedUpdate_f (void)
1702 {
1703
1704         // called once by IN_ReadJoystick and by user whenever an update is needed
1705         // cvars are now available
1706         int     i;
1707         DWORD dwTemp;
1708
1709         // initialize all the maps
1710         for (i = 0; i < JOY_MAX_AXES; i++)
1711         {
1712                 dwAxisMap[i] = AxisNada;
1713                 dwControlMap[i] = JOY_ABSOLUTE_AXIS;
1714                 pdwRawValue[i] = RawValuePointer(i);
1715         }
1716
1717         if( joy_advanced.integer == 0)
1718         {
1719                 // default joystick initialization
1720                 // 2 axes only with joystick control
1721                 dwAxisMap[JOY_AXIS_X] = AxisTurn;
1722                 // dwControlMap[JOY_AXIS_X] = JOY_ABSOLUTE_AXIS;
1723                 dwAxisMap[JOY_AXIS_Y] = AxisForward;
1724                 // dwControlMap[JOY_AXIS_Y] = JOY_ABSOLUTE_AXIS;
1725         }
1726         else
1727         {
1728                 if (strcmp (joy_name.string, "joystick") != 0)
1729                 {
1730                         // notify user of advanced controller
1731                         Con_Printf("\n%s configured\n\n", joy_name.string);
1732                 }
1733
1734                 // advanced initialization here
1735                 // data supplied by user via joy_axisn cvars
1736                 dwTemp = (DWORD) joy_advaxisx.value;
1737                 dwAxisMap[JOY_AXIS_X] = dwTemp & 0x0000000f;
1738                 dwControlMap[JOY_AXIS_X] = dwTemp & JOY_RELATIVE_AXIS;
1739                 dwTemp = (DWORD) joy_advaxisy.value;
1740                 dwAxisMap[JOY_AXIS_Y] = dwTemp & 0x0000000f;
1741                 dwControlMap[JOY_AXIS_Y] = dwTemp & JOY_RELATIVE_AXIS;
1742                 dwTemp = (DWORD) joy_advaxisz.value;
1743                 dwAxisMap[JOY_AXIS_Z] = dwTemp & 0x0000000f;
1744                 dwControlMap[JOY_AXIS_Z] = dwTemp & JOY_RELATIVE_AXIS;
1745                 dwTemp = (DWORD) joy_advaxisr.value;
1746                 dwAxisMap[JOY_AXIS_R] = dwTemp & 0x0000000f;
1747                 dwControlMap[JOY_AXIS_R] = dwTemp & JOY_RELATIVE_AXIS;
1748                 dwTemp = (DWORD) joy_advaxisu.value;
1749                 dwAxisMap[JOY_AXIS_U] = dwTemp & 0x0000000f;
1750                 dwControlMap[JOY_AXIS_U] = dwTemp & JOY_RELATIVE_AXIS;
1751                 dwTemp = (DWORD) joy_advaxisv.value;
1752                 dwAxisMap[JOY_AXIS_V] = dwTemp & 0x0000000f;
1753                 dwControlMap[JOY_AXIS_V] = dwTemp & JOY_RELATIVE_AXIS;
1754         }
1755
1756         // compute the axes to collect from DirectInput
1757         joy_flags = JOY_RETURNCENTERED | JOY_RETURNBUTTONS | JOY_RETURNPOV;
1758         for (i = 0; i < JOY_MAX_AXES; i++)
1759         {
1760                 if (dwAxisMap[i] != AxisNada)
1761                 {
1762                         joy_flags |= dwAxisFlags[i];
1763                 }
1764         }
1765 }
1766
1767 /*
1768 ===============
1769 IN_ReadJoystick
1770 ===============
1771 */
1772 static qboolean IN_ReadJoystick (void)
1773 {
1774
1775         memset (&ji, 0, sizeof(ji));
1776         ji.dwSize = sizeof(ji);
1777         ji.dwFlags = joy_flags;
1778
1779         if (joyGetPosEx (joy_id, &ji) == JOYERR_NOERROR)
1780         {
1781                 // this is a hack -- there is a bug in the Logitech WingMan Warrior DirectInput Driver
1782                 // rather than having 32768 be the zero point, they have the zero point at 32668
1783                 // go figure -- anyway, now we get the full resolution out of the device
1784                 if (joy_wwhack1.integer != 0.0)
1785                 {
1786                         ji.dwUpos += 100;
1787                 }
1788                 return true;
1789         }
1790         else
1791         {
1792                 // read error occurred
1793                 // turning off the joystick seems too harsh for 1 read error,
1794                 // but what should be done?
1795                 return false;
1796         }
1797 }
1798
1799
1800 /*
1801 ===========
1802 IN_JoyMove
1803 ===========
1804 */
1805 static void IN_JoyMove (void)
1806 {
1807         float   speed, aspeed;
1808         float   fAxisValue, fTemp;
1809         int             i, mouselook = (in_mlook.state & 1) || freelook.integer;
1810
1811         // complete initialization if first time in
1812         // this is needed as cvars are not available at initialization time
1813         if( joy_advancedinit != true )
1814         {
1815                 Joy_AdvancedUpdate_f();
1816                 joy_advancedinit = true;
1817         }
1818
1819         if (joy_avail)
1820         {
1821                 int             i, key_index;
1822                 DWORD   buttonstate, povstate;
1823
1824                 // loop through the joystick buttons
1825                 // key a joystick event or auxillary event for higher number buttons for each state change
1826                 buttonstate = ji.dwButtons;
1827                 for (i=0 ; i < (int) joy_numbuttons ; i++)
1828                 {
1829                         if ( (buttonstate & (1<<i)) && !(joy_oldbuttonstate & (1<<i)) )
1830                         {
1831                                 key_index = (i < 16) ? K_JOY1 : K_AUX1;
1832                                 Key_Event (key_index + i, 0, true);
1833                         }
1834
1835                         if ( !(buttonstate & (1<<i)) && (joy_oldbuttonstate & (1<<i)) )
1836                         {
1837                                 key_index = (i < 16) ? K_JOY1 : K_AUX1;
1838                                 Key_Event (key_index + i, 0, false);
1839                         }
1840                 }
1841                 joy_oldbuttonstate = buttonstate;
1842
1843                 if (joy_haspov)
1844                 {
1845                         // convert POV information into 4 bits of state information
1846                         // this avoids any potential problems related to moving from one
1847                         // direction to another without going through the center position
1848                         povstate = 0;
1849                         if(ji.dwPOV != JOY_POVCENTERED)
1850                         {
1851                                 if (ji.dwPOV == JOY_POVFORWARD)
1852                                         povstate |= 0x01;
1853                                 if (ji.dwPOV == JOY_POVRIGHT)
1854                                         povstate |= 0x02;
1855                                 if (ji.dwPOV == JOY_POVBACKWARD)
1856                                         povstate |= 0x04;
1857                                 if (ji.dwPOV == JOY_POVLEFT)
1858                                         povstate |= 0x08;
1859                         }
1860                         // determine which bits have changed and key an auxillary event for each change
1861                         for (i=0 ; i < 4 ; i++)
1862                         {
1863                                 if ( (povstate & (1<<i)) && !(joy_oldpovstate & (1<<i)) )
1864                                 {
1865                                         Key_Event (K_AUX29 + i, 0, true);
1866                                 }
1867
1868                                 if ( !(povstate & (1<<i)) && (joy_oldpovstate & (1<<i)) )
1869                                 {
1870                                         Key_Event (K_AUX29 + i, 0, false);
1871                                 }
1872                         }
1873                         joy_oldpovstate = povstate;
1874                 }
1875         }
1876
1877         // verify joystick is available and that the user wants to use it
1878         if (!joy_avail || !in_joystick.integer)
1879         {
1880                 return;
1881         }
1882
1883         // collect the joystick data, if possible
1884         if (IN_ReadJoystick () != true)
1885         {
1886                 return;
1887         }
1888
1889         if (in_speed.state & 1)
1890                 speed = cl_movespeedkey.value;
1891         else
1892                 speed = 1;
1893         // LordHavoc: viewzoom affects sensitivity for sniping
1894         aspeed = speed * cl.realframetime * cl.viewzoom;
1895
1896         // loop through the axes
1897         for (i = 0; i < JOY_MAX_AXES; i++)
1898         {
1899                 // get the floating point zero-centered, potentially-inverted data for the current axis
1900                 fAxisValue = (float) *pdwRawValue[i];
1901                 // move centerpoint to zero
1902                 fAxisValue -= 32768.0;
1903
1904                 if (joy_wwhack2.integer != 0.0)
1905                 {
1906                         if (dwAxisMap[i] == AxisTurn)
1907                         {
1908                                 // this is a special formula for the Logitech WingMan Warrior
1909                                 // y=ax^b; where a = 300 and b = 1.3
1910                                 // also x values are in increments of 800 (so this is factored out)
1911                                 // then bounds check result to level out excessively high spin rates
1912                                 fTemp = 300.0 * pow(abs(fAxisValue) / 800.0, 1.3);
1913                                 if (fTemp > 14000.0)
1914                                         fTemp = 14000.0;
1915                                 // restore direction information
1916                                 fAxisValue = (fAxisValue > 0.0) ? fTemp : -fTemp;
1917                         }
1918                 }
1919
1920                 // convert range from -32768..32767 to -1..1
1921                 fAxisValue /= 32768.0;
1922
1923                 switch (dwAxisMap[i])
1924                 {
1925                 case AxisForward:
1926                         if ((joy_advanced.integer == 0) && mouselook)
1927                         {
1928                                 // user wants forward control to become look control
1929                                 if (fabs(fAxisValue) > joy_pitchthreshold.value)
1930                                 {
1931                                         // if mouse invert is on, invert the joystick pitch value
1932                                         // only absolute control support here (joy_advanced is false)
1933                                         if (m_pitch.value < 0.0)
1934                                         {
1935                                                 cl.viewangles[PITCH] -= (fAxisValue * joy_pitchsensitivity.value) * aspeed * cl_pitchspeed.value;
1936                                         }
1937                                         else
1938                                         {
1939                                                 cl.viewangles[PITCH] += (fAxisValue * joy_pitchsensitivity.value) * aspeed * cl_pitchspeed.value;
1940                                         }
1941                                         V_StopPitchDrift();
1942                                 }
1943                                 else
1944                                 {
1945                                         // no pitch movement
1946                                         // disable pitch return-to-center unless requested by user
1947                                         // *** this code can be removed when the lookspring bug is fixed
1948                                         // *** the bug always has the lookspring feature on
1949                                         if(lookspring.value == 0.0)
1950                                                 V_StopPitchDrift();
1951                                 }
1952                         }
1953                         else
1954                         {
1955                                 // user wants forward control to be forward control
1956                                 if (fabs(fAxisValue) > joy_forwardthreshold.value)
1957                                 {
1958                                         cl.cmd.forwardmove += (fAxisValue * joy_forwardsensitivity.value) * speed * cl_forwardspeed.value;
1959                                 }
1960                         }
1961                         break;
1962
1963                 case AxisSide:
1964                         if (fabs(fAxisValue) > joy_sidethreshold.value)
1965                         {
1966                                 cl.cmd.sidemove += (fAxisValue * joy_sidesensitivity.value) * speed * cl_sidespeed.value;
1967                         }
1968                         break;
1969
1970                 case AxisTurn:
1971                         if ((in_strafe.state & 1) || (lookstrafe.integer && mouselook))
1972                         {
1973                                 // user wants turn control to become side control
1974                                 if (fabs(fAxisValue) > joy_sidethreshold.value)
1975                                 {
1976                                         cl.cmd.sidemove -= (fAxisValue * joy_sidesensitivity.value) * speed * cl_sidespeed.value;
1977                                 }
1978                         }
1979                         else
1980                         {
1981                                 // user wants turn control to be turn control
1982                                 if (fabs(fAxisValue) > joy_yawthreshold.value)
1983                                 {
1984                                         if(dwControlMap[i] == JOY_ABSOLUTE_AXIS)
1985                                         {
1986                                                 cl.viewangles[YAW] += (fAxisValue * joy_yawsensitivity.value) * aspeed * cl_yawspeed.value;
1987                                         }
1988                                         else
1989                                         {
1990                                                 cl.viewangles[YAW] += (fAxisValue * joy_yawsensitivity.value) * speed * 180.0;
1991                                         }
1992
1993                                 }
1994                         }
1995                         break;
1996
1997                 case AxisLook:
1998                         if (mouselook)
1999                         {
2000                                 if (fabs(fAxisValue) > joy_pitchthreshold.value)
2001                                 {
2002                                         // pitch movement detected and pitch movement desired by user
2003                                         if(dwControlMap[i] == JOY_ABSOLUTE_AXIS)
2004                                         {
2005                                                 cl.viewangles[PITCH] += (fAxisValue * joy_pitchsensitivity.value) * aspeed * cl_pitchspeed.value;
2006                                         }
2007                                         else
2008                                         {
2009                                                 cl.viewangles[PITCH] += (fAxisValue * joy_pitchsensitivity.value) * speed * 180.0;
2010                                         }
2011                                         V_StopPitchDrift();
2012                                 }
2013                                 else
2014                                 {
2015                                         // no pitch movement
2016                                         // disable pitch return-to-center unless requested by user
2017                                         // *** this code can be removed when the lookspring bug is fixed
2018                                         // *** the bug always has the lookspring feature on
2019                                         if(lookspring.integer == 0)
2020                                                 V_StopPitchDrift();
2021                                 }
2022                         }
2023                         break;
2024
2025                 default:
2026                         break;
2027                 }
2028         }
2029 }
2030
2031 static void IN_Init(void)
2032 {
2033         uiWheelMessage = RegisterWindowMessage ( "MSWHEEL_ROLLMSG" );
2034
2035         // joystick variables
2036         Cvar_RegisterVariable (&in_joystick);
2037         Cvar_RegisterVariable (&joy_name);
2038         Cvar_RegisterVariable (&joy_advanced);
2039         Cvar_RegisterVariable (&joy_advaxisx);
2040         Cvar_RegisterVariable (&joy_advaxisy);
2041         Cvar_RegisterVariable (&joy_advaxisz);
2042         Cvar_RegisterVariable (&joy_advaxisr);
2043         Cvar_RegisterVariable (&joy_advaxisu);
2044         Cvar_RegisterVariable (&joy_advaxisv);
2045         Cvar_RegisterVariable (&joy_forwardthreshold);
2046         Cvar_RegisterVariable (&joy_sidethreshold);
2047         Cvar_RegisterVariable (&joy_pitchthreshold);
2048         Cvar_RegisterVariable (&joy_yawthreshold);
2049         Cvar_RegisterVariable (&joy_forwardsensitivity);
2050         Cvar_RegisterVariable (&joy_sidesensitivity);
2051         Cvar_RegisterVariable (&joy_pitchsensitivity);
2052         Cvar_RegisterVariable (&joy_yawsensitivity);
2053         Cvar_RegisterVariable (&joy_wwhack1);
2054         Cvar_RegisterVariable (&joy_wwhack2);
2055         Cvar_RegisterVariable (&vid_forcerefreshrate);
2056         Cmd_AddCommand ("joyadvancedupdate", Joy_AdvancedUpdate_f, "applies current joyadv* cvar settings to the joystick driver");
2057 }
2058
2059 static void IN_Shutdown(void)
2060 {
2061 #ifdef SUPPORTDIRECTX
2062         if (g_pMouse)
2063                 IDirectInputDevice_Release(g_pMouse);
2064         g_pMouse = NULL;
2065
2066         if (g_pdi)
2067                 IDirectInput_Release(g_pdi);
2068         g_pdi = NULL;
2069 #endif
2070 }
2071
2072 size_t VID_ListModes(vid_mode_t *modes, size_t maxcount)
2073 {
2074         int i;
2075         size_t k;
2076         DEVMODE thismode;
2077
2078         thismode.dmSize = sizeof(thismode);
2079         thismode.dmDriverExtra = 0;
2080         k = 0;
2081         for(i = 0; EnumDisplaySettings(NULL, i, &thismode); ++i)
2082         {
2083                 if(~thismode.dmFields & (DM_BITSPERPEL | DM_PELSWIDTH | DM_PELSHEIGHT | DM_DISPLAYFREQUENCY))
2084                 {
2085                         Con_DPrintf("enumerating modes yielded a bogus item... please debug this\n");
2086                         continue;
2087                 }
2088                 if(k >= maxcount)
2089                         break;
2090                 modes[k].width = thismode.dmPelsWidth;
2091                 modes[k].height = thismode.dmPelsHeight;
2092                 modes[k].bpp = thismode.dmBitsPerPel;
2093                 modes[k].refreshrate = thismode.dmDisplayFrequency;
2094                 modes[k].pixelheight_num = 1;
2095                 modes[k].pixelheight_denom = 1; // Win32 apparently does not provide this (FIXME)
2096                 ++k;
2097         }
2098         return k;
2099 }