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