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