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