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