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