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