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