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
23 #pragma comment(lib, "comctl32.lib")
29 #pragma comment(lib, "dinput8.lib")
30 #pragma comment(lib, "dxguid.lib")
32 #ifndef DIRECTINPUT_VERSION
33 # define DIRECTINPUT_VERSION 0x0500 /* Version 5.0 */
48 #include "dpsoftrast.h"
53 cvar_t vid_dx9 = {CVAR_SAVE, "vid_dx9", "0", "use Microsoft Direct3D9(r) for rendering"};
54 cvar_t vid_dx9_hal = {CVAR_SAVE, "vid_dx9_hal", "1", "enables hardware rendering (1), otherwise software reference rasterizer (0 - very slow), note that 0 is necessary when using NVPerfHUD (which renders in hardware but requires this option to enable it)"};
55 cvar_t vid_dx9_softvertex = {CVAR_SAVE, "vid_dx9_softvertex", "0", "enables software vertex processing (for compatibility testing? or if you have a very fast CPU), usually you want this off"};
56 cvar_t vid_dx9_triplebuffer = {CVAR_SAVE, "vid_dx9_triplebuffer", "0", "enables triple buffering when using vid_vsync in fullscreen, this options adds some latency and only helps when framerate is below 60 so you usually don't want it"};
57 //cvar_t vid_dx10 = {CVAR_SAVE, "vid_dx10", "1", "use Microsoft Direct3D10(r) for rendering"};
58 //cvar_t vid_dx11 = {CVAR_SAVE, "vid_dx11", "1", "use Microsoft Direct3D11(r) for rendering"};
60 D3DPRESENT_PARAMETERS vid_d3dpresentparameters;
62 // we declare this in vid_shared.c because it is required by dedicated server and all clients when SUPPORTD3D is defined
63 extern LPDIRECT3DDEVICE9 vid_d3d9dev;
66 D3DCAPS9 vid_d3d9caps;
67 qboolean vid_d3ddevicelost;
70 extern HINSTANCE global_hInstance;
72 static HINSTANCE gldll;
75 #define WM_MOUSEWHEEL 0x020A
78 // Tell startup code that we have a client
79 int cl_available = true;
81 qboolean vid_supportrefreshrate = true;
83 static int (WINAPI *qwglChoosePixelFormat)(HDC, CONST PIXELFORMATDESCRIPTOR *);
84 static int (WINAPI *qwglDescribePixelFormat)(HDC, int, UINT, LPPIXELFORMATDESCRIPTOR);
85 //static int (WINAPI *qwglGetPixelFormat)(HDC);
86 static BOOL (WINAPI *qwglSetPixelFormat)(HDC, int, CONST PIXELFORMATDESCRIPTOR *);
87 static BOOL (WINAPI *qwglSwapBuffers)(HDC);
88 static HGLRC (WINAPI *qwglCreateContext)(HDC);
89 static BOOL (WINAPI *qwglDeleteContext)(HGLRC);
90 static HGLRC (WINAPI *qwglGetCurrentContext)(VOID);
91 static HDC (WINAPI *qwglGetCurrentDC)(VOID);
92 static PROC (WINAPI *qwglGetProcAddress)(LPCSTR);
93 static BOOL (WINAPI *qwglMakeCurrent)(HDC, HGLRC);
94 static BOOL (WINAPI *qwglSwapIntervalEXT)(int interval);
95 static const char *(WINAPI *qwglGetExtensionsStringARB)(HDC hdc);
96 static BOOL (WINAPI *qwglChoosePixelFormatARB)(HDC hdc, const int *piAttribIList, const FLOAT *pfAttribFList, UINT nMaxFormats, int *piFormats, UINT *nNumFormats);
97 static BOOL (WINAPI *qwglGetPixelFormatAttribivARB)(HDC hdc, int iPixelFormat, int iLayerPlane, UINT nAttributes, const int *piAttributes, int *piValues);
99 static dllfunction_t wglfuncs[] =
101 {"wglChoosePixelFormat", (void **) &qwglChoosePixelFormat},
102 {"wglDescribePixelFormat", (void **) &qwglDescribePixelFormat},
103 // {"wglGetPixelFormat", (void **) &qwglGetPixelFormat},
104 {"wglSetPixelFormat", (void **) &qwglSetPixelFormat},
105 {"wglSwapBuffers", (void **) &qwglSwapBuffers},
106 {"wglCreateContext", (void **) &qwglCreateContext},
107 {"wglDeleteContext", (void **) &qwglDeleteContext},
108 {"wglGetProcAddress", (void **) &qwglGetProcAddress},
109 {"wglMakeCurrent", (void **) &qwglMakeCurrent},
110 {"wglGetCurrentContext", (void **) &qwglGetCurrentContext},
111 {"wglGetCurrentDC", (void **) &qwglGetCurrentDC},
115 static dllfunction_t wglswapintervalfuncs[] =
117 {"wglSwapIntervalEXT", (void **) &qwglSwapIntervalEXT},
121 static dllfunction_t wglpixelformatfuncs[] =
123 {"wglChoosePixelFormatARB", (void **) &qwglChoosePixelFormatARB},
124 {"wglGetPixelFormatAttribivARB", (void **) &qwglGetPixelFormatAttribivARB},
128 static DEVMODE gdevmode, initialdevmode;
129 static qboolean vid_initialized = false;
130 static qboolean vid_wassuspended = false;
131 static qboolean vid_usingmouse = false;
132 static qboolean vid_usinghidecursor = false;
133 static qboolean vid_usingvsync = false;
134 static qboolean vid_usevsync = false;
137 // used by cd_win.c and snd_win.c
143 static HDC vid_softhdc;
144 static HGDIOBJ vid_softhdc_backup;
145 static BITMAPINFO vid_softbmi;
146 static HBITMAP vid_softdibhandle;
148 //HWND WINAPI InitializeWindow (HINSTANCE hInstance, int nCmdShow);
150 static qboolean vid_isfullscreen;
152 //void VID_MenuDraw (void);
153 //void VID_MenuKey (int key);
155 //LONG WINAPI MainWndProc (HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
156 //void AppActivate(BOOL fActive, BOOL minimize);
157 //void ClearAllStates (void);
158 //void VID_UpdateWindowStatus (void);
160 //====================================
162 static int window_x, window_y;
164 static qboolean mouseinitialized;
166 #ifdef SUPPORTDIRECTX
167 static qboolean dinput;
168 #define DINPUT_BUFFERSIZE 16
169 #define iDirectInputCreate(a,b,c,d) pDirectInputCreate(a,b,c,d)
171 static HRESULT (WINAPI *pDirectInputCreate)(HINSTANCE hinst, DWORD dwVersion, LPDIRECTINPUT * lplpDirectInput, LPUNKNOWN punkOuter);
174 // LordHavoc: thanks to backslash for this support for mouse buttons 4 and 5
175 /* backslash :: imouse explorer buttons */
176 /* These are #ifdefed out for non-Win2K in the February 2001 version of
177 MS's platform SDK, but we need them for compilation. . . */
178 #ifndef WM_XBUTTONDOWN
179 #define WM_XBUTTONDOWN 0x020B
180 #define WM_XBUTTONUP 0x020C
183 #define MK_XBUTTON1 0x0020
184 #define MK_XBUTTON2 0x0040
187 // LordHavoc: lets hope this allows more buttons in the future...
188 #define MK_XBUTTON3 0x0080
189 #define MK_XBUTTON4 0x0100
190 #define MK_XBUTTON5 0x0200
191 #define MK_XBUTTON6 0x0400
192 #define MK_XBUTTON7 0x0800
197 static int mouse_buttons;
198 static int mouse_oldbuttonstate;
200 static unsigned int uiWheelMessage;
201 #ifdef SUPPORTDIRECTX
202 static qboolean dinput_acquired;
204 static unsigned int mstate_di;
207 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"};
209 #ifdef SUPPORTDIRECTX
210 static LPDIRECTINPUT g_pdi;
211 static LPDIRECTINPUTDEVICE g_pMouse;
212 static HINSTANCE hInstDI;
215 // forward-referenced functions
216 static void IN_StartupMouse (void);
219 //====================================
221 qboolean vid_reallyhidden = true;
223 qboolean vid_begunscene = false;
225 void VID_Finish (void)
230 vid_hidden = vid_reallyhidden;
232 vid_usevsync = vid_vsync.integer && !cls.timedemo && qwglSwapIntervalEXT;
236 switch(vid.renderpath)
238 case RENDERPATH_GL11:
239 case RENDERPATH_GL13:
240 case RENDERPATH_GL20:
241 case RENDERPATH_GLES1:
242 case RENDERPATH_GLES2:
243 if (vid_usingvsync != vid_usevsync)
245 vid_usingvsync = vid_usevsync;
246 qwglSwapIntervalEXT (vid_usevsync);
248 if (r_speeds.integer == 2 || gl_finish.integer)
252 case RENDERPATH_D3D9:
256 IDirect3DDevice9_EndScene(vid_d3d9dev);
257 vid_begunscene = false;
259 if (!vid_reallyhidden)
261 if (!vid_d3ddevicelost)
263 vid_hidden = vid_reallyhidden;
264 hr = IDirect3DDevice9_Present(vid_d3d9dev, NULL, NULL, NULL, NULL);
265 if (hr == D3DERR_DEVICELOST)
267 vid_d3ddevicelost = true;
274 hr = IDirect3DDevice9_TestCooperativeLevel(vid_d3d9dev);
277 case D3DERR_DEVICELOST:
278 vid_d3ddevicelost = true;
282 case D3DERR_DEVICENOTRESET:
283 vid_d3ddevicelost = false;
284 vid_hidden = vid_reallyhidden;
285 R_Modules_DeviceLost();
286 IDirect3DDevice9_Reset(vid_d3d9dev, &vid_d3dpresentparameters);
287 R_Modules_DeviceRestored();
290 vid_hidden = vid_reallyhidden;
291 IDirect3DDevice9_Present(vid_d3d9dev, NULL, NULL, NULL, NULL);
295 if (!vid_begunscene && !vid_hidden)
297 IDirect3DDevice9_BeginScene(vid_d3d9dev);
298 vid_begunscene = true;
303 case RENDERPATH_D3D10:
305 case RENDERPATH_D3D11:
307 case RENDERPATH_SOFT:
309 // baseDC = GetDC(mainwindow);
310 BitBlt(baseDC, 0, 0, vid.width, vid.height, vid_softhdc, 0, 0, SRCCOPY);
311 // ReleaseDC(mainwindow, baseDC);
317 // make sure a context switch can happen every frame - Logitech drivers
318 // input drivers sometimes eat cpu time every 3 seconds or lag badly
322 VID_UpdateGamma(false, 256);
325 //==========================================================================
330 static unsigned char scantokey[128] =
332 // 0 1 2 3 4 5 6 7 8 9 A B C D E F
333 0 ,27 ,'1' ,'2' ,'3' ,'4' ,'5' ,'6' ,'7' ,'8' ,'9' ,'0' ,'-' ,'=' ,K_BACKSPACE,9 ,//0
334 'q' ,'w' ,'e' ,'r' ,'t' ,'y' ,'u' ,'i' ,'o' ,'p' ,'[' ,']' ,13 ,K_CTRL ,'a' ,'s' ,//1
335 'd' ,'f' ,'g' ,'h' ,'j' ,'k' ,'l' ,';' ,'\'' ,'`' ,K_SHIFT ,'\\' ,'z' ,'x' ,'c' ,'v' ,//2
336 'b' ,'n' ,'m' ,',' ,'.' ,'/' ,K_SHIFT,'*' ,K_ALT ,' ' ,0 ,K_F1 ,K_F2 ,K_F3 ,K_F4 ,K_F5 ,//3
337 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
338 K_DOWNARROW,K_PGDN,K_INS,K_DEL,0 ,0 ,0 ,K_F11 ,K_F12 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,//5
339 0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,//6
340 0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 //7
348 Map from windows to quake keynums
351 static int MapKey (int key, int virtualkey)
354 int modified = (key >> 16) & 255;
355 qboolean is_extended = false;
357 if (modified < 128 && scantokey[modified])
358 result = scantokey[modified];
362 Con_DPrintf("key 0x%02x (0x%8x, 0x%8x) has no translation\n", modified, key, virtualkey);
379 return K_KP_LEFTARROW;
381 return K_KP_RIGHTARROW;
385 return K_KP_DOWNARROW;
412 ===================================================================
416 ===================================================================
424 static void ClearAllStates (void)
428 mouse_oldbuttonstate = 0;
431 void AppActivate(BOOL fActive, BOOL minimize)
432 /****************************************************************************
434 * Function: AppActivate
435 * Parameters: fActive - True if app is activating
437 * Description: If the application is activating, then swap the system
438 * into SYSPAL_NOSTATIC mode so that our palettes will display
441 ****************************************************************************/
443 static qboolean sound_active = false; // initially blocked by Sys_InitConsole()
445 vid_activewindow = fActive != FALSE;
446 vid_reallyhidden = minimize != FALSE;
448 // enable/disable sound on focus gain/loss
449 if ((!vid_reallyhidden && vid_activewindow) || !snd_mutewhenidle.integer)
462 sound_active = false;
468 if (vid_isfullscreen)
470 if (vid_wassuspended)
472 vid_wassuspended = false;
475 ChangeDisplaySettings (&gdevmode, CDS_FULLSCREEN);
476 ShowWindow(mainwindow, SW_SHOWNORMAL);
480 // LordHavoc: from dabb, fix for alt-tab bug in NVidia drivers
482 MoveWindow(mainwindow,0,0,gdevmode.dmPelsWidth,gdevmode.dmPelsHeight,false);
488 VID_SetMouse(false, false, false);
489 if (vid_isfullscreen)
492 ChangeDisplaySettings (NULL, 0);
493 vid_wassuspended = true;
495 VID_RestoreSystemGamma();
499 //TODO: move it around in vid_wgl.c since I dont think this is the right position
500 void Sys_SendKeyEvents (void)
504 while (PeekMessage (&msg, NULL, 0, 0, PM_NOREMOVE))
506 if (!GetMessage (&msg, NULL, 0, 0))
509 TranslateMessage (&msg);
510 DispatchMessage (&msg);
515 LONG CDAudio_MessageHandler(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
518 static keynum_t buttonremap[16] =
538 /* main window procedure */
539 LONG WINAPI MainWndProc (HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
542 int fActive, fMinimized, temp;
543 unsigned char state[256];
544 unsigned char asciichar[4];
547 qboolean down = false;
549 if ( uMsg == uiWheelMessage )
550 uMsg = WM_MOUSEWHEEL;
555 if (vid_isfullscreen)
556 ShowWindow(mainwindow, SW_SHOWMINNOACTIVE);
563 window_x = (int) LOWORD(lParam);
564 window_y = (int) HIWORD(lParam);
565 VID_SetMouse(false, false, false);
573 vkey = MapKey(lParam, wParam);
574 GetKeyboardState (state);
575 // alt/ctrl/shift tend to produce funky ToAscii values,
576 // and if it's not a single character we don't know care about it
577 charlength = ToAscii (wParam, lParam >> 16, state, (LPWORD)asciichar, 0);
578 if (vkey == K_ALT || vkey == K_CTRL || vkey == K_SHIFT || charlength == 0)
580 else if( charlength == 2 ) {
581 asciichar[0] = asciichar[1];
583 if (!VID_JoyBlockEmulatedKeys(vkey))
584 Key_Event (vkey, asciichar[0], down);
588 // keep Alt-Space from happening
592 // prevent screensaver from occuring while the active window
593 // note: password-locked screensavers on Vista still work
594 if (vid_activewindow && ((wParam & 0xFFF0) == SC_SCREENSAVE || (wParam & 0xFFF0) == SC_MONITORPOWER))
597 lRet = DefWindowProc (hWnd, uMsg, wParam, lParam);
600 // this is complicated because Win32 seems to pack multiple mouse events into
601 // one update sometimes, so we always check all states and look for events
608 case WM_XBUTTONDOWN: // backslash :: imouse explorer buttons
609 case WM_XBUTTONUP: // backslash :: imouse explorer buttons
613 if (wParam & MK_LBUTTON)
616 if (wParam & MK_RBUTTON)
619 if (wParam & MK_MBUTTON)
622 /* backslash :: imouse explorer buttons */
623 if (wParam & MK_XBUTTON1)
626 if (wParam & MK_XBUTTON2)
630 // LordHavoc: lets hope this allows more buttons in the future...
631 if (wParam & MK_XBUTTON3)
633 if (wParam & MK_XBUTTON4)
635 if (wParam & MK_XBUTTON5)
637 if (wParam & MK_XBUTTON6)
639 if (wParam & MK_XBUTTON7)
642 #ifdef SUPPORTDIRECTX
643 if (!dinput_acquired)
646 // perform button actions
648 for (i=0 ; i<mouse_buttons && i < 16 ; i++)
649 if ((temp ^ mouse_oldbuttonstate) & (1<<i))
650 Key_Event (buttonremap[i], 0, (temp & (1<<i)) != 0);
651 mouse_oldbuttonstate = temp;
656 // JACK: This is the mouse wheel with the Intellimouse
657 // Its delta is either positive or neg, and we generate the proper
660 if ((short) HIWORD(wParam) > 0) {
661 Key_Event(K_MWHEELUP, 0, true);
662 Key_Event(K_MWHEELUP, 0, false);
664 Key_Event(K_MWHEELDOWN, 0, true);
665 Key_Event(K_MWHEELDOWN, 0, false);
673 if (MessageBox (mainwindow, "Are you sure you want to quit?", "Confirm Exit", MB_YESNO | MB_SETFOREGROUND | MB_ICONQUESTION) == IDYES)
679 fActive = LOWORD(wParam);
680 fMinimized = (BOOL) HIWORD(wParam);
681 AppActivate(!(fActive == WA_INACTIVE), fMinimized);
683 // fix the leftover Alt from any Alt-Tab or the like that switched us away
689 // PostQuitMessage (0);
694 lRet = CDAudio_MessageHandler (hWnd, uMsg, wParam, lParam);
699 /* pass all unhandled messages to DefWindowProc */
700 lRet = DefWindowProc (hWnd, uMsg, wParam, lParam);
704 /* return 1 if handled message, 0 if not */
708 int VID_SetGamma(unsigned short *ramps, int rampsize)
712 HDC hdc = GetDC (NULL);
713 int i = SetDeviceGammaRamp(hdc, ramps);
714 ReleaseDC (NULL, hdc);
715 return i; // return success or failure
721 int VID_GetGamma(unsigned short *ramps, int rampsize)
725 HDC hdc = GetDC (NULL);
726 int i = GetDeviceGammaRamp(hdc, ramps);
727 ReleaseDC (NULL, hdc);
728 return i; // return success or failure
734 static void GL_CloseLibrary(void)
741 qwglGetProcAddress = NULL;
744 gl_platformextensions = "";
748 static int GL_OpenLibrary(const char *name)
750 Con_Printf("Loading OpenGL driver %s\n", name);
752 if (!(gldll = LoadLibrary(name)))
754 Con_Printf("Unable to LoadLibrary %s\n", name);
757 strlcpy(gl_driver, name, sizeof(gl_driver));
761 void *GL_GetProcAddress(const char *name)
766 if (qwglGetProcAddress != NULL)
767 p = (void *) qwglGetProcAddress(name);
769 p = (void *) GetProcAddress(gldll, name);
776 #ifndef WGL_ARB_pixel_format
777 #define WGL_NUMBER_PIXEL_FORMATS_ARB 0x2000
778 #define WGL_DRAW_TO_WINDOW_ARB 0x2001
779 #define WGL_DRAW_TO_BITMAP_ARB 0x2002
780 #define WGL_ACCELERATION_ARB 0x2003
781 #define WGL_NEED_PALETTE_ARB 0x2004
782 #define WGL_NEED_SYSTEM_PALETTE_ARB 0x2005
783 #define WGL_SWAP_LAYER_BUFFERS_ARB 0x2006
784 #define WGL_SWAP_METHOD_ARB 0x2007
785 #define WGL_NUMBER_OVERLAYS_ARB 0x2008
786 #define WGL_NUMBER_UNDERLAYS_ARB 0x2009
787 #define WGL_TRANSPARENT_ARB 0x200A
788 #define WGL_TRANSPARENT_RED_VALUE_ARB 0x2037
789 #define WGL_TRANSPARENT_GREEN_VALUE_ARB 0x2038
790 #define WGL_TRANSPARENT_BLUE_VALUE_ARB 0x2039
791 #define WGL_TRANSPARENT_ALPHA_VALUE_ARB 0x203A
792 #define WGL_TRANSPARENT_INDEX_VALUE_ARB 0x203B
793 #define WGL_SHARE_DEPTH_ARB 0x200C
794 #define WGL_SHARE_STENCIL_ARB 0x200D
795 #define WGL_SHARE_ACCUM_ARB 0x200E
796 #define WGL_SUPPORT_GDI_ARB 0x200F
797 #define WGL_SUPPORT_OPENGL_ARB 0x2010
798 #define WGL_DOUBLE_BUFFER_ARB 0x2011
799 #define WGL_STEREO_ARB 0x2012
800 #define WGL_PIXEL_TYPE_ARB 0x2013
801 #define WGL_COLOR_BITS_ARB 0x2014
802 #define WGL_RED_BITS_ARB 0x2015
803 #define WGL_RED_SHIFT_ARB 0x2016
804 #define WGL_GREEN_BITS_ARB 0x2017
805 #define WGL_GREEN_SHIFT_ARB 0x2018
806 #define WGL_BLUE_BITS_ARB 0x2019
807 #define WGL_BLUE_SHIFT_ARB 0x201A
808 #define WGL_ALPHA_BITS_ARB 0x201B
809 #define WGL_ALPHA_SHIFT_ARB 0x201C
810 #define WGL_ACCUM_BITS_ARB 0x201D
811 #define WGL_ACCUM_RED_BITS_ARB 0x201E
812 #define WGL_ACCUM_GREEN_BITS_ARB 0x201F
813 #define WGL_ACCUM_BLUE_BITS_ARB 0x2020
814 #define WGL_ACCUM_ALPHA_BITS_ARB 0x2021
815 #define WGL_DEPTH_BITS_ARB 0x2022
816 #define WGL_STENCIL_BITS_ARB 0x2023
817 #define WGL_AUX_BUFFERS_ARB 0x2024
818 #define WGL_NO_ACCELERATION_ARB 0x2025
819 #define WGL_GENERIC_ACCELERATION_ARB 0x2026
820 #define WGL_FULL_ACCELERATION_ARB 0x2027
821 #define WGL_SWAP_EXCHANGE_ARB 0x2028
822 #define WGL_SWAP_COPY_ARB 0x2029
823 #define WGL_SWAP_UNDEFINED_ARB 0x202A
824 #define WGL_TYPE_RGBA_ARB 0x202B
825 #define WGL_TYPE_COLORINDEX_ARB 0x202C
828 #ifndef WGL_ARB_multisample
829 #define WGL_SAMPLE_BUFFERS_ARB 0x2041
830 #define WGL_SAMPLES_ARB 0x2042
834 static void IN_Init(void);
840 Cvar_RegisterVariable(&vid_dx9);
841 Cvar_RegisterVariable(&vid_dx9_hal);
842 Cvar_RegisterVariable(&vid_dx9_softvertex);
843 Cvar_RegisterVariable(&vid_dx9_triplebuffer);
844 // Cvar_RegisterVariable(&vid_dx10);
845 // Cvar_RegisterVariable(&vid_dx11);
848 InitCommonControls();
849 hIcon = LoadIcon (global_hInstance, MAKEINTRESOURCE (IDI_ICON1));
851 // Register the frame class
853 wc.lpfnWndProc = (WNDPROC)MainWndProc;
856 wc.hInstance = global_hInstance;
858 wc.hCursor = LoadCursor (NULL,IDC_ARROW);
859 wc.hbrBackground = NULL;
861 wc.lpszClassName = "DarkPlacesWindowClass";
863 if (!RegisterClass (&wc))
864 Con_Printf ("Couldn't register window class\n");
866 memset(&initialdevmode, 0, sizeof(initialdevmode));
867 EnumDisplaySettings(NULL, ENUM_CURRENT_SETTINGS, &initialdevmode);
872 qboolean VID_InitModeGL(viddef_mode_t *mode)
878 PIXELFORMATDESCRIPTOR pfd =
880 sizeof(PIXELFORMATDESCRIPTOR), // size of this pfd
882 PFD_DRAW_TO_WINDOW // support window
883 | PFD_SUPPORT_OPENGL // support OpenGL
884 | PFD_DOUBLEBUFFER , // double buffered
885 PFD_TYPE_RGBA, // RGBA type
886 24, // 24-bit color depth
887 0, 0, 0, 0, 0, 0, // color bits ignored
888 0, // no alpha buffer
889 0, // shift bit ignored
890 0, // no accumulation buffer
891 0, 0, 0, 0, // accum bits ignored
892 32, // 32-bit z-buffer
893 0, // no stencil buffer
894 0, // no auxiliary buffer
895 PFD_MAIN_PLANE, // main layer
897 0, 0, 0 // layer masks ignored
900 int pixelformat, newpixelformat;
901 UINT numpixelformats;
902 DWORD WindowStyle, ExWindowStyle;
903 int CenterX, CenterY;
904 const char *gldrivername;
907 qboolean foundmode, foundgoodmode;
912 int bpp = mode->bitsperpixel;
913 int width = mode->width;
914 int height = mode->height;
915 int refreshrate = (int)floor(mode->refreshrate+0.5);
916 int stereobuffer = mode->stereobuffer;
917 int samples = mode->samples;
918 int fullscreen = mode->fullscreen;
921 Sys_Error("VID_InitMode called when video is already initialised");
923 // if stencil is enabled, ask for alpha too
931 pfd.cStencilBits = 8;
940 pfd.cStencilBits = 0;
944 pfd.dwFlags |= PFD_STEREO;
948 *a++ = WGL_DRAW_TO_WINDOW_ARB;
950 *a++ = WGL_ACCELERATION_ARB;
951 *a++ = WGL_FULL_ACCELERATION_ARB;
952 *a++ = WGL_DOUBLE_BUFFER_ARB;
957 *a++ = WGL_RED_BITS_ARB;
959 *a++ = WGL_GREEN_BITS_ARB;
961 *a++ = WGL_BLUE_BITS_ARB;
963 *a++ = WGL_ALPHA_BITS_ARB;
965 *a++ = WGL_DEPTH_BITS_ARB;
967 *a++ = WGL_STENCIL_BITS_ARB;
972 *a++ = WGL_RED_BITS_ARB;
974 *a++ = WGL_GREEN_BITS_ARB;
976 *a++ = WGL_BLUE_BITS_ARB;
978 *a++ = WGL_DEPTH_BITS_ARB;
984 *a++ = WGL_STEREO_ARB;
990 *a++ = WGL_SAMPLE_BUFFERS_ARB;
992 *a++ = WGL_SAMPLES_ARB;
999 gldrivername = "opengl32.dll";
1000 // 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
1001 i = COM_CheckParm("-gl_driver");
1002 if (i && i < com_argc - 1)
1003 gldrivername = com_argv[i + 1];
1004 if (!GL_OpenLibrary(gldrivername))
1006 Con_Printf("Unable to load GL driver %s\n", gldrivername);
1010 memset(&gdevmode, 0, sizeof(gdevmode));
1012 vid_isfullscreen = false;
1015 if(vid_forcerefreshrate.integer)
1018 gdevmode.dmFields = DM_BITSPERPEL | DM_PELSWIDTH | DM_PELSHEIGHT;
1019 gdevmode.dmBitsPerPel = bpp;
1020 gdevmode.dmPelsWidth = width;
1021 gdevmode.dmPelsHeight = height;
1022 gdevmode.dmSize = sizeof (gdevmode);
1025 gdevmode.dmFields |= DM_DISPLAYFREQUENCY;
1026 gdevmode.dmDisplayFrequency = refreshrate;
1031 if(refreshrate == 0)
1032 refreshrate = initialdevmode.dmDisplayFrequency; // default vid_refreshrate to the rate of the desktop
1035 foundgoodmode = false;
1037 thismode.dmSize = sizeof(thismode);
1038 thismode.dmDriverExtra = 0;
1039 for(i = 0; EnumDisplaySettings(NULL, i, &thismode); ++i)
1041 if(~thismode.dmFields & (DM_BITSPERPEL | DM_PELSWIDTH | DM_PELSHEIGHT | DM_DISPLAYFREQUENCY))
1043 Con_DPrintf("enumerating modes yielded a bogus item... please debug this\n");
1046 if(developer_extra.integer)
1047 Con_DPrintf("Found mode %dx%dx%dbpp %dHz... ", (int)thismode.dmPelsWidth, (int)thismode.dmPelsHeight, (int)thismode.dmBitsPerPel, (int)thismode.dmDisplayFrequency);
1048 if(thismode.dmBitsPerPel != (DWORD)bpp)
1050 if(developer_extra.integer)
1051 Con_DPrintf("wrong bpp\n");
1054 if(thismode.dmPelsWidth != (DWORD)width)
1056 if(developer_extra.integer)
1057 Con_DPrintf("wrong width\n");
1060 if(thismode.dmPelsHeight != (DWORD)height)
1062 if(developer_extra.integer)
1063 Con_DPrintf("wrong height\n");
1069 // if we have a good mode, make sure this mode is better than the previous one, and allowed by the refreshrate
1070 if(thismode.dmDisplayFrequency > (DWORD)refreshrate)
1072 if(developer_extra.integer)
1073 Con_DPrintf("too high refresh rate\n");
1076 else if(thismode.dmDisplayFrequency <= gdevmode.dmDisplayFrequency)
1078 if(developer_extra.integer)
1079 Con_DPrintf("doesn't beat previous best match (too low)\n");
1085 // we do have one, but it isn't good... make sure it has a lower frequency than the previous one
1086 if(thismode.dmDisplayFrequency >= gdevmode.dmDisplayFrequency)
1088 if(developer_extra.integer)
1089 Con_DPrintf("doesn't beat previous best match (too high)\n");
1093 // otherwise, take anything
1095 memcpy(&gdevmode, &thismode, sizeof(gdevmode));
1096 if(thismode.dmDisplayFrequency <= (DWORD)refreshrate)
1097 foundgoodmode = true;
1100 if(developer_extra.integer)
1101 Con_DPrintf("(out of range)\n");
1104 if(developer_extra.integer)
1105 Con_DPrintf("accepted\n");
1112 Con_Printf("Unable to find the requested mode %dx%dx%dbpp\n", width, height, bpp);
1115 else if(ChangeDisplaySettings (&gdevmode, CDS_FULLSCREEN) != DISP_CHANGE_SUCCESSFUL)
1118 Con_Printf("Unable to change to requested mode %dx%dx%dbpp\n", width, height, bpp);
1122 vid_isfullscreen = true;
1123 WindowStyle = WS_POPUP;
1124 ExWindowStyle = WS_EX_TOPMOST;
1129 i = GetDeviceCaps(hdc, RASTERCAPS);
1130 depth = GetDeviceCaps(hdc, PLANES) * GetDeviceCaps(hdc, BITSPIXEL);
1131 ReleaseDC (NULL, hdc);
1135 Con_Print("Can't run in non-RGB mode\n");
1141 Con_Print("A higher desktop depth is required to run this video mode\n");
1145 WindowStyle = WS_OVERLAPPED | WS_BORDER | WS_CAPTION | WS_SYSMENU | WS_MINIMIZEBOX;
1152 rect.bottom = height;
1153 AdjustWindowRectEx(&rect, WindowStyle, false, 0);
1162 CenterX = (GetSystemMetrics(SM_CXSCREEN) - (rect.right - rect.left)) / 2;
1163 CenterY = (GetSystemMetrics(SM_CYSCREEN) - (rect.bottom - rect.top)) / 2;
1165 CenterX = max(0, CenterX);
1166 CenterY = max(0, CenterY);
1168 // x and y may be changed by WM_MOVE messages
1171 rect.left += CenterX;
1172 rect.right += CenterX;
1173 rect.top += CenterY;
1174 rect.bottom += CenterY;
1178 // start out at the final windowpass if samples is 1 as it's the only feature we need extended pixel formats for
1179 for (windowpass = samples == 1;windowpass < 2;windowpass++)
1182 gl_platformextensions = "";
1184 mainwindow = CreateWindowEx (ExWindowStyle, "DarkPlacesWindowClass", gamename, WindowStyle, rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top, NULL, NULL, global_hInstance, NULL);
1187 Con_Printf("CreateWindowEx(%d, %s, %s, %d, %d, %d, %d, %d, %p, %p, %p, %p) failed\n", (int)ExWindowStyle, "DarkPlacesWindowClass", gamename, (int)WindowStyle, (int)(rect.left), (int)(rect.top), (int)(rect.right - rect.left), (int)(rect.bottom - rect.top), (void *)NULL, (void *)NULL, (void *)global_hInstance, (void *)NULL);
1192 baseDC = GetDC(mainwindow);
1194 if (!newpixelformat)
1195 newpixelformat = ChoosePixelFormat(baseDC, &pfd);
1196 pixelformat = newpixelformat;
1200 Con_Printf("ChoosePixelFormat(%p, %p) failed\n", (void *)baseDC, (void *)&pfd);
1204 if (SetPixelFormat(baseDC, pixelformat, &pfd) == false)
1207 Con_Printf("SetPixelFormat(%p, %d, %p) failed\n", (void *)baseDC, pixelformat, (void *)&pfd);
1211 if (!GL_CheckExtension("wgl", wglfuncs, NULL, false))
1214 Con_Print("wgl functions not found\n");
1218 baseRC = qwglCreateContext(baseDC);
1222 Con_Print("Could not initialize GL (wglCreateContext failed).\n\nMake sure you are in 65536 color mode, and try running -window.\n");
1225 if (!qwglMakeCurrent(baseDC, baseRC))
1228 Con_Printf("wglMakeCurrent(%p, %p) failed\n", (void *)baseDC, (void *)baseRC);
1232 if ((qglGetString = (const GLubyte* (GLAPIENTRY *)(GLenum name))GL_GetProcAddress("glGetString")) == NULL)
1235 Con_Print("glGetString not found\n");
1238 if ((qwglGetExtensionsStringARB = (const char *(WINAPI *)(HDC hdc))GL_GetProcAddress("wglGetExtensionsStringARB")) == NULL)
1239 Con_Print("wglGetExtensionsStringARB not found\n");
1241 gl_extensions = (const char *)qglGetString(GL_EXTENSIONS);
1242 gl_platform = "WGL";
1243 gl_platformextensions = "";
1245 if (qwglGetExtensionsStringARB)
1246 gl_platformextensions = (const char *)qwglGetExtensionsStringARB(baseDC);
1250 if (!gl_platformextensions)
1251 gl_platformextensions = "";
1253 // now some nice Windows pain:
1254 // we have created a window, we needed one to find out if there are
1255 // any multisample pixel formats available, the problem is that to
1256 // actually use one of those multisample formats we now have to
1257 // recreate the window (yes Microsoft OpenGL really is that bad)
1259 if (windowpass == 0)
1261 if (!GL_CheckExtension("WGL_ARB_pixel_format", wglpixelformatfuncs, "-noarbpixelformat", false) || !qwglChoosePixelFormatARB(baseDC, attribs, attribsf, 1, &newpixelformat, &numpixelformats) || !newpixelformat)
1263 // ok we got one - do it all over again with newpixelformat
1264 qwglMakeCurrent(NULL, NULL);
1265 qwglDeleteContext(baseRC);baseRC = 0;
1266 ReleaseDC(mainwindow, baseDC);baseDC = 0;
1267 // eat up any messages waiting for us
1268 while (PeekMessage (&msg, NULL, 0, 0, PM_REMOVE))
1270 TranslateMessage (&msg);
1271 DispatchMessage (&msg);
1278 SetWindowPos (mainwindow, NULL, CenterX, CenterY, 0, 0,SWP_NOSIZE | SWP_NOZORDER | SWP_SHOWWINDOW | SWP_DRAWFRAME);
1281 ShowWindow (mainwindow, SW_SHOWDEFAULT);
1282 UpdateWindow (mainwindow);
1284 // now we try to make sure we get the focus on the mode switch, because
1285 // sometimes in some systems we don't. We grab the foreground, then
1286 // finish setting up, pump all our messages, and sleep for a little while
1287 // to let messages finish bouncing around the system, then we put
1288 // ourselves at the top of the z order, then grab the foreground again,
1289 // Who knows if it helps, but it probably doesn't hurt
1290 SetForegroundWindow (mainwindow);
1292 while (PeekMessage (&msg, NULL, 0, 0, PM_REMOVE))
1294 TranslateMessage (&msg);
1295 DispatchMessage (&msg);
1300 SetWindowPos (mainwindow, HWND_TOP, 0, 0, 0, 0, SWP_DRAWFRAME | SWP_NOMOVE | SWP_NOSIZE | SWP_SHOWWINDOW | SWP_NOCOPYBITS);
1302 SetForegroundWindow (mainwindow);
1304 // fix the leftover Alt from any Alt-Tab or the like that switched us away
1307 // COMMANDLINEOPTION: Windows WGL: -novideosync disables WGL_EXT_swap_control
1308 GL_CheckExtension("WGL_EXT_swap_control", wglswapintervalfuncs, "-novideosync", false);
1312 //vid_menudrawfn = VID_MenuDraw;
1313 //vid_menukeyfn = VID_MenuKey;
1314 vid_usingmouse = false;
1315 vid_usinghidecursor = false;
1316 vid_usingvsync = false;
1317 vid_reallyhidden = vid_hidden = false;
1318 vid_initialized = true;
1322 if (qwglSwapIntervalEXT)
1324 vid_usevsync = vid_vsync.integer != 0;
1325 vid_usingvsync = vid_vsync.integer != 0;
1326 qwglSwapIntervalEXT (vid_usevsync);
1333 static D3DADAPTER_IDENTIFIER9 d3d9adapteridentifier;
1335 extern cvar_t gl_info_extensions;
1336 extern cvar_t gl_info_vendor;
1337 extern cvar_t gl_info_renderer;
1338 extern cvar_t gl_info_version;
1339 extern cvar_t gl_info_platform;
1340 extern cvar_t gl_info_driver;
1341 qboolean VID_InitModeDX(viddef_mode_t *mode, int version)
1346 DWORD WindowStyle, ExWindowStyle;
1347 int CenterX, CenterY;
1348 int bpp = mode->bitsperpixel;
1349 int width = mode->width;
1350 int height = mode->height;
1351 int refreshrate = (int)floor(mode->refreshrate+0.5);
1352 // int stereobuffer = mode->stereobuffer;
1353 int samples = mode->samples;
1354 int fullscreen = mode->fullscreen;
1357 if (vid_initialized)
1358 Sys_Error("VID_InitMode called when video is already initialised");
1360 vid_isfullscreen = fullscreen != 0;
1363 WindowStyle = WS_POPUP;
1364 ExWindowStyle = WS_EX_TOPMOST;
1368 WindowStyle = WS_OVERLAPPED | WS_BORDER | WS_CAPTION | WS_SYSMENU | WS_MINIMIZEBOX;
1375 rect.bottom = height;
1376 AdjustWindowRectEx(&rect, WindowStyle, false, 0);
1385 CenterX = (GetSystemMetrics(SM_CXSCREEN) - (rect.right - rect.left)) / 2;
1386 CenterY = (GetSystemMetrics(SM_CYSCREEN) - (rect.bottom - rect.top)) / 2;
1388 CenterX = max(0, CenterX);
1389 CenterY = max(0, CenterY);
1391 // x and y may be changed by WM_MOVE messages
1394 rect.left += CenterX;
1395 rect.right += CenterX;
1396 rect.top += CenterY;
1397 rect.bottom += CenterY;
1400 gl_platformextensions = "";
1402 mainwindow = CreateWindowEx (ExWindowStyle, "DarkPlacesWindowClass", gamename, WindowStyle, rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top, NULL, NULL, global_hInstance, NULL);
1405 Con_Printf("CreateWindowEx(%d, %s, %s, %d, %d, %d, %d, %d, %p, %p, %p, %p) failed\n", (int)ExWindowStyle, "DarkPlacesWindowClass", gamename, (int)WindowStyle, (int)(rect.left), (int)(rect.top), (int)(rect.right - rect.left), (int)(rect.bottom - rect.top), (void *)NULL, (void *)NULL, global_hInstance, (void *)NULL);
1410 baseDC = GetDC(mainwindow);
1412 vid_d3d9 = Direct3DCreate9(D3D_SDK_VERSION);
1414 Sys_Error("VID_InitMode: Direct3DCreate9 failed");
1416 numdevices = IDirect3D9_GetAdapterCount(vid_d3d9);
1418 memset(&d3d9adapteridentifier, 0, sizeof(d3d9adapteridentifier));
1419 for (deviceindex = 0;deviceindex < numdevices && !vid_d3d9dev;deviceindex++)
1421 memset(&vid_d3dpresentparameters, 0, sizeof(vid_d3dpresentparameters));
1422 // vid_d3dpresentparameters.Flags = D3DPRESENTFLAG_DISCARD_DEPTHSTENCIL;
1423 vid_d3dpresentparameters.Flags = 0;
1424 vid_d3dpresentparameters.SwapEffect = D3DSWAPEFFECT_DISCARD;
1425 vid_d3dpresentparameters.hDeviceWindow = mainwindow;
1426 vid_d3dpresentparameters.BackBufferWidth = width;
1427 vid_d3dpresentparameters.BackBufferHeight = height;
1428 vid_d3dpresentparameters.MultiSampleType = samples > 1 ? (D3DMULTISAMPLE_TYPE)samples : D3DMULTISAMPLE_NONE;
1429 vid_d3dpresentparameters.BackBufferCount = fullscreen ? (vid_dx9_triplebuffer.integer ? 3 : 2) : 1;
1430 vid_d3dpresentparameters.FullScreen_RefreshRateInHz = fullscreen ? refreshrate : 0;
1431 vid_d3dpresentparameters.Windowed = !fullscreen;
1432 vid_d3dpresentparameters.EnableAutoDepthStencil = true;
1433 vid_d3dpresentparameters.AutoDepthStencilFormat = bpp > 16 ? D3DFMT_D24S8 : D3DFMT_D16;
1434 vid_d3dpresentparameters.BackBufferFormat = fullscreen?D3DFMT_X8R8G8B8:D3DFMT_UNKNOWN;
1435 vid_d3dpresentparameters.PresentationInterval = vid_vsync.integer ? D3DPRESENT_INTERVAL_ONE : D3DPRESENT_INTERVAL_IMMEDIATE;
1437 memset(&d3d9adapteridentifier, 0, sizeof(d3d9adapteridentifier));
1438 IDirect3D9_GetAdapterIdentifier(vid_d3d9, deviceindex, 0, &d3d9adapteridentifier);
1440 IDirect3D9_CreateDevice(vid_d3d9, deviceindex, vid_dx9_hal.integer ? D3DDEVTYPE_HAL : D3DDEVTYPE_REF, mainwindow, vid_dx9_softvertex.integer ? D3DCREATE_SOFTWARE_VERTEXPROCESSING : D3DCREATE_HARDWARE_VERTEXPROCESSING, &vid_d3dpresentparameters, &vid_d3d9dev);
1449 IDirect3DDevice9_GetDeviceCaps(vid_d3d9dev, &vid_d3d9caps);
1451 Con_Printf("Using D3D9 device: %s\n", d3d9adapteridentifier.Description);
1453 gl_platform = "D3D9";
1454 gl_platformextensions = "";
1456 ShowWindow (mainwindow, SW_SHOWDEFAULT);
1457 UpdateWindow (mainwindow);
1459 // now we try to make sure we get the focus on the mode switch, because
1460 // sometimes in some systems we don't. We grab the foreground, then
1461 // finish setting up, pump all our messages, and sleep for a little while
1462 // to let messages finish bouncing around the system, then we put
1463 // ourselves at the top of the z order, then grab the foreground again,
1464 // Who knows if it helps, but it probably doesn't hurt
1465 SetForegroundWindow (mainwindow);
1467 while (PeekMessage (&msg, NULL, 0, 0, PM_REMOVE))
1469 TranslateMessage (&msg);
1470 DispatchMessage (&msg);
1475 SetWindowPos (mainwindow, HWND_TOP, 0, 0, 0, 0, SWP_DRAWFRAME | SWP_NOMOVE | SWP_NOSIZE | SWP_SHOWWINDOW | SWP_NOCOPYBITS);
1477 SetForegroundWindow (mainwindow);
1479 // fix the leftover Alt from any Alt-Tab or the like that switched us away
1482 gl_renderer = d3d9adapteridentifier.Description;
1483 gl_vendor = d3d9adapteridentifier.Driver;
1487 Con_Printf("D3D9 adapter info:\n");
1488 Con_Printf("Description: %s\n", d3d9adapteridentifier.Description);
1489 Con_Printf("DeviceId: %x\n", (unsigned int)d3d9adapteridentifier.DeviceId);
1490 Con_Printf("DeviceName: %p\n", d3d9adapteridentifier.DeviceName);
1491 Con_Printf("Driver: %s\n", d3d9adapteridentifier.Driver);
1492 Con_Printf("DriverVersion: %08x%08x\n", (unsigned int)d3d9adapteridentifier.DriverVersion.u.HighPart, (unsigned int)d3d9adapteridentifier.DriverVersion.u.LowPart);
1493 Con_DPrintf("GL_EXTENSIONS: %s\n", gl_extensions);
1494 Con_DPrintf("%s_EXTENSIONS: %s\n", gl_platform, gl_platformextensions);
1496 // clear the extension flags
1497 memset(&vid.support, 0, sizeof(vid.support));
1498 Cvar_SetQuick(&gl_info_extensions, "");
1500 // D3D9 requires BGRA
1501 vid.forcetextype = TEXTYPE_BGRA;
1503 vid.forcevbo = false;
1504 vid.support.arb_depth_texture = true;
1505 vid.support.arb_draw_buffers = vid_d3d9caps.NumSimultaneousRTs > 1;
1506 vid.support.arb_occlusion_query = true; // can't find a cap for this
1507 vid.support.arb_shadow = true;
1508 vid.support.arb_texture_compression = true;
1509 vid.support.arb_texture_cube_map = true;
1510 vid.support.arb_texture_non_power_of_two = (vid_d3d9caps.TextureCaps & D3DPTEXTURECAPS_POW2) == 0;
1511 vid.support.arb_vertex_buffer_object = true;
1512 vid.support.ext_blend_subtract = true;
1513 vid.support.ext_draw_range_elements = true;
1514 vid.support.ext_framebuffer_object = true;
1516 vid.support.ext_texture_3d = true;
1517 vid.support.ext_texture_compression_s3tc = true;
1518 vid.support.ext_texture_filter_anisotropic = true;
1519 vid.support.ati_separate_stencil = (vid_d3d9caps.StencilCaps & D3DSTENCILCAPS_TWOSIDED) != 0;
1520 vid.support.ext_texture_srgb = false; // FIXME use D3DSAMP_SRGBTEXTURE if CheckDeviceFormat agrees
1522 vid.maxtexturesize_2d = min(vid_d3d9caps.MaxTextureWidth, vid_d3d9caps.MaxTextureHeight);
1523 vid.maxtexturesize_3d = vid_d3d9caps.MaxVolumeExtent;
1524 vid.maxtexturesize_cubemap = vid.maxtexturesize_2d;
1526 vid.teximageunits = vid_d3d9caps.MaxSimultaneousTextures;
1527 vid.texarrayunits = 8; // can't find a caps field for this?
1528 vid.max_anisotropy = vid_d3d9caps.MaxAnisotropy;
1529 vid.maxdrawbuffers = vid_d3d9caps.NumSimultaneousRTs;
1531 vid.texunits = bound(4, vid.texunits, MAX_TEXTUREUNITS);
1532 vid.teximageunits = bound(16, vid.teximageunits, MAX_TEXTUREUNITS);
1533 vid.texarrayunits = bound(8, vid.texarrayunits, MAX_TEXTUREUNITS);
1534 Con_DPrintf("Using D3D9.0 rendering path - %i texture matrix, %i texture images, %i texcoords, shadowmapping supported%s\n", vid.texunits, vid.teximageunits, vid.texarrayunits, vid.maxdrawbuffers > 1 ? ", MRT detected (allows prepass deferred lighting)" : "");
1535 vid.renderpath = RENDERPATH_D3D9;
1536 vid.sRGBcapable2D = false;
1537 vid.sRGBcapable3D = true;
1538 vid.useinterleavedarrays = true;
1540 Cvar_SetQuick(&gl_info_vendor, gl_vendor);
1541 Cvar_SetQuick(&gl_info_renderer, gl_renderer);
1542 Cvar_SetQuick(&gl_info_version, gl_version);
1543 Cvar_SetQuick(&gl_info_platform, gl_platform ? gl_platform : "");
1544 Cvar_SetQuick(&gl_info_driver, gl_driver);
1546 // LordHavoc: report supported extensions
1547 Con_DPrintf("\nQuakeC extensions for server and client: %s\nQuakeC extensions for menu: %s\n", vm_sv_extensions, vm_m_extensions );
1549 // clear to black (loading plaque will be seen over this)
1550 IDirect3DDevice9_Clear(vid_d3d9dev, 0, NULL, D3DCLEAR_TARGET, D3DCOLOR_XRGB(0, 0, 0), 1.0f, 0);
1551 IDirect3DDevice9_BeginScene(vid_d3d9dev);
1552 IDirect3DDevice9_EndScene(vid_d3d9dev);
1553 IDirect3DDevice9_Present(vid_d3d9dev, NULL, NULL, NULL, NULL);
1554 // because the only time we end/begin scene is in VID_Finish, we'd better start a scene now...
1555 IDirect3DDevice9_BeginScene(vid_d3d9dev);
1556 vid_begunscene = true;
1558 //vid_menudrawfn = VID_MenuDraw;
1559 //vid_menukeyfn = VID_MenuKey;
1560 vid_usingmouse = false;
1561 vid_usinghidecursor = false;
1562 vid_usingvsync = false;
1563 vid_hidden = vid_reallyhidden = false;
1564 vid_initialized = true;
1572 qboolean VID_InitModeSOFT(viddef_mode_t *mode)
1578 int pixelformat, newpixelformat;
1579 DWORD WindowStyle, ExWindowStyle;
1580 int CenterX, CenterY;
1583 qboolean foundmode, foundgoodmode;
1584 int bpp = mode->bitsperpixel;
1585 int width = mode->width;
1586 int height = mode->height;
1587 int refreshrate = (int)floor(mode->refreshrate+0.5);
1588 int fullscreen = mode->fullscreen;
1590 if (vid_initialized)
1591 Sys_Error("VID_InitMode called when video is already initialised");
1593 memset(&gdevmode, 0, sizeof(gdevmode));
1595 vid_isfullscreen = false;
1598 if(vid_forcerefreshrate.integer)
1601 gdevmode.dmFields = DM_BITSPERPEL | DM_PELSWIDTH | DM_PELSHEIGHT;
1602 gdevmode.dmBitsPerPel = bpp;
1603 gdevmode.dmPelsWidth = width;
1604 gdevmode.dmPelsHeight = height;
1605 gdevmode.dmSize = sizeof (gdevmode);
1608 gdevmode.dmFields |= DM_DISPLAYFREQUENCY;
1609 gdevmode.dmDisplayFrequency = refreshrate;
1614 if(refreshrate == 0)
1615 refreshrate = initialdevmode.dmDisplayFrequency; // default vid_refreshrate to the rate of the desktop
1618 foundgoodmode = false;
1620 thismode.dmSize = sizeof(thismode);
1621 thismode.dmDriverExtra = 0;
1622 for(i = 0; EnumDisplaySettings(NULL, i, &thismode); ++i)
1624 if(~thismode.dmFields & (DM_BITSPERPEL | DM_PELSWIDTH | DM_PELSHEIGHT | DM_DISPLAYFREQUENCY))
1626 Con_DPrintf("enumerating modes yielded a bogus item... please debug this\n");
1629 if(developer_extra.integer)
1630 Con_DPrintf("Found mode %dx%dx%dbpp %dHz... ", (int)thismode.dmPelsWidth, (int)thismode.dmPelsHeight, (int)thismode.dmBitsPerPel, (int)thismode.dmDisplayFrequency);
1631 if(thismode.dmBitsPerPel != (DWORD)bpp)
1633 if(developer_extra.integer)
1634 Con_DPrintf("wrong bpp\n");
1637 if(thismode.dmPelsWidth != (DWORD)width)
1639 if(developer_extra.integer)
1640 Con_DPrintf("wrong width\n");
1643 if(thismode.dmPelsHeight != (DWORD)height)
1645 if(developer_extra.integer)
1646 Con_DPrintf("wrong height\n");
1652 // if we have a good mode, make sure this mode is better than the previous one, and allowed by the refreshrate
1653 if(thismode.dmDisplayFrequency > (DWORD)refreshrate)
1655 if(developer_extra.integer)
1656 Con_DPrintf("too high refresh rate\n");
1659 else if(thismode.dmDisplayFrequency <= gdevmode.dmDisplayFrequency)
1661 if(developer_extra.integer)
1662 Con_DPrintf("doesn't beat previous best match (too low)\n");
1668 // we do have one, but it isn't good... make sure it has a lower frequency than the previous one
1669 if(thismode.dmDisplayFrequency >= gdevmode.dmDisplayFrequency)
1671 if(developer_extra.integer)
1672 Con_DPrintf("doesn't beat previous best match (too high)\n");
1676 // otherwise, take anything
1678 memcpy(&gdevmode, &thismode, sizeof(gdevmode));
1679 if(thismode.dmDisplayFrequency <= (DWORD)refreshrate)
1680 foundgoodmode = true;
1683 if(developer_extra.integer)
1684 Con_DPrintf("(out of range)\n");
1687 if(developer_extra.integer)
1688 Con_DPrintf("accepted\n");
1695 Con_Printf("Unable to find the requested mode %dx%dx%dbpp\n", width, height, bpp);
1698 else if(ChangeDisplaySettings (&gdevmode, CDS_FULLSCREEN) != DISP_CHANGE_SUCCESSFUL)
1701 Con_Printf("Unable to change to requested mode %dx%dx%dbpp\n", width, height, bpp);
1705 vid_isfullscreen = true;
1706 WindowStyle = WS_POPUP;
1707 ExWindowStyle = WS_EX_TOPMOST;
1712 i = GetDeviceCaps(hdc, RASTERCAPS);
1713 depth = GetDeviceCaps(hdc, PLANES) * GetDeviceCaps(hdc, BITSPIXEL);
1714 ReleaseDC (NULL, hdc);
1718 Con_Print("Can't run in non-RGB mode\n");
1724 Con_Print("A higher desktop depth is required to run this video mode\n");
1728 WindowStyle = WS_OVERLAPPED | WS_BORDER | WS_CAPTION | WS_SYSMENU | WS_MINIMIZEBOX;
1735 rect.bottom = height;
1736 AdjustWindowRectEx(&rect, WindowStyle, false, 0);
1745 CenterX = (GetSystemMetrics(SM_CXSCREEN) - (rect.right - rect.left)) / 2;
1746 CenterY = (GetSystemMetrics(SM_CYSCREEN) - (rect.bottom - rect.top)) / 2;
1748 CenterX = max(0, CenterX);
1749 CenterY = max(0, CenterY);
1751 // x and y may be changed by WM_MOVE messages
1754 rect.left += CenterX;
1755 rect.right += CenterX;
1756 rect.top += CenterY;
1757 rect.bottom += CenterY;
1762 gl_platformextensions = "";
1764 mainwindow = CreateWindowEx (ExWindowStyle, "DarkPlacesWindowClass", gamename, WindowStyle, rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top, NULL, NULL, global_hInstance, NULL);
1767 Con_Printf("CreateWindowEx(%d, %s, %s, %d, %d, %d, %d, %d, %p, %p, %p, %p) failed\n", (int)ExWindowStyle, "DarkPlacesWindowClass", gamename, (int)WindowStyle, (int)(rect.left), (int)(rect.top), (int)(rect.right - rect.left), (int)(rect.bottom - rect.top), (void *)NULL, (void *)NULL, (void *)global_hInstance, (void *)NULL);
1772 baseDC = GetDC(mainwindow);
1773 vid.softpixels = NULL;
1774 memset(&vid_softbmi, 0, sizeof(vid_softbmi));
1775 vid_softbmi.bmiHeader.biSize = sizeof(vid_softbmi.bmiHeader);
1776 vid_softbmi.bmiHeader.biWidth = width;
1777 vid_softbmi.bmiHeader.biHeight = -height; // negative to make a top-down bitmap
1778 vid_softbmi.bmiHeader.biPlanes = 1;
1779 vid_softbmi.bmiHeader.biBitCount = 32;
1780 vid_softbmi.bmiHeader.biCompression = BI_RGB;
1781 vid_softbmi.bmiHeader.biSizeImage = width*height*4;
1782 vid_softbmi.bmiHeader.biClrUsed = 256;
1783 vid_softbmi.bmiHeader.biClrImportant = 256;
1784 vid_softdibhandle = CreateDIBSection(baseDC, &vid_softbmi, DIB_RGB_COLORS, (void **)&vid.softpixels, NULL, 0);
1785 if (!vid_softdibhandle)
1787 Con_Printf("CreateDIBSection failed\n");
1792 vid_softhdc = CreateCompatibleDC(baseDC);
1793 vid_softhdc_backup = SelectObject(vid_softhdc, vid_softdibhandle);
1794 if (!vid_softhdc_backup)
1796 Con_Printf("SelectObject failed\n");
1800 // ReleaseDC(mainwindow, baseDC);
1803 vid.softdepthpixels = (unsigned int *)calloc(1, mode->width * mode->height * 4);
1804 if (DPSOFTRAST_Init(mode->width, mode->height, vid_soft_threads.integer, vid_soft_interlace.integer, (unsigned int *)vid.softpixels, (unsigned int *)vid.softdepthpixels) < 0)
1806 Con_Printf("Failed to initialize software rasterizer\n");
1811 VID_Soft_SharedSetup();
1813 ShowWindow (mainwindow, SW_SHOWDEFAULT);
1814 UpdateWindow (mainwindow);
1816 // now we try to make sure we get the focus on the mode switch, because
1817 // sometimes in some systems we don't. We grab the foreground, then
1818 // finish setting up, pump all our messages, and sleep for a little while
1819 // to let messages finish bouncing around the system, then we put
1820 // ourselves at the top of the z order, then grab the foreground again,
1821 // Who knows if it helps, but it probably doesn't hurt
1822 SetForegroundWindow (mainwindow);
1824 while (PeekMessage (&msg, NULL, 0, 0, PM_REMOVE))
1826 TranslateMessage (&msg);
1827 DispatchMessage (&msg);
1832 SetWindowPos (mainwindow, HWND_TOP, 0, 0, 0, 0, SWP_DRAWFRAME | SWP_NOMOVE | SWP_NOSIZE | SWP_SHOWWINDOW | SWP_NOCOPYBITS);
1834 SetForegroundWindow (mainwindow);
1836 // fix the leftover Alt from any Alt-Tab or the like that switched us away
1839 //vid_menudrawfn = VID_MenuDraw;
1840 //vid_menukeyfn = VID_MenuKey;
1841 vid_usingmouse = false;
1842 vid_usinghidecursor = false;
1843 vid_usingvsync = false;
1844 vid_reallyhidden = vid_hidden = false;
1845 vid_initialized = true;
1852 qboolean VID_InitMode(viddef_mode_t *mode)
1855 if (vid_soft.integer)
1856 return VID_InitModeSOFT(mode);
1859 // if (vid_dx11.integer)
1860 // return VID_InitModeDX(mode, 11);
1861 // if (vid_dx10.integer)
1862 // return VID_InitModeDX(mode, 10);
1863 if (vid_dx9.integer)
1864 return VID_InitModeDX(mode, 9);
1866 return VID_InitModeGL(mode);
1870 static void IN_Shutdown(void);
1871 void VID_Shutdown (void)
1874 if(vid_initialized == false)
1877 VID_EnableJoystick(false);
1878 VID_SetMouse(false, false, false);
1879 VID_RestoreSystemGamma();
1881 vid_initialized = false;
1882 isgl = gldll != NULL;
1887 gl_platformextensions = "";
1890 SelectObject(vid_softhdc, vid_softhdc_backup);
1891 ReleaseDC(mainwindow, vid_softhdc);
1894 vid_softhdc_backup = NULL;
1895 if (vid_softdibhandle)
1896 DeleteObject(vid_softdibhandle);
1897 vid_softdibhandle = NULL;
1898 vid.softpixels = NULL;
1899 if (vid.softdepthpixels)
1900 free(vid.softdepthpixels);
1901 vid.softdepthpixels = NULL;
1906 IDirect3DDevice9_EndScene(vid_d3d9dev);
1907 vid_begunscene = false;
1908 // Cmd_ExecuteString("r_texturestats", src_command, true);
1909 // Cmd_ExecuteString("memlist", src_command, true);
1910 IDirect3DDevice9_Release(vid_d3d9dev);
1914 IDirect3D9_Release(vid_d3d9);
1917 if (qwglMakeCurrent)
1918 qwglMakeCurrent(NULL, NULL);
1919 qwglMakeCurrent = NULL;
1920 if (baseRC && qwglDeleteContext)
1921 qwglDeleteContext(baseRC);
1922 qwglDeleteContext = NULL;
1923 // close the library before we get rid of the window
1925 if (baseDC && mainwindow)
1926 ReleaseDC(mainwindow, baseDC);
1928 AppActivate(false, false);
1930 DestroyWindow(mainwindow);
1932 if (vid_isfullscreen && isgl)
1933 ChangeDisplaySettings (NULL, 0);
1934 vid_isfullscreen = false;
1937 void VID_SetMouse(qboolean fullscreengrab, qboolean relative, qboolean hidecursor)
1939 static qboolean restore_spi;
1940 static int originalmouseparms[3];
1942 if (!mouseinitialized)
1947 if (!vid_usingmouse)
1949 vid_usingmouse = true;
1950 cl_ignoremousemoves = 2;
1951 #ifdef SUPPORTDIRECTX
1952 if (dinput && g_pMouse)
1954 IDirectInputDevice_Acquire(g_pMouse);
1955 dinput_acquired = true;
1961 window_rect.left = window_x;
1962 window_rect.top = window_y;
1963 window_rect.right = window_x + vid.width;
1964 window_rect.bottom = window_y + vid.height;
1966 // change mouse settings to turn off acceleration
1967 // COMMANDLINEOPTION: Windows GDI Input: -noforcemparms disables setting of mouse parameters (not used with -dinput, windows only)
1968 if (!COM_CheckParm ("-noforcemparms") && SystemParametersInfo (SPI_GETMOUSE, 0, originalmouseparms, 0))
1970 int newmouseparms[3];
1971 newmouseparms[0] = 0; // threshold to double movement (only if accel level is >= 1)
1972 newmouseparms[1] = 0; // threshold to quadruple movement (only if accel level is >= 2)
1973 newmouseparms[2] = 0; // maximum level of acceleration (0 = off)
1974 restore_spi = SystemParametersInfo (SPI_SETMOUSE, 0, newmouseparms, 0) != FALSE;
1977 restore_spi = false;
1978 SetCursorPos ((window_x + vid.width / 2), (window_y + vid.height / 2));
1980 SetCapture (mainwindow);
1981 ClipCursor (&window_rect);
1989 vid_usingmouse = false;
1990 cl_ignoremousemoves = 2;
1991 #ifdef SUPPORTDIRECTX
1992 if (dinput_acquired)
1994 IDirectInputDevice_Unacquire(g_pMouse);
1995 dinput_acquired = false;
2000 // restore system mouseparms if we changed them
2002 SystemParametersInfo (SPI_SETMOUSE, 0, originalmouseparms, 0);
2003 restore_spi = false;
2010 if (vid_usinghidecursor != hidecursor)
2012 vid_usinghidecursor = hidecursor;
2013 ShowCursor (!hidecursor);
2017 void VID_BuildJoyState(vid_joystate_t *joystate)
2019 VID_Shared_BuildJoyState_Begin(joystate);
2020 VID_Shared_BuildJoyState_Finish(joystate);
2023 void VID_EnableJoystick(qboolean enable)
2025 int index = joy_enable.integer > 0 ? joy_index.integer : -1;
2026 qboolean success = false;
2027 int sharedcount = 0;
2028 sharedcount = VID_Shared_SetJoystick(index);
2029 if (index >= 0 && index < sharedcount)
2032 // update cvar containing count of XInput joysticks
2033 if (joy_detected.integer != sharedcount)
2034 Cvar_SetValueQuick(&joy_detected, sharedcount);
2036 if (joy_active.integer != (success ? 1 : 0))
2037 Cvar_SetValueQuick(&joy_active, success ? 1 : 0);
2040 #ifdef SUPPORTDIRECTX
2046 static qboolean IN_InitDInput (void)
2049 DIPROPDWORD dipdw = {
2051 sizeof(DIPROPDWORD), // diph.dwSize
2052 sizeof(DIPROPHEADER), // diph.dwHeaderSize
2054 DIPH_DEVICE, // diph.dwHow
2056 DINPUT_BUFFERSIZE, // dwData
2061 hInstDI = LoadLibrary("dinput.dll");
2063 if (hInstDI == NULL)
2065 Con_Print("Couldn't load dinput.dll\n");
2070 if (!pDirectInputCreate)
2072 pDirectInputCreate = (HRESULT (__stdcall *)(HINSTANCE,DWORD,LPDIRECTINPUT *,LPUNKNOWN))GetProcAddress(hInstDI,"DirectInputCreateA");
2074 if (!pDirectInputCreate)
2076 Con_Print("Couldn't get DI proc addr\n");
2081 // register with DirectInput and get an IDirectInput to play with.
2082 hr = iDirectInputCreate(global_hInstance, DIRECTINPUT_VERSION, &g_pdi, NULL);
2089 // obtain an interface to the system mouse device.
2091 hr = IDirectInput_CreateDevice(g_pdi, GUID_SysMouse, &g_pMouse, NULL);
2093 hr = IDirectInput_CreateDevice(g_pdi, &GUID_SysMouse, &g_pMouse, NULL);
2098 Con_Print("Couldn't open DI mouse device\n");
2102 // set the data format to "mouse format".
2103 hr = IDirectInputDevice_SetDataFormat(g_pMouse, &c_dfDIMouse);
2107 Con_Print("Couldn't set DI mouse format\n");
2111 // set the cooperativity level.
2112 hr = IDirectInputDevice_SetCooperativeLevel(g_pMouse, mainwindow,
2113 DISCL_EXCLUSIVE | DISCL_FOREGROUND);
2117 Con_Print("Couldn't set DI coop level\n");
2122 // set the buffer size to DINPUT_BUFFERSIZE elements.
2123 // the buffer size is a DWORD property associated with the device
2124 hr = IDirectInputDevice_SetProperty(g_pMouse, DIPROP_BUFFERSIZE, &dipdw.diph);
2128 Con_Print("Couldn't set DI buffersize\n");
2142 static void IN_StartupMouse (void)
2144 if (COM_CheckParm ("-nomouse"))
2147 mouseinitialized = true;
2149 #ifdef SUPPORTDIRECTX
2150 // COMMANDLINEOPTION: Windows Input: -dinput enables DirectInput for mouse input
2151 if (COM_CheckParm ("-dinput"))
2152 dinput = IN_InitDInput ();
2155 Con_Print("DirectInput initialized\n");
2157 Con_Print("DirectInput not initialized\n");
2169 static void IN_MouseMove (void)
2173 GetCursorPos (¤t_pos);
2174 in_windowmouse_x = current_pos.x - window_x;
2175 in_windowmouse_y = current_pos.y - window_y;
2177 if (!vid_usingmouse)
2180 #ifdef SUPPORTDIRECTX
2181 if (dinput_acquired)
2184 DIDEVICEOBJECTDATA od;
2192 hr = IDirectInputDevice_GetDeviceData(g_pMouse,
2193 sizeof(DIDEVICEOBJECTDATA), &od, &dwElements, 0);
2195 if ((hr == DIERR_INPUTLOST) || (hr == DIERR_NOTACQUIRED))
2197 IDirectInputDevice_Acquire(g_pMouse);
2201 /* Unable to read data or no data available */
2202 if (FAILED(hr) || dwElements == 0)
2205 /* Look at the element to see what happened */
2207 if ((int)od.dwOfs == DIMOFS_X)
2208 in_mouse_x += (LONG) od.dwData;
2209 if ((int)od.dwOfs == DIMOFS_Y)
2210 in_mouse_y += (LONG) od.dwData;
2211 if ((int)od.dwOfs == DIMOFS_Z)
2213 if((LONG)od.dwData < 0)
2215 Key_Event(K_MWHEELDOWN, 0, true);
2216 Key_Event(K_MWHEELDOWN, 0, false);
2218 else if((LONG)od.dwData > 0)
2220 Key_Event(K_MWHEELUP, 0, true);
2221 Key_Event(K_MWHEELUP, 0, false);
2224 if ((int)od.dwOfs == DIMOFS_BUTTON0)
2225 mstate_di = (mstate_di & ~1) | ((od.dwData & 0x80) >> 7);
2226 if ((int)od.dwOfs == DIMOFS_BUTTON1)
2227 mstate_di = (mstate_di & ~2) | ((od.dwData & 0x80) >> 6);
2228 if ((int)od.dwOfs == DIMOFS_BUTTON2)
2229 mstate_di = (mstate_di & ~4) | ((od.dwData & 0x80) >> 5);
2230 if ((int)od.dwOfs == DIMOFS_BUTTON3)
2231 mstate_di = (mstate_di & ~8) | ((od.dwData & 0x80) >> 4);
2234 // perform button actions
2235 for (i=0 ; i<mouse_buttons && i < 16 ; i++)
2236 if ((mstate_di ^ mouse_oldbuttonstate) & (1<<i))
2237 Key_Event (buttonremap[i], 0, (mstate_di & (1<<i)) != 0);
2238 mouse_oldbuttonstate = mstate_di;
2243 in_mouse_x += in_windowmouse_x - (int)(vid.width / 2);
2244 in_mouse_y += in_windowmouse_y - (int)(vid.height / 2);
2246 // if the mouse has moved, force it to the center, so there's room to move
2247 if (in_mouse_x || in_mouse_y)
2248 SetCursorPos ((window_x + vid.width / 2), (window_y + vid.height / 2));
2260 vid_joystate_t joystate;
2261 if (vid_activewindow && !vid_reallyhidden)
2263 VID_EnableJoystick(true);
2264 VID_BuildJoyState(&joystate);
2265 VID_ApplyJoyState(&joystate);
2269 static void IN_Init(void)
2271 uiWheelMessage = RegisterWindowMessage ( "MSWHEEL_ROLLMSG" );
2272 Cvar_RegisterVariable (&vid_forcerefreshrate);
2275 static void IN_Shutdown(void)
2277 #ifdef SUPPORTDIRECTX
2279 IDirectInputDevice_Release(g_pMouse);
2283 IDirectInput_Release(g_pdi);
2288 size_t VID_ListModes(vid_mode_t *modes, size_t maxcount)
2294 thismode.dmSize = sizeof(thismode);
2295 thismode.dmDriverExtra = 0;
2297 for(i = 0; EnumDisplaySettings(NULL, i, &thismode); ++i)
2299 if(~thismode.dmFields & (DM_BITSPERPEL | DM_PELSWIDTH | DM_PELSHEIGHT | DM_DISPLAYFREQUENCY))
2301 Con_DPrintf("enumerating modes yielded a bogus item... please debug this\n");
2306 modes[k].width = thismode.dmPelsWidth;
2307 modes[k].height = thismode.dmPelsHeight;
2308 modes[k].bpp = thismode.dmBitsPerPel;
2309 modes[k].refreshrate = thismode.dmDisplayFrequency;
2310 modes[k].pixelheight_num = 1;
2311 modes[k].pixelheight_denom = 1; // Win32 apparently does not provide this (FIXME)