added in_pitch_min and in_pitch_max cvars to limit pitch (default: -90 to +90)
[divverent/darkplaces.git] / in_win.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 // in_win.c -- windows 95 mouse and joystick code
21 // 02/21/97 JCB Added extended DirectInput code to support external controllers.
22
23 #include "quakedef.h"
24 #include "winquake.h"
25 //#include "dosisms.h"
26
27 #include <dinput.h>
28
29 #define DINPUT_BUFFERSIZE           16
30 #define iDirectInputCreate(a,b,c,d)     pDirectInputCreate(a,b,c,d)
31
32 HRESULT (WINAPI *pDirectInputCreate)(HINSTANCE hinst, DWORD dwVersion,
33         LPDIRECTINPUT * lplpDirectInput, LPUNKNOWN punkOuter);
34
35 // mouse variables
36 cvar_t  m_filter = {CVAR_SAVE, "m_filter","0"};
37
38 int                     mouse_buttons;
39 int                     mouse_oldbuttonstate;
40 POINT           current_pos;
41 int                     mouse_x, mouse_y, old_mouse_x, old_mouse_y, mx_accum, my_accum;
42
43 static qboolean restore_spi;
44 static int              originalmouseparms[3], newmouseparms[3] = {0, 0, 1};
45
46 unsigned int uiWheelMessage;
47 qboolean        mouseactive;
48 qboolean                mouseinitialized;
49 static qboolean mouseparmsvalid, mouseactivatetoggle;
50 static qboolean mouseshowtoggle = 1;
51 static qboolean dinput_acquired;
52
53 static unsigned int             mstate_di;
54
55 // joystick defines and variables
56 // where should defines be moved?
57 #define JOY_ABSOLUTE_AXIS       0x00000000              // control like a joystick
58 #define JOY_RELATIVE_AXIS       0x00000010              // control like a mouse, spinner, trackball
59 #define JOY_MAX_AXES            6                               // X, Y, Z, R, U, V
60 #define JOY_AXIS_X                      0
61 #define JOY_AXIS_Y                      1
62 #define JOY_AXIS_Z                      2
63 #define JOY_AXIS_R                      3
64 #define JOY_AXIS_U                      4
65 #define JOY_AXIS_V                      5
66
67 enum _ControlList
68 {
69         AxisNada = 0, AxisForward, AxisLook, AxisSide, AxisTurn
70 };
71
72 DWORD   dwAxisFlags[JOY_MAX_AXES] =
73 {
74         JOY_RETURNX, JOY_RETURNY, JOY_RETURNZ, JOY_RETURNR, JOY_RETURNU, JOY_RETURNV
75 };
76
77 DWORD   dwAxisMap[JOY_MAX_AXES];
78 DWORD   dwControlMap[JOY_MAX_AXES];
79 PDWORD  pdwRawValue[JOY_MAX_AXES];
80
81 // none of these cvars are saved over a session
82 // this means that advanced controller configuration needs to be executed
83 // each time.  this avoids any problems with getting back to a default usage
84 // or when changing from one controller to another.  this way at least something
85 // works.
86 cvar_t  in_joystick = {CVAR_SAVE, "joystick","0"};
87 cvar_t  joy_name = {0, "joyname", "joystick"};
88 cvar_t  joy_advanced = {0, "joyadvanced", "0"};
89 cvar_t  joy_advaxisx = {0, "joyadvaxisx", "0"};
90 cvar_t  joy_advaxisy = {0, "joyadvaxisy", "0"};
91 cvar_t  joy_advaxisz = {0, "joyadvaxisz", "0"};
92 cvar_t  joy_advaxisr = {0, "joyadvaxisr", "0"};
93 cvar_t  joy_advaxisu = {0, "joyadvaxisu", "0"};
94 cvar_t  joy_advaxisv = {0, "joyadvaxisv", "0"};
95 cvar_t  joy_forwardthreshold = {0, "joyforwardthreshold", "0.15"};
96 cvar_t  joy_sidethreshold = {0, "joysidethreshold", "0.15"};
97 cvar_t  joy_pitchthreshold = {0, "joypitchthreshold", "0.15"};
98 cvar_t  joy_yawthreshold = {0, "joyyawthreshold", "0.15"};
99 cvar_t  joy_forwardsensitivity = {0, "joyforwardsensitivity", "-1.0"};
100 cvar_t  joy_sidesensitivity = {0, "joysidesensitivity", "-1.0"};
101 cvar_t  joy_pitchsensitivity = {0, "joypitchsensitivity", "1.0"};
102 cvar_t  joy_yawsensitivity = {0, "joyyawsensitivity", "-1.0"};
103 cvar_t  joy_wwhack1 = {0, "joywwhack1", "0.0"};
104 cvar_t  joy_wwhack2 = {0, "joywwhack2", "0.0"};
105
106 qboolean        joy_avail, joy_advancedinit, joy_haspov;
107 DWORD           joy_oldbuttonstate, joy_oldpovstate;
108
109 int                     joy_id;
110 DWORD           joy_flags;
111 DWORD           joy_numbuttons;
112
113 static LPDIRECTINPUT            g_pdi;
114 static LPDIRECTINPUTDEVICE      g_pMouse;
115
116 static JOYINFOEX        ji;
117
118 static HINSTANCE hInstDI;
119
120 static qboolean dinput;
121
122 typedef struct MYDATA {
123         LONG  lX;                   // X axis goes here
124         LONG  lY;                   // Y axis goes here
125         LONG  lZ;                   // Z axis goes here
126         BYTE  bButtonA;             // One button goes here
127         BYTE  bButtonB;             // Another button goes here
128         BYTE  bButtonC;             // Another button goes here
129         BYTE  bButtonD;             // Another button goes here
130 } MYDATA;
131
132 static DIOBJECTDATAFORMAT rgodf[] = {
133   { &GUID_XAxis,    FIELD_OFFSET(MYDATA, lX),       DIDFT_AXIS | DIDFT_ANYINSTANCE,   0,},
134   { &GUID_YAxis,    FIELD_OFFSET(MYDATA, lY),       DIDFT_AXIS | DIDFT_ANYINSTANCE,   0,},
135   { &GUID_ZAxis,    FIELD_OFFSET(MYDATA, lZ),       0x80000000 | DIDFT_AXIS | DIDFT_ANYINSTANCE,   0,},
136   { 0,              FIELD_OFFSET(MYDATA, bButtonA), DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0,},
137   { 0,              FIELD_OFFSET(MYDATA, bButtonB), DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0,},
138   { 0,              FIELD_OFFSET(MYDATA, bButtonC), 0x80000000 | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0,},
139   { 0,              FIELD_OFFSET(MYDATA, bButtonD), 0x80000000 | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0,},
140 };
141
142 #define NUM_OBJECTS (sizeof(rgodf) / sizeof(rgodf[0]))
143
144 static DIDATAFORMAT     df = {
145         sizeof(DIDATAFORMAT),       // this structure
146         sizeof(DIOBJECTDATAFORMAT), // size of object data format
147         DIDF_RELAXIS,               // absolute axis coordinates
148         sizeof(MYDATA),             // device data size
149         NUM_OBJECTS,                // number of objects
150         rgodf,                      // and here they are
151 };
152
153 // forward-referenced functions
154 void IN_StartupJoystick (void);
155 void Joy_AdvancedUpdate_f (void);
156 void IN_JoyMove (usercmd_t *cmd);
157
158
159 /*
160 ===========
161 IN_UpdateClipCursor
162 ===========
163 */
164 void IN_UpdateClipCursor (void)
165 {
166
167         if (mouseinitialized && mouseactive && !dinput)
168         {
169                 ClipCursor (&window_rect);
170         }
171 }
172
173
174 /*
175 ===========
176 IN_ShowMouse
177 ===========
178 */
179 void IN_ShowMouse (void)
180 {
181         if (!mouseshowtoggle)
182         {
183                 ShowCursor (true);
184                 mouseshowtoggle = 1;
185         }
186 }
187
188
189 /*
190 ===========
191 IN_HideMouse
192 ===========
193 */
194 void IN_HideMouse (void)
195 {
196         if (mouseshowtoggle)
197         {
198                 ShowCursor (false);
199                 mouseshowtoggle = 0;
200         }
201 }
202
203
204 /*
205 ===========
206 IN_ActivateMouse
207 ===========
208 */
209 void IN_ActivateMouse (void)
210 {
211
212         mouseactivatetoggle = true;
213
214         if (mouseinitialized)
215         {
216                 if (dinput)
217                 {
218                         if (g_pMouse)
219                         {
220                                 if (!dinput_acquired)
221                                 {
222                                         IDirectInputDevice_Acquire(g_pMouse);
223                                         dinput_acquired = true;
224                                 }
225                         }
226                         else
227                         {
228                                 return;
229                         }
230                 }
231                 else
232                 {
233                         if (mouseparmsvalid)
234                                 restore_spi = SystemParametersInfo (SPI_SETMOUSE, 0, newmouseparms, 0);
235
236                         SetCursorPos (window_center_x, window_center_y);
237                         SetCapture (mainwindow);
238                         ClipCursor (&window_rect);
239                         
240                 }
241
242                 mouseactive = true;
243         }
244 }
245
246
247 /*
248 ===========
249 IN_DeactivateMouse
250 ===========
251 */
252 void IN_DeactivateMouse (void)
253 {
254
255         mouseactivatetoggle = false;
256
257         if (mouseinitialized)
258         {
259                 if (dinput)
260                 {
261                         if (g_pMouse)
262                         {
263                                 if (dinput_acquired)
264                                 {
265                                         IDirectInputDevice_Unacquire(g_pMouse);
266                                         dinput_acquired = false;
267                                 }
268                         }
269                 }
270                 else
271                 {
272                         if (restore_spi)
273                                 SystemParametersInfo (SPI_SETMOUSE, 0, originalmouseparms, 0);
274
275                         ClipCursor (NULL);
276                         ReleaseCapture ();
277                 }
278
279                 mouseactive = false;
280         }
281 }
282
283
284 /*
285 ===========
286 IN_InitDInput
287 ===========
288 */
289 qboolean IN_InitDInput (void)
290 {
291     HRESULT             hr;
292         DIPROPDWORD     dipdw = {
293                 {
294                         sizeof(DIPROPDWORD),        // diph.dwSize
295                         sizeof(DIPROPHEADER),       // diph.dwHeaderSize
296                         0,                          // diph.dwObj
297                         DIPH_DEVICE,                // diph.dwHow
298                 },
299                 DINPUT_BUFFERSIZE,              // dwData
300         };
301
302         if (!hInstDI)
303         {
304                 hInstDI = LoadLibrary("dinput.dll");
305                 
306                 if (hInstDI == NULL)
307                 {
308                         Con_SafePrintf ("Couldn't load dinput.dll\n");
309                         return false;
310                 }
311         }
312
313         if (!pDirectInputCreate)
314         {
315                 pDirectInputCreate = (void *)GetProcAddress(hInstDI,"DirectInputCreateA");
316
317                 if (!pDirectInputCreate)
318                 {
319                         Con_SafePrintf ("Couldn't get DI proc addr\n");
320                         return false;
321                 }
322         }
323
324 // register with DirectInput and get an IDirectInput to play with.
325         hr = iDirectInputCreate(global_hInstance, DIRECTINPUT_VERSION, &g_pdi, NULL);
326
327         if (FAILED(hr))
328         {
329                 return false;
330         }
331
332 // obtain an interface to the system mouse device.
333         hr = IDirectInput_CreateDevice(g_pdi, &GUID_SysMouse, &g_pMouse, NULL);
334
335         if (FAILED(hr))
336         {
337                 Con_SafePrintf ("Couldn't open DI mouse device\n");
338                 return false;
339         }
340
341 // set the data format to "mouse format".
342         hr = IDirectInputDevice_SetDataFormat(g_pMouse, &df);
343
344         if (FAILED(hr))
345         {
346                 Con_SafePrintf ("Couldn't set DI mouse format\n");
347                 return false;
348         }
349
350 // set the cooperativity level.
351         hr = IDirectInputDevice_SetCooperativeLevel(g_pMouse, mainwindow,
352                         DISCL_EXCLUSIVE | DISCL_FOREGROUND);
353
354         if (FAILED(hr))
355         {
356                 Con_SafePrintf ("Couldn't set DI coop level\n");
357                 return false;
358         }
359
360
361 // set the buffer size to DINPUT_BUFFERSIZE elements.
362 // the buffer size is a DWORD property associated with the device
363         hr = IDirectInputDevice_SetProperty(g_pMouse, DIPROP_BUFFERSIZE, &dipdw.diph);
364
365         if (FAILED(hr))
366         {
367                 Con_SafePrintf ("Couldn't set DI buffersize\n");
368                 return false;
369         }
370
371         return true;
372 }
373
374
375 /*
376 ===========
377 IN_StartupMouse
378 ===========
379 */
380 void IN_StartupMouse (void)
381 {
382         if ( COM_CheckParm ("-nomouse") ) 
383                 return; 
384
385         mouseinitialized = true;
386
387         if (COM_CheckParm ("-dinput"))
388         {
389                 dinput = IN_InitDInput ();
390
391                 if (dinput)
392                 {
393                         Con_SafePrintf ("DirectInput initialized\n");
394                 }
395                 else
396                 {
397                         Con_SafePrintf ("DirectInput not initialized\n");
398                 }
399         }
400
401         if (!dinput)
402         {
403                 mouseparmsvalid = SystemParametersInfo (SPI_GETMOUSE, 0, originalmouseparms, 0);
404
405                 if (mouseparmsvalid)
406                 {
407                         if ( COM_CheckParm ("-noforcemspd") ) 
408                                 newmouseparms[2] = originalmouseparms[2];
409
410                         if ( COM_CheckParm ("-noforcemaccel") ) 
411                         {
412                                 newmouseparms[0] = originalmouseparms[0];
413                                 newmouseparms[1] = originalmouseparms[1];
414                         }
415
416                         if ( COM_CheckParm ("-noforcemparms") ) 
417                         {
418                                 newmouseparms[0] = originalmouseparms[0];
419                                 newmouseparms[1] = originalmouseparms[1];
420                                 newmouseparms[2] = originalmouseparms[2];
421                         }
422                 }
423         }
424
425         mouse_buttons = 3;
426
427 // if a fullscreen video mode was set before the mouse was initialized,
428 // set the mouse state appropriately
429         if (mouseactivatetoggle)
430                 IN_ActivateMouse ();
431 }
432
433
434 /*
435 ===========
436 IN_Init
437 ===========
438 */
439 void IN_Init (void)
440 {
441         // mouse variables
442         Cvar_RegisterVariable (&m_filter);
443
444         // joystick variables
445         Cvar_RegisterVariable (&in_joystick);
446         Cvar_RegisterVariable (&joy_name);
447         Cvar_RegisterVariable (&joy_advanced);
448         Cvar_RegisterVariable (&joy_advaxisx);
449         Cvar_RegisterVariable (&joy_advaxisy);
450         Cvar_RegisterVariable (&joy_advaxisz);
451         Cvar_RegisterVariable (&joy_advaxisr);
452         Cvar_RegisterVariable (&joy_advaxisu);
453         Cvar_RegisterVariable (&joy_advaxisv);
454         Cvar_RegisterVariable (&joy_forwardthreshold);
455         Cvar_RegisterVariable (&joy_sidethreshold);
456         Cvar_RegisterVariable (&joy_pitchthreshold);
457         Cvar_RegisterVariable (&joy_yawthreshold);
458         Cvar_RegisterVariable (&joy_forwardsensitivity);
459         Cvar_RegisterVariable (&joy_sidesensitivity);
460         Cvar_RegisterVariable (&joy_pitchsensitivity);
461         Cvar_RegisterVariable (&joy_yawsensitivity);
462         Cvar_RegisterVariable (&joy_wwhack1);
463         Cvar_RegisterVariable (&joy_wwhack2);
464
465         Cmd_AddCommand ("joyadvancedupdate", Joy_AdvancedUpdate_f);
466
467         uiWheelMessage = RegisterWindowMessage ( "MSWHEEL_ROLLMSG" );
468
469         IN_StartupMouse ();
470         IN_StartupJoystick ();
471 }
472
473 /*
474 ===========
475 IN_Shutdown
476 ===========
477 */
478 void IN_Shutdown (void)
479 {
480 //      usingmouse = false;
481         IN_DeactivateMouse ();
482         IN_ShowMouse ();
483
484     if (g_pMouse)
485         {
486                 IDirectInputDevice_Release(g_pMouse);
487                 g_pMouse = NULL;
488         }
489
490     if (g_pdi)
491         {
492                 IDirectInput_Release(g_pdi);
493                 g_pdi = NULL;
494         }
495 }
496
497
498 /*
499 ===========
500 IN_MouseEvent
501 ===========
502 */
503 void IN_MouseEvent (int mstate)
504 {
505         int     i;
506
507         if (mouseactive && !dinput)
508         {
509         // perform button actions
510                 for (i=0 ; i<mouse_buttons ; i++)
511                 {
512                         if ( (mstate & (1<<i)) &&
513                                 !(mouse_oldbuttonstate & (1<<i)) )
514                         {
515                                 Key_Event (K_MOUSE1 + i, true);
516                         }
517
518                         if ( !(mstate & (1<<i)) &&
519                                 (mouse_oldbuttonstate & (1<<i)) )
520                         {
521                                 Key_Event (K_MOUSE1 + i, false);
522                         }
523                 }       
524                         
525                 mouse_oldbuttonstate = mstate;
526         }
527 }
528
529
530 /*
531 ===========
532 IN_MouseMove
533 ===========
534 */
535 void IN_MouseMove (usercmd_t *cmd)
536 {
537         int                                     i, mx, my, mouselook = (in_mlook.state & 1) || freelook.integer;
538         DIDEVICEOBJECTDATA      od;
539         DWORD                           dwElements;
540         HRESULT                         hr;
541
542         if (!mouseactive)
543         {
544                 GetCursorPos (&current_pos);
545                 ui_mouseupdate(current_pos.x - window_x, current_pos.y - window_y);
546                 return;
547         }
548
549         if (dinput)
550         {
551                 mx = 0;
552                 my = 0;
553
554                 for (;;)
555                 {
556                         dwElements = 1;
557
558                         hr = IDirectInputDevice_GetDeviceData(g_pMouse,
559                                         sizeof(DIDEVICEOBJECTDATA), &od, &dwElements, 0);
560
561                         if ((hr == DIERR_INPUTLOST) || (hr == DIERR_NOTACQUIRED))
562                         {
563                                 dinput_acquired = true;
564                                 IDirectInputDevice_Acquire(g_pMouse);
565                                 break;
566                         }
567
568                         /* Unable to read data or no data available */
569                         if (FAILED(hr) || dwElements == 0)
570                         {
571                                 break;
572                         }
573
574                         /* Look at the element to see what happened */
575
576                         switch (od.dwOfs)
577                         {
578                                 case DIMOFS_X:
579                                         mx += od.dwData;
580                                         break;
581
582                                 case DIMOFS_Y:
583                                         my += od.dwData;
584                                         break;
585
586                                 case DIMOFS_BUTTON0:
587                                         if (od.dwData & 0x80)
588                                                 mstate_di |= 1;
589                                         else
590                                                 mstate_di &= ~1;
591                                         break;
592
593                                 case DIMOFS_BUTTON1:
594                                         if (od.dwData & 0x80)
595                                                 mstate_di |= (1<<1);
596                                         else
597                                                 mstate_di &= ~(1<<1);
598                                         break;
599
600                                 case DIMOFS_BUTTON2:
601                                         if (od.dwData & 0x80)
602                                                 mstate_di |= (1<<2);
603                                         else
604                                                 mstate_di &= ~(1<<2);
605                                         break;
606                         }
607                 }
608
609         // perform button actions
610                 for (i=0 ; i<mouse_buttons ; i++)
611                 {
612                         if ( (mstate_di & (1<<i)) &&
613                                 !(mouse_oldbuttonstate & (1<<i)) )
614                         {
615                                 Key_Event (K_MOUSE1 + i, true);
616                         }
617
618                         if ( !(mstate_di & (1<<i)) &&
619                                 (mouse_oldbuttonstate & (1<<i)) )
620                         {
621                                 Key_Event (K_MOUSE1 + i, false);
622                         }
623                 }
624
625                 mouse_oldbuttonstate = mstate_di;
626         }
627         else
628         {
629                 GetCursorPos (&current_pos);
630                 mx = current_pos.x - window_center_x + mx_accum;
631                 my = current_pos.y - window_center_y + my_accum;
632                 mx_accum = 0;
633                 my_accum = 0;
634         }
635
636 //if (mx ||  my)
637 //      Con_DPrintf("mx=%d, my=%d\n", mx, my);
638
639         if (m_filter.integer)
640         {
641                 mouse_x = (mx + old_mouse_x) * 0.5;
642                 mouse_y = (my + old_mouse_y) * 0.5;
643         }
644         else
645         {
646                 mouse_x = mx;
647                 mouse_y = my;
648         }
649
650         old_mouse_x = mx;
651         old_mouse_y = my;
652
653         // LordHavoc: viewzoom affects mouse sensitivity for sniping
654         mouse_x *= sensitivity.value * cl.viewzoom;
655         mouse_y *= sensitivity.value * cl.viewzoom;
656
657 // add mouse X/Y movement to cmd
658         if ( (in_strafe.state & 1) || (lookstrafe.integer && mouselook))
659                 cmd->sidemove += m_side.value * mouse_x;
660         else
661                 cl.viewangles[YAW] -= m_yaw.value * mouse_x;
662
663         if (mouselook)
664                 V_StopPitchDrift ();
665         
666         // LordHavoc: changed limits on pitch from -70 to 80, to -90 to 90
667         if (mouselook && !(in_strafe.state & 1))
668                 cl.viewangles[PITCH] += m_pitch.value * mouse_y;
669         else
670         {
671                 if ((in_strafe.state & 1) && noclip_anglehack)
672                         cmd->upmove -= m_forward.value * mouse_y;
673                 else
674                         cmd->forwardmove -= m_forward.value * mouse_y;
675         }
676
677 // if the mouse has moved, force it to the center, so there's room to move
678         if (mx || my)
679         {
680                 SetCursorPos (window_center_x, window_center_y);
681         }
682 }
683
684
685 /*
686 ===========
687 IN_Move
688 ===========
689 */
690 void IN_Move (usercmd_t *cmd)
691 {
692         if (ActiveApp && !Minimized)
693         {
694                 IN_MouseMove (cmd);
695                 IN_JoyMove (cmd);
696         }
697
698         cl.viewangles[PITCH] = bound (in_pitch_min.value, cl.viewangles[PITCH], in_pitch_max.value);
699 }
700
701
702 /*
703 ===========
704 IN_Accumulate
705 ===========
706 */
707 void IN_Accumulate (void)
708 {
709         if (mouseactive)
710         {
711                 if (!dinput)
712                 {
713                         GetCursorPos (&current_pos);
714
715                         mx_accum += current_pos.x - window_center_x;
716                         my_accum += current_pos.y - window_center_y;
717
718                 // force the mouse to the center, so there's room to move
719                         SetCursorPos (window_center_x, window_center_y);
720                 }
721         }
722 }
723
724
725 /*
726 ===================
727 IN_ClearStates
728 ===================
729 */
730 void IN_ClearStates (void)
731 {
732
733         if (mouseactive)
734         {
735                 mx_accum = 0;
736                 my_accum = 0;
737                 mouse_oldbuttonstate = 0;
738         }
739 }
740
741
742 /* 
743 =============== 
744 IN_StartupJoystick 
745 =============== 
746 */  
747 void IN_StartupJoystick (void) 
748
749         int                     numdevs;
750         JOYCAPS         jc;
751         MMRESULT        mmr;
752  
753         // assume no joystick
754         joy_avail = false; 
755
756         // abort startup if user requests no joystick
757         if ( COM_CheckParm ("-nojoy") ) 
758                 return; 
759  
760         // verify joystick driver is present
761         if ((numdevs = joyGetNumDevs ()) == 0)
762         {
763                 Con_Printf ("\njoystick not found -- driver not present\n\n");
764                 return;
765         }
766
767         // cycle through the joystick ids for the first valid one
768         for (joy_id=0 ; joy_id<numdevs ; joy_id++)
769         {
770                 memset (&ji, 0, sizeof(ji));
771                 ji.dwSize = sizeof(ji);
772                 ji.dwFlags = JOY_RETURNCENTERED;
773
774                 if ((mmr = joyGetPosEx (joy_id, &ji)) == JOYERR_NOERROR)
775                         break;
776         } 
777
778         // abort startup if we didn't find a valid joystick
779         if (mmr != JOYERR_NOERROR)
780         {
781                 Con_Printf ("\njoystick not found -- no valid joysticks (%x)\n\n", mmr);
782                 return;
783         }
784
785         // get the capabilities of the selected joystick
786         // abort startup if command fails
787         memset (&jc, 0, sizeof(jc));
788         if ((mmr = joyGetDevCaps (joy_id, &jc, sizeof(jc))) != JOYERR_NOERROR)
789         {
790                 Con_Printf ("\njoystick not found -- invalid joystick capabilities (%x)\n\n", mmr); 
791                 return;
792         }
793
794         // save the joystick's number of buttons and POV status
795         joy_numbuttons = jc.wNumButtons;
796         joy_haspov = jc.wCaps & JOYCAPS_HASPOV;
797
798         // old button and POV states default to no buttons pressed
799         joy_oldbuttonstate = joy_oldpovstate = 0;
800
801         // mark the joystick as available and advanced initialization not completed
802         // this is needed as cvars are not available during initialization
803
804         joy_avail = true; 
805         joy_advancedinit = false;
806
807         Con_Printf ("\njoystick detected\n\n"); 
808 }
809
810
811 /*
812 ===========
813 RawValuePointer
814 ===========
815 */
816 PDWORD RawValuePointer (int axis)
817 {
818         switch (axis)
819         {
820         case JOY_AXIS_X:
821                 return &ji.dwXpos;
822         case JOY_AXIS_Y:
823                 return &ji.dwYpos;
824         case JOY_AXIS_Z:
825                 return &ji.dwZpos;
826         case JOY_AXIS_R:
827                 return &ji.dwRpos;
828         case JOY_AXIS_U:
829                 return &ji.dwUpos;
830         case JOY_AXIS_V:
831                 return &ji.dwVpos;
832         }
833         return NULL; // LordHavoc: hush compiler warning
834 }
835
836
837 /*
838 ===========
839 Joy_AdvancedUpdate_f
840 ===========
841 */
842 void Joy_AdvancedUpdate_f (void)
843 {
844
845         // called once by IN_ReadJoystick and by user whenever an update is needed
846         // cvars are now available
847         int     i;
848         DWORD dwTemp;
849
850         // initialize all the maps
851         for (i = 0; i < JOY_MAX_AXES; i++)
852         {
853                 dwAxisMap[i] = AxisNada;
854                 dwControlMap[i] = JOY_ABSOLUTE_AXIS;
855                 pdwRawValue[i] = RawValuePointer(i);
856         }
857
858         if( joy_advanced.integer == 0)
859         {
860                 // default joystick initialization
861                 // 2 axes only with joystick control
862                 dwAxisMap[JOY_AXIS_X] = AxisTurn;
863                 // dwControlMap[JOY_AXIS_X] = JOY_ABSOLUTE_AXIS;
864                 dwAxisMap[JOY_AXIS_Y] = AxisForward;
865                 // dwControlMap[JOY_AXIS_Y] = JOY_ABSOLUTE_AXIS;
866         }
867         else
868         {
869                 if (strcmp (joy_name.string, "joystick") != 0)
870                 {
871                         // notify user of advanced controller
872                         Con_Printf ("\n%s configured\n\n", joy_name.string);
873                 }
874
875                 // advanced initialization here
876                 // data supplied by user via joy_axisn cvars
877                 dwTemp = (DWORD) joy_advaxisx.value;
878                 dwAxisMap[JOY_AXIS_X] = dwTemp & 0x0000000f;
879                 dwControlMap[JOY_AXIS_X] = dwTemp & JOY_RELATIVE_AXIS;
880                 dwTemp = (DWORD) joy_advaxisy.value;
881                 dwAxisMap[JOY_AXIS_Y] = dwTemp & 0x0000000f;
882                 dwControlMap[JOY_AXIS_Y] = dwTemp & JOY_RELATIVE_AXIS;
883                 dwTemp = (DWORD) joy_advaxisz.value;
884                 dwAxisMap[JOY_AXIS_Z] = dwTemp & 0x0000000f;
885                 dwControlMap[JOY_AXIS_Z] = dwTemp & JOY_RELATIVE_AXIS;
886                 dwTemp = (DWORD) joy_advaxisr.value;
887                 dwAxisMap[JOY_AXIS_R] = dwTemp & 0x0000000f;
888                 dwControlMap[JOY_AXIS_R] = dwTemp & JOY_RELATIVE_AXIS;
889                 dwTemp = (DWORD) joy_advaxisu.value;
890                 dwAxisMap[JOY_AXIS_U] = dwTemp & 0x0000000f;
891                 dwControlMap[JOY_AXIS_U] = dwTemp & JOY_RELATIVE_AXIS;
892                 dwTemp = (DWORD) joy_advaxisv.value;
893                 dwAxisMap[JOY_AXIS_V] = dwTemp & 0x0000000f;
894                 dwControlMap[JOY_AXIS_V] = dwTemp & JOY_RELATIVE_AXIS;
895         }
896
897         // compute the axes to collect from DirectInput
898         joy_flags = JOY_RETURNCENTERED | JOY_RETURNBUTTONS | JOY_RETURNPOV;
899         for (i = 0; i < JOY_MAX_AXES; i++)
900         {
901                 if (dwAxisMap[i] != AxisNada)
902                 {
903                         joy_flags |= dwAxisFlags[i];
904                 }
905         }
906 }
907
908
909 /*
910 ===========
911 IN_Commands
912 ===========
913 */
914 void IN_Commands (void)
915 {
916         int             i, key_index;
917         DWORD   buttonstate, povstate;
918
919         if (!joy_avail)
920         {
921                 return;
922         }
923
924         
925         // loop through the joystick buttons
926         // key a joystick event or auxillary event for higher number buttons for each state change
927         buttonstate = ji.dwButtons;
928         for (i=0 ; i < (int) joy_numbuttons ; i++)
929         {
930                 if ( (buttonstate & (1<<i)) && !(joy_oldbuttonstate & (1<<i)) )
931                 {
932                         key_index = (i < 4) ? K_JOY1 : K_AUX1;
933                         Key_Event (key_index + i, true);
934                 }
935
936                 if ( !(buttonstate & (1<<i)) && (joy_oldbuttonstate & (1<<i)) )
937                 {
938                         key_index = (i < 4) ? K_JOY1 : K_AUX1;
939                         Key_Event (key_index + i, false);
940                 }
941         }
942         joy_oldbuttonstate = buttonstate;
943
944         if (joy_haspov)
945         {
946                 // convert POV information into 4 bits of state information
947                 // this avoids any potential problems related to moving from one
948                 // direction to another without going through the center position
949                 povstate = 0;
950                 if(ji.dwPOV != JOY_POVCENTERED)
951                 {
952                         if (ji.dwPOV == JOY_POVFORWARD)
953                                 povstate |= 0x01;
954                         if (ji.dwPOV == JOY_POVRIGHT)
955                                 povstate |= 0x02;
956                         if (ji.dwPOV == JOY_POVBACKWARD)
957                                 povstate |= 0x04;
958                         if (ji.dwPOV == JOY_POVLEFT)
959                                 povstate |= 0x08;
960                 }
961                 // determine which bits have changed and key an auxillary event for each change
962                 for (i=0 ; i < 4 ; i++)
963                 {
964                         if ( (povstate & (1<<i)) && !(joy_oldpovstate & (1<<i)) )
965                         {
966                                 Key_Event (K_AUX29 + i, true);
967                         }
968
969                         if ( !(povstate & (1<<i)) && (joy_oldpovstate & (1<<i)) )
970                         {
971                                 Key_Event (K_AUX29 + i, false);
972                         }
973                 }
974                 joy_oldpovstate = povstate;
975         }
976 }
977
978
979 /* 
980 =============== 
981 IN_ReadJoystick
982 =============== 
983 */  
984 qboolean IN_ReadJoystick (void)
985 {
986
987         memset (&ji, 0, sizeof(ji));
988         ji.dwSize = sizeof(ji);
989         ji.dwFlags = joy_flags;
990
991         if (joyGetPosEx (joy_id, &ji) == JOYERR_NOERROR)
992         {
993                 // this is a hack -- there is a bug in the Logitech WingMan Warrior DirectInput Driver
994                 // rather than having 32768 be the zero point, they have the zero point at 32668
995                 // go figure -- anyway, now we get the full resolution out of the device
996                 if (joy_wwhack1.integer != 0.0)
997                 {
998                         ji.dwUpos += 100;
999                 }
1000                 return true;
1001         }
1002         else
1003         {
1004                 // read error occurred
1005                 // turning off the joystick seems too harsh for 1 read error,\
1006                 // but what should be done?
1007                 // Con_Printf ("IN_ReadJoystick: no response\n");
1008                 // joy_avail = false;
1009                 return false;
1010         }
1011 }
1012
1013
1014 /*
1015 ===========
1016 IN_JoyMove
1017 ===========
1018 */
1019 void IN_JoyMove (usercmd_t *cmd)
1020 {
1021         float   speed, aspeed;
1022         float   fAxisValue, fTemp;
1023         int             i, mouselook = (in_mlook.state & 1) || freelook.integer;
1024
1025         // complete initialization if first time in
1026         // this is needed as cvars are not available at initialization time
1027         if( joy_advancedinit != true )
1028         {
1029                 Joy_AdvancedUpdate_f();
1030                 joy_advancedinit = true;
1031         }
1032
1033         // verify joystick is available and that the user wants to use it
1034         if (!joy_avail || !in_joystick.integer)
1035         {
1036                 return; 
1037         }
1038
1039         // collect the joystick data, if possible
1040         if (IN_ReadJoystick () != true)
1041         {
1042                 return;
1043         }
1044
1045         if (in_speed.state & 1)
1046                 speed = cl_movespeedkey.value;
1047         else
1048                 speed = 1;
1049         // LordHavoc: viewzoom affects sensitivity for sniping
1050         aspeed = speed * host_realframetime * cl.viewzoom;
1051
1052         // loop through the axes
1053         for (i = 0; i < JOY_MAX_AXES; i++)
1054         {
1055                 // get the floating point zero-centered, potentially-inverted data for the current axis
1056                 fAxisValue = (float) *pdwRawValue[i];
1057                 // move centerpoint to zero
1058                 fAxisValue -= 32768.0;
1059
1060                 if (joy_wwhack2.integer != 0.0)
1061                 {
1062                         if (dwAxisMap[i] == AxisTurn)
1063                         {
1064                                 // this is a special formula for the Logitech WingMan Warrior
1065                                 // y=ax^b; where a = 300 and b = 1.3
1066                                 // also x values are in increments of 800 (so this is factored out)
1067                                 // then bounds check result to level out excessively high spin rates
1068                                 fTemp = 300.0 * pow(abs(fAxisValue) / 800.0, 1.3);
1069                                 if (fTemp > 14000.0)
1070                                         fTemp = 14000.0;
1071                                 // restore direction information
1072                                 fAxisValue = (fAxisValue > 0.0) ? fTemp : -fTemp;
1073                         }
1074                 }
1075
1076                 // convert range from -32768..32767 to -1..1 
1077                 fAxisValue /= 32768.0;
1078
1079                 switch (dwAxisMap[i])
1080                 {
1081                 case AxisForward:
1082                         if ((joy_advanced.integer == 0) && mouselook)
1083                         {
1084                                 // user wants forward control to become look control
1085                                 if (fabs(fAxisValue) > joy_pitchthreshold.value)
1086                                 {               
1087                                         // if mouse invert is on, invert the joystick pitch value
1088                                         // only absolute control support here (joy_advanced is false)
1089                                         if (m_pitch.value < 0.0)
1090                                         {
1091                                                 cl.viewangles[PITCH] -= (fAxisValue * joy_pitchsensitivity.value) * aspeed * cl_pitchspeed.value;
1092                                         }
1093                                         else
1094                                         {
1095                                                 cl.viewangles[PITCH] += (fAxisValue * joy_pitchsensitivity.value) * aspeed * cl_pitchspeed.value;
1096                                         }
1097                                         V_StopPitchDrift();
1098                                 }
1099                                 else
1100                                 {
1101                                         // no pitch movement
1102                                         // disable pitch return-to-center unless requested by user
1103                                         // *** this code can be removed when the lookspring bug is fixed
1104                                         // *** the bug always has the lookspring feature on
1105                                         if(lookspring.value == 0.0)
1106                                                 V_StopPitchDrift();
1107                                 }
1108                         }
1109                         else
1110                         {
1111                                 // user wants forward control to be forward control
1112                                 if (fabs(fAxisValue) > joy_forwardthreshold.value)
1113                                 {
1114                                         cmd->forwardmove += (fAxisValue * joy_forwardsensitivity.value) * speed * cl_forwardspeed.value;
1115                                 }
1116                         }
1117                         break;
1118
1119                 case AxisSide:
1120                         if (fabs(fAxisValue) > joy_sidethreshold.value)
1121                         {
1122                                 cmd->sidemove += (fAxisValue * joy_sidesensitivity.value) * speed * cl_sidespeed.value;
1123                         }
1124                         break;
1125
1126                 case AxisTurn:
1127                         if ((in_strafe.state & 1) || (lookstrafe.integer && mouselook))
1128                         {
1129                                 // user wants turn control to become side control
1130                                 if (fabs(fAxisValue) > joy_sidethreshold.value)
1131                                 {
1132                                         cmd->sidemove -= (fAxisValue * joy_sidesensitivity.value) * speed * cl_sidespeed.value;
1133                                 }
1134                         }
1135                         else
1136                         {
1137                                 // user wants turn control to be turn control
1138                                 if (fabs(fAxisValue) > joy_yawthreshold.value)
1139                                 {
1140                                         if(dwControlMap[i] == JOY_ABSOLUTE_AXIS)
1141                                         {
1142                                                 cl.viewangles[YAW] += (fAxisValue * joy_yawsensitivity.value) * aspeed * cl_yawspeed.value;
1143                                         }
1144                                         else
1145                                         {
1146                                                 cl.viewangles[YAW] += (fAxisValue * joy_yawsensitivity.value) * speed * 180.0;
1147                                         }
1148
1149                                 }
1150                         }
1151                         break;
1152
1153                 case AxisLook:
1154                         if (mouselook)
1155                         {
1156                                 if (fabs(fAxisValue) > joy_pitchthreshold.value)
1157                                 {
1158                                         // pitch movement detected and pitch movement desired by user
1159                                         if(dwControlMap[i] == JOY_ABSOLUTE_AXIS)
1160                                         {
1161                                                 cl.viewangles[PITCH] += (fAxisValue * joy_pitchsensitivity.value) * aspeed * cl_pitchspeed.value;
1162                                         }
1163                                         else
1164                                         {
1165                                                 cl.viewangles[PITCH] += (fAxisValue * joy_pitchsensitivity.value) * speed * 180.0;
1166                                         }
1167                                         V_StopPitchDrift();
1168                                 }
1169                                 else
1170                                 {
1171                                         // no pitch movement
1172                                         // disable pitch return-to-center unless requested by user
1173                                         // *** this code can be removed when the lookspring bug is fixed
1174                                         // *** the bug always has the lookspring feature on
1175                                         if(lookspring.integer == 0)
1176                                                 V_StopPitchDrift();
1177                                 }
1178                         }
1179                         break;
1180
1181                 default:
1182                         break;
1183                 }
1184         }
1185
1186         // bounds check pitch
1187         if (cl.viewangles[PITCH] > 80.0)
1188                 cl.viewangles[PITCH] = 80.0;
1189         if (cl.viewangles[PITCH] < -70.0)
1190                 cl.viewangles[PITCH] = -70.0;
1191 }