2 Copyright (C) 1996-1997 Id Software, Inc.
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.
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.
13 See the GNU General Public License for more details.
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.
20 // vid_wgl.c -- NT GL vid component
24 #pragma comment(lib, "dinput8.lib")
25 #pragma comment(lib, "dxguid.lib")
26 #ifndef DIRECTINPUT_VERSION
27 # define DIRECTINPUT_VERSION 0x0500 /* Version 5.0 */
43 extern HINSTANCE global_hInstance;
47 #define WM_MOUSEWHEEL 0x020A
50 // Tell startup code that we have a client
51 int cl_available = true;
53 qboolean vid_supportrefreshrate = true;
55 static int (WINAPI *qwglChoosePixelFormat)(HDC, CONST PIXELFORMATDESCRIPTOR *);
56 static int (WINAPI *qwglDescribePixelFormat)(HDC, int, UINT, LPPIXELFORMATDESCRIPTOR);
57 //static int (WINAPI *qwglGetPixelFormat)(HDC);
58 static BOOL (WINAPI *qwglSetPixelFormat)(HDC, int, CONST PIXELFORMATDESCRIPTOR *);
59 static BOOL (WINAPI *qwglSwapBuffers)(HDC);
60 static HGLRC (WINAPI *qwglCreateContext)(HDC);
61 static BOOL (WINAPI *qwglDeleteContext)(HGLRC);
62 static HGLRC (WINAPI *qwglGetCurrentContext)(VOID);
63 static HDC (WINAPI *qwglGetCurrentDC)(VOID);
64 static PROC (WINAPI *qwglGetProcAddress)(LPCSTR);
65 static BOOL (WINAPI *qwglMakeCurrent)(HDC, HGLRC);
66 static BOOL (WINAPI *qwglSwapIntervalEXT)(int interval);
67 static const char *(WINAPI *qwglGetExtensionsStringARB)(HDC hdc);
68 static BOOL (WINAPI *qwglChoosePixelFormatARB)(HDC hdc, const int *piAttribIList, const FLOAT *pfAttribFList, UINT nMaxFormats, int *piFormats, UINT *nNumFormats);
69 static BOOL (WINAPI *qwglGetPixelFormatAttribivARB)(HDC hdc, int iPixelFormat, int iLayerPlane, UINT nAttributes, const int *piAttributes, int *piValues);
71 static dllfunction_t wglfuncs[] =
73 {"wglChoosePixelFormat", (void **) &qwglChoosePixelFormat},
74 {"wglDescribePixelFormat", (void **) &qwglDescribePixelFormat},
75 // {"wglGetPixelFormat", (void **) &qwglGetPixelFormat},
76 {"wglSetPixelFormat", (void **) &qwglSetPixelFormat},
77 {"wglSwapBuffers", (void **) &qwglSwapBuffers},
78 {"wglCreateContext", (void **) &qwglCreateContext},
79 {"wglDeleteContext", (void **) &qwglDeleteContext},
80 {"wglGetProcAddress", (void **) &qwglGetProcAddress},
81 {"wglMakeCurrent", (void **) &qwglMakeCurrent},
82 {"wglGetCurrentContext", (void **) &qwglGetCurrentContext},
83 {"wglGetCurrentDC", (void **) &qwglGetCurrentDC},
87 static dllfunction_t wglswapintervalfuncs[] =
89 {"wglSwapIntervalEXT", (void **) &qwglSwapIntervalEXT},
93 static dllfunction_t wglpixelformatfuncs[] =
95 {"wglChoosePixelFormatARB", (void **) &qwglChoosePixelFormatARB},
96 {"wglGetPixelFormatAttribivARB", (void **) &qwglGetPixelFormatAttribivARB},
100 static DEVMODE gdevmode, initialdevmode;
101 static qboolean vid_initialized = false;
102 static qboolean vid_wassuspended = false;
103 static qboolean vid_usingmouse = false;
104 static qboolean vid_usinghidecursor = false;
105 static qboolean vid_usingvsync = false;
106 static qboolean vid_usevsync = false;
109 // used by cd_win.c and snd_win.c
115 //HWND WINAPI InitializeWindow (HINSTANCE hInstance, int nCmdShow);
117 static qboolean vid_isfullscreen;
119 //void VID_MenuDraw (void);
120 //void VID_MenuKey (int key);
122 //LONG WINAPI MainWndProc (HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
123 //void AppActivate(BOOL fActive, BOOL minimize);
124 //void ClearAllStates (void);
125 //void VID_UpdateWindowStatus (void);
127 //====================================
129 static int window_x, window_y;
131 static qboolean mouseinitialized;
133 #ifdef SUPPORTDIRECTX
134 static qboolean dinput;
135 #define DINPUT_BUFFERSIZE 16
136 #define iDirectInputCreate(a,b,c,d) pDirectInputCreate(a,b,c,d)
138 static HRESULT (WINAPI *pDirectInputCreate)(HINSTANCE hinst, DWORD dwVersion, LPDIRECTINPUT * lplpDirectInput, LPUNKNOWN punkOuter);
141 // LordHavoc: thanks to backslash for this support for mouse buttons 4 and 5
142 /* backslash :: imouse explorer buttons */
143 /* These are #ifdefed out for non-Win2K in the February 2001 version of
144 MS's platform SDK, but we need them for compilation. . . */
145 #ifndef WM_XBUTTONDOWN
146 #define WM_XBUTTONDOWN 0x020B
147 #define WM_XBUTTONUP 0x020C
150 #define MK_XBUTTON1 0x0020
151 #define MK_XBUTTON2 0x0040
154 // LordHavoc: lets hope this allows more buttons in the future...
155 #define MK_XBUTTON3 0x0080
156 #define MK_XBUTTON4 0x0100
157 #define MK_XBUTTON5 0x0200
158 #define MK_XBUTTON6 0x0400
159 #define MK_XBUTTON7 0x0800
164 static int mouse_buttons;
165 static int mouse_oldbuttonstate;
167 static unsigned int uiWheelMessage;
168 #ifdef SUPPORTDIRECTX
169 static qboolean dinput_acquired;
171 static unsigned int mstate_di;
174 // joystick defines and variables
175 // where should defines be moved?
176 #define JOY_ABSOLUTE_AXIS 0x00000000 // control like a joystick
177 #define JOY_RELATIVE_AXIS 0x00000010 // control like a mouse, spinner, trackball
178 #define JOY_MAX_AXES 6 // X, Y, Z, R, U, V
186 // joystick axes state
194 static joy_axiscache_t joy_axescache[JOY_MAX_AXES];
198 AxisNada = 0, AxisForward, AxisLook, AxisSide, AxisTurn
201 static DWORD dwAxisFlags[JOY_MAX_AXES] =
203 JOY_RETURNX, JOY_RETURNY, JOY_RETURNZ, JOY_RETURNR, JOY_RETURNU, JOY_RETURNV
206 static DWORD dwAxisMap[JOY_MAX_AXES];
207 static DWORD dwControlMap[JOY_MAX_AXES];
208 static PDWORD pdwRawValue[JOY_MAX_AXES];
210 // none of these cvars are saved over a session
211 // this means that advanced controller configuration needs to be executed
212 // each time. this avoids any problems with getting back to a default usage
213 // or when changing from one controller to another. this way at least something
215 static cvar_t in_joystick = {CVAR_SAVE, "joystick","0", "enables joysticks"};
216 static cvar_t joy_name = {0, "joyname", "joystick", "name of joystick to use (informational only, used only by joyadvanced 1 mode)"};
217 static cvar_t joy_advanced = {0, "joyadvanced", "0", "use more than 2 axis joysticks (configuring this is very technical)"};
218 static cvar_t joy_advaxisx = {0, "joyadvaxisx", "0", "axis mapping for joyadvanced 1 mode"};
219 static cvar_t joy_advaxisy = {0, "joyadvaxisy", "0", "axis mapping for joyadvanced 1 mode"};
220 static cvar_t joy_advaxisz = {0, "joyadvaxisz", "0", "axis mapping for joyadvanced 1 mode"};
221 static cvar_t joy_advaxisr = {0, "joyadvaxisr", "0", "axis mapping for joyadvanced 1 mode"};
222 static cvar_t joy_advaxisu = {0, "joyadvaxisu", "0", "axis mapping for joyadvanced 1 mode"};
223 static cvar_t joy_advaxisv = {0, "joyadvaxisv", "0", "axis mapping for joyadvanced 1 mode"};
224 static cvar_t joy_forwardthreshold = {0, "joyforwardthreshold", "0.15", "minimum joystick movement necessary to move forward"};
225 static cvar_t joy_sidethreshold = {0, "joysidethreshold", "0.15", "minimum joystick movement necessary to move sideways (strafing)"};
226 static cvar_t joy_pitchthreshold = {0, "joypitchthreshold", "0.15", "minimum joystick movement necessary to look up/down"};
227 static cvar_t joy_yawthreshold = {0, "joyyawthreshold", "0.15", "minimum joystick movement necessary to turn left/right"};
228 static cvar_t joy_forwardsensitivity = {0, "joyforwardsensitivity", "-1.0", "how fast the joystick moves forward"};
229 static cvar_t joy_sidesensitivity = {0, "joysidesensitivity", "-1.0", "how fast the joystick moves sideways (strafing)"};
230 static cvar_t joy_pitchsensitivity = {0, "joypitchsensitivity", "1.0", "how fast the joystick looks up/down"};
231 static cvar_t joy_yawsensitivity = {0, "joyyawsensitivity", "-1.0", "how fast the joystick turns left/right"};
232 static cvar_t joy_wwhack1 = {0, "joywwhack1", "0.0", "special hack for wingman warrior"};
233 static cvar_t joy_wwhack2 = {0, "joywwhack2", "0.0", "special hack for wingman warrior"};
234 static cvar_t joy_axiskeyevents = {CVAR_SAVE, "joy_axiskeyevents", "0", "generate uparrow/leftarrow etc. keyevents for joystick axes, use if your joystick driver is not generating them"};
236 static cvar_t vid_forcerefreshrate = {0, "vid_forcerefreshrate", "0", "try to set the given vid_refreshrate even if Windows doesn't list it as valid video mode"};
238 static qboolean joy_avail, joy_advancedinit, joy_haspov;
239 static DWORD joy_oldbuttonstate, joy_oldpovstate;
242 static DWORD joy_flags;
243 static DWORD joy_numbuttons;
245 #ifdef SUPPORTDIRECTX
246 static LPDIRECTINPUT g_pdi;
247 static LPDIRECTINPUTDEVICE g_pMouse;
248 static HINSTANCE hInstDI;
253 // forward-referenced functions
254 static void IN_StartupJoystick (void);
255 static void Joy_AdvancedUpdate_f (void);
256 static void IN_JoyMove (void);
257 static void IN_StartupMouse (void);
260 //====================================
262 void VID_Finish (void)
264 vid_usevsync = vid_vsync.integer && !cls.timedemo && qwglSwapIntervalEXT;
265 if (vid_usingvsync != vid_usevsync)
267 vid_usingvsync = vid_usevsync;
268 qwglSwapIntervalEXT (vid_usevsync);
274 if (r_speeds.integer == 2 || gl_finish.integer)
276 qglFinish();CHECKGLERROR
281 // make sure a context switch can happen every frame - Logitech drivers
282 // input drivers sometimes eat cpu time every 3 seconds or lag badly
286 VID_UpdateGamma(false, 256);
289 //==========================================================================
294 static unsigned char scantokey[128] =
296 // 0 1 2 3 4 5 6 7 8 9 A B C D E F
297 0 ,27 ,'1' ,'2' ,'3' ,'4' ,'5' ,'6' ,'7' ,'8' ,'9' ,'0' ,'-' ,'=' ,K_BACKSPACE,9 ,//0
298 'q' ,'w' ,'e' ,'r' ,'t' ,'y' ,'u' ,'i' ,'o' ,'p' ,'[' ,']' ,13 ,K_CTRL ,'a' ,'s' ,//1
299 'd' ,'f' ,'g' ,'h' ,'j' ,'k' ,'l' ,';' ,'\'' ,'`' ,K_SHIFT ,'\\' ,'z' ,'x' ,'c' ,'v' ,//2
300 'b' ,'n' ,'m' ,',' ,'.' ,'/' ,K_SHIFT,'*' ,K_ALT ,' ' ,0 ,K_F1 ,K_F2 ,K_F3 ,K_F4 ,K_F5 ,//3
301 K_F6 ,K_F7 ,K_F8 ,K_F9 ,K_F10,K_PAUSE,0 ,K_HOME,K_UPARROW,K_PGUP,K_KP_MINUS,K_LEFTARROW,K_KP_5,K_RIGHTARROW,K_KP_PLUS ,K_END,//4
302 K_DOWNARROW,K_PGDN,K_INS,K_DEL,0 ,0 ,0 ,K_F11 ,K_F12 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,//5
303 0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,//6
304 0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 //7
312 Map from windows to quake keynums
315 static int MapKey (int key, int virtualkey)
318 int modified = (key >> 16) & 255;
319 qboolean is_extended = false;
321 if (modified < 128 && scantokey[modified])
322 result = scantokey[modified];
326 Con_DPrintf("key 0x%02x (0x%8x, 0x%8x) has no translation\n", modified, key, virtualkey);
343 return K_KP_LEFTARROW;
345 return K_KP_RIGHTARROW;
349 return K_KP_DOWNARROW;
376 ===================================================================
380 ===================================================================
388 static void ClearAllStates (void)
392 mouse_oldbuttonstate = 0;
395 void AppActivate(BOOL fActive, BOOL minimize)
396 /****************************************************************************
398 * Function: AppActivate
399 * Parameters: fActive - True if app is activating
401 * Description: If the application is activating, then swap the system
402 * into SYSPAL_NOSTATIC mode so that our palettes will display
405 ****************************************************************************/
407 static qboolean sound_active = false; // initially blocked by Sys_InitConsole()
409 vid_activewindow = fActive != FALSE;
410 vid_hidden = minimize != FALSE;
412 // enable/disable sound on focus gain/loss
413 if ((!vid_hidden && vid_activewindow) || !snd_mutewhenidle.integer)
426 sound_active = false;
432 if (vid_isfullscreen)
434 if (vid_wassuspended)
436 vid_wassuspended = false;
437 ChangeDisplaySettings (&gdevmode, CDS_FULLSCREEN);
438 ShowWindow(mainwindow, SW_SHOWNORMAL);
441 // LordHavoc: from dabb, fix for alt-tab bug in NVidia drivers
442 MoveWindow(mainwindow,0,0,gdevmode.dmPelsWidth,gdevmode.dmPelsHeight,false);
448 VID_SetMouse(false, false, false);
449 if (vid_isfullscreen)
451 ChangeDisplaySettings (NULL, 0);
452 vid_wassuspended = true;
454 VID_RestoreSystemGamma();
458 //TODO: move it around in vid_wgl.c since I dont think this is the right position
459 void Sys_SendKeyEvents (void)
463 while (PeekMessage (&msg, NULL, 0, 0, PM_NOREMOVE))
465 if (!GetMessage (&msg, NULL, 0, 0))
468 TranslateMessage (&msg);
469 DispatchMessage (&msg);
473 LONG CDAudio_MessageHandler(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
475 static keynum_t buttonremap[16] =
495 /* main window procedure */
496 static qboolean IN_JoystickBlockDoubledKeyEvents(int keycode);
497 LONG WINAPI MainWndProc (HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
500 int fActive, fMinimized, temp;
501 unsigned char state[256];
502 unsigned char asciichar[4];
505 qboolean down = false;
507 if ( uMsg == uiWheelMessage )
508 uMsg = WM_MOUSEWHEEL;
513 if (vid_isfullscreen)
514 ShowWindow(mainwindow, SW_SHOWMINNOACTIVE);
521 window_x = (int) LOWORD(lParam);
522 window_y = (int) HIWORD(lParam);
523 VID_SetMouse(false, false, false);
531 vkey = MapKey(lParam, wParam);
532 GetKeyboardState (state);
533 // alt/ctrl/shift tend to produce funky ToAscii values,
534 // and if it's not a single character we don't know care about it
535 charlength = ToAscii (wParam, lParam >> 16, state, (LPWORD)asciichar, 0);
536 if (vkey == K_ALT || vkey == K_CTRL || vkey == K_SHIFT || charlength == 0)
538 else if( charlength == 2 ) {
539 asciichar[0] = asciichar[1];
541 if (!IN_JoystickBlockDoubledKeyEvents(vkey))
542 Key_Event (vkey, asciichar[0], down);
546 // keep Alt-Space from happening
550 // prevent screensaver from occuring while the active window
551 // note: password-locked screensavers on Vista still work
552 if (vid_activewindow && ((wParam & 0xFFF0) == SC_SCREENSAVE || (wParam & 0xFFF0) == SC_MONITORPOWER))
555 lRet = DefWindowProc (hWnd, uMsg, wParam, lParam);
558 // this is complicated because Win32 seems to pack multiple mouse events into
559 // one update sometimes, so we always check all states and look for events
566 case WM_XBUTTONDOWN: // backslash :: imouse explorer buttons
567 case WM_XBUTTONUP: // backslash :: imouse explorer buttons
571 if (wParam & MK_LBUTTON)
574 if (wParam & MK_RBUTTON)
577 if (wParam & MK_MBUTTON)
580 /* backslash :: imouse explorer buttons */
581 if (wParam & MK_XBUTTON1)
584 if (wParam & MK_XBUTTON2)
588 // LordHavoc: lets hope this allows more buttons in the future...
589 if (wParam & MK_XBUTTON3)
591 if (wParam & MK_XBUTTON4)
593 if (wParam & MK_XBUTTON5)
595 if (wParam & MK_XBUTTON6)
597 if (wParam & MK_XBUTTON7)
600 #ifdef SUPPORTDIRECTX
601 if (!dinput_acquired)
604 // perform button actions
606 for (i=0 ; i<mouse_buttons && i < 16 ; i++)
607 if ((temp ^ mouse_oldbuttonstate) & (1<<i))
608 Key_Event (buttonremap[i], 0, (temp & (1<<i)) != 0);
609 mouse_oldbuttonstate = temp;
614 // JACK: This is the mouse wheel with the Intellimouse
615 // Its delta is either positive or neg, and we generate the proper
618 if ((short) HIWORD(wParam) > 0) {
619 Key_Event(K_MWHEELUP, 0, true);
620 Key_Event(K_MWHEELUP, 0, false);
622 Key_Event(K_MWHEELDOWN, 0, true);
623 Key_Event(K_MWHEELDOWN, 0, false);
631 if (MessageBox (mainwindow, "Are you sure you want to quit?", "Confirm Exit", MB_YESNO | MB_SETFOREGROUND | MB_ICONQUESTION) == IDYES)
637 fActive = LOWORD(wParam);
638 fMinimized = (BOOL) HIWORD(wParam);
639 AppActivate(!(fActive == WA_INACTIVE), fMinimized);
641 // fix the leftover Alt from any Alt-Tab or the like that switched us away
647 // PostQuitMessage (0);
651 lRet = CDAudio_MessageHandler (hWnd, uMsg, wParam, lParam);
655 /* pass all unhandled messages to DefWindowProc */
656 lRet = DefWindowProc (hWnd, uMsg, wParam, lParam);
660 /* return 1 if handled message, 0 if not */
664 int VID_SetGamma(unsigned short *ramps, int rampsize)
666 HDC hdc = GetDC (NULL);
667 int i = SetDeviceGammaRamp(hdc, ramps);
668 ReleaseDC (NULL, hdc);
669 return i; // return success or failure
672 int VID_GetGamma(unsigned short *ramps, int rampsize)
674 HDC hdc = GetDC (NULL);
675 int i = GetDeviceGammaRamp(hdc, ramps);
676 ReleaseDC (NULL, hdc);
677 return i; // return success or failure
680 static HINSTANCE gldll;
682 static void GL_CloseLibrary(void)
687 qwglGetProcAddress = NULL;
690 gl_platformextensions = "";
693 static int GL_OpenLibrary(const char *name)
695 Con_Printf("Loading OpenGL driver %s\n", name);
697 if (!(gldll = LoadLibrary(name)))
699 Con_Printf("Unable to LoadLibrary %s\n", name);
702 strlcpy(gl_driver, name, sizeof(gl_driver));
706 void *GL_GetProcAddress(const char *name)
709 if (qwglGetProcAddress != NULL)
710 p = (void *) qwglGetProcAddress(name);
712 p = (void *) GetProcAddress(gldll, name);
716 #ifndef WGL_ARB_pixel_format
717 #define WGL_NUMBER_PIXEL_FORMATS_ARB 0x2000
718 #define WGL_DRAW_TO_WINDOW_ARB 0x2001
719 #define WGL_DRAW_TO_BITMAP_ARB 0x2002
720 #define WGL_ACCELERATION_ARB 0x2003
721 #define WGL_NEED_PALETTE_ARB 0x2004
722 #define WGL_NEED_SYSTEM_PALETTE_ARB 0x2005
723 #define WGL_SWAP_LAYER_BUFFERS_ARB 0x2006
724 #define WGL_SWAP_METHOD_ARB 0x2007
725 #define WGL_NUMBER_OVERLAYS_ARB 0x2008
726 #define WGL_NUMBER_UNDERLAYS_ARB 0x2009
727 #define WGL_TRANSPARENT_ARB 0x200A
728 #define WGL_TRANSPARENT_RED_VALUE_ARB 0x2037
729 #define WGL_TRANSPARENT_GREEN_VALUE_ARB 0x2038
730 #define WGL_TRANSPARENT_BLUE_VALUE_ARB 0x2039
731 #define WGL_TRANSPARENT_ALPHA_VALUE_ARB 0x203A
732 #define WGL_TRANSPARENT_INDEX_VALUE_ARB 0x203B
733 #define WGL_SHARE_DEPTH_ARB 0x200C
734 #define WGL_SHARE_STENCIL_ARB 0x200D
735 #define WGL_SHARE_ACCUM_ARB 0x200E
736 #define WGL_SUPPORT_GDI_ARB 0x200F
737 #define WGL_SUPPORT_OPENGL_ARB 0x2010
738 #define WGL_DOUBLE_BUFFER_ARB 0x2011
739 #define WGL_STEREO_ARB 0x2012
740 #define WGL_PIXEL_TYPE_ARB 0x2013
741 #define WGL_COLOR_BITS_ARB 0x2014
742 #define WGL_RED_BITS_ARB 0x2015
743 #define WGL_RED_SHIFT_ARB 0x2016
744 #define WGL_GREEN_BITS_ARB 0x2017
745 #define WGL_GREEN_SHIFT_ARB 0x2018
746 #define WGL_BLUE_BITS_ARB 0x2019
747 #define WGL_BLUE_SHIFT_ARB 0x201A
748 #define WGL_ALPHA_BITS_ARB 0x201B
749 #define WGL_ALPHA_SHIFT_ARB 0x201C
750 #define WGL_ACCUM_BITS_ARB 0x201D
751 #define WGL_ACCUM_RED_BITS_ARB 0x201E
752 #define WGL_ACCUM_GREEN_BITS_ARB 0x201F
753 #define WGL_ACCUM_BLUE_BITS_ARB 0x2020
754 #define WGL_ACCUM_ALPHA_BITS_ARB 0x2021
755 #define WGL_DEPTH_BITS_ARB 0x2022
756 #define WGL_STENCIL_BITS_ARB 0x2023
757 #define WGL_AUX_BUFFERS_ARB 0x2024
758 #define WGL_NO_ACCELERATION_ARB 0x2025
759 #define WGL_GENERIC_ACCELERATION_ARB 0x2026
760 #define WGL_FULL_ACCELERATION_ARB 0x2027
761 #define WGL_SWAP_EXCHANGE_ARB 0x2028
762 #define WGL_SWAP_COPY_ARB 0x2029
763 #define WGL_SWAP_UNDEFINED_ARB 0x202A
764 #define WGL_TYPE_RGBA_ARB 0x202B
765 #define WGL_TYPE_COLORINDEX_ARB 0x202C
768 #ifndef WGL_ARB_multisample
769 #define WGL_SAMPLE_BUFFERS_ARB 0x2041
770 #define WGL_SAMPLES_ARB 0x2042
774 static void IN_Init(void);
779 InitCommonControls();
780 hIcon = LoadIcon (global_hInstance, MAKEINTRESOURCE (IDI_ICON1));
782 // Register the frame class
784 wc.lpfnWndProc = (WNDPROC)MainWndProc;
787 wc.hInstance = global_hInstance;
789 wc.hCursor = LoadCursor (NULL,IDC_ARROW);
790 wc.hbrBackground = NULL;
792 wc.lpszClassName = "DarkPlacesWindowClass";
794 if (!RegisterClass (&wc))
795 Con_Printf ("Couldn't register window class\n");
797 memset(&initialdevmode, 0, sizeof(initialdevmode));
798 EnumDisplaySettings(NULL, ENUM_CURRENT_SETTINGS, &initialdevmode);
803 qboolean VID_InitMode(viddef_mode_t *mode)
809 PIXELFORMATDESCRIPTOR pfd =
811 sizeof(PIXELFORMATDESCRIPTOR), // size of this pfd
813 PFD_DRAW_TO_WINDOW // support window
814 | PFD_SUPPORT_OPENGL // support OpenGL
815 | PFD_DOUBLEBUFFER , // double buffered
816 PFD_TYPE_RGBA, // RGBA type
817 24, // 24-bit color depth
818 0, 0, 0, 0, 0, 0, // color bits ignored
819 0, // no alpha buffer
820 0, // shift bit ignored
821 0, // no accumulation buffer
822 0, 0, 0, 0, // accum bits ignored
823 32, // 32-bit z-buffer
824 0, // no stencil buffer
825 0, // no auxiliary buffer
826 PFD_MAIN_PLANE, // main layer
828 0, 0, 0 // layer masks ignored
831 int pixelformat, newpixelformat;
832 UINT numpixelformats;
833 DWORD WindowStyle, ExWindowStyle;
834 int CenterX, CenterY;
835 const char *gldrivername;
838 qboolean foundmode, foundgoodmode;
843 int bpp = mode->bitsperpixel;
844 int width = mode->width;
845 int height = mode->height;
846 int refreshrate = (int)floor(mode->refreshrate+0.5);
847 int stereobuffer = mode->stereobuffer;
848 int samples = mode->samples;
849 int fullscreen = mode->fullscreen;
852 Sys_Error("VID_InitMode called when video is already initialised");
854 // if stencil is enabled, ask for alpha too
862 pfd.cStencilBits = 8;
871 pfd.cStencilBits = 0;
875 pfd.dwFlags |= PFD_STEREO;
879 *a++ = WGL_DRAW_TO_WINDOW_ARB;
881 *a++ = WGL_ACCELERATION_ARB;
882 *a++ = WGL_FULL_ACCELERATION_ARB;
883 *a++ = WGL_DOUBLE_BUFFER_ARB;
888 *a++ = WGL_RED_BITS_ARB;
890 *a++ = WGL_GREEN_BITS_ARB;
892 *a++ = WGL_BLUE_BITS_ARB;
894 *a++ = WGL_ALPHA_BITS_ARB;
896 *a++ = WGL_DEPTH_BITS_ARB;
898 *a++ = WGL_STENCIL_BITS_ARB;
903 *a++ = WGL_RED_BITS_ARB;
905 *a++ = WGL_GREEN_BITS_ARB;
907 *a++ = WGL_BLUE_BITS_ARB;
909 *a++ = WGL_DEPTH_BITS_ARB;
915 *a++ = WGL_STEREO_ARB;
921 *a++ = WGL_SAMPLE_BUFFERS_ARB;
923 *a++ = WGL_SAMPLES_ARB;
930 gldrivername = "opengl32.dll";
931 // COMMANDLINEOPTION: Windows WGL: -gl_driver <drivername> selects a GL driver library, default is opengl32.dll, useful only for 3dfxogl.dll or 3dfxvgl.dll, if you don't know what this is for, you don't need it
932 i = COM_CheckParm("-gl_driver");
933 if (i && i < com_argc - 1)
934 gldrivername = com_argv[i + 1];
935 if (!GL_OpenLibrary(gldrivername))
937 Con_Printf("Unable to load GL driver %s\n", gldrivername);
941 memset(&gdevmode, 0, sizeof(gdevmode));
943 vid_isfullscreen = false;
946 if(vid_forcerefreshrate.integer)
949 gdevmode.dmFields = DM_BITSPERPEL | DM_PELSWIDTH | DM_PELSHEIGHT;
950 gdevmode.dmBitsPerPel = bpp;
951 gdevmode.dmPelsWidth = width;
952 gdevmode.dmPelsHeight = height;
953 gdevmode.dmSize = sizeof (gdevmode);
956 gdevmode.dmFields |= DM_DISPLAYFREQUENCY;
957 gdevmode.dmDisplayFrequency = refreshrate;
963 refreshrate = initialdevmode.dmDisplayFrequency; // default vid_refreshrate to the rate of the desktop
966 foundgoodmode = false;
968 thismode.dmSize = sizeof(thismode);
969 thismode.dmDriverExtra = 0;
970 for(i = 0; EnumDisplaySettings(NULL, i, &thismode); ++i)
972 if(~thismode.dmFields & (DM_BITSPERPEL | DM_PELSWIDTH | DM_PELSHEIGHT | DM_DISPLAYFREQUENCY))
974 Con_DPrintf("enumerating modes yielded a bogus item... please debug this\n");
977 if(developer_extra.integer)
978 Con_DPrintf("Found mode %dx%dx%dbpp %dHz... ", (int)thismode.dmPelsWidth, (int)thismode.dmPelsHeight, (int)thismode.dmBitsPerPel, (int)thismode.dmDisplayFrequency);
979 if(thismode.dmBitsPerPel != (DWORD)bpp)
981 if(developer_extra.integer)
982 Con_DPrintf("wrong bpp\n");
985 if(thismode.dmPelsWidth != (DWORD)width)
987 if(developer_extra.integer)
988 Con_DPrintf("wrong width\n");
991 if(thismode.dmPelsHeight != (DWORD)height)
993 if(developer_extra.integer)
994 Con_DPrintf("wrong height\n");
1000 // if we have a good mode, make sure this mode is better than the previous one, and allowed by the refreshrate
1001 if(thismode.dmDisplayFrequency > (DWORD)refreshrate)
1003 if(developer_extra.integer)
1004 Con_DPrintf("too high refresh rate\n");
1007 else if(thismode.dmDisplayFrequency <= gdevmode.dmDisplayFrequency)
1009 if(developer_extra.integer)
1010 Con_DPrintf("doesn't beat previous best match (too low)\n");
1016 // we do have one, but it isn't good... make sure it has a lower frequency than the previous one
1017 if(thismode.dmDisplayFrequency >= gdevmode.dmDisplayFrequency)
1019 if(developer_extra.integer)
1020 Con_DPrintf("doesn't beat previous best match (too high)\n");
1024 // otherwise, take anything
1026 memcpy(&gdevmode, &thismode, sizeof(gdevmode));
1027 if(thismode.dmDisplayFrequency <= (DWORD)refreshrate)
1028 foundgoodmode = true;
1031 if(developer_extra.integer)
1032 Con_DPrintf("(out of range)\n");
1035 if(developer_extra.integer)
1036 Con_DPrintf("accepted\n");
1043 Con_Printf("Unable to find the requested mode %dx%dx%dbpp\n", width, height, bpp);
1046 else if(ChangeDisplaySettings (&gdevmode, CDS_FULLSCREEN) != DISP_CHANGE_SUCCESSFUL)
1049 Con_Printf("Unable to change to requested mode %dx%dx%dbpp\n", width, height, bpp);
1053 vid_isfullscreen = true;
1054 WindowStyle = WS_POPUP;
1055 ExWindowStyle = WS_EX_TOPMOST;
1060 i = GetDeviceCaps(hdc, RASTERCAPS);
1061 depth = GetDeviceCaps(hdc, PLANES) * GetDeviceCaps(hdc, BITSPIXEL);
1062 ReleaseDC (NULL, hdc);
1066 Con_Print("Can't run in non-RGB mode\n");
1072 Con_Print("A higher desktop depth is required to run this video mode\n");
1076 WindowStyle = WS_OVERLAPPED | WS_BORDER | WS_CAPTION | WS_SYSMENU | WS_MINIMIZEBOX;
1083 rect.bottom = height;
1084 AdjustWindowRectEx(&rect, WindowStyle, false, 0);
1093 CenterX = (GetSystemMetrics(SM_CXSCREEN) - (rect.right - rect.left)) / 2;
1094 CenterY = (GetSystemMetrics(SM_CYSCREEN) - (rect.bottom - rect.top)) / 2;
1096 CenterX = max(0, CenterX);
1097 CenterY = max(0, CenterY);
1099 // x and y may be changed by WM_MOVE messages
1102 rect.left += CenterX;
1103 rect.right += CenterX;
1104 rect.top += CenterY;
1105 rect.bottom += CenterY;
1109 // start out at the final windowpass if samples is 1 as it's the only feature we need extended pixel formats for
1110 for (windowpass = samples == 1;windowpass < 2;windowpass++)
1113 gl_platformextensions = "";
1115 mainwindow = CreateWindowEx (ExWindowStyle, "DarkPlacesWindowClass", gamename, WindowStyle, rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top, NULL, NULL, global_hInstance, NULL);
1118 Con_Printf("CreateWindowEx(%d, %s, %s, %d, %d, %d, %d, %d, %p, %p, %p, %p) failed\n", (int)ExWindowStyle, "DarkPlacesWindowClass", gamename, (int)WindowStyle, (int)(rect.left), (int)(rect.top), (int)(rect.right - rect.left), (int)(rect.bottom - rect.top), NULL, NULL, global_hInstance, NULL);
1123 baseDC = GetDC(mainwindow);
1125 if (!newpixelformat)
1126 newpixelformat = ChoosePixelFormat(baseDC, &pfd);
1127 pixelformat = newpixelformat;
1131 Con_Printf("ChoosePixelFormat(%p, %p) failed\n", baseDC, &pfd);
1135 if (SetPixelFormat(baseDC, pixelformat, &pfd) == false)
1138 Con_Printf("SetPixelFormat(%p, %d, %p) failed\n", baseDC, pixelformat, &pfd);
1142 if (!GL_CheckExtension("wgl", wglfuncs, NULL, false))
1145 Con_Print("wgl functions not found\n");
1149 baseRC = qwglCreateContext(baseDC);
1153 Con_Print("Could not initialize GL (wglCreateContext failed).\n\nMake sure you are in 65536 color mode, and try running -window.\n");
1156 if (!qwglMakeCurrent(baseDC, baseRC))
1159 Con_Printf("wglMakeCurrent(%p, %p) failed\n", baseDC, baseRC);
1163 if ((qglGetString = (const GLubyte* (GLAPIENTRY *)(GLenum name))GL_GetProcAddress("glGetString")) == NULL)
1166 Con_Print("glGetString not found\n");
1169 if ((qwglGetExtensionsStringARB = (const char *(WINAPI *)(HDC hdc))GL_GetProcAddress("wglGetExtensionsStringARB")) == NULL)
1170 Con_Print("wglGetExtensionsStringARB not found\n");
1172 gl_extensions = (const char *)qglGetString(GL_EXTENSIONS);
1173 gl_platform = "WGL";
1174 gl_platformextensions = "";
1176 if (qwglGetExtensionsStringARB)
1177 gl_platformextensions = (const char *)qwglGetExtensionsStringARB(baseDC);
1181 if (!gl_platformextensions)
1182 gl_platformextensions = "";
1184 // now some nice Windows pain:
1185 // we have created a window, we needed one to find out if there are
1186 // any multisample pixel formats available, the problem is that to
1187 // actually use one of those multisample formats we now have to
1188 // recreate the window (yes Microsoft OpenGL really is that bad)
1190 if (windowpass == 0)
1192 if (!GL_CheckExtension("WGL_ARB_pixel_format", wglpixelformatfuncs, "-noarbpixelformat", false) || !qwglChoosePixelFormatARB(baseDC, attribs, attribsf, 1, &newpixelformat, &numpixelformats) || !newpixelformat)
1194 // ok we got one - do it all over again with newpixelformat
1195 qwglMakeCurrent(NULL, NULL);
1196 qwglDeleteContext(baseRC);baseRC = 0;
1197 ReleaseDC(mainwindow, baseDC);baseDC = 0;
1198 // eat up any messages waiting for us
1199 while (PeekMessage (&msg, NULL, 0, 0, PM_REMOVE))
1201 TranslateMessage (&msg);
1202 DispatchMessage (&msg);
1209 SetWindowPos (mainwindow, NULL, CenterX, CenterY, 0, 0,SWP_NOSIZE | SWP_NOZORDER | SWP_SHOWWINDOW | SWP_DRAWFRAME);
1212 ShowWindow (mainwindow, SW_SHOWDEFAULT);
1213 UpdateWindow (mainwindow);
1215 // now we try to make sure we get the focus on the mode switch, because
1216 // sometimes in some systems we don't. We grab the foreground, then
1217 // finish setting up, pump all our messages, and sleep for a little while
1218 // to let messages finish bouncing around the system, then we put
1219 // ourselves at the top of the z order, then grab the foreground again,
1220 // Who knows if it helps, but it probably doesn't hurt
1221 SetForegroundWindow (mainwindow);
1223 while (PeekMessage (&msg, NULL, 0, 0, PM_REMOVE))
1225 TranslateMessage (&msg);
1226 DispatchMessage (&msg);
1231 SetWindowPos (mainwindow, HWND_TOP, 0, 0, 0, 0, SWP_DRAWFRAME | SWP_NOMOVE | SWP_NOSIZE | SWP_SHOWWINDOW | SWP_NOCOPYBITS);
1233 SetForegroundWindow (mainwindow);
1235 // fix the leftover Alt from any Alt-Tab or the like that switched us away
1238 // COMMANDLINEOPTION: Windows WGL: -novideosync disables WGL_EXT_swap_control
1239 GL_CheckExtension("WGL_EXT_swap_control", wglswapintervalfuncs, "-novideosync", false);
1243 //vid_menudrawfn = VID_MenuDraw;
1244 //vid_menukeyfn = VID_MenuKey;
1245 vid_usingmouse = false;
1246 vid_usinghidecursor = false;
1247 vid_usingvsync = false;
1249 vid_initialized = true;
1252 IN_StartupJoystick ();
1254 if (qwglSwapIntervalEXT)
1256 vid_usevsync = vid_vsync.integer != 0;
1257 vid_usingvsync = vid_vsync.integer != 0;
1258 qwglSwapIntervalEXT (vid_usevsync);
1264 static void IN_Shutdown(void);
1265 void VID_Shutdown (void)
1267 if(vid_initialized == false)
1270 VID_SetMouse(false, false, false);
1271 VID_RestoreSystemGamma();
1273 vid_initialized = false;
1275 if (qwglMakeCurrent)
1276 qwglMakeCurrent(NULL, NULL);
1277 if (baseRC && qwglDeleteContext)
1278 qwglDeleteContext(baseRC);
1279 // close the library before we get rid of the window
1281 if (baseDC && mainwindow)
1282 ReleaseDC(mainwindow, baseDC);
1283 AppActivate(false, false);
1285 DestroyWindow(mainwindow);
1287 if (vid_isfullscreen)
1288 ChangeDisplaySettings (NULL, 0);
1289 vid_isfullscreen = false;
1292 void VID_SetMouse(qboolean fullscreengrab, qboolean relative, qboolean hidecursor)
1294 static qboolean restore_spi;
1295 static int originalmouseparms[3];
1297 if (!mouseinitialized)
1302 if (!vid_usingmouse)
1304 vid_usingmouse = true;
1305 cl_ignoremousemoves = 2;
1306 #ifdef SUPPORTDIRECTX
1307 if (dinput && g_pMouse)
1309 IDirectInputDevice_Acquire(g_pMouse);
1310 dinput_acquired = true;
1316 window_rect.left = window_x;
1317 window_rect.top = window_y;
1318 window_rect.right = window_x + vid.width;
1319 window_rect.bottom = window_y + vid.height;
1321 // change mouse settings to turn off acceleration
1322 // COMMANDLINEOPTION: Windows GDI Input: -noforcemparms disables setting of mouse parameters (not used with -dinput, windows only)
1323 if (!COM_CheckParm ("-noforcemparms") && SystemParametersInfo (SPI_GETMOUSE, 0, originalmouseparms, 0))
1325 int newmouseparms[3];
1326 newmouseparms[0] = 0; // threshold to double movement (only if accel level is >= 1)
1327 newmouseparms[1] = 0; // threshold to quadruple movement (only if accel level is >= 2)
1328 newmouseparms[2] = 0; // maximum level of acceleration (0 = off)
1329 restore_spi = SystemParametersInfo (SPI_SETMOUSE, 0, newmouseparms, 0) != FALSE;
1332 restore_spi = false;
1333 SetCursorPos ((window_x + vid.width / 2), (window_y + vid.height / 2));
1335 SetCapture (mainwindow);
1336 ClipCursor (&window_rect);
1344 vid_usingmouse = false;
1345 cl_ignoremousemoves = 2;
1346 #ifdef SUPPORTDIRECTX
1347 if (dinput_acquired)
1349 IDirectInputDevice_Unacquire(g_pMouse);
1350 dinput_acquired = false;
1355 // restore system mouseparms if we changed them
1357 SystemParametersInfo (SPI_SETMOUSE, 0, originalmouseparms, 0);
1358 restore_spi = false;
1365 if (vid_usinghidecursor != hidecursor)
1367 vid_usinghidecursor = hidecursor;
1368 ShowCursor (!hidecursor);
1373 #ifdef SUPPORTDIRECTX
1379 static qboolean IN_InitDInput (void)
1382 DIPROPDWORD dipdw = {
1384 sizeof(DIPROPDWORD), // diph.dwSize
1385 sizeof(DIPROPHEADER), // diph.dwHeaderSize
1387 DIPH_DEVICE, // diph.dwHow
1389 DINPUT_BUFFERSIZE, // dwData
1394 hInstDI = LoadLibrary("dinput.dll");
1396 if (hInstDI == NULL)
1398 Con_Print("Couldn't load dinput.dll\n");
1403 if (!pDirectInputCreate)
1405 pDirectInputCreate = (HRESULT (__stdcall *)(HINSTANCE,DWORD,LPDIRECTINPUT *,LPUNKNOWN))GetProcAddress(hInstDI,"DirectInputCreateA");
1407 if (!pDirectInputCreate)
1409 Con_Print("Couldn't get DI proc addr\n");
1414 // register with DirectInput and get an IDirectInput to play with.
1415 hr = iDirectInputCreate(global_hInstance, DIRECTINPUT_VERSION, &g_pdi, NULL);
1422 // obtain an interface to the system mouse device.
1424 hr = IDirectInput_CreateDevice(g_pdi, GUID_SysMouse, &g_pMouse, NULL);
1426 hr = IDirectInput_CreateDevice(g_pdi, &GUID_SysMouse, &g_pMouse, NULL);
1431 Con_Print("Couldn't open DI mouse device\n");
1435 // set the data format to "mouse format".
1436 hr = IDirectInputDevice_SetDataFormat(g_pMouse, &c_dfDIMouse);
1440 Con_Print("Couldn't set DI mouse format\n");
1444 // set the cooperativity level.
1445 hr = IDirectInputDevice_SetCooperativeLevel(g_pMouse, mainwindow,
1446 DISCL_EXCLUSIVE | DISCL_FOREGROUND);
1450 Con_Print("Couldn't set DI coop level\n");
1455 // set the buffer size to DINPUT_BUFFERSIZE elements.
1456 // the buffer size is a DWORD property associated with the device
1457 hr = IDirectInputDevice_SetProperty(g_pMouse, DIPROP_BUFFERSIZE, &dipdw.diph);
1461 Con_Print("Couldn't set DI buffersize\n");
1475 static void IN_StartupMouse (void)
1477 if (COM_CheckParm ("-nomouse"))
1480 mouseinitialized = true;
1482 #ifdef SUPPORTDIRECTX
1483 // COMMANDLINEOPTION: Windows Input: -dinput enables DirectInput for mouse/joystick input
1484 if (COM_CheckParm ("-dinput"))
1485 dinput = IN_InitDInput ();
1488 Con_Print("DirectInput initialized\n");
1490 Con_Print("DirectInput not initialized\n");
1502 static void IN_MouseMove (void)
1506 GetCursorPos (¤t_pos);
1507 in_windowmouse_x = current_pos.x - window_x;
1508 in_windowmouse_y = current_pos.y - window_y;
1510 if (!vid_usingmouse)
1513 #ifdef SUPPORTDIRECTX
1514 if (dinput_acquired)
1517 DIDEVICEOBJECTDATA od;
1525 hr = IDirectInputDevice_GetDeviceData(g_pMouse,
1526 sizeof(DIDEVICEOBJECTDATA), &od, &dwElements, 0);
1528 if ((hr == DIERR_INPUTLOST) || (hr == DIERR_NOTACQUIRED))
1530 IDirectInputDevice_Acquire(g_pMouse);
1534 /* Unable to read data or no data available */
1535 if (FAILED(hr) || dwElements == 0)
1538 /* Look at the element to see what happened */
1543 in_mouse_x += (LONG) od.dwData;
1547 in_mouse_y += (LONG) od.dwData;
1551 if((LONG) od.dwData < 0)
1553 Key_Event (K_MWHEELDOWN, 0, true);
1554 Key_Event (K_MWHEELDOWN, 0, false);
1556 else if((LONG) od.dwData > 0)
1558 Key_Event (K_MWHEELUP, 0, true);
1559 Key_Event (K_MWHEELUP, 0, false);
1563 case DIMOFS_BUTTON0:
1564 if (od.dwData & 0x80)
1570 case DIMOFS_BUTTON1:
1571 if (od.dwData & 0x80)
1572 mstate_di |= (1<<1);
1574 mstate_di &= ~(1<<1);
1577 case DIMOFS_BUTTON2:
1578 if (od.dwData & 0x80)
1579 mstate_di |= (1<<2);
1581 mstate_di &= ~(1<<2);
1584 case DIMOFS_BUTTON3:
1585 if (od.dwData & 0x80)
1586 mstate_di |= (1<<3);
1588 mstate_di &= ~(1<<3);
1593 // perform button actions
1594 for (i=0 ; i<mouse_buttons && i < 16 ; i++)
1595 if ((mstate_di ^ mouse_oldbuttonstate) & (1<<i))
1596 Key_Event (buttonremap[i], 0, (mstate_di & (1<<i)) != 0);
1597 mouse_oldbuttonstate = mstate_di;
1602 in_mouse_x += in_windowmouse_x - (int)(vid.width / 2);
1603 in_mouse_y += in_windowmouse_y - (int)(vid.height / 2);
1605 // if the mouse has moved, force it to the center, so there's room to move
1606 if (in_mouse_x || in_mouse_y)
1607 SetCursorPos ((window_x + vid.width / 2), (window_y + vid.height / 2));
1619 if (vid_activewindow && !vid_hidden)
1632 static void IN_StartupJoystick (void)
1639 // assume no joystick
1642 // abort startup if user requests no joystick
1643 // COMMANDLINEOPTION: Windows Input: -nojoy disables joystick support, may be a small speed increase
1644 if (COM_CheckParm ("-nojoy"))
1647 // verify joystick driver is present
1648 if ((numdevs = joyGetNumDevs ()) == 0)
1650 Con_Print("\njoystick not found -- driver not present\n\n");
1654 // cycle through the joystick ids for the first valid one
1655 for (joy_id=0 ; joy_id<numdevs ; joy_id++)
1657 memset (&ji, 0, sizeof(ji));
1658 ji.dwSize = sizeof(ji);
1659 ji.dwFlags = JOY_RETURNCENTERED;
1661 if ((mmr = joyGetPosEx (joy_id, &ji)) == JOYERR_NOERROR)
1665 // abort startup if we didn't find a valid joystick
1666 if (mmr != JOYERR_NOERROR)
1668 Con_Printf("\njoystick not found -- no valid joysticks (%x)\n\n", mmr);
1672 // get the capabilities of the selected joystick
1673 // abort startup if command fails
1674 memset (&jc, 0, sizeof(jc));
1675 if ((mmr = joyGetDevCaps (joy_id, &jc, sizeof(jc))) != JOYERR_NOERROR)
1677 Con_Printf("\njoystick not found -- invalid joystick capabilities (%x)\n\n", mmr);
1681 // save the joystick's number of buttons and POV status
1682 joy_numbuttons = jc.wNumButtons;
1683 joy_haspov = (jc.wCaps & JOYCAPS_HASPOV) != 0;
1685 // old button and POV states default to no buttons pressed
1686 joy_oldbuttonstate = joy_oldpovstate = 0;
1688 // mark the joystick as available and advanced initialization not completed
1689 // this is needed as cvars are not available during initialization
1692 joy_advancedinit = false;
1694 Con_Print("\njoystick detected\n\n");
1703 static PDWORD RawValuePointer (int axis)
1720 return NULL; // LordHavoc: hush compiler warning
1726 Joy_AdvancedUpdate_f
1729 static void Joy_AdvancedUpdate_f (void)
1732 // called once by IN_ReadJoystick and by user whenever an update is needed
1733 // cvars are now available
1737 // initialize all the maps
1738 for (i = 0; i < JOY_MAX_AXES; i++)
1740 dwAxisMap[i] = AxisNada;
1741 dwControlMap[i] = JOY_ABSOLUTE_AXIS;
1742 pdwRawValue[i] = RawValuePointer(i);
1745 if( joy_advanced.integer == 0)
1747 // default joystick initialization
1748 // 2 axes only with joystick control
1749 dwAxisMap[JOY_AXIS_X] = AxisTurn;
1750 // dwControlMap[JOY_AXIS_X] = JOY_ABSOLUTE_AXIS;
1751 dwAxisMap[JOY_AXIS_Y] = AxisForward;
1752 // dwControlMap[JOY_AXIS_Y] = JOY_ABSOLUTE_AXIS;
1756 if (strcmp (joy_name.string, "joystick") != 0)
1758 // notify user of advanced controller
1759 Con_Printf("\n%s configured\n\n", joy_name.string);
1762 // advanced initialization here
1763 // data supplied by user via joy_axisn cvars
1764 dwTemp = (DWORD) joy_advaxisx.value;
1765 dwAxisMap[JOY_AXIS_X] = dwTemp & 0x0000000f;
1766 dwControlMap[JOY_AXIS_X] = dwTemp & JOY_RELATIVE_AXIS;
1767 dwTemp = (DWORD) joy_advaxisy.value;
1768 dwAxisMap[JOY_AXIS_Y] = dwTemp & 0x0000000f;
1769 dwControlMap[JOY_AXIS_Y] = dwTemp & JOY_RELATIVE_AXIS;
1770 dwTemp = (DWORD) joy_advaxisz.value;
1771 dwAxisMap[JOY_AXIS_Z] = dwTemp & 0x0000000f;
1772 dwControlMap[JOY_AXIS_Z] = dwTemp & JOY_RELATIVE_AXIS;
1773 dwTemp = (DWORD) joy_advaxisr.value;
1774 dwAxisMap[JOY_AXIS_R] = dwTemp & 0x0000000f;
1775 dwControlMap[JOY_AXIS_R] = dwTemp & JOY_RELATIVE_AXIS;
1776 dwTemp = (DWORD) joy_advaxisu.value;
1777 dwAxisMap[JOY_AXIS_U] = dwTemp & 0x0000000f;
1778 dwControlMap[JOY_AXIS_U] = dwTemp & JOY_RELATIVE_AXIS;
1779 dwTemp = (DWORD) joy_advaxisv.value;
1780 dwAxisMap[JOY_AXIS_V] = dwTemp & 0x0000000f;
1781 dwControlMap[JOY_AXIS_V] = dwTemp & JOY_RELATIVE_AXIS;
1784 // compute the axes to collect from DirectInput
1785 joy_flags = JOY_RETURNCENTERED | JOY_RETURNBUTTONS | JOY_RETURNPOV;
1786 for (i = 0; i < JOY_MAX_AXES; i++)
1788 if (dwAxisMap[i] != AxisNada)
1790 joy_flags |= dwAxisFlags[i];
1800 static qboolean IN_ReadJoystick (void)
1803 memset (&ji, 0, sizeof(ji));
1804 ji.dwSize = sizeof(ji);
1805 ji.dwFlags = joy_flags;
1807 if (joyGetPosEx (joy_id, &ji) == JOYERR_NOERROR)
1809 // this is a hack -- there is a bug in the Logitech WingMan Warrior DirectInput Driver
1810 // rather than having 32768 be the zero point, they have the zero point at 32668
1811 // go figure -- anyway, now we get the full resolution out of the device
1812 if (joy_wwhack1.integer != 0.0)
1820 // read error occurred
1821 // turning off the joystick seems too harsh for 1 read error,
1822 // but what should be done?
1829 IN_JoystickGetAxisNum
1833 int IN_JoystickGetAxisNum(int ControlListType)
1837 for (i = 0; i < JOY_MAX_AXES; i++)
1838 if (dwAxisMap[i] == ControlListType)
1848 static double IN_JoystickGetAxis(int axis, double sensitivity, double deadzone)
1850 float fAxisValue, fTemp;
1852 if (!joy_avail || axis < 0 || axis >= JOY_MAX_AXES)
1853 return 0; // no such axis on this joystick
1855 // get the floating point zero-centered, potentially-inverted data for the current axis
1856 fAxisValue = (float) *pdwRawValue[axis];
1858 // move centerpoint to zero
1859 fAxisValue -= 32768.0;
1861 if (joy_wwhack2.integer != 0.0)
1863 if (dwAxisMap[axis] == AxisTurn)
1865 // this is a special formula for the Logitech WingMan Warrior
1866 // y=ax^b; where a = 300 and b = 1.3
1867 // also x values are in increments of 800 (so this is factored out)
1868 // then bounds check result to level out excessively high spin rates
1869 fTemp = 300.0 * pow(abs(fAxisValue) / 800.0, 1.3);
1870 if (fTemp > 14000.0)
1872 // restore direction information
1873 fAxisValue = (fAxisValue > 0.0) ? fTemp : -fTemp;
1877 // convert range from -32768..32767 to -1..1
1878 fAxisValue /= 32768.0;
1880 // deadzone around center
1881 if (fabs(fAxisValue) < deadzone)
1884 // apply sensitivity
1885 return fAxisValue * sensitivity;
1890 IN_JoystickKeyeventForAxis
1894 static void IN_JoystickKeyeventForAxis(int axis, int key_pos, int key_neg)
1898 if (axis < 0 || axis >= JOY_MAX_AXES)
1899 return; // no such axis on this joystick
1901 joytime = Sys_DoubleTime();
1902 // no key event, continuous keydown event
1903 if (joy_axescache[axis].move == joy_axescache[axis].oldmove)
1905 if (joy_axescache[axis].move != 0 && joytime > joy_axescache[axis].keytime)
1907 //Con_Printf("joy %s %i %f\n", Key_KeynumToString((joy_axescache[axis].move > 0) ? key_pos : key_neg), 1, cl.time);
1908 Key_Event((joy_axescache[axis].move > 0) ? key_pos : key_neg, 0, 1);
1909 joy_axescache[axis].keytime = joytime + 0.5 / 20;
1913 // generate key up event
1914 if (joy_axescache[axis].oldmove)
1916 //Con_Printf("joy %s %i %f\n", Key_KeynumToString((joy_axescache[axis].oldmove > 0) ? key_pos : key_neg), 1, cl.time);
1917 Key_Event((joy_axescache[axis].oldmove > 0) ? key_pos : key_neg, 0, 0);
1919 // generate key down event
1920 if (joy_axescache[axis].move)
1922 //Con_Printf("joy %s %i %f\n", Key_KeynumToString((joy_axescache[axis].move > 0) ? key_pos : key_neg), 1, cl.time);
1923 Key_Event((joy_axescache[axis].move > 0) ? key_pos : key_neg, 0, 1);
1924 joy_axescache[axis].keytime = joytime + 0.5;
1930 IN_JoystickBlockDoubledKeyEvents
1934 static qboolean IN_ReadJoystick (void);
1935 static qboolean IN_JoystickBlockDoubledKeyEvents(int keycode)
1939 if (!joy_axiskeyevents.integer)
1942 // block keyevent if it's going to be provided by joystick keyevent system
1945 // collect the joystick data, if possible
1946 if (IN_ReadJoystick() != true)
1948 axis = IN_JoystickGetAxisNum(AxisForward);
1949 if (keycode == K_UPARROW || keycode == K_DOWNARROW)
1950 if (IN_JoystickGetAxis(axis, 1, 0.01) || joy_axescache[axis].move || joy_axescache[axis].oldmove)
1952 axis = IN_JoystickGetAxisNum(AxisSide);
1953 if (keycode == K_RIGHTARROW || keycode == K_LEFTARROW)
1954 if (IN_JoystickGetAxis(axis, 1, 0.01) || joy_axescache[axis].move || joy_axescache[axis].oldmove)
1966 static void IN_JoyMove (void)
1968 float speed, aspeed;
1970 int i, mouselook = (in_mlook.state & 1) || freelook.integer, AxisForwardIndex = -1, AxisSideIndex = -1;
1972 // complete initialization if first time in
1973 // this is needed as cvars are not available at initialization time
1974 if( joy_advancedinit != true )
1976 Joy_AdvancedUpdate_f();
1977 joy_advancedinit = true;
1983 DWORD buttonstate, povstate;
1985 // loop through the joystick buttons
1986 // key a joystick event or auxillary event for higher number buttons for each state change
1987 buttonstate = ji.dwButtons;
1988 for (i=0 ; i < (int) joy_numbuttons ; i++)
1990 if ( (buttonstate & (1<<i)) && !(joy_oldbuttonstate & (1<<i)) )
1992 key_index = (i < 16) ? K_JOY1 : K_AUX1;
1993 Key_Event (key_index + i, 0, true);
1995 if ( !(buttonstate & (1<<i)) && (joy_oldbuttonstate & (1<<i)) )
1997 key_index = (i < 16) ? K_JOY1 : K_AUX1;
1998 Key_Event (key_index + i, 0, false);
2001 joy_oldbuttonstate = buttonstate;
2005 // convert POV information into 4 bits of state information
2006 // this avoids any potential problems related to moving from one
2007 // direction to another without going through the center position
2009 if(ji.dwPOV != JOY_POVCENTERED)
2011 if (ji.dwPOV == JOY_POVFORWARD)
2013 if (ji.dwPOV == JOY_POVRIGHT)
2015 if (ji.dwPOV == JOY_POVBACKWARD)
2017 if (ji.dwPOV == JOY_POVLEFT)
2020 // determine which bits have changed and key an auxillary event for each change
2021 for (i=0 ; i < 4 ; i++)
2023 if ( (povstate & (1<<i)) && !(joy_oldpovstate & (1<<i)) )
2025 Key_Event (K_AUX29 + i, 0, true);
2028 if ( !(povstate & (1<<i)) && (joy_oldpovstate & (1<<i)) )
2030 Key_Event (K_AUX29 + i, 0, false);
2033 joy_oldpovstate = povstate;
2037 // verify joystick is available and that the user wants to use it
2038 if (!joy_avail || !in_joystick.integer)
2043 // collect the joystick data, if possible
2044 if (IN_ReadJoystick () != true)
2049 if (in_speed.state & 1)
2050 speed = cl_movespeedkey.value;
2053 // LordHavoc: viewzoom affects sensitivity for sniping
2054 aspeed = speed * cl.realframetime * cl.viewzoom;
2056 // loop through the axes
2057 for (i = 0; i < JOY_MAX_AXES; i++)
2059 // convert axis to real move
2060 switch (dwAxisMap[i])
2063 if (AxisForwardIndex < 0)
2064 AxisForwardIndex = i;
2065 if ((joy_advanced.integer == 0) && mouselook)
2067 // user wants forward control to become look control
2068 fAxisValue = IN_JoystickGetAxis(i, joy_pitchsensitivity.value, joy_pitchthreshold.value);
2069 if (fAxisValue != 0)
2071 // if mouse invert is on, invert the joystick pitch value
2072 // only absolute control support here (joy_advanced is false)
2073 if (m_pitch.value < 0.0)
2074 cl.viewangles[PITCH] -= fAxisValue * aspeed * cl_pitchspeed.value;
2076 cl.viewangles[PITCH] += fAxisValue * aspeed * cl_pitchspeed.value;
2081 // no pitch movement
2082 // disable pitch return-to-center unless requested by user
2083 // *** this code can be removed when the lookspring bug is fixed
2084 // *** the bug always has the lookspring feature on
2085 if (lookspring.value == 0.0)
2091 // user wants forward control to be forward control
2092 fAxisValue = IN_JoystickGetAxis(i, joy_forwardsensitivity.value, joy_forwardthreshold.value);
2093 cl.cmd.forwardmove += fAxisValue * speed * cl_forwardspeed.value;
2098 if (AxisSideIndex < 0)
2100 fAxisValue = IN_JoystickGetAxis(i, joy_sidesensitivity.value, joy_sidethreshold.value);
2101 cl.cmd.sidemove += fAxisValue * speed * cl_sidespeed.value;
2105 if ((in_strafe.state & 1) || (lookstrafe.integer && mouselook))
2107 // user wants turn control to become side control
2108 fAxisValue = IN_JoystickGetAxis(i, joy_sidesensitivity.value, joy_sidethreshold.value);
2109 cl.cmd.sidemove -= fAxisValue * speed * cl_sidespeed.value;
2113 // user wants turn control to be turn control
2114 fAxisValue = IN_JoystickGetAxis(i, joy_yawsensitivity.value, joy_yawthreshold.value);
2115 if (dwControlMap[i] == JOY_ABSOLUTE_AXIS)
2116 cl.viewangles[YAW] += fAxisValue * aspeed * cl_yawspeed.value;
2118 cl.viewangles[YAW] += fAxisValue * speed * 180.0;
2123 fAxisValue = IN_JoystickGetAxis(i, joy_pitchsensitivity.value, joy_pitchthreshold.value);
2126 if (fAxisValue != 0)
2128 // pitch movement detected and pitch movement desired by user
2129 if (dwControlMap[i] == JOY_ABSOLUTE_AXIS)
2130 cl.viewangles[PITCH] += fAxisValue * aspeed * cl_pitchspeed.value;
2132 cl.viewangles[PITCH] += fAxisValue * speed * 180.0;
2137 // no pitch movement
2138 // disable pitch return-to-center unless requested by user
2139 // *** this code can be removed when the lookspring bug is fixed
2140 // *** the bug always has the lookspring feature on
2141 if(lookspring.integer == 0)
2148 fAxisValue = IN_JoystickGetAxis(i, 1, 0.01);
2152 // cache for keyevents
2153 joy_axescache[i].oldmove = joy_axescache[i].move;
2154 joy_axescache[i].move = IN_JoystickGetAxis(i, 1, 0.01);
2158 if (joy_axiskeyevents.integer)
2160 IN_JoystickKeyeventForAxis(AxisForwardIndex, K_DOWNARROW, K_UPARROW);
2161 IN_JoystickKeyeventForAxis(AxisSideIndex, K_RIGHTARROW, K_LEFTARROW);
2165 static void IN_Init(void)
2167 uiWheelMessage = RegisterWindowMessage ( "MSWHEEL_ROLLMSG" );
2169 // joystick variables
2170 Cvar_RegisterVariable (&in_joystick);
2171 Cvar_RegisterVariable (&joy_name);
2172 Cvar_RegisterVariable (&joy_advanced);
2173 Cvar_RegisterVariable (&joy_advaxisx);
2174 Cvar_RegisterVariable (&joy_advaxisy);
2175 Cvar_RegisterVariable (&joy_advaxisz);
2176 Cvar_RegisterVariable (&joy_advaxisr);
2177 Cvar_RegisterVariable (&joy_advaxisu);
2178 Cvar_RegisterVariable (&joy_advaxisv);
2179 Cvar_RegisterVariable (&joy_forwardthreshold);
2180 Cvar_RegisterVariable (&joy_sidethreshold);
2181 Cvar_RegisterVariable (&joy_pitchthreshold);
2182 Cvar_RegisterVariable (&joy_yawthreshold);
2183 Cvar_RegisterVariable (&joy_forwardsensitivity);
2184 Cvar_RegisterVariable (&joy_sidesensitivity);
2185 Cvar_RegisterVariable (&joy_pitchsensitivity);
2186 Cvar_RegisterVariable (&joy_yawsensitivity);
2187 Cvar_RegisterVariable (&joy_wwhack1);
2188 Cvar_RegisterVariable (&joy_wwhack2);
2189 Cvar_RegisterVariable (&joy_axiskeyevents);
2190 Cvar_RegisterVariable (&vid_forcerefreshrate);
2191 Cmd_AddCommand ("joyadvancedupdate", Joy_AdvancedUpdate_f, "applies current joyadv* cvar settings to the joystick driver");
2194 static void IN_Shutdown(void)
2196 #ifdef SUPPORTDIRECTX
2198 IDirectInputDevice_Release(g_pMouse);
2202 IDirectInput_Release(g_pdi);
2207 size_t VID_ListModes(vid_mode_t *modes, size_t maxcount)
2213 thismode.dmSize = sizeof(thismode);
2214 thismode.dmDriverExtra = 0;
2216 for(i = 0; EnumDisplaySettings(NULL, i, &thismode); ++i)
2218 if(~thismode.dmFields & (DM_BITSPERPEL | DM_PELSWIDTH | DM_PELSHEIGHT | DM_DISPLAYFREQUENCY))
2220 Con_DPrintf("enumerating modes yielded a bogus item... please debug this\n");
2225 modes[k].width = thismode.dmPelsWidth;
2226 modes[k].height = thismode.dmPelsHeight;
2227 modes[k].bpp = thismode.dmBitsPerPel;
2228 modes[k].refreshrate = thismode.dmDisplayFrequency;
2229 modes[k].pixelheight_num = 1;
2230 modes[k].pixelheight_denom = 1; // Win32 apparently does not provide this (FIXME)