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