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
188 AxisNada = 0, AxisForward, AxisLook, AxisSide, AxisTurn
191 static DWORD dwAxisFlags[JOY_MAX_AXES] =
193 JOY_RETURNX, JOY_RETURNY, JOY_RETURNZ, JOY_RETURNR, JOY_RETURNU, JOY_RETURNV
196 static DWORD dwAxisMap[JOY_MAX_AXES];
197 static DWORD dwControlMap[JOY_MAX_AXES];
198 static PDWORD pdwRawValue[JOY_MAX_AXES];
200 // none of these cvars are saved over a session
201 // this means that advanced controller configuration needs to be executed
202 // each time. this avoids any problems with getting back to a default usage
203 // or when changing from one controller to another. this way at least something
205 static cvar_t in_joystick = {CVAR_SAVE, "joystick","0", "enables joysticks"};
206 static cvar_t joy_name = {0, "joyname", "joystick", "name of joystick to use (informational only, used only by joyadvanced 1 mode)"};
207 static cvar_t joy_advanced = {0, "joyadvanced", "0", "use more than 2 axis joysticks (configuring this is very technical)"};
208 static cvar_t joy_advaxisx = {0, "joyadvaxisx", "0", "axis mapping for joyadvanced 1 mode"};
209 static cvar_t joy_advaxisy = {0, "joyadvaxisy", "0", "axis mapping for joyadvanced 1 mode"};
210 static cvar_t joy_advaxisz = {0, "joyadvaxisz", "0", "axis mapping for joyadvanced 1 mode"};
211 static cvar_t joy_advaxisr = {0, "joyadvaxisr", "0", "axis mapping for joyadvanced 1 mode"};
212 static cvar_t joy_advaxisu = {0, "joyadvaxisu", "0", "axis mapping for joyadvanced 1 mode"};
213 static cvar_t joy_advaxisv = {0, "joyadvaxisv", "0", "axis mapping for joyadvanced 1 mode"};
214 static cvar_t joy_forwardthreshold = {0, "joyforwardthreshold", "0.15", "minimum joystick movement necessary to move forward"};
215 static cvar_t joy_sidethreshold = {0, "joysidethreshold", "0.15", "minimum joystick movement necessary to move sideways (strafing)"};
216 static cvar_t joy_pitchthreshold = {0, "joypitchthreshold", "0.15", "minimum joystick movement necessary to look up/down"};
217 static cvar_t joy_yawthreshold = {0, "joyyawthreshold", "0.15", "minimum joystick movement necessary to turn left/right"};
218 static cvar_t joy_forwardsensitivity = {0, "joyforwardsensitivity", "-1.0", "how fast the joystick moves forward"};
219 static cvar_t joy_sidesensitivity = {0, "joysidesensitivity", "-1.0", "how fast the joystick moves sideways (strafing)"};
220 static cvar_t joy_pitchsensitivity = {0, "joypitchsensitivity", "1.0", "how fast the joystick looks up/down"};
221 static cvar_t joy_yawsensitivity = {0, "joyyawsensitivity", "-1.0", "how fast the joystick turns left/right"};
222 static cvar_t joy_wwhack1 = {0, "joywwhack1", "0.0", "special hack for wingman warrior"};
223 static cvar_t joy_wwhack2 = {0, "joywwhack2", "0.0", "special hack for wingman warrior"};
225 static cvar_t vid_forcerefreshrate = {0, "vid_forcerefreshrate", "0", "try to set the given vid_refreshrate even if Windows doesn't list it as valid video mode"};
227 static qboolean joy_avail, joy_advancedinit, joy_haspov;
228 static DWORD joy_oldbuttonstate, joy_oldpovstate;
231 static DWORD joy_flags;
232 static DWORD joy_numbuttons;
234 #ifdef SUPPORTDIRECTX
235 static LPDIRECTINPUT g_pdi;
236 static LPDIRECTINPUTDEVICE g_pMouse;
237 static HINSTANCE hInstDI;
242 // forward-referenced functions
243 static void IN_StartupJoystick (void);
244 static void Joy_AdvancedUpdate_f (void);
245 static void IN_JoyMove (void);
246 static void IN_StartupMouse (void);
249 //====================================
251 void VID_Finish (void)
253 vid_usevsync = vid_vsync.integer && !cls.timedemo && gl_videosyncavailable;
254 if (vid_usingvsync != vid_usevsync && gl_videosyncavailable)
256 vid_usingvsync = vid_usevsync;
257 qwglSwapIntervalEXT (vid_usevsync);
260 if (r_render.integer && !vid_hidden)
263 if (r_speeds.integer == 2 || gl_finish.integer)
265 qglFinish();CHECKGLERROR
270 // make sure a context switch can happen every frame - Logitech drivers
271 // input drivers sometimes eat cpu time every 3 seconds or lag badly
275 VID_UpdateGamma(false, 256);
278 //==========================================================================
283 static unsigned char scantokey[128] =
285 // 0 1 2 3 4 5 6 7 8 9 A B C D E F
286 0 ,27 ,'1' ,'2' ,'3' ,'4' ,'5' ,'6' ,'7' ,'8' ,'9' ,'0' ,'-' ,'=' ,K_BACKSPACE,9 ,//0
287 'q' ,'w' ,'e' ,'r' ,'t' ,'y' ,'u' ,'i' ,'o' ,'p' ,'[' ,']' ,13 ,K_CTRL ,'a' ,'s' ,//1
288 'd' ,'f' ,'g' ,'h' ,'j' ,'k' ,'l' ,';' ,'\'' ,'`' ,K_SHIFT ,'\\' ,'z' ,'x' ,'c' ,'v' ,//2
289 'b' ,'n' ,'m' ,',' ,'.' ,'/' ,K_SHIFT,'*' ,K_ALT ,' ' ,0 ,K_F1 ,K_F2 ,K_F3 ,K_F4 ,K_F5 ,//3
290 K_F6 ,K_F7 ,K_F8 ,K_F9 ,K_F10,K_PAUSE,0 ,K_HOME,K_UPARROW,K_PGUP,K_KP_MINUS,K_LEFTARROW,K_KP_5,K_RIGHTARROW,K_KP_PLUS ,K_END,//4
291 K_DOWNARROW,K_PGDN,K_INS,K_DEL,0 ,0 ,0 ,K_F11 ,K_F12 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,//5
292 0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,//6
293 0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 //7
301 Map from windows to quake keynums
304 static int MapKey (int key, int virtualkey)
307 int modified = (key >> 16) & 255;
308 qboolean is_extended = false;
310 if (modified < 128 && scantokey[modified])
311 result = scantokey[modified];
315 Con_DPrintf("key 0x%02x (0x%8x, 0x%8x) has no translation\n", modified, key, virtualkey);
332 return K_KP_LEFTARROW;
334 return K_KP_RIGHTARROW;
338 return K_KP_DOWNARROW;
365 ===================================================================
369 ===================================================================
377 static void ClearAllStates (void)
381 mouse_oldbuttonstate = 0;
384 void AppActivate(BOOL fActive, BOOL minimize)
385 /****************************************************************************
387 * Function: AppActivate
388 * Parameters: fActive - True if app is activating
390 * Description: If the application is activating, then swap the system
391 * into SYSPAL_NOSTATIC mode so that our palettes will display
394 ****************************************************************************/
396 static qboolean sound_active = false; // initially blocked by Sys_InitConsole()
398 vid_activewindow = fActive;
399 vid_hidden = minimize;
401 // enable/disable sound on focus gain/loss
402 if ((!vid_hidden && vid_activewindow) || !snd_mutewhenidle.integer)
415 sound_active = false;
421 if (vid_isfullscreen)
423 if (vid_wassuspended)
425 vid_wassuspended = false;
426 ChangeDisplaySettings (&gdevmode, CDS_FULLSCREEN);
427 ShowWindow(mainwindow, SW_SHOWNORMAL);
430 // LordHavoc: from dabb, fix for alt-tab bug in NVidia drivers
431 MoveWindow(mainwindow,0,0,gdevmode.dmPelsWidth,gdevmode.dmPelsHeight,false);
437 VID_SetMouse(false, false, false);
438 if (vid_isfullscreen)
440 ChangeDisplaySettings (NULL, 0);
441 vid_wassuspended = true;
443 VID_RestoreSystemGamma();
447 //TODO: move it around in vid_wgl.c since I dont think this is the right position
448 void Sys_SendKeyEvents (void)
452 while (PeekMessage (&msg, NULL, 0, 0, PM_NOREMOVE))
454 if (!GetMessage (&msg, NULL, 0, 0))
457 TranslateMessage (&msg);
458 DispatchMessage (&msg);
462 LONG CDAudio_MessageHandler(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
464 static keynum_t buttonremap[16] =
484 /* main window procedure */
485 LONG WINAPI MainWndProc (HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
488 int fActive, fMinimized, temp;
489 unsigned char state[256];
490 unsigned char asciichar[4];
493 qboolean down = false;
495 if ( uMsg == uiWheelMessage )
496 uMsg = WM_MOUSEWHEEL;
501 if (vid_isfullscreen)
502 ShowWindow(mainwindow, SW_SHOWMINNOACTIVE);
509 window_x = (int) LOWORD(lParam);
510 window_y = (int) HIWORD(lParam);
511 VID_SetMouse(false, false, false);
519 vkey = MapKey(lParam, wParam);
520 GetKeyboardState (state);
521 // alt/ctrl/shift tend to produce funky ToAscii values,
522 // and if it's not a single character we don't know care about it
523 charlength = ToAscii (wParam, lParam >> 16, state, (LPWORD)asciichar, 0);
524 if (vkey == K_ALT || vkey == K_CTRL || vkey == K_SHIFT || charlength == 0)
526 else if( charlength == 2 ) {
527 asciichar[0] = asciichar[1];
529 Key_Event (vkey, asciichar[0], down);
533 // keep Alt-Space from happening
537 // prevent screensaver from occuring while the active window
538 // note: password-locked screensavers on Vista still work
539 if (vid_activewindow && ((wParam & 0xFFF0) == SC_SCREENSAVE || (wParam & 0xFFF0) == SC_MONITORPOWER))
542 lRet = DefWindowProc (hWnd, uMsg, wParam, lParam);
545 // this is complicated because Win32 seems to pack multiple mouse events into
546 // one update sometimes, so we always check all states and look for events
553 case WM_XBUTTONDOWN: // backslash :: imouse explorer buttons
554 case WM_XBUTTONUP: // backslash :: imouse explorer buttons
558 if (wParam & MK_LBUTTON)
561 if (wParam & MK_RBUTTON)
564 if (wParam & MK_MBUTTON)
567 /* backslash :: imouse explorer buttons */
568 if (wParam & MK_XBUTTON1)
571 if (wParam & MK_XBUTTON2)
575 // LordHavoc: lets hope this allows more buttons in the future...
576 if (wParam & MK_XBUTTON3)
578 if (wParam & MK_XBUTTON4)
580 if (wParam & MK_XBUTTON5)
582 if (wParam & MK_XBUTTON6)
584 if (wParam & MK_XBUTTON7)
587 #ifdef SUPPORTDIRECTX
588 if (!dinput_acquired)
591 // perform button actions
593 for (i=0 ; i<mouse_buttons && i < 16 ; i++)
594 if ((temp ^ mouse_oldbuttonstate) & (1<<i))
595 Key_Event (buttonremap[i], 0, (temp & (1<<i)) != 0);
596 mouse_oldbuttonstate = temp;
601 // JACK: This is the mouse wheel with the Intellimouse
602 // Its delta is either positive or neg, and we generate the proper
605 if ((short) HIWORD(wParam) > 0) {
606 Key_Event(K_MWHEELUP, 0, true);
607 Key_Event(K_MWHEELUP, 0, false);
609 Key_Event(K_MWHEELDOWN, 0, true);
610 Key_Event(K_MWHEELDOWN, 0, false);
618 if (MessageBox (mainwindow, "Are you sure you want to quit?", "Confirm Exit", MB_YESNO | MB_SETFOREGROUND | MB_ICONQUESTION) == IDYES)
624 fActive = LOWORD(wParam);
625 fMinimized = (BOOL) HIWORD(wParam);
626 AppActivate(!(fActive == WA_INACTIVE), fMinimized);
628 // fix the leftover Alt from any Alt-Tab or the like that switched us away
634 // PostQuitMessage (0);
638 lRet = CDAudio_MessageHandler (hWnd, uMsg, wParam, lParam);
642 /* pass all unhandled messages to DefWindowProc */
643 lRet = DefWindowProc (hWnd, uMsg, wParam, lParam);
647 /* return 1 if handled message, 0 if not */
651 int VID_SetGamma(unsigned short *ramps, int rampsize)
653 HDC hdc = GetDC (NULL);
654 int i = SetDeviceGammaRamp(hdc, ramps);
655 ReleaseDC (NULL, hdc);
656 return i; // return success or failure
659 int VID_GetGamma(unsigned short *ramps, int rampsize)
661 HDC hdc = GetDC (NULL);
662 int i = GetDeviceGammaRamp(hdc, ramps);
663 ReleaseDC (NULL, hdc);
664 return i; // return success or failure
667 static HINSTANCE gldll;
669 static void GL_CloseLibrary(void)
674 qwglGetProcAddress = NULL;
677 gl_platformextensions = "";
680 static int GL_OpenLibrary(const char *name)
682 Con_Printf("Loading OpenGL driver %s\n", name);
684 if (!(gldll = LoadLibrary(name)))
686 Con_Printf("Unable to LoadLibrary %s\n", name);
689 strlcpy(gl_driver, name, sizeof(gl_driver));
693 void *GL_GetProcAddress(const char *name)
696 if (qwglGetProcAddress != NULL)
697 p = (void *) qwglGetProcAddress(name);
699 p = (void *) GetProcAddress(gldll, name);
703 #ifndef WGL_ARB_pixel_format
704 #define WGL_NUMBER_PIXEL_FORMATS_ARB 0x2000
705 #define WGL_DRAW_TO_WINDOW_ARB 0x2001
706 #define WGL_DRAW_TO_BITMAP_ARB 0x2002
707 #define WGL_ACCELERATION_ARB 0x2003
708 #define WGL_NEED_PALETTE_ARB 0x2004
709 #define WGL_NEED_SYSTEM_PALETTE_ARB 0x2005
710 #define WGL_SWAP_LAYER_BUFFERS_ARB 0x2006
711 #define WGL_SWAP_METHOD_ARB 0x2007
712 #define WGL_NUMBER_OVERLAYS_ARB 0x2008
713 #define WGL_NUMBER_UNDERLAYS_ARB 0x2009
714 #define WGL_TRANSPARENT_ARB 0x200A
715 #define WGL_TRANSPARENT_RED_VALUE_ARB 0x2037
716 #define WGL_TRANSPARENT_GREEN_VALUE_ARB 0x2038
717 #define WGL_TRANSPARENT_BLUE_VALUE_ARB 0x2039
718 #define WGL_TRANSPARENT_ALPHA_VALUE_ARB 0x203A
719 #define WGL_TRANSPARENT_INDEX_VALUE_ARB 0x203B
720 #define WGL_SHARE_DEPTH_ARB 0x200C
721 #define WGL_SHARE_STENCIL_ARB 0x200D
722 #define WGL_SHARE_ACCUM_ARB 0x200E
723 #define WGL_SUPPORT_GDI_ARB 0x200F
724 #define WGL_SUPPORT_OPENGL_ARB 0x2010
725 #define WGL_DOUBLE_BUFFER_ARB 0x2011
726 #define WGL_STEREO_ARB 0x2012
727 #define WGL_PIXEL_TYPE_ARB 0x2013
728 #define WGL_COLOR_BITS_ARB 0x2014
729 #define WGL_RED_BITS_ARB 0x2015
730 #define WGL_RED_SHIFT_ARB 0x2016
731 #define WGL_GREEN_BITS_ARB 0x2017
732 #define WGL_GREEN_SHIFT_ARB 0x2018
733 #define WGL_BLUE_BITS_ARB 0x2019
734 #define WGL_BLUE_SHIFT_ARB 0x201A
735 #define WGL_ALPHA_BITS_ARB 0x201B
736 #define WGL_ALPHA_SHIFT_ARB 0x201C
737 #define WGL_ACCUM_BITS_ARB 0x201D
738 #define WGL_ACCUM_RED_BITS_ARB 0x201E
739 #define WGL_ACCUM_GREEN_BITS_ARB 0x201F
740 #define WGL_ACCUM_BLUE_BITS_ARB 0x2020
741 #define WGL_ACCUM_ALPHA_BITS_ARB 0x2021
742 #define WGL_DEPTH_BITS_ARB 0x2022
743 #define WGL_STENCIL_BITS_ARB 0x2023
744 #define WGL_AUX_BUFFERS_ARB 0x2024
745 #define WGL_NO_ACCELERATION_ARB 0x2025
746 #define WGL_GENERIC_ACCELERATION_ARB 0x2026
747 #define WGL_FULL_ACCELERATION_ARB 0x2027
748 #define WGL_SWAP_EXCHANGE_ARB 0x2028
749 #define WGL_SWAP_COPY_ARB 0x2029
750 #define WGL_SWAP_UNDEFINED_ARB 0x202A
751 #define WGL_TYPE_RGBA_ARB 0x202B
752 #define WGL_TYPE_COLORINDEX_ARB 0x202C
755 #ifndef WGL_ARB_multisample
756 #define WGL_SAMPLE_BUFFERS_ARB 0x2041
757 #define WGL_SAMPLES_ARB 0x2042
761 static void IN_Init(void);
766 InitCommonControls();
767 hIcon = LoadIcon (global_hInstance, MAKEINTRESOURCE (IDI_ICON1));
769 // Register the frame class
771 wc.lpfnWndProc = (WNDPROC)MainWndProc;
774 wc.hInstance = global_hInstance;
776 wc.hCursor = LoadCursor (NULL,IDC_ARROW);
777 wc.hbrBackground = NULL;
779 wc.lpszClassName = "DarkPlacesWindowClass";
781 if (!RegisterClass (&wc))
782 Con_Printf ("Couldn't register window class\n");
784 memset(&initialdevmode, 0, sizeof(initialdevmode));
785 EnumDisplaySettings(NULL, ENUM_CURRENT_SETTINGS, &initialdevmode);
790 int VID_InitMode (int fullscreen, int *width, int *height, int bpp, int refreshrate, int stereobuffer, int samples)
796 PIXELFORMATDESCRIPTOR pfd =
798 sizeof(PIXELFORMATDESCRIPTOR), // size of this pfd
800 PFD_DRAW_TO_WINDOW // support window
801 | PFD_SUPPORT_OPENGL // support OpenGL
802 | PFD_DOUBLEBUFFER , // double buffered
803 PFD_TYPE_RGBA, // RGBA type
804 24, // 24-bit color depth
805 0, 0, 0, 0, 0, 0, // color bits ignored
806 0, // no alpha buffer
807 0, // shift bit ignored
808 0, // no accumulation buffer
809 0, 0, 0, 0, // accum bits ignored
810 32, // 32-bit z-buffer
811 0, // no stencil buffer
812 0, // no auxiliary buffer
813 PFD_MAIN_PLANE, // main layer
815 0, 0, 0 // layer masks ignored
818 int pixelformat, newpixelformat;
819 UINT numpixelformats;
820 DWORD WindowStyle, ExWindowStyle;
821 int CenterX, CenterY;
822 const char *gldrivername;
825 qboolean foundmode, foundgoodmode;
832 Sys_Error("VID_InitMode called when video is already initialised");
834 // if stencil is enabled, ask for alpha too
842 pfd.cStencilBits = 8;
851 pfd.cStencilBits = 0;
855 pfd.dwFlags |= PFD_STEREO;
859 *a++ = WGL_DRAW_TO_WINDOW_ARB;
861 *a++ = WGL_ACCELERATION_ARB;
862 *a++ = WGL_FULL_ACCELERATION_ARB;
863 *a++ = WGL_DOUBLE_BUFFER_ARB;
868 *a++ = WGL_RED_BITS_ARB;
870 *a++ = WGL_GREEN_BITS_ARB;
872 *a++ = WGL_BLUE_BITS_ARB;
874 *a++ = WGL_ALPHA_BITS_ARB;
876 *a++ = WGL_DEPTH_BITS_ARB;
878 *a++ = WGL_STENCIL_BITS_ARB;
883 *a++ = WGL_RED_BITS_ARB;
885 *a++ = WGL_GREEN_BITS_ARB;
887 *a++ = WGL_BLUE_BITS_ARB;
889 *a++ = WGL_DEPTH_BITS_ARB;
895 *a++ = WGL_STEREO_ARB;
901 *a++ = WGL_SAMPLE_BUFFERS_ARB;
903 *a++ = WGL_SAMPLES_ARB;
910 gldrivername = "opengl32.dll";
911 // 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
912 i = COM_CheckParm("-gl_driver");
913 if (i && i < com_argc - 1)
914 gldrivername = com_argv[i + 1];
915 if (!GL_OpenLibrary(gldrivername))
917 Con_Printf("Unable to load GL driver %s\n", gldrivername);
921 memset(&gdevmode, 0, sizeof(gdevmode));
923 vid_isfullscreen = false;
926 if(vid_forcerefreshrate.integer)
929 gdevmode.dmFields = DM_BITSPERPEL | DM_PELSWIDTH | DM_PELSHEIGHT;
930 gdevmode.dmBitsPerPel = bpp;
931 gdevmode.dmPelsWidth = *width;
932 gdevmode.dmPelsHeight = *height;
933 gdevmode.dmSize = sizeof (gdevmode);
936 gdevmode.dmFields |= DM_DISPLAYFREQUENCY;
937 gdevmode.dmDisplayFrequency = refreshrate;
943 refreshrate = initialdevmode.dmDisplayFrequency; // default vid_refreshrate to the rate of the desktop
946 foundgoodmode = false;
948 thismode.dmSize = sizeof(thismode);
949 thismode.dmDriverExtra = 0;
950 for(i = 0; EnumDisplaySettings(NULL, i, &thismode); ++i)
952 if(~thismode.dmFields & (DM_BITSPERPEL | DM_PELSWIDTH | DM_PELSHEIGHT | DM_DISPLAYFREQUENCY))
954 Con_DPrintf("enumerating modes yielded a bogus item... please debug this\n");
957 if(developer.integer >= 100)
958 Con_Printf("Found mode %dx%dx%dbpp %dHz... ", (int)thismode.dmPelsWidth, (int)thismode.dmPelsHeight, (int)thismode.dmBitsPerPel, (int)thismode.dmDisplayFrequency);
959 if(thismode.dmBitsPerPel != (DWORD)bpp)
961 if(developer.integer >= 100)
962 Con_Printf("wrong bpp\n");
965 if(thismode.dmPelsWidth != (DWORD)*width)
967 if(developer.integer >= 100)
968 Con_Printf("wrong width\n");
971 if(thismode.dmPelsHeight != (DWORD)*height)
973 if(developer.integer >= 100)
974 Con_Printf("wrong height\n");
980 // if we have a good mode, make sure this mode is better than the previous one, and allowed by the refreshrate
981 if(thismode.dmDisplayFrequency > (DWORD)refreshrate)
983 if(developer.integer >= 100)
984 Con_Printf("too high refresh rate\n");
987 else if(thismode.dmDisplayFrequency <= gdevmode.dmDisplayFrequency)
989 if(developer.integer >= 100)
990 Con_Printf("doesn't beat previous best match (too low)\n");
996 // we do have one, but it isn't good... make sure it has a lower frequency than the previous one
997 if(thismode.dmDisplayFrequency >= gdevmode.dmDisplayFrequency)
999 if(developer.integer >= 100)
1000 Con_Printf("doesn't beat previous best match (too high)\n");
1004 // otherwise, take anything
1006 memcpy(&gdevmode, &thismode, sizeof(gdevmode));
1007 if(thismode.dmDisplayFrequency <= (DWORD)refreshrate)
1008 foundgoodmode = true;
1011 if(developer.integer >= 100)
1012 Con_Printf("(out of range)\n");
1015 if(developer.integer >= 100)
1016 Con_Printf("accepted\n");
1023 Con_Printf("Unable to find the requested mode %dx%dx%dbpp\n", *width, *height, bpp);
1026 else if(ChangeDisplaySettings (&gdevmode, CDS_FULLSCREEN) != DISP_CHANGE_SUCCESSFUL)
1029 Con_Printf("Unable to change to requested mode %dx%dx%dbpp\n", *width, *height, bpp);
1033 vid_isfullscreen = true;
1034 WindowStyle = WS_POPUP;
1035 ExWindowStyle = WS_EX_TOPMOST;
1040 i = GetDeviceCaps(hdc, RASTERCAPS);
1041 depth = GetDeviceCaps(hdc, PLANES) * GetDeviceCaps(hdc, BITSPIXEL);
1042 ReleaseDC (NULL, hdc);
1046 Con_Print("Can't run in non-RGB mode\n");
1052 Con_Print("A higher desktop depth is required to run this video mode\n");
1056 WindowStyle = WS_OVERLAPPED | WS_BORDER | WS_CAPTION | WS_SYSMENU | WS_MINIMIZEBOX;
1062 rect.right = *width;
1063 rect.bottom = *height;
1064 AdjustWindowRectEx(&rect, WindowStyle, false, 0);
1073 CenterX = (GetSystemMetrics(SM_CXSCREEN) - (rect.right - rect.left)) / 2;
1074 CenterY = (GetSystemMetrics(SM_CYSCREEN) - (rect.bottom - rect.top)) / 2;
1076 CenterX = max(0, CenterX);
1077 CenterY = max(0, CenterY);
1079 // x and y may be changed by WM_MOVE messages
1082 rect.left += CenterX;
1083 rect.right += CenterX;
1084 rect.top += CenterY;
1085 rect.bottom += CenterY;
1089 // start out at the final windowpass if samples is 1 as it's the only feature we need extended pixel formats for
1090 for (windowpass = samples == 1;windowpass < 2;windowpass++)
1093 gl_platformextensions = "";
1095 mainwindow = CreateWindowEx (ExWindowStyle, "DarkPlacesWindowClass", gamename, WindowStyle, rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top, NULL, NULL, global_hInstance, NULL);
1098 Con_Printf("CreateWindowEx(%d, %s, %s, %d, %d, %d, %d, %d, %p, %p, %d, %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, (int)global_hInstance, NULL);
1103 baseDC = GetDC(mainwindow);
1105 if (!newpixelformat)
1106 newpixelformat = ChoosePixelFormat(baseDC, &pfd);
1107 pixelformat = newpixelformat;
1111 Con_Printf("ChoosePixelFormat(%d, %p) failed\n", (int)baseDC, &pfd);
1115 if (SetPixelFormat(baseDC, pixelformat, &pfd) == false)
1118 Con_Printf("SetPixelFormat(%d, %d, %p) failed\n", (int)baseDC, pixelformat, &pfd);
1122 if (!GL_CheckExtension("wgl", wglfuncs, NULL, false))
1125 Con_Print("wgl functions not found\n");
1129 baseRC = qwglCreateContext(baseDC);
1133 Con_Print("Could not initialize GL (wglCreateContext failed).\n\nMake sure you are in 65536 color mode, and try running -window.\n");
1136 if (!qwglMakeCurrent(baseDC, baseRC))
1139 Con_Printf("wglMakeCurrent(%d, %d) failed\n", (int)baseDC, (int)baseRC);
1143 if ((qglGetString = (const GLubyte* (GLAPIENTRY *)(GLenum name))GL_GetProcAddress("glGetString")) == NULL)
1146 Con_Print("glGetString not found\n");
1149 if ((qwglGetExtensionsStringARB = (const char *(WINAPI *)(HDC hdc))GL_GetProcAddress("wglGetExtensionsStringARB")) == NULL)
1150 Con_Print("wglGetExtensionsStringARB not found\n");
1152 gl_extensions = (const char *)qglGetString(GL_EXTENSIONS);
1153 gl_platform = "WGL";
1154 gl_platformextensions = "";
1156 if (qwglGetExtensionsStringARB)
1157 gl_platformextensions = (const char *)qwglGetExtensionsStringARB(baseDC);
1161 if (!gl_platformextensions)
1162 gl_platformextensions = "";
1164 // now some nice Windows pain:
1165 // we have created a window, we needed one to find out if there are
1166 // any multisample pixel formats available, the problem is that to
1167 // actually use one of those multisample formats we now have to
1168 // recreate the window (yes Microsoft OpenGL really is that bad)
1170 if (windowpass == 0)
1172 if (!GL_CheckExtension("WGL_ARB_pixel_format", wglpixelformatfuncs, "-noarbpixelformat", false) || !qwglChoosePixelFormatARB(baseDC, attribs, attribsf, 1, &newpixelformat, &numpixelformats) || !newpixelformat)
1174 // ok we got one - do it all over again with newpixelformat
1175 qwglMakeCurrent(NULL, NULL);
1176 qwglDeleteContext(baseRC);baseRC = 0;
1177 ReleaseDC(mainwindow, baseDC);baseDC = 0;
1178 // eat up any messages waiting for us
1179 while (PeekMessage (&msg, NULL, 0, 0, PM_REMOVE))
1181 TranslateMessage (&msg);
1182 DispatchMessage (&msg);
1189 SetWindowPos (mainwindow, NULL, CenterX, CenterY, 0, 0,SWP_NOSIZE | SWP_NOZORDER | SWP_SHOWWINDOW | SWP_DRAWFRAME);
1192 ShowWindow (mainwindow, SW_SHOWDEFAULT);
1193 UpdateWindow (mainwindow);
1195 // now we try to make sure we get the focus on the mode switch, because
1196 // sometimes in some systems we don't. We grab the foreground, then
1197 // finish setting up, pump all our messages, and sleep for a little while
1198 // to let messages finish bouncing around the system, then we put
1199 // ourselves at the top of the z order, then grab the foreground again,
1200 // Who knows if it helps, but it probably doesn't hurt
1201 SetForegroundWindow (mainwindow);
1203 while (PeekMessage (&msg, NULL, 0, 0, PM_REMOVE))
1205 TranslateMessage (&msg);
1206 DispatchMessage (&msg);
1211 SetWindowPos (mainwindow, HWND_TOP, 0, 0, 0, 0, SWP_DRAWFRAME | SWP_NOMOVE | SWP_NOSIZE | SWP_SHOWWINDOW | SWP_NOCOPYBITS);
1213 SetForegroundWindow (mainwindow);
1215 // fix the leftover Alt from any Alt-Tab or the like that switched us away
1218 gl_videosyncavailable = false;
1220 // COMMANDLINEOPTION: Windows WGL: -novideosync disables WGL_EXT_swap_control
1221 gl_videosyncavailable = GL_CheckExtension("WGL_EXT_swap_control", wglswapintervalfuncs, "-novideosync", false);
1225 //vid_menudrawfn = VID_MenuDraw;
1226 //vid_menukeyfn = VID_MenuKey;
1227 vid_usingmouse = false;
1228 vid_usinghidecursor = false;
1229 vid_usingvsync = false;
1231 vid_initialized = true;
1234 IN_StartupJoystick ();
1236 if (gl_videosyncavailable)
1238 vid_usevsync = vid_vsync.integer;
1239 vid_usingvsync = vid_vsync.integer;
1240 qwglSwapIntervalEXT (vid_usevsync);
1246 static void IN_Shutdown(void);
1247 void VID_Shutdown (void)
1249 if(vid_initialized == false)
1252 VID_SetMouse(false, false, false);
1253 VID_RestoreSystemGamma();
1255 vid_initialized = false;
1257 if (qwglMakeCurrent)
1258 qwglMakeCurrent(NULL, NULL);
1259 if (baseRC && qwglDeleteContext)
1260 qwglDeleteContext(baseRC);
1261 // close the library before we get rid of the window
1263 if (baseDC && mainwindow)
1264 ReleaseDC(mainwindow, baseDC);
1265 AppActivate(false, false);
1267 DestroyWindow(mainwindow);
1269 if (vid_isfullscreen)
1270 ChangeDisplaySettings (NULL, 0);
1271 vid_isfullscreen = false;
1274 void VID_SetMouse(qboolean fullscreengrab, qboolean relative, qboolean hidecursor)
1276 static qboolean restore_spi;
1277 static int originalmouseparms[3];
1279 if (!mouseinitialized)
1284 if (!vid_usingmouse)
1286 vid_usingmouse = true;
1287 cl_ignoremousemoves = 2;
1288 #ifdef SUPPORTDIRECTX
1289 if (dinput && g_pMouse)
1291 IDirectInputDevice_Acquire(g_pMouse);
1292 dinput_acquired = true;
1298 window_rect.left = window_x;
1299 window_rect.top = window_y;
1300 window_rect.right = window_x + vid.width;
1301 window_rect.bottom = window_y + vid.height;
1303 // change mouse settings to turn off acceleration
1304 // COMMANDLINEOPTION: Windows GDI Input: -noforcemparms disables setting of mouse parameters (not used with -dinput, windows only)
1305 if (!COM_CheckParm ("-noforcemparms") && SystemParametersInfo (SPI_GETMOUSE, 0, originalmouseparms, 0))
1307 int newmouseparms[3];
1308 newmouseparms[0] = 0; // threshold to double movement (only if accel level is >= 1)
1309 newmouseparms[1] = 0; // threshold to quadruple movement (only if accel level is >= 2)
1310 newmouseparms[2] = 0; // maximum level of acceleration (0 = off)
1311 restore_spi = SystemParametersInfo (SPI_SETMOUSE, 0, newmouseparms, 0);
1314 restore_spi = false;
1315 SetCursorPos ((window_x + vid.width / 2), (window_y + vid.height / 2));
1317 SetCapture (mainwindow);
1318 ClipCursor (&window_rect);
1326 vid_usingmouse = false;
1327 cl_ignoremousemoves = 2;
1328 #ifdef SUPPORTDIRECTX
1329 if (dinput_acquired)
1331 IDirectInputDevice_Unacquire(g_pMouse);
1332 dinput_acquired = false;
1337 // restore system mouseparms if we changed them
1339 SystemParametersInfo (SPI_SETMOUSE, 0, originalmouseparms, 0);
1340 restore_spi = false;
1347 if (vid_usinghidecursor != hidecursor)
1349 vid_usinghidecursor = hidecursor;
1350 ShowCursor (!hidecursor);
1355 #ifdef SUPPORTDIRECTX
1361 static qboolean IN_InitDInput (void)
1364 DIPROPDWORD dipdw = {
1366 sizeof(DIPROPDWORD), // diph.dwSize
1367 sizeof(DIPROPHEADER), // diph.dwHeaderSize
1369 DIPH_DEVICE, // diph.dwHow
1371 DINPUT_BUFFERSIZE, // dwData
1376 hInstDI = LoadLibrary("dinput.dll");
1378 if (hInstDI == NULL)
1380 Con_Print("Couldn't load dinput.dll\n");
1385 if (!pDirectInputCreate)
1387 pDirectInputCreate = (void *)GetProcAddress(hInstDI,"DirectInputCreateA");
1389 if (!pDirectInputCreate)
1391 Con_Print("Couldn't get DI proc addr\n");
1396 // register with DirectInput and get an IDirectInput to play with.
1397 hr = iDirectInputCreate(global_hInstance, DIRECTINPUT_VERSION, &g_pdi, NULL);
1404 // obtain an interface to the system mouse device.
1405 hr = IDirectInput_CreateDevice(g_pdi, &GUID_SysMouse, &g_pMouse, NULL);
1409 Con_Print("Couldn't open DI mouse device\n");
1413 // set the data format to "mouse format".
1414 hr = IDirectInputDevice_SetDataFormat(g_pMouse, &c_dfDIMouse);
1418 Con_Print("Couldn't set DI mouse format\n");
1422 // set the cooperativity level.
1423 hr = IDirectInputDevice_SetCooperativeLevel(g_pMouse, mainwindow,
1424 DISCL_EXCLUSIVE | DISCL_FOREGROUND);
1428 Con_Print("Couldn't set DI coop level\n");
1433 // set the buffer size to DINPUT_BUFFERSIZE elements.
1434 // the buffer size is a DWORD property associated with the device
1435 hr = IDirectInputDevice_SetProperty(g_pMouse, DIPROP_BUFFERSIZE, &dipdw.diph);
1439 Con_Print("Couldn't set DI buffersize\n");
1453 static void IN_StartupMouse (void)
1455 if (COM_CheckParm ("-nomouse"))
1458 mouseinitialized = true;
1460 #ifdef SUPPORTDIRECTX
1461 // COMMANDLINEOPTION: Windows Input: -dinput enables DirectInput for mouse/joystick input
1462 if (COM_CheckParm ("-dinput"))
1463 dinput = IN_InitDInput ();
1466 Con_Print("DirectInput initialized\n");
1468 Con_Print("DirectInput not initialized\n");
1480 static void IN_MouseMove (void)
1484 GetCursorPos (¤t_pos);
1485 in_windowmouse_x = current_pos.x - window_x;
1486 in_windowmouse_y = current_pos.y - window_y;
1488 if (!vid_usingmouse)
1491 #ifdef SUPPORTDIRECTX
1492 if (dinput_acquired)
1495 DIDEVICEOBJECTDATA od;
1503 hr = IDirectInputDevice_GetDeviceData(g_pMouse,
1504 sizeof(DIDEVICEOBJECTDATA), &od, &dwElements, 0);
1506 if ((hr == DIERR_INPUTLOST) || (hr == DIERR_NOTACQUIRED))
1508 IDirectInputDevice_Acquire(g_pMouse);
1512 /* Unable to read data or no data available */
1513 if (FAILED(hr) || dwElements == 0)
1516 /* Look at the element to see what happened */
1521 in_mouse_x += (LONG) od.dwData;
1525 in_mouse_y += (LONG) od.dwData;
1529 if((LONG) od.dwData < 0)
1531 Key_Event (K_MWHEELDOWN, 0, true);
1532 Key_Event (K_MWHEELDOWN, 0, false);
1534 else if((LONG) od.dwData > 0)
1536 Key_Event (K_MWHEELUP, 0, true);
1537 Key_Event (K_MWHEELUP, 0, false);
1541 case DIMOFS_BUTTON0:
1542 if (od.dwData & 0x80)
1548 case DIMOFS_BUTTON1:
1549 if (od.dwData & 0x80)
1550 mstate_di |= (1<<1);
1552 mstate_di &= ~(1<<1);
1555 case DIMOFS_BUTTON2:
1556 if (od.dwData & 0x80)
1557 mstate_di |= (1<<2);
1559 mstate_di &= ~(1<<2);
1562 case DIMOFS_BUTTON3:
1563 if (od.dwData & 0x80)
1564 mstate_di |= (1<<3);
1566 mstate_di &= ~(1<<3);
1571 // perform button actions
1572 for (i=0 ; i<mouse_buttons && i < 16 ; i++)
1573 if ((mstate_di ^ mouse_oldbuttonstate) & (1<<i))
1574 Key_Event (buttonremap[i], 0, (mstate_di & (1<<i)) != 0);
1575 mouse_oldbuttonstate = mstate_di;
1580 in_mouse_x += in_windowmouse_x - (int)(vid.width / 2);
1581 in_mouse_y += in_windowmouse_y - (int)(vid.height / 2);
1583 // if the mouse has moved, force it to the center, so there's room to move
1584 if (in_mouse_x || in_mouse_y)
1585 SetCursorPos ((window_x + vid.width / 2), (window_y + vid.height / 2));
1597 if (vid_activewindow && !vid_hidden)
1610 static void IN_StartupJoystick (void)
1617 // assume no joystick
1620 // abort startup if user requests no joystick
1621 // COMMANDLINEOPTION: Windows Input: -nojoy disables joystick support, may be a small speed increase
1622 if (COM_CheckParm ("-nojoy"))
1625 // verify joystick driver is present
1626 if ((numdevs = joyGetNumDevs ()) == 0)
1628 Con_Print("\njoystick not found -- driver not present\n\n");
1632 // cycle through the joystick ids for the first valid one
1633 for (joy_id=0 ; joy_id<numdevs ; joy_id++)
1635 memset (&ji, 0, sizeof(ji));
1636 ji.dwSize = sizeof(ji);
1637 ji.dwFlags = JOY_RETURNCENTERED;
1639 if ((mmr = joyGetPosEx (joy_id, &ji)) == JOYERR_NOERROR)
1643 // abort startup if we didn't find a valid joystick
1644 if (mmr != JOYERR_NOERROR)
1646 Con_Printf("\njoystick not found -- no valid joysticks (%x)\n\n", mmr);
1650 // get the capabilities of the selected joystick
1651 // abort startup if command fails
1652 memset (&jc, 0, sizeof(jc));
1653 if ((mmr = joyGetDevCaps (joy_id, &jc, sizeof(jc))) != JOYERR_NOERROR)
1655 Con_Printf("\njoystick not found -- invalid joystick capabilities (%x)\n\n", mmr);
1659 // save the joystick's number of buttons and POV status
1660 joy_numbuttons = jc.wNumButtons;
1661 joy_haspov = jc.wCaps & JOYCAPS_HASPOV;
1663 // old button and POV states default to no buttons pressed
1664 joy_oldbuttonstate = joy_oldpovstate = 0;
1666 // mark the joystick as available and advanced initialization not completed
1667 // this is needed as cvars are not available during initialization
1670 joy_advancedinit = false;
1672 Con_Print("\njoystick detected\n\n");
1681 static PDWORD RawValuePointer (int axis)
1698 return NULL; // LordHavoc: hush compiler warning
1704 Joy_AdvancedUpdate_f
1707 static void Joy_AdvancedUpdate_f (void)
1710 // called once by IN_ReadJoystick and by user whenever an update is needed
1711 // cvars are now available
1715 // initialize all the maps
1716 for (i = 0; i < JOY_MAX_AXES; i++)
1718 dwAxisMap[i] = AxisNada;
1719 dwControlMap[i] = JOY_ABSOLUTE_AXIS;
1720 pdwRawValue[i] = RawValuePointer(i);
1723 if( joy_advanced.integer == 0)
1725 // default joystick initialization
1726 // 2 axes only with joystick control
1727 dwAxisMap[JOY_AXIS_X] = AxisTurn;
1728 // dwControlMap[JOY_AXIS_X] = JOY_ABSOLUTE_AXIS;
1729 dwAxisMap[JOY_AXIS_Y] = AxisForward;
1730 // dwControlMap[JOY_AXIS_Y] = JOY_ABSOLUTE_AXIS;
1734 if (strcmp (joy_name.string, "joystick") != 0)
1736 // notify user of advanced controller
1737 Con_Printf("\n%s configured\n\n", joy_name.string);
1740 // advanced initialization here
1741 // data supplied by user via joy_axisn cvars
1742 dwTemp = (DWORD) joy_advaxisx.value;
1743 dwAxisMap[JOY_AXIS_X] = dwTemp & 0x0000000f;
1744 dwControlMap[JOY_AXIS_X] = dwTemp & JOY_RELATIVE_AXIS;
1745 dwTemp = (DWORD) joy_advaxisy.value;
1746 dwAxisMap[JOY_AXIS_Y] = dwTemp & 0x0000000f;
1747 dwControlMap[JOY_AXIS_Y] = dwTemp & JOY_RELATIVE_AXIS;
1748 dwTemp = (DWORD) joy_advaxisz.value;
1749 dwAxisMap[JOY_AXIS_Z] = dwTemp & 0x0000000f;
1750 dwControlMap[JOY_AXIS_Z] = dwTemp & JOY_RELATIVE_AXIS;
1751 dwTemp = (DWORD) joy_advaxisr.value;
1752 dwAxisMap[JOY_AXIS_R] = dwTemp & 0x0000000f;
1753 dwControlMap[JOY_AXIS_R] = dwTemp & JOY_RELATIVE_AXIS;
1754 dwTemp = (DWORD) joy_advaxisu.value;
1755 dwAxisMap[JOY_AXIS_U] = dwTemp & 0x0000000f;
1756 dwControlMap[JOY_AXIS_U] = dwTemp & JOY_RELATIVE_AXIS;
1757 dwTemp = (DWORD) joy_advaxisv.value;
1758 dwAxisMap[JOY_AXIS_V] = dwTemp & 0x0000000f;
1759 dwControlMap[JOY_AXIS_V] = dwTemp & JOY_RELATIVE_AXIS;
1762 // compute the axes to collect from DirectInput
1763 joy_flags = JOY_RETURNCENTERED | JOY_RETURNBUTTONS | JOY_RETURNPOV;
1764 for (i = 0; i < JOY_MAX_AXES; i++)
1766 if (dwAxisMap[i] != AxisNada)
1768 joy_flags |= dwAxisFlags[i];
1778 static qboolean IN_ReadJoystick (void)
1781 memset (&ji, 0, sizeof(ji));
1782 ji.dwSize = sizeof(ji);
1783 ji.dwFlags = joy_flags;
1785 if (joyGetPosEx (joy_id, &ji) == JOYERR_NOERROR)
1787 // this is a hack -- there is a bug in the Logitech WingMan Warrior DirectInput Driver
1788 // rather than having 32768 be the zero point, they have the zero point at 32668
1789 // go figure -- anyway, now we get the full resolution out of the device
1790 if (joy_wwhack1.integer != 0.0)
1798 // read error occurred
1799 // turning off the joystick seems too harsh for 1 read error,
1800 // but what should be done?
1811 static void IN_JoyMove (void)
1813 float speed, aspeed;
1814 float fAxisValue, fTemp;
1815 int i, mouselook = (in_mlook.state & 1) || freelook.integer;
1817 // complete initialization if first time in
1818 // this is needed as cvars are not available at initialization time
1819 if( joy_advancedinit != true )
1821 Joy_AdvancedUpdate_f();
1822 joy_advancedinit = true;
1828 DWORD buttonstate, povstate;
1830 // loop through the joystick buttons
1831 // key a joystick event or auxillary event for higher number buttons for each state change
1832 buttonstate = ji.dwButtons;
1833 for (i=0 ; i < (int) joy_numbuttons ; i++)
1835 if ( (buttonstate & (1<<i)) && !(joy_oldbuttonstate & (1<<i)) )
1837 key_index = (i < 16) ? K_JOY1 : K_AUX1;
1838 Key_Event (key_index + i, 0, true);
1841 if ( !(buttonstate & (1<<i)) && (joy_oldbuttonstate & (1<<i)) )
1843 key_index = (i < 16) ? K_JOY1 : K_AUX1;
1844 Key_Event (key_index + i, 0, false);
1847 joy_oldbuttonstate = buttonstate;
1851 // convert POV information into 4 bits of state information
1852 // this avoids any potential problems related to moving from one
1853 // direction to another without going through the center position
1855 if(ji.dwPOV != JOY_POVCENTERED)
1857 if (ji.dwPOV == JOY_POVFORWARD)
1859 if (ji.dwPOV == JOY_POVRIGHT)
1861 if (ji.dwPOV == JOY_POVBACKWARD)
1863 if (ji.dwPOV == JOY_POVLEFT)
1866 // determine which bits have changed and key an auxillary event for each change
1867 for (i=0 ; i < 4 ; i++)
1869 if ( (povstate & (1<<i)) && !(joy_oldpovstate & (1<<i)) )
1871 Key_Event (K_AUX29 + i, 0, true);
1874 if ( !(povstate & (1<<i)) && (joy_oldpovstate & (1<<i)) )
1876 Key_Event (K_AUX29 + i, 0, false);
1879 joy_oldpovstate = povstate;
1883 // verify joystick is available and that the user wants to use it
1884 if (!joy_avail || !in_joystick.integer)
1889 // collect the joystick data, if possible
1890 if (IN_ReadJoystick () != true)
1895 if (in_speed.state & 1)
1896 speed = cl_movespeedkey.value;
1899 // LordHavoc: viewzoom affects sensitivity for sniping
1900 aspeed = speed * cl.realframetime * cl.viewzoom;
1902 // loop through the axes
1903 for (i = 0; i < JOY_MAX_AXES; i++)
1905 // get the floating point zero-centered, potentially-inverted data for the current axis
1906 fAxisValue = (float) *pdwRawValue[i];
1907 // move centerpoint to zero
1908 fAxisValue -= 32768.0;
1910 if (joy_wwhack2.integer != 0.0)
1912 if (dwAxisMap[i] == AxisTurn)
1914 // this is a special formula for the Logitech WingMan Warrior
1915 // y=ax^b; where a = 300 and b = 1.3
1916 // also x values are in increments of 800 (so this is factored out)
1917 // then bounds check result to level out excessively high spin rates
1918 fTemp = 300.0 * pow(abs(fAxisValue) / 800.0, 1.3);
1919 if (fTemp > 14000.0)
1921 // restore direction information
1922 fAxisValue = (fAxisValue > 0.0) ? fTemp : -fTemp;
1926 // convert range from -32768..32767 to -1..1
1927 fAxisValue /= 32768.0;
1929 switch (dwAxisMap[i])
1932 if ((joy_advanced.integer == 0) && mouselook)
1934 // user wants forward control to become look control
1935 if (fabs(fAxisValue) > joy_pitchthreshold.value)
1937 // if mouse invert is on, invert the joystick pitch value
1938 // only absolute control support here (joy_advanced is false)
1939 if (m_pitch.value < 0.0)
1941 cl.viewangles[PITCH] -= (fAxisValue * joy_pitchsensitivity.value) * aspeed * cl_pitchspeed.value;
1945 cl.viewangles[PITCH] += (fAxisValue * joy_pitchsensitivity.value) * aspeed * cl_pitchspeed.value;
1951 // no pitch movement
1952 // disable pitch return-to-center unless requested by user
1953 // *** this code can be removed when the lookspring bug is fixed
1954 // *** the bug always has the lookspring feature on
1955 if(lookspring.value == 0.0)
1961 // user wants forward control to be forward control
1962 if (fabs(fAxisValue) > joy_forwardthreshold.value)
1964 cl.cmd.forwardmove += (fAxisValue * joy_forwardsensitivity.value) * speed * cl_forwardspeed.value;
1970 if (fabs(fAxisValue) > joy_sidethreshold.value)
1972 cl.cmd.sidemove += (fAxisValue * joy_sidesensitivity.value) * speed * cl_sidespeed.value;
1977 if ((in_strafe.state & 1) || (lookstrafe.integer && mouselook))
1979 // user wants turn control to become side control
1980 if (fabs(fAxisValue) > joy_sidethreshold.value)
1982 cl.cmd.sidemove -= (fAxisValue * joy_sidesensitivity.value) * speed * cl_sidespeed.value;
1987 // user wants turn control to be turn control
1988 if (fabs(fAxisValue) > joy_yawthreshold.value)
1990 if(dwControlMap[i] == JOY_ABSOLUTE_AXIS)
1992 cl.viewangles[YAW] += (fAxisValue * joy_yawsensitivity.value) * aspeed * cl_yawspeed.value;
1996 cl.viewangles[YAW] += (fAxisValue * joy_yawsensitivity.value) * speed * 180.0;
2006 if (fabs(fAxisValue) > joy_pitchthreshold.value)
2008 // pitch movement detected and pitch movement desired by user
2009 if(dwControlMap[i] == JOY_ABSOLUTE_AXIS)
2011 cl.viewangles[PITCH] += (fAxisValue * joy_pitchsensitivity.value) * aspeed * cl_pitchspeed.value;
2015 cl.viewangles[PITCH] += (fAxisValue * joy_pitchsensitivity.value) * speed * 180.0;
2021 // no pitch movement
2022 // disable pitch return-to-center unless requested by user
2023 // *** this code can be removed when the lookspring bug is fixed
2024 // *** the bug always has the lookspring feature on
2025 if(lookspring.integer == 0)
2037 static void IN_Init(void)
2039 uiWheelMessage = RegisterWindowMessage ( "MSWHEEL_ROLLMSG" );
2041 // joystick variables
2042 Cvar_RegisterVariable (&in_joystick);
2043 Cvar_RegisterVariable (&joy_name);
2044 Cvar_RegisterVariable (&joy_advanced);
2045 Cvar_RegisterVariable (&joy_advaxisx);
2046 Cvar_RegisterVariable (&joy_advaxisy);
2047 Cvar_RegisterVariable (&joy_advaxisz);
2048 Cvar_RegisterVariable (&joy_advaxisr);
2049 Cvar_RegisterVariable (&joy_advaxisu);
2050 Cvar_RegisterVariable (&joy_advaxisv);
2051 Cvar_RegisterVariable (&joy_forwardthreshold);
2052 Cvar_RegisterVariable (&joy_sidethreshold);
2053 Cvar_RegisterVariable (&joy_pitchthreshold);
2054 Cvar_RegisterVariable (&joy_yawthreshold);
2055 Cvar_RegisterVariable (&joy_forwardsensitivity);
2056 Cvar_RegisterVariable (&joy_sidesensitivity);
2057 Cvar_RegisterVariable (&joy_pitchsensitivity);
2058 Cvar_RegisterVariable (&joy_yawsensitivity);
2059 Cvar_RegisterVariable (&joy_wwhack1);
2060 Cvar_RegisterVariable (&joy_wwhack2);
2061 Cvar_RegisterVariable (&vid_forcerefreshrate);
2062 Cmd_AddCommand ("joyadvancedupdate", Joy_AdvancedUpdate_f, "applies current joyadv* cvar settings to the joystick driver");
2065 static void IN_Shutdown(void)
2067 #ifdef SUPPORTDIRECTX
2069 IDirectInputDevice_Release(g_pMouse);
2073 IDirectInput_Release(g_pdi);
2078 size_t VID_ListModes(vid_mode_t *modes, size_t maxcount)
2084 thismode.dmSize = sizeof(thismode);
2085 thismode.dmDriverExtra = 0;
2087 for(i = 0; EnumDisplaySettings(NULL, i, &thismode); ++i)
2089 if(~thismode.dmFields & (DM_BITSPERPEL | DM_PELSWIDTH | DM_PELSHEIGHT | DM_DISPLAYFREQUENCY))
2091 Con_DPrintf("enumerating modes yielded a bogus item... please debug this\n");
2096 modes[k].width = thismode.dmPelsWidth;
2097 modes[k].height = thismode.dmPelsHeight;
2098 modes[k].bpp = thismode.dmBitsPerPel;
2099 modes[k].refreshrate = thismode.dmDisplayFrequency;
2100 modes[k].pixelheight_num = 1;
2101 modes[k].pixelheight_denom = 1; // Win32 apparently does not provide this (FIXME)