]> git.xonotic.org Git - xonotic/darkplaces.git/blob - vid_wgl.c
now that performance of cl_decals_newsystem is not terrible, enable it
[xonotic/darkplaces.git] / vid_wgl.c
1 /*
2 Copyright (C) 1996-1997 Id Software, Inc.
3
4 This program is free software; you can redistribute it and/or
5 modify it under the terms of the GNU General Public License
6 as published by the Free Software Foundation; either version 2
7 of the License, or (at your option) any later version.
8
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
12
13 See the GNU General Public License for more details.
14
15 You should have received a copy of the GNU General Public License
16 along with this program; if not, write to the Free Software
17 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
18
19 */
20 // vid_wgl.c -- NT GL vid component
21
22 #ifdef SUPPORTDIRECTX
23 // Include DX libs
24 #pragma comment(lib, "dinput8.lib")
25 #pragma comment(lib, "dxguid.lib")
26 #ifndef DIRECTINPUT_VERSION
27 #       define DIRECTINPUT_VERSION 0x0500  /* Version 5.0 */
28 #endif
29 #endif
30
31 #include "quakedef.h"
32 #include <windows.h>
33 #include <mmsystem.h>
34 #ifdef SUPPORTDIRECTX
35 #include <dsound.h>
36 #endif
37 #include "resource.h"
38 #include <commctrl.h>
39 #ifdef SUPPORTDIRECTX
40 #include <dinput.h>
41 #endif
42
43 extern HINSTANCE global_hInstance;
44
45
46 #ifndef WM_MOUSEWHEEL
47 #define WM_MOUSEWHEEL                   0x020A
48 #endif
49
50 // Tell startup code that we have a client
51 int cl_available = true;
52
53 qboolean vid_supportrefreshrate = true;
54
55 static int (WINAPI *qwglChoosePixelFormat)(HDC, CONST PIXELFORMATDESCRIPTOR *);
56 static int (WINAPI *qwglDescribePixelFormat)(HDC, int, UINT, LPPIXELFORMATDESCRIPTOR);
57 //static int (WINAPI *qwglGetPixelFormat)(HDC);
58 static BOOL (WINAPI *qwglSetPixelFormat)(HDC, int, CONST PIXELFORMATDESCRIPTOR *);
59 static BOOL (WINAPI *qwglSwapBuffers)(HDC);
60 static HGLRC (WINAPI *qwglCreateContext)(HDC);
61 static BOOL (WINAPI *qwglDeleteContext)(HGLRC);
62 static HGLRC (WINAPI *qwglGetCurrentContext)(VOID);
63 static HDC (WINAPI *qwglGetCurrentDC)(VOID);
64 static PROC (WINAPI *qwglGetProcAddress)(LPCSTR);
65 static BOOL (WINAPI *qwglMakeCurrent)(HDC, HGLRC);
66 static BOOL (WINAPI *qwglSwapIntervalEXT)(int interval);
67 static const char *(WINAPI *qwglGetExtensionsStringARB)(HDC hdc);
68 static BOOL (WINAPI *qwglChoosePixelFormatARB)(HDC hdc, const int *piAttribIList, const FLOAT *pfAttribFList, UINT nMaxFormats, int *piFormats, UINT *nNumFormats);
69 static BOOL (WINAPI *qwglGetPixelFormatAttribivARB)(HDC hdc, int iPixelFormat, int iLayerPlane, UINT nAttributes, const int *piAttributes, int *piValues);
70
71 static dllfunction_t wglfuncs[] =
72 {
73         {"wglChoosePixelFormat", (void **) &qwglChoosePixelFormat},
74         {"wglDescribePixelFormat", (void **) &qwglDescribePixelFormat},
75 //      {"wglGetPixelFormat", (void **) &qwglGetPixelFormat},
76         {"wglSetPixelFormat", (void **) &qwglSetPixelFormat},
77         {"wglSwapBuffers", (void **) &qwglSwapBuffers},
78         {"wglCreateContext", (void **) &qwglCreateContext},
79         {"wglDeleteContext", (void **) &qwglDeleteContext},
80         {"wglGetProcAddress", (void **) &qwglGetProcAddress},
81         {"wglMakeCurrent", (void **) &qwglMakeCurrent},
82         {"wglGetCurrentContext", (void **) &qwglGetCurrentContext},
83         {"wglGetCurrentDC", (void **) &qwglGetCurrentDC},
84         {NULL, NULL}
85 };
86
87 static dllfunction_t wglswapintervalfuncs[] =
88 {
89         {"wglSwapIntervalEXT", (void **) &qwglSwapIntervalEXT},
90         {NULL, NULL}
91 };
92
93 static dllfunction_t wglpixelformatfuncs[] =
94 {
95         {"wglChoosePixelFormatARB", (void **) &qwglChoosePixelFormatARB},
96         {"wglGetPixelFormatAttribivARB", (void **) &qwglGetPixelFormatAttribivARB},
97         {NULL, NULL}
98 };
99
100 static DEVMODE gdevmode, initialdevmode;
101 static qboolean vid_initialized = false;
102 static qboolean vid_wassuspended = false;
103 static qboolean vid_usingmouse = false;
104 static qboolean vid_usinghidecursor = false;
105 static qboolean vid_usingvsync = false;
106 static qboolean vid_usevsync = false;
107 static HICON hIcon;
108
109 // used by cd_win.c and snd_win.c
110 HWND mainwindow;
111
112 static HDC       baseDC;
113 static HGLRC baseRC;
114
115 //HWND WINAPI InitializeWindow (HINSTANCE hInstance, int nCmdShow);
116
117 static qboolean vid_isfullscreen;
118
119 //void VID_MenuDraw (void);
120 //void VID_MenuKey (int key);
121
122 //LONG WINAPI MainWndProc (HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
123 //void AppActivate(BOOL fActive, BOOL minimize);
124 //void ClearAllStates (void);
125 //void VID_UpdateWindowStatus (void);
126
127 //====================================
128
129 static int window_x, window_y;
130
131 static qboolean mouseinitialized;
132
133 #ifdef SUPPORTDIRECTX
134 static qboolean dinput;
135 #define DINPUT_BUFFERSIZE           16
136 #define iDirectInputCreate(a,b,c,d)     pDirectInputCreate(a,b,c,d)
137
138 static HRESULT (WINAPI *pDirectInputCreate)(HINSTANCE hinst, DWORD dwVersion, LPDIRECTINPUT * lplpDirectInput, LPUNKNOWN punkOuter);
139 #endif
140
141 // LordHavoc: thanks to backslash for this support for mouse buttons 4 and 5
142 /* backslash :: imouse explorer buttons */
143 /* These are #ifdefed out for non-Win2K in the February 2001 version of
144    MS's platform SDK, but we need them for compilation. . . */
145 #ifndef WM_XBUTTONDOWN
146    #define WM_XBUTTONDOWN      0x020B
147    #define WM_XBUTTONUP      0x020C
148 #endif
149 #ifndef MK_XBUTTON1
150    #define MK_XBUTTON1         0x0020
151    #define MK_XBUTTON2         0x0040
152 #endif
153 #ifndef MK_XBUTTON3
154 // LordHavoc: lets hope this allows more buttons in the future...
155    #define MK_XBUTTON3         0x0080
156    #define MK_XBUTTON4         0x0100
157    #define MK_XBUTTON5         0x0200
158    #define MK_XBUTTON6         0x0400
159    #define MK_XBUTTON7         0x0800
160 #endif
161 /* :: backslash */
162
163 // mouse variables
164 static int                      mouse_buttons;
165 static int                      mouse_oldbuttonstate;
166
167 static unsigned int uiWheelMessage;
168 #ifdef SUPPORTDIRECTX
169 static qboolean dinput_acquired;
170
171 static unsigned int             mstate_di;
172 #endif
173
174 // joystick defines and variables
175 // where should defines be moved?
176 #define JOY_ABSOLUTE_AXIS       0x00000000              // control like a joystick
177 #define JOY_RELATIVE_AXIS       0x00000010              // control like a mouse, spinner, trackball
178 #define JOY_MAX_AXES            6                               // X, Y, Z, R, U, V
179 #define JOY_AXIS_X                      0
180 #define JOY_AXIS_Y                      1
181 #define JOY_AXIS_Z                      2
182 #define JOY_AXIS_R                      3
183 #define JOY_AXIS_U                      4
184 #define JOY_AXIS_V                      5
185
186 // joystick axes state
187 typedef struct
188 {
189         float oldmove;
190         float move;
191         float mdelta;
192         double keytime;
193 }joy_axiscache_t;
194 static joy_axiscache_t joy_axescache[JOY_MAX_AXES];
195
196 enum _ControlList
197 {
198         AxisNada = 0, AxisForward, AxisLook, AxisSide, AxisTurn
199 };
200
201 static DWORD    dwAxisFlags[JOY_MAX_AXES] =
202 {
203         JOY_RETURNX, JOY_RETURNY, JOY_RETURNZ, JOY_RETURNR, JOY_RETURNU, JOY_RETURNV
204 };
205
206 static DWORD    dwAxisMap[JOY_MAX_AXES];
207 static DWORD    dwControlMap[JOY_MAX_AXES];
208 static PDWORD   pdwRawValue[JOY_MAX_AXES];
209
210 // none of these cvars are saved over a session
211 // this means that advanced controller configuration needs to be executed
212 // each time.  this avoids any problems with getting back to a default usage
213 // or when changing from one controller to another.  this way at least something
214 // works.
215 static cvar_t in_joystick = {CVAR_SAVE, "joystick","0", "enables joysticks"};
216 static cvar_t joy_name = {0, "joyname", "joystick", "name of joystick to use (informational only, used only by joyadvanced 1 mode)"};
217 static cvar_t joy_advanced = {0, "joyadvanced", "0", "use more than 2 axis joysticks (configuring this is very technical)"};
218 static cvar_t joy_advaxisx = {0, "joyadvaxisx", "0", "axis mapping for joyadvanced 1 mode"};
219 static cvar_t joy_advaxisy = {0, "joyadvaxisy", "0", "axis mapping for joyadvanced 1 mode"};
220 static cvar_t joy_advaxisz = {0, "joyadvaxisz", "0", "axis mapping for joyadvanced 1 mode"};
221 static cvar_t joy_advaxisr = {0, "joyadvaxisr", "0", "axis mapping for joyadvanced 1 mode"};
222 static cvar_t joy_advaxisu = {0, "joyadvaxisu", "0", "axis mapping for joyadvanced 1 mode"};
223 static cvar_t joy_advaxisv = {0, "joyadvaxisv", "0", "axis mapping for joyadvanced 1 mode"};
224 static cvar_t joy_forwardthreshold = {0, "joyforwardthreshold", "0.15", "minimum joystick movement necessary to move forward"};
225 static cvar_t joy_sidethreshold = {0, "joysidethreshold", "0.15", "minimum joystick movement necessary to move sideways (strafing)"};
226 static cvar_t joy_pitchthreshold = {0, "joypitchthreshold", "0.15", "minimum joystick movement necessary to look up/down"};
227 static cvar_t joy_yawthreshold = {0, "joyyawthreshold", "0.15", "minimum joystick movement necessary to turn left/right"};
228 static cvar_t joy_forwardsensitivity = {0, "joyforwardsensitivity", "-1.0", "how fast the joystick moves forward"};
229 static cvar_t joy_sidesensitivity = {0, "joysidesensitivity", "-1.0", "how fast the joystick moves sideways (strafing)"};
230 static cvar_t joy_pitchsensitivity = {0, "joypitchsensitivity", "1.0", "how fast the joystick looks up/down"};
231 static cvar_t joy_yawsensitivity = {0, "joyyawsensitivity", "-1.0", "how fast the joystick turns left/right"};
232 static cvar_t joy_wwhack1 = {0, "joywwhack1", "0.0", "special hack for wingman warrior"};
233 static cvar_t joy_wwhack2 = {0, "joywwhack2", "0.0", "special hack for wingman warrior"};
234 static cvar_t joy_axiskeyevents = {CVAR_SAVE, "joy_axiskeyevents", "0", "generate uparrow/leftarrow etc. keyevents for joystick axes, use if your joystick driver is not generating them"};
235
236 static cvar_t vid_forcerefreshrate = {0, "vid_forcerefreshrate", "0", "try to set the given vid_refreshrate even if Windows doesn't list it as valid video mode"};
237
238 static qboolean joy_avail, joy_advancedinit, joy_haspov;
239 static DWORD            joy_oldbuttonstate, joy_oldpovstate;
240
241 static int                      joy_id;
242 static DWORD            joy_flags;
243 static DWORD            joy_numbuttons;
244
245 #ifdef SUPPORTDIRECTX
246 static LPDIRECTINPUT            g_pdi;
247 static LPDIRECTINPUTDEVICE      g_pMouse;
248 static HINSTANCE hInstDI;
249 #endif
250
251 static JOYINFOEX        ji;
252
253 // forward-referenced functions
254 static void IN_StartupJoystick (void);
255 static void Joy_AdvancedUpdate_f (void);
256 static void IN_JoyMove (void);
257 static void IN_StartupMouse (void);
258
259
260 //====================================
261
262 void VID_Finish (void)
263 {
264         vid_usevsync = vid_vsync.integer && !cls.timedemo && qwglSwapIntervalEXT;
265         if (vid_usingvsync != vid_usevsync)
266         {
267                 vid_usingvsync = vid_usevsync;
268                 qwglSwapIntervalEXT (vid_usevsync);
269         }
270
271         if (!vid_hidden)
272         {
273                 CHECKGLERROR
274                 if (r_speeds.integer == 2 || gl_finish.integer)
275                 {
276                         qglFinish();CHECKGLERROR
277                 }
278                 SwapBuffers(baseDC);
279         }
280
281         // make sure a context switch can happen every frame - Logitech drivers
282         // input drivers sometimes eat cpu time every 3 seconds or lag badly
283         // without this help
284         Sleep(0);
285
286         VID_UpdateGamma(false, 256);
287 }
288
289 //==========================================================================
290
291
292
293
294 static unsigned char scantokey[128] =
295 {
296 //  0           1       2    3     4     5       6       7      8         9      A          B           C       D           E           F
297         0          ,27    ,'1'  ,'2'  ,'3'  ,'4'    ,'5'    ,'6'   ,'7'      ,'8'   ,'9'       ,'0'        ,'-'   ,'='         ,K_BACKSPACE,9    ,//0
298         'q'        ,'w'   ,'e'  ,'r'  ,'t'  ,'y'    ,'u'    ,'i'   ,'o'      ,'p'   ,'['       ,']'        ,13    ,K_CTRL      ,'a'        ,'s'  ,//1
299         'd'        ,'f'   ,'g'  ,'h'  ,'j'  ,'k'    ,'l'    ,';'   ,'\''     ,'`'   ,K_SHIFT   ,'\\'       ,'z'   ,'x'         ,'c'        ,'v'  ,//2
300         'b'        ,'n'   ,'m'  ,','  ,'.'  ,'/'    ,K_SHIFT,'*'   ,K_ALT    ,' '   ,0         ,K_F1       ,K_F2  ,K_F3        ,K_F4       ,K_F5 ,//3
301         K_F6       ,K_F7  ,K_F8 ,K_F9 ,K_F10,K_PAUSE,0      ,K_HOME,K_UPARROW,K_PGUP,K_KP_MINUS,K_LEFTARROW,K_KP_5,K_RIGHTARROW,K_KP_PLUS  ,K_END,//4
302         K_DOWNARROW,K_PGDN,K_INS,K_DEL,0    ,0      ,0      ,K_F11 ,K_F12    ,0     ,0         ,0          ,0     ,0           ,0          ,0    ,//5
303         0          ,0     ,0    ,0    ,0    ,0      ,0      ,0     ,0        ,0     ,0         ,0          ,0     ,0           ,0          ,0    ,//6
304         0          ,0     ,0    ,0    ,0    ,0      ,0      ,0     ,0        ,0     ,0         ,0          ,0     ,0           ,0          ,0     //7
305 };
306
307
308 /*
309 =======
310 MapKey
311
312 Map from windows to quake keynums
313 =======
314 */
315 static int MapKey (int key, int virtualkey)
316 {
317         int result;
318         int modified = (key >> 16) & 255;
319         qboolean is_extended = false;
320
321         if (modified < 128 && scantokey[modified])
322                 result = scantokey[modified];
323         else
324         {
325                 result = 0;
326                 Con_DPrintf("key 0x%02x (0x%8x, 0x%8x) has no translation\n", modified, key, virtualkey);
327         }
328
329         if (key & (1 << 24))
330                 is_extended = true;
331
332         if ( !is_extended )
333         {
334                 switch ( result )
335                 {
336                 case K_HOME:
337                         return K_KP_HOME;
338                 case K_UPARROW:
339                         return K_KP_UPARROW;
340                 case K_PGUP:
341                         return K_KP_PGUP;
342                 case K_LEFTARROW:
343                         return K_KP_LEFTARROW;
344                 case K_RIGHTARROW:
345                         return K_KP_RIGHTARROW;
346                 case K_END:
347                         return K_KP_END;
348                 case K_DOWNARROW:
349                         return K_KP_DOWNARROW;
350                 case K_PGDN:
351                         return K_KP_PGDN;
352                 case K_INS:
353                         return K_KP_INS;
354                 case K_DEL:
355                         return K_KP_DEL;
356                 default:
357                         return result;
358                 }
359         }
360         else
361         {
362                 switch ( result )
363                 {
364                 case 0x0D:
365                         return K_KP_ENTER;
366                 case 0x2F:
367                         return K_KP_SLASH;
368                 case 0xAF:
369                         return K_KP_PLUS;
370                 }
371                 return result;
372         }
373 }
374
375 /*
376 ===================================================================
377
378 MAIN WINDOW
379
380 ===================================================================
381 */
382
383 /*
384 ================
385 ClearAllStates
386 ================
387 */
388 static void ClearAllStates (void)
389 {
390         Key_ClearStates ();
391         if (vid_usingmouse)
392                 mouse_oldbuttonstate = 0;
393 }
394
395 void AppActivate(BOOL fActive, BOOL minimize)
396 /****************************************************************************
397 *
398 * Function:     AppActivate
399 * Parameters:   fActive - True if app is activating
400 *
401 * Description:  If the application is activating, then swap the system
402 *               into SYSPAL_NOSTATIC mode so that our palettes will display
403 *               correctly.
404 *
405 ****************************************************************************/
406 {
407         static qboolean sound_active = false;  // initially blocked by Sys_InitConsole()
408
409         vid_activewindow = fActive != FALSE;
410         vid_hidden = minimize != FALSE;
411
412         // enable/disable sound on focus gain/loss
413         if ((!vid_hidden && vid_activewindow) || !snd_mutewhenidle.integer)
414         {
415                 if (!sound_active)
416                 {
417                         S_UnblockSound ();
418                         sound_active = true;
419                 }
420         }
421         else
422         {
423                 if (sound_active)
424                 {
425                         S_BlockSound ();
426                         sound_active = false;
427                 }
428         }
429
430         if (fActive)
431         {
432                 if (vid_isfullscreen)
433                 {
434                         if (vid_wassuspended)
435                         {
436                                 vid_wassuspended = false;
437                                 ChangeDisplaySettings (&gdevmode, CDS_FULLSCREEN);
438                                 ShowWindow(mainwindow, SW_SHOWNORMAL);
439                         }
440
441                         // LordHavoc: from dabb, fix for alt-tab bug in NVidia drivers
442                         MoveWindow(mainwindow,0,0,gdevmode.dmPelsWidth,gdevmode.dmPelsHeight,false);
443                 }
444         }
445
446         if (!fActive)
447         {
448                 VID_SetMouse(false, false, false);
449                 if (vid_isfullscreen)
450                 {
451                         ChangeDisplaySettings (NULL, 0);
452                         vid_wassuspended = true;
453                 }
454                 VID_RestoreSystemGamma();
455         }
456 }
457
458 //TODO: move it around in vid_wgl.c since I dont think this is the right position
459 void Sys_SendKeyEvents (void)
460 {
461         MSG msg;
462
463         while (PeekMessage (&msg, NULL, 0, 0, PM_NOREMOVE))
464         {
465                 if (!GetMessage (&msg, NULL, 0, 0))
466                         Sys_Quit (1);
467
468                 TranslateMessage (&msg);
469                 DispatchMessage (&msg);
470         }
471 }
472
473 LONG CDAudio_MessageHandler(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
474
475 static keynum_t buttonremap[16] =
476 {
477         K_MOUSE1,
478         K_MOUSE2,
479         K_MOUSE3,
480         K_MOUSE4,
481         K_MOUSE5,
482         K_MOUSE6,
483         K_MOUSE7,
484         K_MOUSE8,
485         K_MOUSE9,
486         K_MOUSE10,
487         K_MOUSE11,
488         K_MOUSE12,
489         K_MOUSE13,
490         K_MOUSE14,
491         K_MOUSE15,
492         K_MOUSE16,
493 };
494
495 /* main window procedure */
496 static qboolean IN_JoystickBlockDoubledKeyEvents(int keycode);
497 LONG WINAPI MainWndProc (HWND hWnd, UINT uMsg, WPARAM  wParam, LPARAM lParam)
498 {
499         LONG    lRet = 1;
500         int             fActive, fMinimized, temp;
501         unsigned char state[256];
502         unsigned char asciichar[4];
503         int             vkey;
504         int             charlength;
505         qboolean down = false;
506
507         if ( uMsg == uiWheelMessage )
508                 uMsg = WM_MOUSEWHEEL;
509
510         switch (uMsg)
511         {
512                 case WM_KILLFOCUS:
513                         if (vid_isfullscreen)
514                                 ShowWindow(mainwindow, SW_SHOWMINNOACTIVE);
515                         break;
516
517                 case WM_CREATE:
518                         break;
519
520                 case WM_MOVE:
521                         window_x = (int) LOWORD(lParam);
522                         window_y = (int) HIWORD(lParam);
523                         VID_SetMouse(false, false, false);
524                         break;
525
526                 case WM_KEYDOWN:
527                 case WM_SYSKEYDOWN:
528                         down = true;
529                 case WM_KEYUP:
530                 case WM_SYSKEYUP:
531                         vkey = MapKey(lParam, wParam);
532                         GetKeyboardState (state);
533                         // alt/ctrl/shift tend to produce funky ToAscii values,
534                         // and if it's not a single character we don't know care about it
535                         charlength = ToAscii (wParam, lParam >> 16, state, (LPWORD)asciichar, 0);
536                         if (vkey == K_ALT || vkey == K_CTRL || vkey == K_SHIFT || charlength == 0)
537                                 asciichar[0] = 0;
538                         else if( charlength == 2 ) {
539                                 asciichar[0] = asciichar[1];
540                         }
541                         if (!IN_JoystickBlockDoubledKeyEvents(vkey))
542                                 Key_Event (vkey, asciichar[0], down);
543                         break;
544
545                 case WM_SYSCHAR:
546                 // keep Alt-Space from happening
547                         break;
548
549                 case WM_SYSCOMMAND:
550                         // prevent screensaver from occuring while the active window
551                         // note: password-locked screensavers on Vista still work
552                         if (vid_activewindow && ((wParam & 0xFFF0) == SC_SCREENSAVE || (wParam & 0xFFF0) == SC_MONITORPOWER))
553                                 lRet = 0;
554                         else
555                                 lRet = DefWindowProc (hWnd, uMsg, wParam, lParam);
556                         break;
557
558         // this is complicated because Win32 seems to pack multiple mouse events into
559         // one update sometimes, so we always check all states and look for events
560                 case WM_LBUTTONDOWN:
561                 case WM_LBUTTONUP:
562                 case WM_RBUTTONDOWN:
563                 case WM_RBUTTONUP:
564                 case WM_MBUTTONDOWN:
565                 case WM_MBUTTONUP:
566                 case WM_XBUTTONDOWN:   // backslash :: imouse explorer buttons
567                 case WM_XBUTTONUP:      // backslash :: imouse explorer buttons
568                 case WM_MOUSEMOVE:
569                         temp = 0;
570
571                         if (wParam & MK_LBUTTON)
572                                 temp |= 1;
573
574                         if (wParam & MK_RBUTTON)
575                                 temp |= 2;
576
577                         if (wParam & MK_MBUTTON)
578                                 temp |= 4;
579
580                         /* backslash :: imouse explorer buttons */
581                         if (wParam & MK_XBUTTON1)
582                                 temp |= 8;
583
584                         if (wParam & MK_XBUTTON2)
585                                 temp |= 16;
586                         /* :: backslash */
587
588                         // LordHavoc: lets hope this allows more buttons in the future...
589                         if (wParam & MK_XBUTTON3)
590                                 temp |= 32;
591                         if (wParam & MK_XBUTTON4)
592                                 temp |= 64;
593                         if (wParam & MK_XBUTTON5)
594                                 temp |= 128;
595                         if (wParam & MK_XBUTTON6)
596                                 temp |= 256;
597                         if (wParam & MK_XBUTTON7)
598                                 temp |= 512;
599
600 #ifdef SUPPORTDIRECTX
601                         if (!dinput_acquired)
602 #endif
603                         {
604                                 // perform button actions
605                                 int i;
606                                 for (i=0 ; i<mouse_buttons && i < 16 ; i++)
607                                         if ((temp ^ mouse_oldbuttonstate) & (1<<i))
608                                                 Key_Event (buttonremap[i], 0, (temp & (1<<i)) != 0);
609                                 mouse_oldbuttonstate = temp;
610                         }
611
612                         break;
613
614                 // JACK: This is the mouse wheel with the Intellimouse
615                 // Its delta is either positive or neg, and we generate the proper
616                 // Event.
617                 case WM_MOUSEWHEEL:
618                         if ((short) HIWORD(wParam) > 0) {
619                                 Key_Event(K_MWHEELUP, 0, true);
620                                 Key_Event(K_MWHEELUP, 0, false);
621                         } else {
622                                 Key_Event(K_MWHEELDOWN, 0, true);
623                                 Key_Event(K_MWHEELDOWN, 0, false);
624                         }
625                         break;
626
627                 case WM_SIZE:
628                         break;
629
630                 case WM_CLOSE:
631                         if (MessageBox (mainwindow, "Are you sure you want to quit?", "Confirm Exit", MB_YESNO | MB_SETFOREGROUND | MB_ICONQUESTION) == IDYES)
632                                 Sys_Quit (0);
633
634                         break;
635
636                 case WM_ACTIVATE:
637                         fActive = LOWORD(wParam);
638                         fMinimized = (BOOL) HIWORD(wParam);
639                         AppActivate(!(fActive == WA_INACTIVE), fMinimized);
640
641                 // fix the leftover Alt from any Alt-Tab or the like that switched us away
642                         ClearAllStates ();
643
644                         break;
645
646                 //case WM_DESTROY:
647                 //      PostQuitMessage (0);
648                 //      break;
649
650                 case MM_MCINOTIFY:
651                         lRet = CDAudio_MessageHandler (hWnd, uMsg, wParam, lParam);
652                         break;
653
654                 default:
655                         /* pass all unhandled messages to DefWindowProc */
656                         lRet = DefWindowProc (hWnd, uMsg, wParam, lParam);
657                 break;
658         }
659
660         /* return 1 if handled message, 0 if not */
661         return lRet;
662 }
663
664 int VID_SetGamma(unsigned short *ramps, int rampsize)
665 {
666         HDC hdc = GetDC (NULL);
667         int i = SetDeviceGammaRamp(hdc, ramps);
668         ReleaseDC (NULL, hdc);
669         return i; // return success or failure
670 }
671
672 int VID_GetGamma(unsigned short *ramps, int rampsize)
673 {
674         HDC hdc = GetDC (NULL);
675         int i = GetDeviceGammaRamp(hdc, ramps);
676         ReleaseDC (NULL, hdc);
677         return i; // return success or failure
678 }
679
680 static HINSTANCE gldll;
681
682 static void GL_CloseLibrary(void)
683 {
684         FreeLibrary(gldll);
685         gldll = 0;
686         gl_driver[0] = 0;
687         qwglGetProcAddress = NULL;
688         gl_extensions = "";
689         gl_platform = "";
690         gl_platformextensions = "";
691 }
692
693 static int GL_OpenLibrary(const char *name)
694 {
695         Con_Printf("Loading OpenGL driver %s\n", name);
696         GL_CloseLibrary();
697         if (!(gldll = LoadLibrary(name)))
698         {
699                 Con_Printf("Unable to LoadLibrary %s\n", name);
700                 return false;
701         }
702         strlcpy(gl_driver, name, sizeof(gl_driver));
703         return true;
704 }
705
706 void *GL_GetProcAddress(const char *name)
707 {
708         void *p = NULL;
709         if (qwglGetProcAddress != NULL)
710                 p = (void *) qwglGetProcAddress(name);
711         if (p == NULL)
712                 p = (void *) GetProcAddress(gldll, name);
713         return p;
714 }
715
716 #ifndef WGL_ARB_pixel_format
717 #define WGL_NUMBER_PIXEL_FORMATS_ARB   0x2000
718 #define WGL_DRAW_TO_WINDOW_ARB         0x2001
719 #define WGL_DRAW_TO_BITMAP_ARB         0x2002
720 #define WGL_ACCELERATION_ARB           0x2003
721 #define WGL_NEED_PALETTE_ARB           0x2004
722 #define WGL_NEED_SYSTEM_PALETTE_ARB    0x2005
723 #define WGL_SWAP_LAYER_BUFFERS_ARB     0x2006
724 #define WGL_SWAP_METHOD_ARB            0x2007
725 #define WGL_NUMBER_OVERLAYS_ARB        0x2008
726 #define WGL_NUMBER_UNDERLAYS_ARB       0x2009
727 #define WGL_TRANSPARENT_ARB            0x200A
728 #define WGL_TRANSPARENT_RED_VALUE_ARB  0x2037
729 #define WGL_TRANSPARENT_GREEN_VALUE_ARB 0x2038
730 #define WGL_TRANSPARENT_BLUE_VALUE_ARB 0x2039
731 #define WGL_TRANSPARENT_ALPHA_VALUE_ARB 0x203A
732 #define WGL_TRANSPARENT_INDEX_VALUE_ARB 0x203B
733 #define WGL_SHARE_DEPTH_ARB            0x200C
734 #define WGL_SHARE_STENCIL_ARB          0x200D
735 #define WGL_SHARE_ACCUM_ARB            0x200E
736 #define WGL_SUPPORT_GDI_ARB            0x200F
737 #define WGL_SUPPORT_OPENGL_ARB         0x2010
738 #define WGL_DOUBLE_BUFFER_ARB          0x2011
739 #define WGL_STEREO_ARB                 0x2012
740 #define WGL_PIXEL_TYPE_ARB             0x2013
741 #define WGL_COLOR_BITS_ARB             0x2014
742 #define WGL_RED_BITS_ARB               0x2015
743 #define WGL_RED_SHIFT_ARB              0x2016
744 #define WGL_GREEN_BITS_ARB             0x2017
745 #define WGL_GREEN_SHIFT_ARB            0x2018
746 #define WGL_BLUE_BITS_ARB              0x2019
747 #define WGL_BLUE_SHIFT_ARB             0x201A
748 #define WGL_ALPHA_BITS_ARB             0x201B
749 #define WGL_ALPHA_SHIFT_ARB            0x201C
750 #define WGL_ACCUM_BITS_ARB             0x201D
751 #define WGL_ACCUM_RED_BITS_ARB         0x201E
752 #define WGL_ACCUM_GREEN_BITS_ARB       0x201F
753 #define WGL_ACCUM_BLUE_BITS_ARB        0x2020
754 #define WGL_ACCUM_ALPHA_BITS_ARB       0x2021
755 #define WGL_DEPTH_BITS_ARB             0x2022
756 #define WGL_STENCIL_BITS_ARB           0x2023
757 #define WGL_AUX_BUFFERS_ARB            0x2024
758 #define WGL_NO_ACCELERATION_ARB        0x2025
759 #define WGL_GENERIC_ACCELERATION_ARB   0x2026
760 #define WGL_FULL_ACCELERATION_ARB      0x2027
761 #define WGL_SWAP_EXCHANGE_ARB          0x2028
762 #define WGL_SWAP_COPY_ARB              0x2029
763 #define WGL_SWAP_UNDEFINED_ARB         0x202A
764 #define WGL_TYPE_RGBA_ARB              0x202B
765 #define WGL_TYPE_COLORINDEX_ARB        0x202C
766 #endif
767
768 #ifndef WGL_ARB_multisample
769 #define WGL_SAMPLE_BUFFERS_ARB         0x2041
770 #define WGL_SAMPLES_ARB                0x2042
771 #endif
772
773
774 static void IN_Init(void);
775 void VID_Init(void)
776 {
777         WNDCLASS wc;
778
779         InitCommonControls();
780         hIcon = LoadIcon (global_hInstance, MAKEINTRESOURCE (IDI_ICON1));
781
782         // Register the frame class
783         wc.style         = 0;
784         wc.lpfnWndProc   = (WNDPROC)MainWndProc;
785         wc.cbClsExtra    = 0;
786         wc.cbWndExtra    = 0;
787         wc.hInstance     = global_hInstance;
788         wc.hIcon         = hIcon;
789         wc.hCursor       = LoadCursor (NULL,IDC_ARROW);
790         wc.hbrBackground = NULL;
791         wc.lpszMenuName  = 0;
792         wc.lpszClassName = "DarkPlacesWindowClass";
793
794         if (!RegisterClass (&wc))
795                 Con_Printf ("Couldn't register window class\n");
796
797         memset(&initialdevmode, 0, sizeof(initialdevmode));
798         EnumDisplaySettings(NULL, ENUM_CURRENT_SETTINGS, &initialdevmode);
799
800         IN_Init();
801 }
802
803 qboolean VID_InitMode(viddef_mode_t *mode)
804 {
805         int i;
806         HDC hdc;
807         RECT rect;
808         MSG msg;
809         PIXELFORMATDESCRIPTOR pfd =
810         {
811                 sizeof(PIXELFORMATDESCRIPTOR),  // size of this pfd
812                 1,                              // version number
813                 PFD_DRAW_TO_WINDOW              // support window
814                 |  PFD_SUPPORT_OPENGL   // support OpenGL
815                 |  PFD_DOUBLEBUFFER ,   // double buffered
816                 PFD_TYPE_RGBA,                  // RGBA type
817                 24,                             // 24-bit color depth
818                 0, 0, 0, 0, 0, 0,               // color bits ignored
819                 0,                              // no alpha buffer
820                 0,                              // shift bit ignored
821                 0,                              // no accumulation buffer
822                 0, 0, 0, 0,                     // accum bits ignored
823                 32,                             // 32-bit z-buffer
824                 0,                              // no stencil buffer
825                 0,                              // no auxiliary buffer
826                 PFD_MAIN_PLANE,                 // main layer
827                 0,                              // reserved
828                 0, 0, 0                         // layer masks ignored
829         };
830         int windowpass;
831         int pixelformat, newpixelformat;
832         UINT numpixelformats;
833         DWORD WindowStyle, ExWindowStyle;
834         int CenterX, CenterY;
835         const char *gldrivername;
836         int depth;
837         DEVMODE thismode;
838         qboolean foundmode, foundgoodmode;
839         int *a;
840         float *af;
841         int attribs[128];
842         float attribsf[16];
843         int bpp = mode->bitsperpixel;
844         int width = mode->width;
845         int height = mode->height;
846         int refreshrate = (int)floor(mode->refreshrate+0.5);
847         int stereobuffer = mode->stereobuffer;
848         int samples = mode->samples;
849         int fullscreen = mode->fullscreen;
850
851         if (vid_initialized)
852                 Sys_Error("VID_InitMode called when video is already initialised");
853
854         // if stencil is enabled, ask for alpha too
855         if (bpp >= 32)
856         {
857                 pfd.cRedBits = 8;
858                 pfd.cGreenBits = 8;
859                 pfd.cBlueBits = 8;
860                 pfd.cAlphaBits = 8;
861                 pfd.cDepthBits = 24;
862                 pfd.cStencilBits = 8;
863         }
864         else
865         {
866                 pfd.cRedBits = 5;
867                 pfd.cGreenBits = 5;
868                 pfd.cBlueBits = 5;
869                 pfd.cAlphaBits = 0;
870                 pfd.cDepthBits = 16;
871                 pfd.cStencilBits = 0;
872         }
873
874         if (stereobuffer)
875                 pfd.dwFlags |= PFD_STEREO;
876
877         a = attribs;
878         af = attribsf;
879         *a++ = WGL_DRAW_TO_WINDOW_ARB;
880         *a++ = GL_TRUE;
881         *a++ = WGL_ACCELERATION_ARB;
882         *a++ = WGL_FULL_ACCELERATION_ARB;
883         *a++ = WGL_DOUBLE_BUFFER_ARB;
884         *a++ = true;
885
886         if (bpp >= 32)
887         {
888                 *a++ = WGL_RED_BITS_ARB;
889                 *a++ = 8;
890                 *a++ = WGL_GREEN_BITS_ARB;
891                 *a++ = 8;
892                 *a++ = WGL_BLUE_BITS_ARB;
893                 *a++ = 8;
894                 *a++ = WGL_ALPHA_BITS_ARB;
895                 *a++ = 8;
896                 *a++ = WGL_DEPTH_BITS_ARB;
897                 *a++ = 24;
898                 *a++ = WGL_STENCIL_BITS_ARB;
899                 *a++ = 8;
900         }
901         else
902         {
903                 *a++ = WGL_RED_BITS_ARB;
904                 *a++ = 1;
905                 *a++ = WGL_GREEN_BITS_ARB;
906                 *a++ = 1;
907                 *a++ = WGL_BLUE_BITS_ARB;
908                 *a++ = 1;
909                 *a++ = WGL_DEPTH_BITS_ARB;
910                 *a++ = 16;
911         }
912
913         if (stereobuffer)
914         {
915                 *a++ = WGL_STEREO_ARB;
916                 *a++ = GL_TRUE;
917         }
918
919         if (samples > 1)
920         {
921                 *a++ = WGL_SAMPLE_BUFFERS_ARB;
922                 *a++ = 1;
923                 *a++ = WGL_SAMPLES_ARB;
924                 *a++ = samples;
925         }
926
927         *a = 0;
928         *af = 0;
929
930         gldrivername = "opengl32.dll";
931 // COMMANDLINEOPTION: Windows WGL: -gl_driver <drivername> selects a GL driver library, default is opengl32.dll, useful only for 3dfxogl.dll or 3dfxvgl.dll, if you don't know what this is for, you don't need it
932         i = COM_CheckParm("-gl_driver");
933         if (i && i < com_argc - 1)
934                 gldrivername = com_argv[i + 1];
935         if (!GL_OpenLibrary(gldrivername))
936         {
937                 Con_Printf("Unable to load GL driver %s\n", gldrivername);
938                 return false;
939         }
940
941         memset(&gdevmode, 0, sizeof(gdevmode));
942
943         vid_isfullscreen = false;
944         if (fullscreen)
945         {
946                 if(vid_forcerefreshrate.integer)
947                 {
948                         foundmode = true;
949                         gdevmode.dmFields = DM_BITSPERPEL | DM_PELSWIDTH | DM_PELSHEIGHT;
950                         gdevmode.dmBitsPerPel = bpp;
951                         gdevmode.dmPelsWidth = width;
952                         gdevmode.dmPelsHeight = height;
953                         gdevmode.dmSize = sizeof (gdevmode);
954                         if(refreshrate)
955                         {
956                                 gdevmode.dmFields |= DM_DISPLAYFREQUENCY;
957                                 gdevmode.dmDisplayFrequency = refreshrate;
958                         }
959                 }
960                 else
961                 {
962                         if(refreshrate == 0)
963                                 refreshrate = initialdevmode.dmDisplayFrequency; // default vid_refreshrate to the rate of the desktop
964
965                         foundmode = false;
966                         foundgoodmode = false;
967
968                         thismode.dmSize = sizeof(thismode);
969                         thismode.dmDriverExtra = 0;
970                         for(i = 0; EnumDisplaySettings(NULL, i, &thismode); ++i)
971                         {
972                                 if(~thismode.dmFields & (DM_BITSPERPEL | DM_PELSWIDTH | DM_PELSHEIGHT | DM_DISPLAYFREQUENCY))
973                                 {
974                                         Con_DPrintf("enumerating modes yielded a bogus item... please debug this\n");
975                                         continue;
976                                 }
977                                 if(developer_extra.integer)
978                                         Con_DPrintf("Found mode %dx%dx%dbpp %dHz... ", (int)thismode.dmPelsWidth, (int)thismode.dmPelsHeight, (int)thismode.dmBitsPerPel, (int)thismode.dmDisplayFrequency);
979                                 if(thismode.dmBitsPerPel != (DWORD)bpp)
980                                 {
981                                         if(developer_extra.integer)
982                                                 Con_DPrintf("wrong bpp\n");
983                                         continue;
984                                 }
985                                 if(thismode.dmPelsWidth != (DWORD)width)
986                                 {
987                                         if(developer_extra.integer)
988                                                 Con_DPrintf("wrong width\n");
989                                         continue;
990                                 }
991                                 if(thismode.dmPelsHeight != (DWORD)height)
992                                 {
993                                         if(developer_extra.integer)
994                                                 Con_DPrintf("wrong height\n");
995                                         continue;
996                                 }
997
998                                 if(foundgoodmode)
999                                 {
1000                                         // if we have a good mode, make sure this mode is better than the previous one, and allowed by the refreshrate
1001                                         if(thismode.dmDisplayFrequency > (DWORD)refreshrate)
1002                                         {
1003                                                 if(developer_extra.integer)
1004                                                         Con_DPrintf("too high refresh rate\n");
1005                                                 continue;
1006                                         }
1007                                         else if(thismode.dmDisplayFrequency <= gdevmode.dmDisplayFrequency)
1008                                         {
1009                                                 if(developer_extra.integer)
1010                                                         Con_DPrintf("doesn't beat previous best match (too low)\n");
1011                                                 continue;
1012                                         }
1013                                 }
1014                                 else if(foundmode)
1015                                 {
1016                                         // we do have one, but it isn't good... make sure it has a lower frequency than the previous one
1017                                         if(thismode.dmDisplayFrequency >= gdevmode.dmDisplayFrequency)
1018                                         {
1019                                                 if(developer_extra.integer)
1020                                                         Con_DPrintf("doesn't beat previous best match (too high)\n");
1021                                                 continue;
1022                                         }
1023                                 }
1024                                 // otherwise, take anything
1025
1026                                 memcpy(&gdevmode, &thismode, sizeof(gdevmode));
1027                                 if(thismode.dmDisplayFrequency <= (DWORD)refreshrate)
1028                                         foundgoodmode = true;
1029                                 else
1030                                 {
1031                                         if(developer_extra.integer)
1032                                                 Con_DPrintf("(out of range)\n");
1033                                 }
1034                                 foundmode = true;
1035                                 if(developer_extra.integer)
1036                                         Con_DPrintf("accepted\n");
1037                         }
1038                 }
1039
1040                 if (!foundmode)
1041                 {
1042                         VID_Shutdown();
1043                         Con_Printf("Unable to find the requested mode %dx%dx%dbpp\n", width, height, bpp);
1044                         return false;
1045                 }
1046                 else if(ChangeDisplaySettings (&gdevmode, CDS_FULLSCREEN) != DISP_CHANGE_SUCCESSFUL)
1047                 {
1048                         VID_Shutdown();
1049                         Con_Printf("Unable to change to requested mode %dx%dx%dbpp\n", width, height, bpp);
1050                         return false;
1051                 }
1052
1053                 vid_isfullscreen = true;
1054                 WindowStyle = WS_POPUP;
1055                 ExWindowStyle = WS_EX_TOPMOST;
1056         }
1057         else
1058         {
1059                 hdc = GetDC (NULL);
1060                 i = GetDeviceCaps(hdc, RASTERCAPS);
1061                 depth = GetDeviceCaps(hdc, PLANES) * GetDeviceCaps(hdc, BITSPIXEL);
1062                 ReleaseDC (NULL, hdc);
1063                 if (i & RC_PALETTE)
1064                 {
1065                         VID_Shutdown();
1066                         Con_Print("Can't run in non-RGB mode\n");
1067                         return false;
1068                 }
1069                 if (bpp > depth)
1070                 {
1071                         VID_Shutdown();
1072                         Con_Print("A higher desktop depth is required to run this video mode\n");
1073                         return false;
1074                 }
1075
1076                 WindowStyle = WS_OVERLAPPED | WS_BORDER | WS_CAPTION | WS_SYSMENU | WS_MINIMIZEBOX;
1077                 ExWindowStyle = 0;
1078         }
1079
1080         rect.top = 0;
1081         rect.left = 0;
1082         rect.right = width;
1083         rect.bottom = height;
1084         AdjustWindowRectEx(&rect, WindowStyle, false, 0);
1085
1086         if (fullscreen)
1087         {
1088                 CenterX = 0;
1089                 CenterY = 0;
1090         }
1091         else
1092         {
1093                 CenterX = (GetSystemMetrics(SM_CXSCREEN) - (rect.right - rect.left)) / 2;
1094                 CenterY = (GetSystemMetrics(SM_CYSCREEN) - (rect.bottom - rect.top)) / 2;
1095         }
1096         CenterX = max(0, CenterX);
1097         CenterY = max(0, CenterY);
1098
1099         // x and y may be changed by WM_MOVE messages
1100         window_x = CenterX;
1101         window_y = CenterY;
1102         rect.left += CenterX;
1103         rect.right += CenterX;
1104         rect.top += CenterY;
1105         rect.bottom += CenterY;
1106
1107         pixelformat = 0;
1108         newpixelformat = 0;
1109         // start out at the final windowpass if samples is 1 as it's the only feature we need extended pixel formats for
1110         for (windowpass = samples == 1;windowpass < 2;windowpass++)
1111         {
1112                 gl_extensions = "";
1113                 gl_platformextensions = "";
1114
1115                 mainwindow = CreateWindowEx (ExWindowStyle, "DarkPlacesWindowClass", gamename, WindowStyle, rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top, NULL, NULL, global_hInstance, NULL);
1116                 if (!mainwindow)
1117                 {
1118                         Con_Printf("CreateWindowEx(%d, %s, %s, %d, %d, %d, %d, %d, %p, %p, %p, %p) failed\n", (int)ExWindowStyle, "DarkPlacesWindowClass", gamename, (int)WindowStyle, (int)(rect.left), (int)(rect.top), (int)(rect.right - rect.left), (int)(rect.bottom - rect.top), NULL, NULL, global_hInstance, NULL);
1119                         VID_Shutdown();
1120                         return false;
1121                 }
1122
1123                 baseDC = GetDC(mainwindow);
1124
1125                 if (!newpixelformat)
1126                         newpixelformat = ChoosePixelFormat(baseDC, &pfd);
1127                 pixelformat = newpixelformat;
1128                 if (!pixelformat)
1129                 {
1130                         VID_Shutdown();
1131                         Con_Printf("ChoosePixelFormat(%p, %p) failed\n", baseDC, &pfd);
1132                         return false;
1133                 }
1134
1135                 if (SetPixelFormat(baseDC, pixelformat, &pfd) == false)
1136                 {
1137                         VID_Shutdown();
1138                         Con_Printf("SetPixelFormat(%p, %d, %p) failed\n", baseDC, pixelformat, &pfd);
1139                         return false;
1140                 }
1141
1142                 if (!GL_CheckExtension("wgl", wglfuncs, NULL, false))
1143                 {
1144                         VID_Shutdown();
1145                         Con_Print("wgl functions not found\n");
1146                         return false;
1147                 }
1148
1149                 baseRC = qwglCreateContext(baseDC);
1150                 if (!baseRC)
1151                 {
1152                         VID_Shutdown();
1153                         Con_Print("Could not initialize GL (wglCreateContext failed).\n\nMake sure you are in 65536 color mode, and try running -window.\n");
1154                         return false;
1155                 }
1156                 if (!qwglMakeCurrent(baseDC, baseRC))
1157                 {
1158                         VID_Shutdown();
1159                         Con_Printf("wglMakeCurrent(%p, %p) failed\n", baseDC, baseRC);
1160                         return false;
1161                 }
1162
1163                 if ((qglGetString = (const GLubyte* (GLAPIENTRY *)(GLenum name))GL_GetProcAddress("glGetString")) == NULL)
1164                 {
1165                         VID_Shutdown();
1166                         Con_Print("glGetString not found\n");
1167                         return false;
1168                 }
1169                 if ((qwglGetExtensionsStringARB = (const char *(WINAPI *)(HDC hdc))GL_GetProcAddress("wglGetExtensionsStringARB")) == NULL)
1170                         Con_Print("wglGetExtensionsStringARB not found\n");
1171
1172                 gl_extensions = (const char *)qglGetString(GL_EXTENSIONS);
1173                 gl_platform = "WGL";
1174                 gl_platformextensions = "";
1175
1176                 if (qwglGetExtensionsStringARB)
1177                         gl_platformextensions = (const char *)qwglGetExtensionsStringARB(baseDC);
1178
1179                 if (!gl_extensions)
1180                         gl_extensions = "";
1181                 if (!gl_platformextensions)
1182                         gl_platformextensions = "";
1183
1184                 // now some nice Windows pain:
1185                 // we have created a window, we needed one to find out if there are
1186                 // any multisample pixel formats available, the problem is that to
1187                 // actually use one of those multisample formats we now have to
1188                 // recreate the window (yes Microsoft OpenGL really is that bad)
1189
1190                 if (windowpass == 0)
1191                 {
1192                         if (!GL_CheckExtension("WGL_ARB_pixel_format", wglpixelformatfuncs, "-noarbpixelformat", false) || !qwglChoosePixelFormatARB(baseDC, attribs, attribsf, 1, &newpixelformat, &numpixelformats) || !newpixelformat)
1193                                 break;
1194                         // ok we got one - do it all over again with newpixelformat
1195                         qwglMakeCurrent(NULL, NULL);
1196                         qwglDeleteContext(baseRC);baseRC = 0;
1197                         ReleaseDC(mainwindow, baseDC);baseDC = 0;
1198                         // eat up any messages waiting for us
1199                         while (PeekMessage (&msg, NULL, 0, 0, PM_REMOVE))
1200                         {
1201                                 TranslateMessage (&msg);
1202                                 DispatchMessage (&msg);
1203                         }
1204                 }
1205         }
1206
1207         /*
1208         if (!fullscreen)
1209                 SetWindowPos (mainwindow, NULL, CenterX, CenterY, 0, 0,SWP_NOSIZE | SWP_NOZORDER | SWP_SHOWWINDOW | SWP_DRAWFRAME);
1210         */
1211
1212         ShowWindow (mainwindow, SW_SHOWDEFAULT);
1213         UpdateWindow (mainwindow);
1214
1215         // now we try to make sure we get the focus on the mode switch, because
1216         // sometimes in some systems we don't.  We grab the foreground, then
1217         // finish setting up, pump all our messages, and sleep for a little while
1218         // to let messages finish bouncing around the system, then we put
1219         // ourselves at the top of the z order, then grab the foreground again,
1220         // Who knows if it helps, but it probably doesn't hurt
1221         SetForegroundWindow (mainwindow);
1222
1223         while (PeekMessage (&msg, NULL, 0, 0, PM_REMOVE))
1224         {
1225                 TranslateMessage (&msg);
1226                 DispatchMessage (&msg);
1227         }
1228
1229         Sleep (100);
1230
1231         SetWindowPos (mainwindow, HWND_TOP, 0, 0, 0, 0, SWP_DRAWFRAME | SWP_NOMOVE | SWP_NOSIZE | SWP_SHOWWINDOW | SWP_NOCOPYBITS);
1232
1233         SetForegroundWindow (mainwindow);
1234
1235         // fix the leftover Alt from any Alt-Tab or the like that switched us away
1236         ClearAllStates ();
1237
1238 // COMMANDLINEOPTION: Windows WGL: -novideosync disables WGL_EXT_swap_control
1239         GL_CheckExtension("WGL_EXT_swap_control", wglswapintervalfuncs, "-novideosync", false);
1240
1241         GL_Init ();
1242
1243         //vid_menudrawfn = VID_MenuDraw;
1244         //vid_menukeyfn = VID_MenuKey;
1245         vid_usingmouse = false;
1246         vid_usinghidecursor = false;
1247         vid_usingvsync = false;
1248         vid_hidden = false;
1249         vid_initialized = true;
1250
1251         IN_StartupMouse ();
1252         IN_StartupJoystick ();
1253
1254         if (qwglSwapIntervalEXT)
1255         {
1256                 vid_usevsync = vid_vsync.integer != 0;
1257                 vid_usingvsync = vid_vsync.integer != 0;
1258                 qwglSwapIntervalEXT (vid_usevsync);
1259         }
1260
1261         return true;
1262 }
1263
1264 static void IN_Shutdown(void);
1265 void VID_Shutdown (void)
1266 {
1267         if(vid_initialized == false)
1268                 return;
1269
1270         VID_SetMouse(false, false, false);
1271         VID_RestoreSystemGamma();
1272
1273         vid_initialized = false;
1274         IN_Shutdown();
1275         if (qwglMakeCurrent)
1276                 qwglMakeCurrent(NULL, NULL);
1277         if (baseRC && qwglDeleteContext)
1278                 qwglDeleteContext(baseRC);
1279         // close the library before we get rid of the window
1280         GL_CloseLibrary();
1281         if (baseDC && mainwindow)
1282                 ReleaseDC(mainwindow, baseDC);
1283         AppActivate(false, false);
1284         if (mainwindow)
1285                 DestroyWindow(mainwindow);
1286         mainwindow = 0;
1287         if (vid_isfullscreen)
1288                 ChangeDisplaySettings (NULL, 0);
1289         vid_isfullscreen = false;
1290 }
1291
1292 void VID_SetMouse(qboolean fullscreengrab, qboolean relative, qboolean hidecursor)
1293 {
1294         static qboolean restore_spi;
1295         static int originalmouseparms[3];
1296
1297         if (!mouseinitialized)
1298                 return;
1299
1300         if (relative)
1301         {
1302                 if (!vid_usingmouse)
1303                 {
1304                         vid_usingmouse = true;
1305                         cl_ignoremousemoves = 2;
1306 #ifdef SUPPORTDIRECTX
1307                         if (dinput && g_pMouse)
1308                         {
1309                                 IDirectInputDevice_Acquire(g_pMouse);
1310                                 dinput_acquired = true;
1311                         }
1312                         else
1313 #endif
1314                         {
1315                                 RECT window_rect;
1316                                 window_rect.left = window_x;
1317                                 window_rect.top = window_y;
1318                                 window_rect.right = window_x + vid.width;
1319                                 window_rect.bottom = window_y + vid.height;
1320
1321                                 // change mouse settings to turn off acceleration
1322 // COMMANDLINEOPTION: Windows GDI Input: -noforcemparms disables setting of mouse parameters (not used with -dinput, windows only)
1323                                 if (!COM_CheckParm ("-noforcemparms") && SystemParametersInfo (SPI_GETMOUSE, 0, originalmouseparms, 0))
1324                                 {
1325                                         int newmouseparms[3];
1326                                         newmouseparms[0] = 0; // threshold to double movement (only if accel level is >= 1)
1327                                         newmouseparms[1] = 0; // threshold to quadruple movement (only if accel level is >= 2)
1328                                         newmouseparms[2] = 0; // maximum level of acceleration (0 = off)
1329                                         restore_spi = SystemParametersInfo (SPI_SETMOUSE, 0, newmouseparms, 0) != FALSE;
1330                                 }
1331                                 else
1332                                         restore_spi = false;
1333                                 SetCursorPos ((window_x + vid.width / 2), (window_y + vid.height / 2));
1334
1335                                 SetCapture (mainwindow);
1336                                 ClipCursor (&window_rect);
1337                         }
1338                 }
1339         }
1340         else
1341         {
1342                 if (vid_usingmouse)
1343                 {
1344                         vid_usingmouse = false;
1345                         cl_ignoremousemoves = 2;
1346 #ifdef SUPPORTDIRECTX
1347                         if (dinput_acquired)
1348                         {
1349                                 IDirectInputDevice_Unacquire(g_pMouse);
1350                                 dinput_acquired = false;
1351                         }
1352                         else
1353 #endif
1354                         {
1355                                 // restore system mouseparms if we changed them
1356                                 if (restore_spi)
1357                                         SystemParametersInfo (SPI_SETMOUSE, 0, originalmouseparms, 0);
1358                                 restore_spi = false;
1359                                 ClipCursor (NULL);
1360                                 ReleaseCapture ();
1361                         }
1362                 }
1363         }
1364
1365         if (vid_usinghidecursor != hidecursor)
1366         {
1367                 vid_usinghidecursor = hidecursor;
1368                 ShowCursor (!hidecursor);
1369         }
1370 }
1371
1372
1373 #ifdef SUPPORTDIRECTX
1374 /*
1375 ===========
1376 IN_InitDInput
1377 ===========
1378 */
1379 static qboolean IN_InitDInput (void)
1380 {
1381     HRESULT             hr;
1382         DIPROPDWORD     dipdw = {
1383                 {
1384                         sizeof(DIPROPDWORD),        // diph.dwSize
1385                         sizeof(DIPROPHEADER),       // diph.dwHeaderSize
1386                         0,                          // diph.dwObj
1387                         DIPH_DEVICE,                // diph.dwHow
1388                 },
1389                 DINPUT_BUFFERSIZE,              // dwData
1390         };
1391
1392         if (!hInstDI)
1393         {
1394                 hInstDI = LoadLibrary("dinput.dll");
1395
1396                 if (hInstDI == NULL)
1397                 {
1398                         Con_Print("Couldn't load dinput.dll\n");
1399                         return false;
1400                 }
1401         }
1402
1403         if (!pDirectInputCreate)
1404         {
1405                 pDirectInputCreate = (HRESULT (__stdcall *)(HINSTANCE,DWORD,LPDIRECTINPUT *,LPUNKNOWN))GetProcAddress(hInstDI,"DirectInputCreateA");
1406
1407                 if (!pDirectInputCreate)
1408                 {
1409                         Con_Print("Couldn't get DI proc addr\n");
1410                         return false;
1411                 }
1412         }
1413
1414 // register with DirectInput and get an IDirectInput to play with.
1415         hr = iDirectInputCreate(global_hInstance, DIRECTINPUT_VERSION, &g_pdi, NULL);
1416
1417         if (FAILED(hr))
1418         {
1419                 return false;
1420         }
1421
1422 // obtain an interface to the system mouse device.
1423 #ifdef __cplusplus
1424         hr = IDirectInput_CreateDevice(g_pdi, GUID_SysMouse, &g_pMouse, NULL);
1425 #else
1426         hr = IDirectInput_CreateDevice(g_pdi, &GUID_SysMouse, &g_pMouse, NULL);
1427 #endif
1428
1429         if (FAILED(hr))
1430         {
1431                 Con_Print("Couldn't open DI mouse device\n");
1432                 return false;
1433         }
1434
1435 // set the data format to "mouse format".
1436         hr = IDirectInputDevice_SetDataFormat(g_pMouse, &c_dfDIMouse);
1437
1438         if (FAILED(hr))
1439         {
1440                 Con_Print("Couldn't set DI mouse format\n");
1441                 return false;
1442         }
1443
1444 // set the cooperativity level.
1445         hr = IDirectInputDevice_SetCooperativeLevel(g_pMouse, mainwindow,
1446                         DISCL_EXCLUSIVE | DISCL_FOREGROUND);
1447
1448         if (FAILED(hr))
1449         {
1450                 Con_Print("Couldn't set DI coop level\n");
1451                 return false;
1452         }
1453
1454
1455 // set the buffer size to DINPUT_BUFFERSIZE elements.
1456 // the buffer size is a DWORD property associated with the device
1457         hr = IDirectInputDevice_SetProperty(g_pMouse, DIPROP_BUFFERSIZE, &dipdw.diph);
1458
1459         if (FAILED(hr))
1460         {
1461                 Con_Print("Couldn't set DI buffersize\n");
1462                 return false;
1463         }
1464
1465         return true;
1466 }
1467 #endif
1468
1469
1470 /*
1471 ===========
1472 IN_StartupMouse
1473 ===========
1474 */
1475 static void IN_StartupMouse (void)
1476 {
1477         if (COM_CheckParm ("-nomouse"))
1478                 return;
1479
1480         mouseinitialized = true;
1481
1482 #ifdef SUPPORTDIRECTX
1483 // COMMANDLINEOPTION: Windows Input: -dinput enables DirectInput for mouse/joystick input
1484         if (COM_CheckParm ("-dinput"))
1485                 dinput = IN_InitDInput ();
1486
1487         if (dinput)
1488                 Con_Print("DirectInput initialized\n");
1489         else
1490                 Con_Print("DirectInput not initialized\n");
1491 #endif
1492
1493         mouse_buttons = 10;
1494 }
1495
1496
1497 /*
1498 ===========
1499 IN_MouseMove
1500 ===========
1501 */
1502 static void IN_MouseMove (void)
1503 {
1504         POINT current_pos;
1505
1506         GetCursorPos (&current_pos);
1507         in_windowmouse_x = current_pos.x - window_x;
1508         in_windowmouse_y = current_pos.y - window_y;
1509
1510         if (!vid_usingmouse)
1511                 return;
1512
1513 #ifdef SUPPORTDIRECTX
1514         if (dinput_acquired)
1515         {
1516                 int i;
1517                 DIDEVICEOBJECTDATA      od;
1518                 DWORD                           dwElements;
1519                 HRESULT                         hr;
1520
1521                 for (;;)
1522                 {
1523                         dwElements = 1;
1524
1525                         hr = IDirectInputDevice_GetDeviceData(g_pMouse,
1526                                         sizeof(DIDEVICEOBJECTDATA), &od, &dwElements, 0);
1527
1528                         if ((hr == DIERR_INPUTLOST) || (hr == DIERR_NOTACQUIRED))
1529                         {
1530                                 IDirectInputDevice_Acquire(g_pMouse);
1531                                 break;
1532                         }
1533
1534                         /* Unable to read data or no data available */
1535                         if (FAILED(hr) || dwElements == 0)
1536                                 break;
1537
1538                         /* Look at the element to see what happened */
1539
1540                         switch (od.dwOfs)
1541                         {
1542                                 case DIMOFS_X:
1543                                         in_mouse_x += (LONG) od.dwData;
1544                                         break;
1545
1546                                 case DIMOFS_Y:
1547                                         in_mouse_y += (LONG) od.dwData;
1548                                         break;
1549
1550                                 case DIMOFS_Z:
1551                                         if((LONG) od.dwData < 0)
1552                                         {
1553                                                 Key_Event (K_MWHEELDOWN, 0, true);
1554                                                 Key_Event (K_MWHEELDOWN, 0, false);
1555                                         }
1556                                         else if((LONG) od.dwData > 0)
1557                                         {
1558                                                 Key_Event (K_MWHEELUP, 0, true);
1559                                                 Key_Event (K_MWHEELUP, 0, false);
1560                                         }
1561                                         break;
1562
1563                                 case DIMOFS_BUTTON0:
1564                                         if (od.dwData & 0x80)
1565                                                 mstate_di |= 1;
1566                                         else
1567                                                 mstate_di &= ~1;
1568                                         break;
1569
1570                                 case DIMOFS_BUTTON1:
1571                                         if (od.dwData & 0x80)
1572                                                 mstate_di |= (1<<1);
1573                                         else
1574                                                 mstate_di &= ~(1<<1);
1575                                         break;
1576
1577                                 case DIMOFS_BUTTON2:
1578                                         if (od.dwData & 0x80)
1579                                                 mstate_di |= (1<<2);
1580                                         else
1581                                                 mstate_di &= ~(1<<2);
1582                                         break;
1583
1584                                 case DIMOFS_BUTTON3:
1585                                         if (od.dwData & 0x80)
1586                                                 mstate_di |= (1<<3);
1587                                         else
1588                                                 mstate_di &= ~(1<<3);
1589                                         break;
1590                         }
1591                 }
1592
1593                 // perform button actions
1594                 for (i=0 ; i<mouse_buttons && i < 16 ; i++)
1595                         if ((mstate_di ^ mouse_oldbuttonstate) & (1<<i))
1596                                 Key_Event (buttonremap[i], 0, (mstate_di & (1<<i)) != 0);
1597                 mouse_oldbuttonstate = mstate_di;
1598         }
1599         else
1600 #endif
1601         {
1602                 in_mouse_x += in_windowmouse_x - (int)(vid.width / 2);
1603                 in_mouse_y += in_windowmouse_y - (int)(vid.height / 2);
1604
1605                 // if the mouse has moved, force it to the center, so there's room to move
1606                 if (in_mouse_x || in_mouse_y)
1607                         SetCursorPos ((window_x + vid.width / 2), (window_y + vid.height / 2));
1608         }
1609 }
1610
1611
1612 /*
1613 ===========
1614 IN_Move
1615 ===========
1616 */
1617 void IN_Move (void)
1618 {
1619         if (vid_activewindow && !vid_hidden)
1620         {
1621                 IN_MouseMove ();
1622                 IN_JoyMove ();
1623         }
1624 }
1625
1626
1627 /*
1628 ===============
1629 IN_StartupJoystick
1630 ===============
1631 */
1632 static void IN_StartupJoystick (void)
1633 {
1634         int                     numdevs;
1635         JOYCAPS         jc;
1636         MMRESULT        mmr;
1637         mmr = 0;
1638
1639         // assume no joystick
1640         joy_avail = false;
1641
1642         // abort startup if user requests no joystick
1643 // COMMANDLINEOPTION: Windows Input: -nojoy disables joystick support, may be a small speed increase
1644         if (COM_CheckParm ("-nojoy"))
1645                 return;
1646
1647         // verify joystick driver is present
1648         if ((numdevs = joyGetNumDevs ()) == 0)
1649         {
1650                 Con_Print("\njoystick not found -- driver not present\n\n");
1651                 return;
1652         }
1653
1654         // cycle through the joystick ids for the first valid one
1655         for (joy_id=0 ; joy_id<numdevs ; joy_id++)
1656         {
1657                 memset (&ji, 0, sizeof(ji));
1658                 ji.dwSize = sizeof(ji);
1659                 ji.dwFlags = JOY_RETURNCENTERED;
1660
1661                 if ((mmr = joyGetPosEx (joy_id, &ji)) == JOYERR_NOERROR)
1662                         break;
1663         }
1664
1665         // abort startup if we didn't find a valid joystick
1666         if (mmr != JOYERR_NOERROR)
1667         {
1668                 Con_Printf("\njoystick not found -- no valid joysticks (%x)\n\n", mmr);
1669                 return;
1670         }
1671
1672         // get the capabilities of the selected joystick
1673         // abort startup if command fails
1674         memset (&jc, 0, sizeof(jc));
1675         if ((mmr = joyGetDevCaps (joy_id, &jc, sizeof(jc))) != JOYERR_NOERROR)
1676         {
1677                 Con_Printf("\njoystick not found -- invalid joystick capabilities (%x)\n\n", mmr);
1678                 return;
1679         }
1680
1681         // save the joystick's number of buttons and POV status
1682         joy_numbuttons = jc.wNumButtons;
1683         joy_haspov = (jc.wCaps & JOYCAPS_HASPOV) != 0;
1684
1685         // old button and POV states default to no buttons pressed
1686         joy_oldbuttonstate = joy_oldpovstate = 0;
1687
1688         // mark the joystick as available and advanced initialization not completed
1689         // this is needed as cvars are not available during initialization
1690
1691         joy_avail = true;
1692         joy_advancedinit = false;
1693
1694         Con_Print("\njoystick detected\n\n");
1695 }
1696
1697
1698 /*
1699 ===========
1700 RawValuePointer
1701 ===========
1702 */
1703 static PDWORD RawValuePointer (int axis)
1704 {
1705         switch (axis)
1706         {
1707         case JOY_AXIS_X:
1708                 return &ji.dwXpos;
1709         case JOY_AXIS_Y:
1710                 return &ji.dwYpos;
1711         case JOY_AXIS_Z:
1712                 return &ji.dwZpos;
1713         case JOY_AXIS_R:
1714                 return &ji.dwRpos;
1715         case JOY_AXIS_U:
1716                 return &ji.dwUpos;
1717         case JOY_AXIS_V:
1718                 return &ji.dwVpos;
1719         }
1720         return NULL; // LordHavoc: hush compiler warning
1721 }
1722
1723
1724 /*
1725 ===========
1726 Joy_AdvancedUpdate_f
1727 ===========
1728 */
1729 static void Joy_AdvancedUpdate_f (void)
1730 {
1731
1732         // called once by IN_ReadJoystick and by user whenever an update is needed
1733         // cvars are now available
1734         int     i;
1735         DWORD dwTemp;
1736
1737         // initialize all the maps
1738         for (i = 0; i < JOY_MAX_AXES; i++)
1739         {
1740                 dwAxisMap[i] = AxisNada;
1741                 dwControlMap[i] = JOY_ABSOLUTE_AXIS;
1742                 pdwRawValue[i] = RawValuePointer(i);
1743         }
1744
1745         if( joy_advanced.integer == 0)
1746         {
1747                 // default joystick initialization
1748                 // 2 axes only with joystick control
1749                 dwAxisMap[JOY_AXIS_X] = AxisTurn;
1750                 // dwControlMap[JOY_AXIS_X] = JOY_ABSOLUTE_AXIS;
1751                 dwAxisMap[JOY_AXIS_Y] = AxisForward;
1752                 // dwControlMap[JOY_AXIS_Y] = JOY_ABSOLUTE_AXIS;
1753         }
1754         else
1755         {
1756                 if (strcmp (joy_name.string, "joystick") != 0)
1757                 {
1758                         // notify user of advanced controller
1759                         Con_Printf("\n%s configured\n\n", joy_name.string);
1760                 }
1761
1762                 // advanced initialization here
1763                 // data supplied by user via joy_axisn cvars
1764                 dwTemp = (DWORD) joy_advaxisx.value;
1765                 dwAxisMap[JOY_AXIS_X] = dwTemp & 0x0000000f;
1766                 dwControlMap[JOY_AXIS_X] = dwTemp & JOY_RELATIVE_AXIS;
1767                 dwTemp = (DWORD) joy_advaxisy.value;
1768                 dwAxisMap[JOY_AXIS_Y] = dwTemp & 0x0000000f;
1769                 dwControlMap[JOY_AXIS_Y] = dwTemp & JOY_RELATIVE_AXIS;
1770                 dwTemp = (DWORD) joy_advaxisz.value;
1771                 dwAxisMap[JOY_AXIS_Z] = dwTemp & 0x0000000f;
1772                 dwControlMap[JOY_AXIS_Z] = dwTemp & JOY_RELATIVE_AXIS;
1773                 dwTemp = (DWORD) joy_advaxisr.value;
1774                 dwAxisMap[JOY_AXIS_R] = dwTemp & 0x0000000f;
1775                 dwControlMap[JOY_AXIS_R] = dwTemp & JOY_RELATIVE_AXIS;
1776                 dwTemp = (DWORD) joy_advaxisu.value;
1777                 dwAxisMap[JOY_AXIS_U] = dwTemp & 0x0000000f;
1778                 dwControlMap[JOY_AXIS_U] = dwTemp & JOY_RELATIVE_AXIS;
1779                 dwTemp = (DWORD) joy_advaxisv.value;
1780                 dwAxisMap[JOY_AXIS_V] = dwTemp & 0x0000000f;
1781                 dwControlMap[JOY_AXIS_V] = dwTemp & JOY_RELATIVE_AXIS;
1782         }
1783
1784         // compute the axes to collect from DirectInput
1785         joy_flags = JOY_RETURNCENTERED | JOY_RETURNBUTTONS | JOY_RETURNPOV;
1786         for (i = 0; i < JOY_MAX_AXES; i++)
1787         {
1788                 if (dwAxisMap[i] != AxisNada)
1789                 {
1790                         joy_flags |= dwAxisFlags[i];
1791                 }
1792         }
1793 }
1794
1795 /*
1796 ===============
1797 IN_ReadJoystick
1798 ===============
1799 */
1800 static qboolean IN_ReadJoystick (void)
1801 {
1802
1803         memset (&ji, 0, sizeof(ji));
1804         ji.dwSize = sizeof(ji);
1805         ji.dwFlags = joy_flags;
1806
1807         if (joyGetPosEx (joy_id, &ji) == JOYERR_NOERROR)
1808         {
1809                 // this is a hack -- there is a bug in the Logitech WingMan Warrior DirectInput Driver
1810                 // rather than having 32768 be the zero point, they have the zero point at 32668
1811                 // go figure -- anyway, now we get the full resolution out of the device
1812                 if (joy_wwhack1.integer != 0.0)
1813                 {
1814                         ji.dwUpos += 100;
1815                 }
1816                 return true;
1817         }
1818         else
1819         {
1820                 // read error occurred
1821                 // turning off the joystick seems too harsh for 1 read error,
1822                 // but what should be done?
1823                 return false;
1824         }
1825 }
1826
1827 /*
1828 ===========
1829  IN_JoystickGetAxisNum
1830 ===========
1831 */
1832
1833 int IN_JoystickGetAxisNum(int ControlListType)
1834 {
1835         int i;
1836
1837         for (i = 0; i < JOY_MAX_AXES; i++)
1838                 if (dwAxisMap[i] == ControlListType)
1839                         return i;
1840         return -1;
1841 }
1842
1843 /*
1844 ===========
1845  IN_JoystickGetAxis
1846 ===========
1847 */
1848 static double IN_JoystickGetAxis(int axis, double sensitivity, double deadzone)
1849 {
1850         float   fAxisValue, fTemp;
1851
1852         if (!joy_avail || axis < 0 || axis >= JOY_MAX_AXES)
1853                 return 0; // no such axis on this joystick
1854
1855         // get the floating point zero-centered, potentially-inverted data for the current axis
1856         fAxisValue = (float) *pdwRawValue[axis];
1857
1858         // move centerpoint to zero
1859         fAxisValue -= 32768.0;
1860
1861         if (joy_wwhack2.integer != 0.0)
1862         {
1863                 if (dwAxisMap[axis] == AxisTurn)
1864                 {
1865                         // this is a special formula for the Logitech WingMan Warrior
1866                         // y=ax^b; where a = 300 and b = 1.3
1867                         // also x values are in increments of 800 (so this is factored out)
1868                         // then bounds check result to level out excessively high spin rates
1869                         fTemp = 300.0 * pow(abs(fAxisValue) / 800.0, 1.3);
1870                         if (fTemp > 14000.0)
1871                                 fTemp = 14000.0;
1872                         // restore direction information
1873                         fAxisValue = (fAxisValue > 0.0) ? fTemp : -fTemp;
1874                 }
1875         }
1876
1877         // convert range from -32768..32767 to -1..1
1878         fAxisValue /= 32768.0;
1879
1880         // deadzone around center
1881         if (fabs(fAxisValue) < deadzone)
1882                 return 0; 
1883
1884         // apply sensitivity
1885         return fAxisValue * sensitivity;
1886 }
1887
1888 /*
1889 ===========
1890  IN_JoystickKeyeventForAxis
1891 ===========
1892 */
1893
1894 static void IN_JoystickKeyeventForAxis(int axis, int key_pos, int key_neg)
1895 {
1896         double joytime;
1897
1898         if (axis < 0 || axis >= JOY_MAX_AXES)
1899                 return; // no such axis on this joystick
1900
1901         joytime = Sys_DoubleTime();
1902         // no key event, continuous keydown event
1903         if (joy_axescache[axis].move == joy_axescache[axis].oldmove)
1904         {
1905                 if (joy_axescache[axis].move != 0 && joytime > joy_axescache[axis].keytime)
1906                 {
1907                         //Con_Printf("joy %s %i %f\n", Key_KeynumToString((joy_axescache[axis].move > 0) ? key_pos : key_neg), 1, cl.time);
1908                         Key_Event((joy_axescache[axis].move > 0) ? key_pos : key_neg, 0, 1);
1909                         joy_axescache[axis].keytime = joytime + 0.5 / 20;
1910                 }
1911                 return;
1912         }
1913         // generate key up event
1914         if (joy_axescache[axis].oldmove)
1915         {
1916                 //Con_Printf("joy %s %i %f\n", Key_KeynumToString((joy_axescache[axis].oldmove > 0) ? key_pos : key_neg), 1, cl.time);
1917                 Key_Event((joy_axescache[axis].oldmove > 0) ? key_pos : key_neg, 0, 0);
1918         }
1919         // generate key down event
1920         if (joy_axescache[axis].move)
1921         {
1922                 //Con_Printf("joy %s %i %f\n", Key_KeynumToString((joy_axescache[axis].move > 0) ? key_pos : key_neg), 1, cl.time);
1923                 Key_Event((joy_axescache[axis].move > 0) ? key_pos : key_neg, 0, 1);
1924                 joy_axescache[axis].keytime = joytime + 0.5;
1925         }
1926 }
1927
1928 /*
1929 ===========
1930  IN_JoystickBlockDoubledKeyEvents
1931 ===========
1932 */
1933
1934 static qboolean IN_ReadJoystick (void);
1935 static qboolean IN_JoystickBlockDoubledKeyEvents(int keycode)
1936 {
1937         int axis;
1938
1939         if (!joy_axiskeyevents.integer)
1940                 return false;
1941
1942         // block keyevent if it's going to be provided by joystick keyevent system
1943         if (joy_avail)
1944         {
1945                 // collect the joystick data, if possible
1946                 if (IN_ReadJoystick() != true)
1947                         return false;
1948                 axis = IN_JoystickGetAxisNum(AxisForward);
1949                 if (keycode == K_UPARROW || keycode == K_DOWNARROW)
1950                         if (IN_JoystickGetAxis(axis, 1, 0.01) || joy_axescache[axis].move || joy_axescache[axis].oldmove)
1951                                 return true;
1952                 axis = IN_JoystickGetAxisNum(AxisSide);
1953                 if (keycode == K_RIGHTARROW || keycode == K_LEFTARROW)
1954                         if (IN_JoystickGetAxis(axis, 1, 0.01) || joy_axescache[axis].move || joy_axescache[axis].oldmove)
1955                                 return true;
1956         }
1957
1958         return false;
1959 }
1960
1961 /*
1962 ===========
1963  IN_JoyMove
1964 ===========
1965 */
1966 static void IN_JoyMove (void)
1967 {
1968         float   speed, aspeed;
1969         float   fAxisValue;
1970         int             i, mouselook = (in_mlook.state & 1) || freelook.integer, AxisForwardIndex = -1, AxisSideIndex = -1;
1971
1972         // complete initialization if first time in
1973         // this is needed as cvars are not available at initialization time
1974         if( joy_advancedinit != true )
1975         {
1976                 Joy_AdvancedUpdate_f();
1977                 joy_advancedinit = true;
1978         }
1979
1980         if (joy_avail)
1981         {
1982                 int             i, key_index;
1983                 DWORD   buttonstate, povstate;
1984
1985                 // loop through the joystick buttons
1986                 // key a joystick event or auxillary event for higher number buttons for each state change
1987                 buttonstate = ji.dwButtons;
1988                 for (i=0 ; i < (int) joy_numbuttons ; i++)
1989                 {
1990                         if ( (buttonstate & (1<<i)) && !(joy_oldbuttonstate & (1<<i)) )
1991                         {
1992                                 key_index = (i < 16) ? K_JOY1 : K_AUX1;
1993                                 Key_Event (key_index + i, 0, true);
1994                         }
1995                         if ( !(buttonstate & (1<<i)) && (joy_oldbuttonstate & (1<<i)) )
1996                         {
1997                                 key_index = (i < 16) ? K_JOY1 : K_AUX1;
1998                                 Key_Event (key_index + i, 0, false);
1999                         }
2000                 }
2001                 joy_oldbuttonstate = buttonstate;
2002
2003                 if (joy_haspov)
2004                 {
2005                         // convert POV information into 4 bits of state information
2006                         // this avoids any potential problems related to moving from one
2007                         // direction to another without going through the center position
2008                         povstate = 0;
2009                         if(ji.dwPOV != JOY_POVCENTERED)
2010                         {
2011                                 if (ji.dwPOV == JOY_POVFORWARD)
2012                                         povstate |= 0x01;
2013                                 if (ji.dwPOV == JOY_POVRIGHT)
2014                                         povstate |= 0x02;
2015                                 if (ji.dwPOV == JOY_POVBACKWARD)
2016                                         povstate |= 0x04;
2017                                 if (ji.dwPOV == JOY_POVLEFT)
2018                                         povstate |= 0x08;
2019                         }
2020                         // determine which bits have changed and key an auxillary event for each change
2021                         for (i=0 ; i < 4 ; i++)
2022                         {
2023                                 if ( (povstate & (1<<i)) && !(joy_oldpovstate & (1<<i)) )
2024                                 {
2025                                         Key_Event (K_AUX29 + i, 0, true);
2026                                 }
2027
2028                                 if ( !(povstate & (1<<i)) && (joy_oldpovstate & (1<<i)) )
2029                                 {
2030                                         Key_Event (K_AUX29 + i, 0, false);
2031                                 }
2032                         }
2033                         joy_oldpovstate = povstate;
2034                 }
2035         }
2036
2037         // verify joystick is available and that the user wants to use it
2038         if (!joy_avail || !in_joystick.integer)
2039         {
2040                 return;
2041         }
2042
2043         // collect the joystick data, if possible
2044         if (IN_ReadJoystick () != true)
2045         {
2046                 return;
2047         }
2048
2049         if (in_speed.state & 1)
2050                 speed = cl_movespeedkey.value;
2051         else
2052                 speed = 1;
2053         // LordHavoc: viewzoom affects sensitivity for sniping
2054         aspeed = speed * cl.realframetime * cl.viewzoom;
2055
2056         // loop through the axes
2057         for (i = 0; i < JOY_MAX_AXES; i++)
2058         {
2059                 // convert axis to real move
2060                 switch (dwAxisMap[i])
2061                 {
2062                         case AxisForward:
2063                                 if (AxisForwardIndex < 0)
2064                                         AxisForwardIndex = i;
2065                                 if ((joy_advanced.integer == 0) && mouselook)
2066                                 {
2067                                         // user wants forward control to become look control
2068                                         fAxisValue = IN_JoystickGetAxis(i, joy_pitchsensitivity.value, joy_pitchthreshold.value);
2069                                         if (fAxisValue != 0)
2070                                         {
2071                                                 // if mouse invert is on, invert the joystick pitch value
2072                                                 // only absolute control support here (joy_advanced is false)
2073                                                 if (m_pitch.value < 0.0)
2074                                                         cl.viewangles[PITCH] -= fAxisValue * aspeed * cl_pitchspeed.value;
2075                                                 else
2076                                                         cl.viewangles[PITCH] += fAxisValue * aspeed * cl_pitchspeed.value;
2077                                                 V_StopPitchDrift();
2078                                         }
2079                                         else
2080                                         {
2081                                                 // no pitch movement
2082                                                 // disable pitch return-to-center unless requested by user
2083                                                 // *** this code can be removed when the lookspring bug is fixed
2084                                                 // *** the bug always has the lookspring feature on
2085                                                 if (lookspring.value == 0.0)
2086                                                         V_StopPitchDrift();
2087                                         }
2088                                 }
2089                                 else
2090                                 {
2091                                         // user wants forward control to be forward control
2092                                         fAxisValue = IN_JoystickGetAxis(i, joy_forwardsensitivity.value, joy_forwardthreshold.value);
2093                                         cl.cmd.forwardmove += fAxisValue * speed * cl_forwardspeed.value;
2094                                 }
2095                                 break;
2096
2097                         case AxisSide:
2098                                 if (AxisSideIndex < 0)
2099                                         AxisSideIndex = i;
2100                                 fAxisValue = IN_JoystickGetAxis(i, joy_sidesensitivity.value, joy_sidethreshold.value);
2101                                 cl.cmd.sidemove += fAxisValue * speed * cl_sidespeed.value;
2102                                 break;
2103
2104                         case AxisTurn:
2105                                 if ((in_strafe.state & 1) || (lookstrafe.integer && mouselook))
2106                                 {
2107                                         // user wants turn control to become side control
2108                                         fAxisValue = IN_JoystickGetAxis(i, joy_sidesensitivity.value, joy_sidethreshold.value);
2109                                         cl.cmd.sidemove -= fAxisValue * speed * cl_sidespeed.value;
2110                                 }
2111                                 else
2112                                 {
2113                                         // user wants turn control to be turn control
2114                                         fAxisValue = IN_JoystickGetAxis(i, joy_yawsensitivity.value, joy_yawthreshold.value);
2115                                         if (dwControlMap[i] == JOY_ABSOLUTE_AXIS)
2116                                                 cl.viewangles[YAW] += fAxisValue * aspeed * cl_yawspeed.value;
2117                                         else
2118                                                 cl.viewangles[YAW] += fAxisValue * speed * 180.0;
2119                                 }
2120                                 break;
2121
2122                         case AxisLook:
2123                                 fAxisValue = IN_JoystickGetAxis(i, joy_pitchsensitivity.value, joy_pitchthreshold.value);
2124                                 if (mouselook)
2125                                 {
2126                                         if (fAxisValue != 0)
2127                                         {
2128                                                 // pitch movement detected and pitch movement desired by user
2129                                                 if (dwControlMap[i] == JOY_ABSOLUTE_AXIS)
2130                                                         cl.viewangles[PITCH] += fAxisValue * aspeed * cl_pitchspeed.value;
2131                                                 else
2132                                                         cl.viewangles[PITCH] += fAxisValue * speed * 180.0;
2133                                                 V_StopPitchDrift();
2134                                         }
2135                                         else
2136                                         {
2137                                                 // no pitch movement
2138                                                 // disable pitch return-to-center unless requested by user
2139                                                 // *** this code can be removed when the lookspring bug is fixed
2140                                                 // *** the bug always has the lookspring feature on
2141                                                 if(lookspring.integer == 0)
2142                                                         V_StopPitchDrift();
2143                                         }
2144                                 }
2145                                 break;
2146
2147                         default:
2148                                 fAxisValue = IN_JoystickGetAxis(i, 1, 0.01);
2149                                 break;
2150                 }
2151         
2152                 // cache for keyevents
2153                 joy_axescache[i].oldmove = joy_axescache[i].move;
2154                 joy_axescache[i].move = IN_JoystickGetAxis(i, 1, 0.01);
2155         }
2156
2157         // run keyevents
2158         if (joy_axiskeyevents.integer)
2159         {
2160                 IN_JoystickKeyeventForAxis(AxisForwardIndex, K_DOWNARROW, K_UPARROW);
2161                 IN_JoystickKeyeventForAxis(AxisSideIndex, K_RIGHTARROW, K_LEFTARROW);
2162         }
2163 }
2164
2165 static void IN_Init(void)
2166 {
2167         uiWheelMessage = RegisterWindowMessage ( "MSWHEEL_ROLLMSG" );
2168
2169         // joystick variables
2170         Cvar_RegisterVariable (&in_joystick);
2171         Cvar_RegisterVariable (&joy_name);
2172         Cvar_RegisterVariable (&joy_advanced);
2173         Cvar_RegisterVariable (&joy_advaxisx);
2174         Cvar_RegisterVariable (&joy_advaxisy);
2175         Cvar_RegisterVariable (&joy_advaxisz);
2176         Cvar_RegisterVariable (&joy_advaxisr);
2177         Cvar_RegisterVariable (&joy_advaxisu);
2178         Cvar_RegisterVariable (&joy_advaxisv);
2179         Cvar_RegisterVariable (&joy_forwardthreshold);
2180         Cvar_RegisterVariable (&joy_sidethreshold);
2181         Cvar_RegisterVariable (&joy_pitchthreshold);
2182         Cvar_RegisterVariable (&joy_yawthreshold);
2183         Cvar_RegisterVariable (&joy_forwardsensitivity);
2184         Cvar_RegisterVariable (&joy_sidesensitivity);
2185         Cvar_RegisterVariable (&joy_pitchsensitivity);
2186         Cvar_RegisterVariable (&joy_yawsensitivity);
2187         Cvar_RegisterVariable (&joy_wwhack1);
2188         Cvar_RegisterVariable (&joy_wwhack2);
2189         Cvar_RegisterVariable (&joy_axiskeyevents);
2190         Cvar_RegisterVariable (&vid_forcerefreshrate);
2191         Cmd_AddCommand ("joyadvancedupdate", Joy_AdvancedUpdate_f, "applies current joyadv* cvar settings to the joystick driver");
2192 }
2193
2194 static void IN_Shutdown(void)
2195 {
2196 #ifdef SUPPORTDIRECTX
2197         if (g_pMouse)
2198                 IDirectInputDevice_Release(g_pMouse);
2199         g_pMouse = NULL;
2200
2201         if (g_pdi)
2202                 IDirectInput_Release(g_pdi);
2203         g_pdi = NULL;
2204 #endif
2205 }
2206
2207 size_t VID_ListModes(vid_mode_t *modes, size_t maxcount)
2208 {
2209         int i;
2210         size_t k;
2211         DEVMODE thismode;
2212
2213         thismode.dmSize = sizeof(thismode);
2214         thismode.dmDriverExtra = 0;
2215         k = 0;
2216         for(i = 0; EnumDisplaySettings(NULL, i, &thismode); ++i)
2217         {
2218                 if(~thismode.dmFields & (DM_BITSPERPEL | DM_PELSWIDTH | DM_PELSHEIGHT | DM_DISPLAYFREQUENCY))
2219                 {
2220                         Con_DPrintf("enumerating modes yielded a bogus item... please debug this\n");
2221                         continue;
2222                 }
2223                 if(k >= maxcount)
2224                         break;
2225                 modes[k].width = thismode.dmPelsWidth;
2226                 modes[k].height = thismode.dmPelsHeight;
2227                 modes[k].bpp = thismode.dmBitsPerPel;
2228                 modes[k].refreshrate = thismode.dmDisplayFrequency;
2229                 modes[k].pixelheight_num = 1;
2230                 modes[k].pixelheight_denom = 1; // Win32 apparently does not provide this (FIXME)
2231                 ++k;
2232         }
2233         return k;
2234 }