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