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