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