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