Fixed video modes menu on Win32
[divverent/darkplaces.git] / vid_wgl.c
1 /*
2 Copyright (C) 1996-1997 Id Software, Inc.
3
4 This program is free software; you can redistribute it and/or
5 modify it under the terms of the GNU General Public License
6 as published by the Free Software Foundation; either version 2
7 of the License, or (at your option) any later version.
8
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  
12
13 See the GNU General Public License for more details.
14
15 You should have received a copy of the GNU General Public License
16 along with this program; if not, write to the Free Software
17 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
18
19 */
20 // gl_vidnt.c -- NT GL vid component
21
22 #include "quakedef.h"
23 #include "winquake.h"
24 #include "resource.h"
25 #include <commctrl.h>
26
27 #define MAX_MODE_LIST   30
28 #define VID_ROW_SIZE    3
29 #define MAXWIDTH                10000
30 #define MAXHEIGHT               10000
31
32 #define MODE_WINDOWED                   0
33 #define NO_MODE                                 (MODE_WINDOWED - 1)
34 #define MODE_FULLSCREEN_DEFAULT (MODE_WINDOWED + 1)
35
36 typedef struct {
37         modestate_t     type;
38         int                     width;
39         int                     height;
40         int                     modenum;
41         int                     dib;
42         int                     fullscreen;
43         int                     bpp;
44         int                     halfscreen;
45         char            modedesc[17];
46 } vmode_t;
47
48 typedef struct {
49         int                     width;
50         int                     height;
51 } lmode_t;
52
53 lmode_t lowresmodes[] = {
54         {320, 200},
55         {320, 240},
56         {400, 300},
57         {512, 384},
58 };
59
60 const char *gl_vendor;
61 const char *gl_renderer;
62 const char *gl_version;
63 const char *gl_extensions;
64
65 qboolean                scr_skipupdate;
66
67 static vmode_t  modelist[MAX_MODE_LIST];
68 static int              nummodes;
69 static vmode_t  badmode;
70
71 static DEVMODE  gdevmode;
72 static qboolean vid_initialized = false;
73 static qboolean windowed, leavecurrentmode;
74 static qboolean vid_canalttab = false;
75 static qboolean vid_wassuspended = false;
76 static int              usingmouse;
77 extern qboolean mouseactive;  // from in_win.c
78 static HICON    hIcon;
79
80 int                     DIBWidth, DIBHeight;
81 RECT            WindowRect;
82 DWORD           WindowStyle, ExWindowStyle;
83
84 HWND    mainwindow;
85
86 int                     vid_modenum = NO_MODE;
87 int                     vid_realmode;
88 int                     vid_default = MODE_WINDOWED;
89 static int      windowed_default;
90 unsigned char   vid_curpal[256*3];
91
92 HGLRC   baseRC;
93 HDC             maindc;
94
95 HWND WINAPI InitializeWindow (HINSTANCE hInstance, int nCmdShow);
96
97 viddef_t        vid;                            // global video state
98
99 modestate_t     modestate = MS_UNINIT;
100
101 void VID_MenuDraw (void);
102 void VID_MenuKey (int key);
103
104 LONG WINAPI MainWndProc (HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
105 void AppActivate(BOOL fActive, BOOL minimize);
106 char *VID_GetModeDescription (int mode);
107 void ClearAllStates (void);
108 void VID_UpdateWindowStatus (void);
109
110 //====================================
111
112 int                     window_center_x, window_center_y, window_x, window_y, window_width, window_height;
113 RECT            window_rect;
114
115 // direct draw software compatability stuff
116
117 void CenterWindow(HWND hWndCenter, int width, int height, BOOL lefttopjustify)
118 {
119     int     CenterX, CenterY;
120
121         CenterX = (GetSystemMetrics(SM_CXSCREEN) - width) / 2;
122         CenterY = (GetSystemMetrics(SM_CYSCREEN) - height) / 2;
123         if (CenterX > CenterY*2)
124                 CenterX >>= 1;  // dual screens
125         CenterX = (CenterX < 0) ? 0: CenterX;
126         CenterY = (CenterY < 0) ? 0: CenterY;
127         SetWindowPos (hWndCenter, NULL, CenterX, CenterY, 0, 0,
128                         SWP_NOSIZE | SWP_NOZORDER | SWP_SHOWWINDOW | SWP_DRAWFRAME);
129 }
130
131 qboolean VID_SetWindowedMode (int modenum)
132 {
133         int                             lastmodestate, width, height;
134         RECT                    rect;
135
136         lastmodestate = modestate;
137
138         WindowRect.top = WindowRect.left = 0;
139
140         WindowRect.right = modelist[modenum].width;
141         WindowRect.bottom = modelist[modenum].height;
142
143         DIBWidth = modelist[modenum].width;
144         DIBHeight = modelist[modenum].height;
145
146         WindowStyle = WS_OVERLAPPED | WS_BORDER | WS_CAPTION | WS_SYSMENU | WS_MINIMIZEBOX;
147         ExWindowStyle = 0;
148
149         rect = WindowRect;
150         AdjustWindowRectEx(&rect, WindowStyle, false, 0);
151
152         width = rect.right - rect.left;
153         height = rect.bottom - rect.top;
154
155         // Create the DIB window
156         mainwindow = CreateWindowEx (ExWindowStyle, gamename, gamename, WindowStyle, rect.left, rect.top, width, height, NULL, NULL, global_hInstance, NULL);
157
158         if (!mainwindow)
159                 Sys_Error ("Couldn't create DIB window");
160
161         // Center and show the DIB window
162         CenterWindow(mainwindow, WindowRect.right - WindowRect.left, WindowRect.bottom - WindowRect.top, false);
163
164         ShowWindow (mainwindow, SW_SHOWDEFAULT);
165         UpdateWindow (mainwindow);
166
167         modestate = MS_WINDOWED;
168
169         if (vid.conheight > modelist[modenum].height)
170                 vid.conheight = modelist[modenum].height;
171         if (vid.conwidth > modelist[modenum].width)
172                 vid.conwidth = modelist[modenum].width;
173
174         SendMessage (mainwindow, WM_SETICON, (WPARAM)true, (LPARAM)hIcon);
175         SendMessage (mainwindow, WM_SETICON, (WPARAM)false, (LPARAM)hIcon);
176
177         return true;
178 }
179
180
181 qboolean VID_SetFullDIBMode (int modenum)
182 {
183         int                             lastmodestate, width, height;
184         RECT                    rect;
185
186         if (!leavecurrentmode)
187         {
188                 gdevmode.dmFields = DM_BITSPERPEL | DM_PELSWIDTH | DM_PELSHEIGHT;
189                 gdevmode.dmBitsPerPel = modelist[modenum].bpp;
190                 gdevmode.dmPelsWidth = modelist[modenum].width <<
191                                                            modelist[modenum].halfscreen;
192                 gdevmode.dmPelsHeight = modelist[modenum].height;
193                 gdevmode.dmSize = sizeof (gdevmode);
194
195                 if (ChangeDisplaySettings (&gdevmode, CDS_FULLSCREEN) != DISP_CHANGE_SUCCESSFUL)
196                         Sys_Error ("Couldn't set fullscreen DIB mode");
197         }
198
199         lastmodestate = modestate;
200         modestate = MS_FULLDIB;
201
202         WindowRect.top = WindowRect.left = 0;
203
204         WindowRect.right = modelist[modenum].width;
205         WindowRect.bottom = modelist[modenum].height;
206
207         DIBWidth = modelist[modenum].width;
208         DIBHeight = modelist[modenum].height;
209
210         WindowStyle = WS_POPUP;
211         ExWindowStyle = 0;
212
213         rect = WindowRect;
214         AdjustWindowRectEx(&rect, WindowStyle, false, 0);
215
216         width = rect.right - rect.left;
217         height = rect.bottom - rect.top;
218
219         // Create the DIB window
220         mainwindow = CreateWindowEx (ExWindowStyle, gamename, gamename, WindowStyle, rect.left, rect.top, width, height, NULL, NULL, global_hInstance, NULL);
221
222         if (!mainwindow)
223                 Sys_Error ("Couldn't create DIB window");
224
225         ShowWindow (mainwindow, SW_SHOWDEFAULT);
226         UpdateWindow (mainwindow);
227
228         if (vid.conheight > modelist[modenum].height)
229                 vid.conheight = modelist[modenum].height;
230         if (vid.conwidth > modelist[modenum].width)
231                 vid.conwidth = modelist[modenum].width;
232
233 // needed because we're not getting WM_MOVE messages fullscreen on NT
234         window_x = 0;
235         window_y = 0;
236
237         SendMessage (mainwindow, WM_SETICON, (WPARAM)true, (LPARAM)hIcon);
238         SendMessage (mainwindow, WM_SETICON, (WPARAM)false, (LPARAM)hIcon);
239
240         return true;
241 }
242
243
244 int VID_SetMode (int modenum)
245 {
246         int                             original_mode;
247         qboolean                stat = 0;
248     MSG                         msg;
249
250         if ((windowed && (modenum != 0)) || (!windowed && (modenum < 1)) || (!windowed && (modenum >= nummodes)))
251                 Sys_Error ("Bad video mode\n");
252
253         CDAudio_Pause ();
254
255         if (vid_modenum == NO_MODE)
256                 original_mode = windowed_default;
257         else
258                 original_mode = vid_modenum;
259
260         // Set either the fullscreen or windowed mode
261         if (modelist[modenum].type == MS_WINDOWED)
262                 stat = VID_SetWindowedMode(modenum);
263         else if (modelist[modenum].type == MS_FULLDIB)
264                 stat = VID_SetFullDIBMode(modenum);
265         else
266                 Sys_Error ("VID_SetMode: Bad mode type in modelist");
267
268         window_width = DIBWidth;
269         window_height = DIBHeight;
270         VID_UpdateWindowStatus ();
271
272         CDAudio_Resume ();
273
274         if (!stat)
275                 Sys_Error ("Couldn't set video mode");
276
277 // now we try to make sure we get the focus on the mode switch, because
278 // sometimes in some systems we don't.  We grab the foreground, then
279 // finish setting up, pump all our messages, and sleep for a little while
280 // to let messages finish bouncing around the system, then we put
281 // ourselves at the top of the z order, then grab the foreground again,
282 // Who knows if it helps, but it probably doesn't hurt
283         SetForegroundWindow (mainwindow);
284         vid_modenum = modenum;
285         Cvar_SetValue ("vid_mode", (float)vid_modenum);
286
287         while (PeekMessage (&msg, NULL, 0, 0, PM_REMOVE))
288         {
289         TranslateMessage (&msg);
290         DispatchMessage (&msg);
291         }
292
293         Sleep (100);
294
295         SetWindowPos (mainwindow, HWND_TOP, 0, 0, 0, 0, SWP_DRAWFRAME | SWP_NOMOVE | SWP_NOSIZE | SWP_SHOWWINDOW | SWP_NOCOPYBITS);
296
297         SetForegroundWindow (mainwindow);
298
299 // fix the leftover Alt from any Alt-Tab or the like that switched us away
300         ClearAllStates ();
301
302         if (!msg_suppress_1)
303                 Con_SafePrintf ("Video mode %s initialized.\n", VID_GetModeDescription (vid_modenum));
304
305         return true;
306 }
307
308
309 /*
310 ================
311 VID_UpdateWindowStatus
312 ================
313 */
314 void VID_UpdateWindowStatus (void)
315 {
316
317         window_rect.left = window_x;
318         window_rect.top = window_y;
319         window_rect.right = window_x + window_width;
320         window_rect.bottom = window_y + window_height;
321         window_center_x = (window_rect.left + window_rect.right) / 2;
322         window_center_y = (window_rect.top + window_rect.bottom) / 2;
323
324         IN_UpdateClipCursor ();
325 }
326
327
328 //====================================
329
330 /*
331 =================
332 VID_GetWindowSize
333 =================
334 */
335 void VID_GetWindowSize (int *x, int *y, int *width, int *height)
336 {
337         *x = *y = 0;
338         *width = WindowRect.right - WindowRect.left;
339         *height = WindowRect.bottom - WindowRect.top;
340 }
341
342
343 void VID_Finish (void)
344 {
345         int usemouse;
346         if (r_render.integer && !scr_skipupdate)
347         {
348                 qglFinish();
349                 SwapBuffers(maindc);
350         }
351
352 // handle the mouse state when windowed if that's changed
353         usemouse = false;
354         if (vid_mouse.integer && key_dest == key_game)
355                 usemouse = true;
356         if (modestate == MS_FULLDIB)
357                 usemouse = true;
358         if (!ActiveApp)
359                 usemouse = false;
360         if (usemouse)
361         {
362                 if (!usingmouse)
363                 {
364                         usingmouse = true;
365                         IN_ActivateMouse ();
366                         IN_HideMouse();
367                 }
368         }
369         else
370         {
371                 if (usingmouse)
372                 {
373                         usingmouse = false;
374                         IN_DeactivateMouse ();
375                         IN_ShowMouse();
376                 }
377         }
378 }
379
380 void VID_SetDefaultMode (void)
381 {
382         IN_DeactivateMouse ();
383 }
384
385 void VID_RestoreSystemGamma(void);
386
387 void    VID_Shutdown (void)
388 {
389         HGLRC hRC;
390         HDC       hDC;
391         int i;
392         GLuint temp[8192];
393
394         if (vid_initialized)
395         {
396                 vid_canalttab = false;
397                 hRC = wglGetCurrentContext();
398         hDC = wglGetCurrentDC();
399
400         wglMakeCurrent(NULL, NULL);
401
402                 // LordHavoc: free textures before closing (may help NVIDIA)
403                 for (i = 0;i < 8192;i++)
404                         temp[i] = i+1;
405                 qglDeleteTextures(8192, temp);
406
407         if (hRC)
408             wglDeleteContext(hRC);
409
410                 if (hDC && mainwindow)
411                         ReleaseDC(mainwindow, hDC);
412
413                 if (modestate == MS_FULLDIB)
414                         ChangeDisplaySettings (NULL, 0);
415
416                 if (maindc && mainwindow)
417                         ReleaseDC (mainwindow, maindc);
418
419                 AppActivate(false, false);
420
421                 VID_RestoreSystemGamma();
422         }
423 }
424
425
426 //==========================================================================
427
428
429 BOOL bSetupPixelFormat(HDC hDC)
430 {
431     static PIXELFORMATDESCRIPTOR pfd = {
432         sizeof(PIXELFORMATDESCRIPTOR),  // size of this pfd
433         1,                              // version number
434         PFD_DRAW_TO_WINDOW              // support window
435         |  PFD_SUPPORT_OPENGL   // support OpenGL
436         |  PFD_DOUBLEBUFFER ,   // double buffered
437         PFD_TYPE_RGBA,                  // RGBA type
438         24,                             // 24-bit color depth
439         0, 0, 0, 0, 0, 0,               // color bits ignored
440         0,                              // no alpha buffer
441         0,                              // shift bit ignored
442         0,                              // no accumulation buffer
443         0, 0, 0, 0,                     // accum bits ignored
444         32,                             // 32-bit z-buffer      
445         0,                              // no stencil buffer
446         0,                              // no auxiliary buffer
447         PFD_MAIN_PLANE,                 // main layer
448         0,                              // reserved
449         0, 0, 0                         // layer masks ignored
450     };
451     int pixelformat;
452
453     if ( (pixelformat = ChoosePixelFormat(hDC, &pfd)) == 0 )
454     {
455         MessageBox(NULL, "ChoosePixelFormat failed", "Error", MB_OK);
456         return false;
457     }
458
459     if (SetPixelFormat(hDC, pixelformat, &pfd) == false)
460     {
461         MessageBox(NULL, "SetPixelFormat failed", "Error", MB_OK);
462         return false;
463     }
464
465     return true;
466 }
467
468
469
470 qbyte scantokey[128] =
471 {
472 //      0           1      2     3     4     5       6       7      8         9      A       B           C     D            E           F
473         0          ,27    ,'1'  ,'2'  ,'3'  ,'4'    ,'5'    ,'6'   ,'7'      ,'8'   ,'9'    ,'0'        ,'-'  ,'='         ,K_BACKSPACE,9     , // 0
474         'q'        ,'w'   ,'e'  ,'r'  ,'t'  ,'y'    ,'u'    ,'i'   ,'o'      ,'p'   ,'['    ,']'        ,13   ,K_CTRL      ,'a'        ,'s'   , // 1
475         'd'        ,'f'   ,'g'  ,'h'  ,'j'  ,'k'    ,'l'    ,';'   ,'\''     ,'`'   ,K_SHIFT,'\\'       ,'z'  ,'x'         ,'c'        ,'v'   , // 2
476         'b'        ,'n'   ,'m'  ,','  ,'.'  ,'/'    ,K_SHIFT,'*'   ,K_ALT    ,' '   ,0      ,K_F1       ,K_F2 ,K_F3        ,K_F4       ,K_F5  , // 3
477         K_F6       ,K_F7  ,K_F8 ,K_F9 ,K_F10,K_PAUSE,0      ,K_HOME,K_UPARROW,K_PGUP,'-'    ,K_LEFTARROW,'5'  ,K_RIGHTARROW,'+'        ,K_END , // 4
478         K_DOWNARROW,K_PGDN,K_INS,K_DEL,0    ,0      ,0      ,K_F11 ,K_F12    ,0     ,0      ,0          ,0    ,0           ,0          ,0     , // 5
479         0          ,0     ,0    ,0    ,0    ,0      ,0      ,0     ,0        ,0     ,0      ,0          ,0    ,0           ,0          ,0     , // 6
480         0          ,0     ,0    ,0    ,0    ,0      ,0      ,0     ,0        ,0     ,0      ,0          ,0    ,0           ,0          ,0       // 7
481 };
482
483
484 /*
485 =======
486 MapKey
487
488 Map from windows to quake keynums
489 =======
490 */
491 int MapKey (int key, int virtualkey)
492 {
493         key = (key>>16)&255;
494         if (key > 127)
495                 return 0;
496         if (scantokey[key] == 0)
497                 Con_DPrintf("key 0x%02x has no translation\n", key);
498         return scantokey[key];
499 }
500
501 /*
502 ===================================================================
503
504 MAIN WINDOW
505
506 ===================================================================
507 */
508
509 /*
510 ================
511 ClearAllStates
512 ================
513 */
514 void ClearAllStates (void)
515 {
516         int             i;
517         
518 // send an up event for each key, to make sure the server clears them all
519         for (i=0 ; i<256 ; i++)
520         {
521                 Key_Event (i, false);
522         }
523
524         Key_ClearStates ();
525         IN_ClearStates ();
526 }
527
528 void VID_RestoreGameGamma(void);
529 extern qboolean host_loopactive;
530
531 void AppActivate(BOOL fActive, BOOL minimize)
532 /****************************************************************************
533 *
534 * Function:     AppActivate
535 * Parameters:   fActive - True if app is activating
536 *
537 * Description:  If the application is activating, then swap the system
538 *               into SYSPAL_NOSTATIC mode so that our palettes will display
539 *               correctly.
540 *
541 ****************************************************************************/
542 {
543         static BOOL     sound_active;
544
545         ActiveApp = fActive;
546         Minimized = minimize;
547
548 // enable/disable sound on focus gain/loss
549         if (!ActiveApp && sound_active)
550         {
551                 S_BlockSound ();
552                 sound_active = false;
553         }
554         else if (ActiveApp && !sound_active)
555         {
556                 S_UnblockSound ();
557                 sound_active = true;
558         }
559
560         if (fActive)
561         {
562                 if (modestate == MS_FULLDIB)
563                 {
564                         if (vid_canalttab && vid_wassuspended)
565                         {
566                                 vid_wassuspended = false;
567                                 ChangeDisplaySettings (&gdevmode, CDS_FULLSCREEN);
568                                 ShowWindow(mainwindow, SW_SHOWNORMAL);
569                         }
570
571                         // LordHavoc: from dabb, fix for alt-tab bug in NVidia drivers
572                         MoveWindow(mainwindow,0,0,gdevmode.dmPelsWidth,gdevmode.dmPelsHeight,false);
573                 }
574                 if (host_loopactive)
575                         VID_RestoreGameGamma();
576         }
577
578         if (!fActive)
579         {
580                 usingmouse = false;
581                 IN_DeactivateMouse ();
582                 IN_ShowMouse ();
583                 if (modestate == MS_FULLDIB && vid_canalttab)
584                 { 
585                         ChangeDisplaySettings (NULL, 0);
586                         vid_wassuspended = true;
587                 }
588                 VID_RestoreSystemGamma();
589         }
590 }
591
592 LONG CDAudio_MessageHandler(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
593
594 /* main window procedure */
595 LONG WINAPI MainWndProc (HWND hWnd, UINT uMsg, WPARAM  wParam, LPARAM lParam)
596 {
597     LONG    lRet = 1;
598         int             fActive, fMinimized, temp;
599         extern unsigned int uiWheelMessage;
600
601         if ( uMsg == uiWheelMessage )
602                 uMsg = WM_MOUSEWHEEL;
603
604     switch (uMsg)
605     {
606                 case WM_KILLFOCUS:
607                         if (modestate == MS_FULLDIB)
608                                 ShowWindow(mainwindow, SW_SHOWMINNOACTIVE);
609                         break;
610
611                 case WM_CREATE:
612                         break;
613
614                 case WM_MOVE:
615                         window_x = (int) LOWORD(lParam);
616                         window_y = (int) HIWORD(lParam);
617                         VID_UpdateWindowStatus ();
618                         break;
619
620                 case WM_KEYDOWN:
621                 case WM_SYSKEYDOWN:
622                         Key_Event (MapKey(lParam, wParam), true);
623                         break;
624                         
625                 case WM_KEYUP:
626                 case WM_SYSKEYUP:
627                         Key_Event (MapKey(lParam, wParam), false);
628                         break;
629
630                 case WM_SYSCHAR:
631                 // keep Alt-Space from happening
632                         break;
633
634         // this is complicated because Win32 seems to pack multiple mouse events into
635         // one update sometimes, so we always check all states and look for events
636                 case WM_LBUTTONDOWN:
637                 case WM_LBUTTONUP:
638                 case WM_RBUTTONDOWN:
639                 case WM_RBUTTONUP:
640                 case WM_MBUTTONDOWN:
641                 case WM_MBUTTONUP:
642                 case WM_MOUSEMOVE:
643                         temp = 0;
644
645                         if (wParam & MK_LBUTTON)
646                                 temp |= 1;
647
648                         if (wParam & MK_RBUTTON)
649                                 temp |= 2;
650
651                         if (wParam & MK_MBUTTON)
652                                 temp |= 4;
653
654                         IN_MouseEvent (temp);
655
656                         break;
657
658                 // JACK: This is the mouse wheel with the Intellimouse
659                 // Its delta is either positive or neg, and we generate the proper
660                 // Event.
661                 case WM_MOUSEWHEEL: 
662                         if ((short) HIWORD(wParam) > 0) {
663                                 Key_Event(K_MWHEELUP, true);
664                                 Key_Event(K_MWHEELUP, false);
665                         } else {
666                                 Key_Event(K_MWHEELDOWN, true);
667                                 Key_Event(K_MWHEELDOWN, false);
668                         }
669                         break;
670
671         case WM_SIZE:
672             break;
673
674             case WM_CLOSE:
675                         if (MessageBox (mainwindow, "Are you sure you want to quit?", "Confirm Exit", MB_YESNO | MB_SETFOREGROUND | MB_ICONQUESTION) == IDYES)
676                                 Sys_Quit ();
677
678                 break;
679
680                 case WM_ACTIVATE:
681                         fActive = LOWORD(wParam);
682                         fMinimized = (BOOL) HIWORD(wParam);
683                         AppActivate(!(fActive == WA_INACTIVE), fMinimized);
684
685                 // fix the leftover Alt from any Alt-Tab or the like that switched us away
686                         ClearAllStates ();
687
688                         break;
689
690             case WM_DESTROY:
691         {
692                         if (mainwindow)
693                                 DestroyWindow (mainwindow);
694
695             PostQuitMessage (0);
696         }
697         break;
698
699                 case MM_MCINOTIFY:
700             lRet = CDAudio_MessageHandler (hWnd, uMsg, wParam, lParam);
701                         break;
702
703         default:
704             /* pass all unhandled messages to DefWindowProc */
705             lRet = DefWindowProc (hWnd, uMsg, wParam, lParam);
706         break;
707     }
708
709     /* return 1 if handled message, 0 if not */
710     return lRet;
711 }
712
713
714 /*
715 =================
716 VID_NumModes
717 =================
718 */
719 int VID_NumModes (void)
720 {
721         return nummodes;
722 }
723
724         
725 /*
726 =================
727 VID_GetModePtr
728 =================
729 */
730 vmode_t *VID_GetModePtr (int modenum)
731 {
732
733         if ((modenum >= 0) && (modenum < nummodes))
734                 return &modelist[modenum];
735         else
736                 return &badmode;
737 }
738
739
740 /*
741 =================
742 VID_GetModeDescription
743 =================
744 */
745 char *VID_GetModeDescription (int mode)
746 {
747         char            *pinfo;
748         vmode_t         *pv;
749         static char     temp[100];
750
751         if ((mode < 0) || (mode >= nummodes))
752                 return NULL;
753
754         if (!leavecurrentmode)
755         {
756                 pv = VID_GetModePtr (mode);
757                 pinfo = pv->modedesc;
758         }
759         else
760         {
761                 sprintf (temp, "Desktop resolution (%dx%d)", modelist[MODE_FULLSCREEN_DEFAULT].width, modelist[MODE_FULLSCREEN_DEFAULT].height);
762                 pinfo = temp;
763         }
764
765         return pinfo;
766 }
767
768
769 // KJB: Added this to return the mode driver name in description for console
770
771 char *VID_GetExtModeDescription (int mode)
772 {
773         static char     pinfo[40];
774         vmode_t         *pv;
775
776         if ((mode < 0) || (mode >= nummodes))
777                 return NULL;
778
779         pv = VID_GetModePtr (mode);
780         if (modelist[mode].type == MS_FULLDIB)
781         {
782                 if (!leavecurrentmode)
783                         sprintf(pinfo,"%s fullscreen", pv->modedesc);
784                 else
785                         sprintf (pinfo, "Desktop resolution (%dx%d)", modelist[MODE_FULLSCREEN_DEFAULT].width, modelist[MODE_FULLSCREEN_DEFAULT].height);
786         }
787         else
788         {
789                 if (modestate == MS_WINDOWED)
790                         sprintf(pinfo, "%s windowed", pv->modedesc);
791                 else
792                         sprintf(pinfo, "windowed");
793         }
794
795         return pinfo;
796 }
797
798
799 /*
800 =================
801 VID_DescribeCurrentMode_f
802 =================
803 */
804 void VID_DescribeCurrentMode_f (void)
805 {
806         Con_Printf ("%s\n", VID_GetExtModeDescription (vid_modenum));
807 }
808
809
810 /*
811 =================
812 VID_NumModes_f
813 =================
814 */
815 void VID_NumModes_f (void)
816 {
817         if (nummodes == 1)
818                 Con_Printf ("%d video mode is available\n", nummodes);
819         else
820                 Con_Printf ("%d video modes are available\n", nummodes);
821 }
822
823
824 /*
825 =================
826 VID_DescribeMode_f
827 =================
828 */
829 void VID_DescribeMode_f (void)
830 {
831         int             t, modenum;
832         
833         modenum = atoi (Cmd_Argv(1));
834
835         t = leavecurrentmode;
836         leavecurrentmode = 0;
837
838         Con_Printf ("%s\n", VID_GetExtModeDescription (modenum));
839
840         leavecurrentmode = t;
841 }
842
843
844 /*
845 =================
846 VID_DescribeModes_f
847 =================
848 */
849 void VID_DescribeModes_f (void)
850 {
851         int                     i, lnummodes, t;
852         char            *pinfo;
853         vmode_t         *pv;
854
855         lnummodes = VID_NumModes ();
856
857         t = leavecurrentmode;
858         leavecurrentmode = 0;
859
860         for (i=1 ; i<lnummodes ; i++)
861         {
862                 pv = VID_GetModePtr (i);
863                 pinfo = VID_GetExtModeDescription (i);
864                 Con_Printf ("%2d: %s\n", i, pinfo);
865         }
866
867         leavecurrentmode = t;
868 }
869
870 void VID_AddMode(int type, int width, int height, int modenum, int halfscreen, int dib, int fullscreen, int bpp)
871 {
872         int i;
873         if (nummodes >= MAX_MODE_LIST)
874                 return;
875         modelist[nummodes].type = type;
876         modelist[nummodes].width = width;
877         modelist[nummodes].height = height;
878         modelist[nummodes].modenum = modenum;
879         modelist[nummodes].halfscreen = halfscreen;
880         modelist[nummodes].dib = dib;
881         modelist[nummodes].fullscreen = fullscreen;
882         modelist[nummodes].bpp = bpp;
883         if (bpp == 0)
884                 sprintf (modelist[nummodes].modedesc, "%dx%d", width, height);
885         else
886                 sprintf (modelist[nummodes].modedesc, "%dx%dx%d", width, height, bpp);
887         for (i = 0;i < nummodes;i++)
888         {
889                 if (!memcmp(&modelist[i], &modelist[nummodes], sizeof(vmode_t)))
890                         return;
891         }
892         nummodes++;
893 }
894
895 void VID_InitDIB (HINSTANCE hInstance)
896 {
897         int w, h;
898         WNDCLASS                wc;
899
900         // Register the frame class
901     wc.style         = 0;
902     wc.lpfnWndProc   = (WNDPROC)MainWndProc;
903     wc.cbClsExtra    = 0;
904     wc.cbWndExtra    = 0;
905     wc.hInstance     = hInstance;
906     wc.hIcon         = 0;
907     wc.hCursor       = LoadCursor (NULL,IDC_ARROW);
908         wc.hbrBackground = NULL;
909     wc.lpszMenuName  = 0;
910     wc.lpszClassName = gamename;
911
912     if (!RegisterClass (&wc) )
913                 Sys_Error ("Couldn't register window class");
914
915         if (COM_CheckParm("-width"))
916                 w = atoi(com_argv[COM_CheckParm("-width")+1]);
917         else
918                 w = 640;
919
920         if (w < 320)
921                 w = 320;
922
923         if (COM_CheckParm("-height"))
924                 h = atoi(com_argv[COM_CheckParm("-height")+1]);
925         else
926                 h = w * 240/320;
927
928         if (h < 240)
929                 h = 240;
930
931         VID_AddMode(MS_WINDOWED, w, h, 0, 0, 1, 0, 0);
932 }
933
934
935 /*
936 =================
937 VID_InitFullDIB
938 =================
939 */
940 void VID_InitFullDIB (HINSTANCE hInstance)
941 {
942         DEVMODE devmode;
943         int             modenum;
944         int             originalnummodes;
945         int             numlowresmodes;
946         int             j;
947         int             bpp;
948         int             done;
949         BOOL    stat;
950
951 // enumerate >8 bpp modes
952         originalnummodes = nummodes;
953         modenum = 0;
954
955         do
956         {
957                 stat = EnumDisplaySettings (NULL, modenum, &devmode);
958
959                 if ((devmode.dmBitsPerPel >= 15) && (devmode.dmPelsWidth <= MAXWIDTH) && (devmode.dmPelsHeight <= MAXHEIGHT) && (nummodes < MAX_MODE_LIST))
960                 {
961                         devmode.dmFields = DM_BITSPERPEL | DM_PELSWIDTH | DM_PELSHEIGHT;
962
963                         if (ChangeDisplaySettings (&devmode, CDS_TEST | CDS_FULLSCREEN) == DISP_CHANGE_SUCCESSFUL)
964                         {
965                         // if the width is more than twice the height, reduce it by half because this
966                         // is probably a dual-screen monitor
967                                 if ((!COM_CheckParm("-noadjustaspect")) && (devmode.dmPelsWidth > (devmode.dmPelsHeight << 1)))
968                                         VID_AddMode(MS_FULLDIB, devmode.dmPelsWidth >> 1, devmode.dmPelsHeight, 0, 1, 1, 1, devmode.dmBitsPerPel);
969                                 else
970                                         VID_AddMode(MS_FULLDIB, devmode.dmPelsWidth, devmode.dmPelsHeight, 0, 0, 1, 1, devmode.dmBitsPerPel);
971                         }
972                 }
973
974                 modenum++;
975         }
976         while (stat);
977
978 // see if there are any low-res modes that aren't being reported
979         numlowresmodes = sizeof(lowresmodes) / sizeof(lowresmodes[0]);
980         bpp = 16;
981         done = 0;
982
983         do
984         {
985                 for (j=0 ; (j<numlowresmodes) && (nummodes < MAX_MODE_LIST) ; j++)
986                 {
987                         devmode.dmBitsPerPel = bpp;
988                         devmode.dmPelsWidth = lowresmodes[j].width;
989                         devmode.dmPelsHeight = lowresmodes[j].height;
990                         devmode.dmFields = DM_BITSPERPEL | DM_PELSWIDTH | DM_PELSHEIGHT;
991
992                         if (ChangeDisplaySettings (&devmode, CDS_TEST | CDS_FULLSCREEN) == DISP_CHANGE_SUCCESSFUL)
993                                 VID_AddMode(MS_FULLDIB, devmode.dmPelsWidth, devmode.dmPelsHeight, 0, 0, 1, 1, devmode.dmBitsPerPel);
994                 }
995                 switch (bpp)
996                 {
997                         case 16:
998                                 bpp = 32;
999                                 break;
1000
1001                         case 32:
1002                                 bpp = 24;
1003                                 break;
1004
1005                         case 24:
1006                                 done = 1;
1007                                 break;
1008                 }
1009         }
1010         while (!done);
1011
1012         if (nummodes == originalnummodes)
1013                 Con_SafePrintf ("No fullscreen DIB modes found\n");
1014 }
1015
1016 //static int grabsysgamma = true;
1017 WORD systemgammaramps[3][256], currentgammaramps[3][256];
1018
1019 int VID_SetGamma(float prescale, float gamma, float scale, float base)
1020 {
1021         int i;
1022         HDC hdc;
1023         hdc = GetDC (NULL);
1024
1025         BuildGammaTable16(prescale, gamma, scale, base, &currentgammaramps[0][0]);
1026         for (i = 0;i < 256;i++)
1027                 currentgammaramps[1][i] = currentgammaramps[2][i] = currentgammaramps[0][i];
1028
1029         i = SetDeviceGammaRamp(hdc, &currentgammaramps[0][0]);
1030
1031         ReleaseDC (NULL, hdc);
1032         return i; // return success or failure
1033 }
1034
1035 void VID_RestoreGameGamma(void)
1036 {
1037         VID_UpdateGamma(true);
1038 }
1039
1040 void VID_GetSystemGamma(void)
1041 {
1042         HDC hdc;
1043         hdc = GetDC (NULL);
1044
1045         GetDeviceGammaRamp(hdc, &systemgammaramps[0][0]);
1046
1047         ReleaseDC (NULL, hdc);
1048 }
1049
1050 void VID_RestoreSystemGamma(void)
1051 {
1052         HDC hdc;
1053         hdc = GetDC (NULL);
1054
1055         SetDeviceGammaRamp(hdc, &systemgammaramps[0][0]);
1056
1057         ReleaseDC (NULL, hdc);
1058 }
1059
1060 /*
1061 ===================
1062 VID_Init
1063 ===================
1064 */
1065 void    VID_Init (void)
1066 {
1067         int             i;
1068         int             basenummodes, width, height = 0, bpp, findbpp, done;
1069         HDC             hdc;
1070         DEVMODE devmode;
1071
1072         memset(&devmode, 0, sizeof(devmode));
1073
1074         Cmd_AddCommand ("vid_nummodes", VID_NumModes_f);
1075         Cmd_AddCommand ("vid_describecurrentmode", VID_DescribeCurrentMode_f);
1076         Cmd_AddCommand ("vid_describemode", VID_DescribeMode_f);
1077         Cmd_AddCommand ("vid_describemodes", VID_DescribeModes_f);
1078
1079         VID_GetSystemGamma();
1080
1081         hIcon = LoadIcon (global_hInstance, MAKEINTRESOURCE (IDI_ICON2));
1082
1083         InitCommonControls();
1084
1085         VID_InitDIB (global_hInstance);
1086         basenummodes = nummodes = 1;
1087
1088         VID_InitFullDIB (global_hInstance);
1089
1090         if (COM_CheckParm("-window"))
1091         {
1092                 hdc = GetDC (NULL);
1093
1094                 if (GetDeviceCaps(hdc, RASTERCAPS) & RC_PALETTE)
1095                         Sys_Error ("Can't run in non-RGB mode");
1096
1097                 ReleaseDC (NULL, hdc);
1098
1099                 windowed = true;
1100
1101                 vid_default = MODE_WINDOWED;
1102         }
1103         else
1104         {
1105                 if (nummodes == 1)
1106                         Sys_Error ("No RGB fullscreen modes available");
1107
1108                 windowed = false;
1109
1110                 if (COM_CheckParm("-mode"))
1111                         vid_default = atoi(com_argv[COM_CheckParm("-mode")+1]);
1112                 else
1113                 {
1114                         if (COM_CheckParm("-current"))
1115                         {
1116                                 modelist[MODE_FULLSCREEN_DEFAULT].width = GetSystemMetrics (SM_CXSCREEN);
1117                                 modelist[MODE_FULLSCREEN_DEFAULT].height = GetSystemMetrics (SM_CYSCREEN);
1118                                 vid_default = MODE_FULLSCREEN_DEFAULT;
1119                                 leavecurrentmode = 1;
1120                         }
1121                         else
1122                         {
1123                                 if (COM_CheckParm("-width"))
1124                                         width = atoi(com_argv[COM_CheckParm("-width")+1]);
1125                                 else
1126                                         width = 640;
1127
1128                                 if (COM_CheckParm("-bpp"))
1129                                 {
1130                                         bpp = atoi(com_argv[COM_CheckParm("-bpp")+1]);
1131                                         findbpp = 0;
1132                                 }
1133                                 else
1134                                 {
1135                                         bpp = 15;
1136                                         findbpp = 1;
1137                                 }
1138
1139                                 if (COM_CheckParm("-height"))
1140                                         height = atoi(com_argv[COM_CheckParm("-height")+1]);
1141
1142                         // if they want to force it, add the specified mode to the list
1143                                 if (COM_CheckParm("-force") && (nummodes < MAX_MODE_LIST))
1144                                         VID_AddMode(MS_FULLDIB, width, height, 0, 0, 1, 1, bpp);
1145
1146                                 done = 0;
1147
1148                                 do
1149                                 {
1150                                         if (COM_CheckParm("-height"))
1151                                         {
1152                                                 height = atoi(com_argv[COM_CheckParm("-height")+1]);
1153
1154                                                 for (i=1, vid_default=0 ; i<nummodes ; i++)
1155                                                 {
1156                                                         if ((modelist[i].width == width) && (modelist[i].height == height) && (modelist[i].bpp == bpp))
1157                                                         {
1158                                                                 vid_default = i;
1159                                                                 done = 1;
1160                                                                 break;
1161                                                         }
1162                                                 }
1163                                         }
1164                                         else
1165                                         {
1166                                                 for (i=1, vid_default=0 ; i<nummodes ; i++)
1167                                                 {
1168                                                         if ((modelist[i].width == width) && (modelist[i].bpp == bpp))
1169                                                         {
1170                                                                 vid_default = i;
1171                                                                 done = 1;
1172                                                                 break;
1173                                                         }
1174                                                 }
1175                                         }
1176
1177                                         if (!done)
1178                                         {
1179                                                 if (findbpp)
1180                                                 {
1181                                                         switch (bpp)
1182                                                         {
1183                                                         case 15: bpp = 16;break;
1184                                                         case 16: bpp = 32;break;
1185                                                         case 32: bpp = 24;break;
1186                                                         case 24: done = 1;break;
1187                                                         }
1188                                                 }
1189                                                 else
1190                                                         done = 1;
1191                                         }
1192                                 }
1193                                 while (!done);
1194
1195                                 if (!vid_default)
1196                                         Sys_Error ("Specified video mode not available");
1197                         }
1198                 }
1199         }
1200
1201         vid_initialized = true;
1202
1203         if ((i = COM_CheckParm("-conwidth")) != 0)
1204                 vid.conwidth = atoi(com_argv[i+1]);
1205         else
1206                 vid.conwidth = 640;
1207
1208         vid.conwidth &= 0xfff8; // make it a multiple of eight
1209
1210         if (vid.conwidth < 320)
1211                 vid.conwidth = 320;
1212
1213         // pick a conheight that matches with correct aspect
1214         vid.conheight = vid.conwidth*3 / 4;
1215
1216         if ((i = COM_CheckParm("-conheight")) != 0)
1217                 vid.conheight = atoi(com_argv[i+1]);
1218         if (vid.conheight < 200)
1219                 vid.conheight = 200;
1220
1221         VID_SetMode (vid_default);
1222
1223         maindc = GetDC(mainwindow);
1224         bSetupPixelFormat(maindc);
1225
1226         baseRC = wglCreateContext( maindc );
1227         if (!baseRC)
1228                 Sys_Error ("Could not initialize GL (wglCreateContext failed).\n\nMake sure you are in 65536 color mode, and try running -window.");
1229         if (!wglMakeCurrent( maindc, baseRC ))
1230                 Sys_Error ("wglMakeCurrent failed");
1231
1232         GL_Init ();
1233
1234         // LordHavoc: special differences for ATI (broken 8bit color when also using 32bit? weird!)
1235         if (strncasecmp(gl_vendor,"ATI",3)==0)
1236         {
1237                 if (strncasecmp(gl_renderer,"Rage Pro",8)==0)
1238                         isRagePro = true;
1239         }
1240         if (strncasecmp(gl_renderer,"Matrox G200 Direct3D",20)==0) // a D3D driver for GL? sigh...
1241                 isG200 = true;
1242
1243         vid_realmode = vid_modenum;
1244
1245         vid_menudrawfn = VID_MenuDraw;
1246         vid_menukeyfn = VID_MenuKey;
1247
1248         strcpy (badmode.modedesc, "Bad mode");
1249         vid_canalttab = true;
1250 }
1251
1252
1253 //========================================================
1254 // Video menu stuff
1255 //========================================================
1256
1257 extern void M_Menu_Options_f (void);
1258 extern void M_Print (float cx, float cy, char *str);
1259 extern void M_PrintWhite (float cx, float cy, char *str);
1260 extern void M_DrawCharacter (float cx, float cy, int num);
1261 extern void M_DrawPic (float cx, float cy, char *picname);
1262
1263 static int      vid_wmodes;
1264
1265 typedef struct
1266 {
1267         int             modenum;
1268         char    *desc;
1269         int             iscur;
1270 } modedesc_t;
1271
1272 #define MAX_COLUMN_SIZE         9
1273 #define MODE_AREA_HEIGHT        (MAX_COLUMN_SIZE + 2)
1274 #define MAX_MODEDESCS           (MAX_COLUMN_SIZE*3)
1275
1276 static modedesc_t       modedescs[MAX_MODEDESCS];
1277
1278 /*
1279 ================
1280 VID_MenuDraw
1281 ================
1282 */
1283 void VID_MenuDraw (void)
1284 {
1285         cachepic_t *p;
1286         char *ptr;
1287         int lnummodes, i, k, column, row;
1288         vmode_t *pv;
1289
1290         p = Draw_CachePic ("gfx/vidmodes.lmp");
1291         M_DrawPic ( (320-p->width)/2, 4, "gfx/vidmodes.lmp");
1292
1293         vid_wmodes = 0;
1294         lnummodes = VID_NumModes ();
1295
1296         for (i=1 ; (i<lnummodes) && (vid_wmodes < MAX_MODEDESCS) ; i++)
1297         {
1298                 ptr = VID_GetModeDescription (i);
1299                 pv = VID_GetModePtr (i);
1300
1301                 k = vid_wmodes;
1302
1303                 modedescs[k].modenum = i;
1304                 modedescs[k].desc = ptr;
1305                 modedescs[k].iscur = 0;
1306
1307                 if (i == vid_modenum)
1308                         modedescs[k].iscur = 1;
1309
1310                 vid_wmodes++;
1311
1312         }
1313
1314         if (vid_wmodes > 0)
1315         {
1316                 M_Print (2*8, 36+0*8, "Fullscreen Modes (WIDTHxHEIGHTxBPP)");
1317
1318                 column = 8;
1319                 row = 36+2*8;
1320
1321                 for (i=0 ; i<vid_wmodes ; i++)
1322                 {
1323                         if (modedescs[i].iscur)
1324                                 M_PrintWhite (column, row, modedescs[i].desc);
1325                         else
1326                                 M_Print (column, row, modedescs[i].desc);
1327
1328                         column += 13*8;
1329
1330                         if ((i % VID_ROW_SIZE) == (VID_ROW_SIZE - 1))
1331                         {
1332                                 column = 8;
1333                                 row += 8;
1334                         }
1335                 }
1336         }
1337
1338         M_Print (3*8, 36 + MODE_AREA_HEIGHT * 8 + 8*2, "Video modes must be set from the");
1339         M_Print (3*8, 36 + MODE_AREA_HEIGHT * 8 + 8*3, "command line with -width <width>");
1340         M_Print (3*8, 36 + MODE_AREA_HEIGHT * 8 + 8*4, "and -bpp <bits-per-pixel>");
1341         M_Print (3*8, 36 + MODE_AREA_HEIGHT * 8 + 8*6, "Select windowed mode with -window");
1342 }
1343
1344
1345 /*
1346 ================
1347 VID_MenuKey
1348 ================
1349 */
1350 void VID_MenuKey (int key)
1351 {
1352         switch (key)
1353         {
1354         case K_ESCAPE:
1355                 S_LocalSound ("misc/menu1.wav");
1356                 M_Menu_Options_f ();
1357                 break;
1358
1359         default:
1360                 break;
1361         }
1362 }
1363