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