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