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