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