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